text:
Q: iOS autolayout result is not correct I have a customized view with two subviews which divide their superview equally. I want the customized view shown below:
-------------------------------
|              |              |
|             300             |
|              |              |
|-----------------------------|
|    red       |     green    |
|-----------------------------|
|                             |

However, whatever I modify the constraints, the result always show like below:
-------------------------------
|    red       |     green    |
|-----------------------------|
|                             |

The frame of customized view is correct, and it is (0, 300, 375, 60). But the origin of its subview is always (0, -300).
RootController.swift
override func viewDidLoad() {
  super.viewDidLoad()

  let view = RootView()
  view.translatesAutoresizingMaskIntoConstraints = false
  self.view.addSubview(view)
  self.rootView = view

  NSLayoutConstraint.activate([
    NSLayoutConstraint.constraints(withVisualFormat: "V:|-300-[v(60)]", metrics: nil, views: ["v": self.rootView!]),
    NSLayoutConstraint.constraints(withVisualFormat: "H:|[v]|", metrics: nil, views: ["v": self.rootView!])
  ].flatMap({ $0 }))
}

RootView.swift
override init (frame: CGRect) {
  super.init(frame: frame)

  var view = UIView()
  view.translatesAutoresizingMaskIntoConstraints = false
  view.backgroundColor = .red
  self.addSubview(view)
  self.red = view

  view = UIView()
  view.translatesAutoresizingMaskIntoConstraints = false
  view.backgroundColor = .green
  self.addSubview(view)
  self.green = view
}

override func updateConstraints () {
  NSLayoutConstraint.activate([
    NSLayoutConstraint.constraints(withVisualFormat: "H:|[r][g(==r)]|", metrics: nil, views: ["r": self.red, "g": self.green])
  ].flatMap({ $0 }))
  NSLayoutConstraint.activate([
    self.red.heightAnchor.constraint(equalTo: self.heightAnchor),
    self.green.heightAnchor.constraint(equalTo: self.heightAnchor)
  ])
  super.updateConstraints()
}

A: I have missed one vertical constraint which is shown below:
override func updateConstraints () {
  // ...

  NSLayoutConstraint.activate([
    self.red.heightAnchor.constraint(equalTo: self.heightAnchor),
    self.green.heightAnchor.constraint(equalTo: self.heightAnchor),
    self.red.topAnchor.constraint(equalTo: self.topAnchor),
    self.green.topAnchor.constraint(equalTo: self.topAnchor)
  ])

  // ...
}

This will correct my issue.


text:
Q: Expected primary expression before * C++ I can't figure out the error in the following code
#include <iostream>
#include <vector>
using namespace std;

class Spell {
    private:
        string scrollName;
    public:
        Spell(): scrollName("") { }
        Spell(string name): scrollName(name) { }
        virtual ~Spell() { }
        string revealScrollName() {
            return scrollName;
        }
};

class Fireball : public Spell {
    private: int power;
    public:
        Fireball(int power): power(power) { }
        void revealFirepower(){
            cout << "Fireball: " << power << endl;
        }
};

class SpellJournal {
    public:
        static string journal;
        static string read() {
            return journal;
        }
};
string SpellJournal::journal = "";

void counterspell(Spell *spell) {
    if((Fireball *firespell=dynamic_cast<Fireball*>(spell))!=NULL)
    {
    firespell->revealFirepower();

}

 else
    {

    string scname=spell->revealScrollName();
    int m = scname.size();
    int n = SpellJournal::journal.size();
    int L[m+1][n+1];
    for(int i=0; i<=m; i++)
    {
        for(int j=0; j<=n; j++)
        {
            if(i==0 || j==0)
                L[i][j] = 0;
            else if(scname[i-1]==SpellJournal::journal[j-1])
                L[i][j] = L[i-1][j-1]+1;
            else
                L[i][j] = max(L[i-1][j],L[i][j-1]);
        }
    }
    cout<<L[m][n];
}

}

class Wizard {
    public:
        Spell *cast() {
            Spell *spell;
            string s; cin >> s;
            int power; cin >> power;
            if(s == "fire") {
                spell = new Fireball(power);
            }

            else {
                spell = new Spell(s);
                cin >> SpellJournal::journal;
            }
            return spell;
        }
};

int main() {
    int T;
    cin >> T;
    Wizard Arawn;
    while(T--) {
        Spell *spell = Arawn.cast();
        counterspell(spell);
    }
    return 0;
}

The error is that primary expression is expected before * in the statement
if((Fireball *firespell=dynamic_cast<Fireball*>(spell))!=NULL)

also
firespell' was not declared in this scope

I think 2nd error is related to first. I don't know what concept I am missing. I have been following this link http://en.cppreference.com/w/cpp/language/dynamic_cast
kindly help.

A: if((Fireball *firespell=dynamic_cast(spell))!=NULL)

replace by
if(Fireball *firespell = dynamic_cast<Fireball*>(spell))

or by
 Fireball *firespell;
 if( ( firespell = dynamic_cast(spell) ) != nullptr)

Also, I do not have idea how this segment was compiled.
    int m = scname.size();
    int n = SpellJournal::journal.size();
    int L[m+1][n+1];

You can not declare array size in runtime, use dynamic allocation (malloc, new) or some high-level containers
EDIT: Readability decrease in 2-nd code block is controversial statement.

A: From if statement:

Condition [if ( condition ) statement_true] one of

*

*one of expression which is contextually convertible to bool

*declaration of a single non-array variable with a brace-or-equals initializer.

So, you can't have a declaration and a boolean convertible expression in a single if statement.
You have to define it before if:
Fireball* firespell = dynamic_cast<Fireball*>(spell);
if (firespell != nullptr)
    //Do something

A: If it is a c++ program then you can just write
void counterspell(Spell *spell) {
    if( Fireball *firespell=dynamic_cast<Fireball*>(spell) )
    {
    firespell->revealFirepower();

}

The original code is not compiled because a declaration is an operand of an expression in the if statement.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Download pdf file on remote Client Machine where my publish site is running I had publish my site and access it from remote location , but the when i download the pdf file it get downloaded and saved on server side where i published my code.
                    int FOrgCountRows = OrgCountRows;
                    string folderName = @"c:\EStatement\";

                        foreach (DataRow dr in DTAC.Rows)
                        {
                            if (DTAC.Rows[FOrgCountRows - OrgCountRows]["Acc"].ToString() == AccArray[CountAcc].ToString())
                            {
                                DataT.ImportRow(dr);
                                if((FOrgCountRows - OrgCountRows)!=( DTAC.Rows.Count)-1)
                                OrgCountRows--;
                                DTACCount++;
                            }

                            if (DTAC.Rows[FOrgCountRows - OrgCountRows]["Acc"].ToString() != AccArray[CountAcc].ToString())
                            {
                                string fileName = "_" + AccArray[CountAcc] + ".pdf";
                                CountAcc++;
                                string extension;
                                string encoding;
                                string mimeType;
                                string[] streams;
                                Warning[] warnings;

                                LocalReport report = new LocalReport();
                                report.ReportPath = Server.MapPath("~/Rpt123.rdlc");
                                ReportDataSource rds = new ReportDataSource();
                                rds.Name = "DataSet1";
                                rds.Value = DataT;
                                report.DataSources.Add(rds);

                                byte[] mybytes = report.Render("PDF", null, out extension, out encoding, out mimeType, out streams, out warnings); //for exporting to PDF

                                if (!System.IO.File.Exists(folderName))
                                {
                                    using (FileStream fs = File.Create(folderName + fileName))
                                    {
                                        fs.Write(mybytes, 0, mybytes.Length);
                                    }
                                }
                                else
                                {
                                    Console.WriteLine("File \"{0}\" already exists.", fileName);
                                    return;
                                }

                                Response.Buffer = true;
                                Response.Clear();
                                Response.ContentType = contentType;
                                Response.AddHeader("Content-Disposition", "attachment; filename=" + fileName);
                                Response.WriteFile(folderName + fileName);

-----string folderName = @"c:\EStatement\"; this is the Target folder.. I want to download the files on client machine on this specified folder.. ANy SOLUTION?

A: Possible duplicate:
ASP.net download and save file in user folder
Anyway:
"
Filestream will write to a file on server and not on the client's machine.
Try writing the document bytes to response output stream and a content-disposition http header to response.
Response.AddHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");

"
This would prompt user for the file download based on browser setting.
You cannot control which directory file goes in in the client's machine.


text:
Q: Paypal merchant paying facilitator I have set up a sandbox test case whereby I allow merchants to link and grant express checkout permission to my facilitator account, coupled with a second page where end users can purchase items from the merchants accounts. The problem I am having is that on completion of an express checkout, the facilitator is receiving all the money instead of the merchant. The merchant receives the credit card payment but immediately pays the facilitator the full amount.
Using this guide: https://devtools-paypal.com/guide/expresscheckout/php?interactive=OFF&env=sandbox
I have then created an express checkout on behalf of the merchant account.
Auth details:
'mode' => 'sandbox',
'acct1.UserName' => 'dev-facilitator...',
'acct1.Password' => 'dev-facilitator_pw...',
'acct1.Signature' => 'dev-facilitator...',
'acct1.AppId' => 'APP-80W284485P519543T',
'acct1.accessToken' => $merchant_token,
'acct1.tokenSecret' => $merchant_secret

My code looks very similar to the example, with the assumption that the PaymentDetailsType passed through to DoExpressCheckoutPayment is that same as received from GetExpressCheckoutDetails
Everything appears to be working correctly except that when the users completes the payment the merchants paypal ends up looking like:
Purchase From, dev-facilitator, Completed, Details, -$250 NZD
Transfer From, Credit Card    , Completed, Details, $250 NZD

With the final result being:
Dev-facilitator balance: $250 NZD
Dev-merchant balance:    $0 NZD

I'm not sure where in the express checkout setup I should be specifying the kind of invoice the merchant should file against the facilitator in relation to the express checkout.
I can provide further code snippets if required.

A: It appears the core of my problem is the fact that accessToken and tokenSecret are ignored if acct1.Subject is not also supplied (The email associated with the accessToken).
The second thing that caused confusion is that I was not paying attention to what account my buyer action was being performed against... Logging into my merchant account changed the cookies that I was using in the other tab for doing the express checkout. Thus the merchant account ended up being the buyer, and the facilitator the merchant... The Purchase From, Transfer From, was just the way credit card transactions are shown: IE first the credit card gets converted into paypal money and then that is used in the paypal purchase transaction.
Thus,
'mode' => 'sandbox',
'acct1.UserName' => 'dev-facilitator...',
'acct1.Password' => 'dev-facilitator_pw...',
'acct1.Signature' => 'dev-facilitator...',
'acct1.AppId' => 'APP-80W284485P519543T',
'acct1.Subject' => $merchant_email,
'acct1.accessToken' => $merchant_token,
'acct1.tokenSecret' => $merchant_secret

Is what I should have supplied.


text:
Q: Create S3 Bucket along with AMI installation I'm planning to create a small public AMI for converting text files to PDF (I find nothing satisfying on the Store) and I have an issue.
I understood that AMI is nothing else than a frozen copy of a software that I've run successfully on another machine.
I however have an issue: how do I create a S3 Bucket by the installation of the AMI.
Use case:

*

*A user comes to the store and finds the idea of my service cool and launch an instance.

*The instance needs to create a S3 bucket to save the converted files (and maybe the source file as well) and it has to be one bucket per user and not a big bucket for all the files converted via the software.

I have many questions for that:

*

*Is that possible to achieve that (was it designed like this)?

*How should I create the bucket, is there a point and click interface at AMI setup or I need to do via AWS SDK?

*If I need to it via the SDK, is there a way to access the user credentials (or some random token) so that I can create a bucket successfully?

*Am I wrong, should be all the file saved on EBS and made available via an nginx on the AMI (and not using S3 at all)?

Oh and sorry if this question seems silly but I'm very fresh in this AWS cool tech!
Thanks!

A: You can achieve this using AWS cloudformation.
Steps would be that you first create an AMI and then write a cloudformation script that

*

*Creates an instance from that AMI

*Creates the S3 buckets for the

*Map the newly created EC2 with the S3. (Since S3 buckets names are unique globally you might not get the name you want) .

However note that the services in cloud are not installed for each customer like the traditional on-premise system.
Here you have a concept of tenants. So every new customer would be a tenant and should be served from the same infrastructure. Basically when a new customer comes in you onboard that as a tenant and possibly create a folder within the already created S3 for this tenant where you store its artifacts. Or if for some justified business reason you just want to have a separate S3 bucket for each of the tenant then even that new S3 bucket should be created during tenant onboarding. Store the mapping of the tenant and the S3 folder/bucket somewhere so that you know which tenant's artifacts to store where


text:
Q: Non-forking extensions of types over sets Let $p$ be a type over a set $A$ and suppose that $p$ does not fork over $A$.
In proposition 3.39 of http://www.math.ucla.edu/~chernikov/teaching/StabilityTheory285D/StabilityNotes.pdf the following is stated:
"Since $p$ does not fork over $A$ and the set of all $L(\mathbb{M})$ formulas forking over $A$ is an ideal, there is a global $q$ extending $p$ and non-forking over $A$."
I am a little confused by this. The formulas that do not fork over $A$ do form a filter and I know that types can be associated with various ultra-filters. In fact those ideas are used in proposition 3.23 (of the same  set of notes). However it is based on the assumption that the type $p$ is finitely satisfiable in $A$. But I'm not sure how to modify this proof to fit the current setting (While the notes are building up to theorems about simple theories, this particular statement is for an arbitrary theory.)
Edit 1: I found a proof that can be adapted to this context in Tent and Ziegler's Model Theory text. But if anyone knows how to make this proof I'd like to see that proof.


text:
Q: Subnet of a sequence. Denote by $I$ the interval $[0,1]$. The space $\{0,1\}^I$ can be viewed as the space of all functions
$$f: I \to \{0,1\}.$$
With the product topology (or equivalently, the point to point convergence topology), $\{0,1\}^I$ is known to be compact but not sequentially compact.
An example of a sequence without convergent subsequence is $f_n$, where $f_n(x)$ is the n-th binary digit of $x$ (where the number of ones cannot be finite, to avoid different binary representations).
Now, there is no subsequence $n_k$ such that $f_{n_k}(x)$ converges for all $x$. Just take an $x$ such that its binary expansion has the $n_k$-th digit equals to $0$ when $k$ is even and $1$ otherwise.
But since $\{0,1\}^I$ is compact, $f_n$ is supposed to have a convergent subnet! I would like to see such a subnet. :-)
Can you help me with that?

A: Pick an ultrafilter $F\subset \mathcal P(\mathbb N).$ Let $f$ be the function that sends $r$ to $1$ if and only if $\{n\mid f_n(x)=1\}\in F.$ Note $F$ is a directed set under inclusion.
I will argue that the subnet defined by $f'_{S}=f_{\min(S)}$ for $S\in F$ converges to $f.$ Any basic open set containing $f$ is of the form $U=\{g\mid g(r_i)=f'(r_i)\text{ for all $1\leq i\leq k$}\}.$ The sets $\{n\mid f_n(r_i)=f'(r_i)\}$ are in $F,$ so their intersection $S$ is in $F,$ and any $n\in S$ satisfies $f_n\in U.$ So $f'$ is eventually in $U,$ which is the definition of a limit.


text:
Q: How do Klingon senses compare to human senses? A bit of a random question, but biologically, how do the five human senses' abilities compare to the Klingon's equivalent fives senses (ie touch, taste, smell, hearing and sight)?  Eg Do Klingons (on average) have a more acute sense of smell than humans?

A: In the episode Birthright, Part II, Worf teaches a young Klingon how to hunt, and during the hunt he shows the young Klingon how to track prey by scent.  Since humans are not able to do this (at least for animals on Earth), this would imply that the Klingon sense of smell at least is heightened compared to humans.

A: When I was researching I found one website claiming that they have enhanced sense but I do not see where they got their information from :
http://wiki.starbase118.net/wiki/index.php?title=Klingon

Klingons have enhanced senses. Three of them, acute taste, smell, and
  vision, are genetic, but the third, combat reflexes, is learned from
  childhood, and is therefore second nature to Klingons. They are larger
  than Terrans with a greater percentage of their body weight being
  muscle.

Another quote I found is from :
Klingon for the Galactic Traveler

The usual Federation Standard translations of the primary tastes
  ("pungent," "sour," "salty") are a little deceptive.  From the Klingon
  point of view, it is not accurate to say that a particular food is
  sour; rather, it tastes and smells sour.  That is, sourness is not an
  intrinsic quality of food; it is a perception, the effect the food has
  upon the sense of smell and taste, the Klingon sense of smell being
  particularly highly developed.

I also found that the Alpha Memory (Star Trek Wikia) states that Klingons have a type of sixth sense.  They are able to sense if somebody has an intent to kill.
http://en.memory-alpha.org/wiki/Klingon

Klingons such as Kurn had the instinctive ability to sense the
  decision to kill by looking into the eyes of their opponents. (DS9:
  "Sons of Mogh") Worf did not have this ability, probably due to the
  fact that he was raised by Humans on Earth.

It seems to me if these links and quotes are true, then Klingons would at least have a high sense of taste / smell, though I haven't found any evidence of them having enhanced vision.

A: I suppose it's not cannon, but in Star Trek: Starfleet Command III, there is a conversation between human and Klingon starships about the colors used in a jointly-constructed starbase.  The human complains that Klingons overuse the color brown to which the Klingon replies that human eyes are unnaturally attuned to the blue end of the spectrum.  This would make sense if the Klingon star is cooler than Sol, but the Memory Alpha article for the Qo'noS system lists several different possibilities for the star.  Epsilon Sagittarii is certainly hotter than Sol, but Omega Leonis would fit and likely cause the Klingons to be less able to see blue and able to see near-infrared colors.


text:
Q: Преобразование слов в математическое выражение Мне необходимо перевести строку со словами на русском языке в математическое выражение. Пример "сто двадцать три умножить на 4 делить на 10" ---> "123 * 4 / 10". Как это можно сделать?

A: Взято из поста вот тут: тут. Единственное, тут работа с английским, но суть проблемы одна и та же.
def text2int(textnum, numwords={}):
    if not numwords:
      units = [
        "zero", "one", "two", "three", "four", "five", "six", "seven", "eight",
        "nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen",
    "sixteen", "seventeen", "eighteen", "nineteen",
  ]

      tens = ["", "", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety"]

      scales = ["hundred", "thousand", "million", "billion", "trillion"]

      numwords["and"] = (1, 0)
      for idx, word in enumerate(units):    numwords[word] = (1, idx)
      for idx, word in enumerate(tens):     numwords[word] = (1, idx * 10)
      for idx, word in enumerate(scales):   numwords[word] = (10 ** (idx * 3 or 2), 0)

    current = result = 0
    for word in textnum.split():
        if word not in numwords:
          raise Exception("Illegal word: " + word)

        scale, increment = numwords[word]
        current = current * scale + increment
        if scale > 100:
            result += current
            current = 0

    return result + current
print text2int("seven billion one hundred million thirty one thousand three hundred thirty seven")

#7100031337


text:
Q: Database selection for payroll management I am developing my first android app which is payroll management, but I have no idea about which database should be used for this application. Sqlite or mysql?

A: This depends where you are storing the data. If you store the data on a server you can use SQLite (if it's not much data) or MySQL or another larger database (if you store data for hundreds or more users).
If you store it directly on the device you can only use SQLite (or similar alternatives).

A: If you want the database to be stored in the app (on the device) you must use SQLite. But if you have the database on an external server to which you are connecting, you can use MySql and you can perform queries using JSon.
If you give us more information we can help you better


text:
Q: Stop logo and background color scrolling down using css This is demo site, so I am giving credentials. Without giving credentials it is not possible to get an answer.
Please visit this link: http://2.kidsdial.com/customer/account/login
Login with email: kidsdial2@gmail.com password : kidsdial2
Then click here: http://2.kidsdial.com/marketplace/marketplaceaccount/myproductslist/
Keep on scrolling. You can see
"Logo and its background color" is keep on coming at the middle.
I want to avoid this. I want to keep the logo and in its original position when scrolling down.
I want to keep the logo and its background color at constant position, it should not be visible when we are scrolling.
I am using this css:

A: You can overwrite the rule just by using css.
In your css file you can add position: relative !important; to your #main_header This will overwrite the position fixed of your header

A: If you are using bootstrap then you can use this navbar-fixed-top in your class

# menu-id
{
    margin-top: 100px;
    z-index: 0;
    position: absolute;
}


text:
Q: Timeline plotting: horizontal bars of time intervals This text file logs the time that a process (identified by a number) changes state ("Brown", "Blue" etc.")
2014-08-29 03:59:52 , 27273 , Brown
2014-08-29 03:59:53 , 27276 , Green
2014-08-29 03:59:55 , 27276 , Brown
2014-08-29 03:59:57 , 27303 , Red
2014-08-29 03:59:58 , 27303 , Green
2014-08-29 03:59:59 , 27303 , Brown
2014-08-29 04:00:04 , 27317 , Brown
2014-08-29 04:00:07 , 27331 , Blue
2014-08-29 04:00:07 , 27334 , Blue
2014-08-29 04:00:08 , 27331 , Red
2014-08-29 04:00:08 , 27334 , Cyan

What I try to do is to plot horizontal bars as time intervals, colored according to the third column, where x-axis is time, y-axis is process id number. One of the colors (probably Cyan) should not be displayed, as it marks the interval end.
It is actually a timeline of many parallel events.
DatePlot does not seem to help. Any suggestions?

A: dat = "2014-08-29 03:59:52 27273  Brown
       2014-08-29 03:59:53  27276  Green
       2014-08-29 03:59:55  27276  Brown
       2014-08-29 03:59:57  27303  Red
       2014-08-29 03:59:58  27303  Green
       2014-08-29 03:59:59  27303  Brown
       2014-08-29 04:00:04  27317  Brown
       2014-08-29 04:00:07  27331  Blue
       2014-08-29 04:00:07  27334  Blue
       2014-08-29 04:00:08  27331  Red
       2014-08-29 04:00:08  27334  Cyan";
 inputdata = ImportString[dat];

DateListPlot
ClearAll[dateListBars];
dateListBars[inpdata_, leftpadding_, rightpadding_,
  opts : OptionsPattern[]] :=
 Module[{datasets, dates, firstdate, lastdate,
   labels, colors, gdt, dlPltF, options,
   data = {#3, DateList[#1 <> " " <> #2], ToExpression@#4} & @@@
     inpdata},
  gdt = GatherBy[data, First];
  {labels, colors} = Transpose[{#[[1, 1]], #[[All, 3]]} & /@ gdt];
  datasets = {#[[1, 1]], AbsoluteTime /@ #[[All, 2]], #[[All, 3]]} & /@
     gdt;
  dates = DeleteDuplicates@data[[All, 2]];
  {firstdate, lastdate} = DateList /@ ({leftpadding, rightpadding} +
      Through[{Min, Max}[AbsoluteTime /@ dates]]);
  dlPltF := DateListPlot[Thread[{{firstdate, lastdate}, #2[[1]]}],
     Joined -> True, Mesh -> {#[[2]]},
     MeshShading -> {White, Sequence @@ #[[3]], White},
     BaseStyle -> Directive[Thickness[.075], CapForm["Butt"]],
     Frame -> True, MeshStyle -> Opacity[0]] &;
  options = {PlotRange -> All,
    GridLines -> {AbsoluteTime /@ dates, None},
    Method -> {"GridLinesInFront" -> True},
    FrameTicks -> {{Thread[{Range[Length@datasets], labels}], None},
      {{AbsoluteTime@#, Rotate[DateString[#,
            {"Hour", ":", "Minute", ":", "Second"}], Pi/2]} & /@
        {firstdate, Sequence @@ dates, lastdate}, None}},
    PlotRangePadding -> {{.5, .5}, {.5, .5}}};
  Show[MapIndexed[dlPltF, datasets], Sequence @@ options, opts]]

dateListBars[inputdata, -1, 5, ImageSize -> 600, LabelStyle -> 16] /. Cyan -> White

BarChart
Data preparation:
data = {#3, DateList[#1 <> " " <> #2], ToExpression@#4} & @@@ ImportString[dat];
{labels, colors} =  Transpose[{#[[1, 1]], #[[All, 3]]} & /@ GatherBy[data, First]];
datasets = {#[[1,1]], AbsoluteTime /@ #[[All, 2]], #[[All, 3]]} & /@ GatherBy[data, First];
dates = DeleteDuplicates@data[[All, 2]];
{leftpadding, rightpadding} = {-1, 5};
{firstdate, lastdate} = DateList /@ ({leftpadding, rightpadding} +
                                      Through[{Min, Max}[AbsoluteTime /@ dates]]);
bcheights =
  DateDifference[DateList[#1], DateList[#2], "Second"][[1]] & @@@
     Partition[#, 2,
      1] & /@ (Append[Prepend[#, AbsoluteTime[firstdate]],
       AbsoluteTime[lastdate]] & /@ datasets[[All, 2]] );
bccolors = Prepend[#, White] & /@ colors;
bcdata = Thread[Style[#, #2]] & @@@ Transpose[{bcheights, bccolors}];

Handling date ticks:
bcticks = Union[Flatten[Accumulate@# & /@ bcheights]];
bcticks = Thread[{bcticks, Rotate[DateString[
        DatePlus[firstdate, {#, "Second"}],
        {"Hour", ":", "Minute", ":", "Second"}], Pi/2] & /@
     Union[Flatten[Accumulate@# & /@ bcheights]]}];

and the options
bcoptions = {ChartLayout -> "Stacked", BarOrigin -> Left,
   ChartLabels -> {Placed[labels, Axis], None},
   ChartBaseStyle -> Directive[Opacity[1], EdgeForm[]],
   LabelStyle -> 16,
   Frame -> {{False, True}, {True, True}},
   FrameTicks -> {{None, None}, {bcticks, None}},
   GridLines -> {bcticks[[All, 1]], None},
   Method -> {"GridLinesInFront" -> True}, ImageSize -> 600};

 BarChart[bcdata, bcoptions] /. Cyan -> White

BulletGauge
bgaugedata =
  Transpose[{Accumulate /@ bcheights, Prepend[#, White] & /@ colors,
    labels}];
Panel[Column[
   Reverse[BulletGauge[0, foo, Append[Prepend[#1 + 5, 0], 25],
         ScaleRangeStyle -> Thread[{#2, White}], GaugeMarkers -> None,
         GaugeLabels ->
          Placed[Style[#3, "Subsubsection"], {2, Bottom}],
         ImageSize -> 600, Axes -> False, Frame -> False,
         TicksStyle -> Opacity[0], ReferenceMarkerStyle -> Opacity[0],
         AspectRatio -> 1/10] & @@ # & /@ bgaugedata],
   Spacings -> -2]] /. Cyan -> White

TODO: Date ticks ...

A: dat = "2014-08-29 03:59:52 27273  Brown
  2014-08-29 03:59:53  27276  Green
  2014-08-29 03:59:55  27276  Brown
  2014-08-29 03:59:57  27303  Red
  2014-08-29 03:59:58  27303  Green
  2014-08-29 03:59:59  27303  Brown
  2014-08-29 04:00:04  27317  Brown
  2014-08-29 04:00:07  27331  Blue
  2014-08-29 04:00:07  27334  Blue
  2014-08-29 04:00:08  27331  Red
  2014-08-29 04:00:08  27334  Cyan";
data = {DateList[#1 <> " " <> #2], #3, #4} & @@@ ImportString[dat];
{dates, val, col} = Transpose[data];
dlp = DateListPlot[MapThread[{{#1, #2}, {Last@dates, #2}} &, {Most@dates, Most@val}],
     ImageSize -> 500,
     PlotStyle -> (Thread[{Thickness[0.01],Most@(ToExpression /@ col)}]), PlotLegends ->    (Most@val),
  FrameTicks -> {Automatic, None}]

Note if, as the question suggest, the "values" are labels and the bars are desired to be equally spaced this could be done using MapIndexed rather than MapThread

A: With se.dat being exactly what you provided:
dat = StringSplit[#, ","] & /@ Import["~/se.dat", "List"];
dates = ToExpression /@
          (StringSplit[#, ","] & /@
            (StringReplace[StringTrim@#, {"-" | " " | ":" -> ","}] & /@ First /@ dat))
val = ToExpression[#[[2]]] & /@ dat
col = ToExpression[#[[3]]] & /@ dat
DateListPlot[List /@ Thread@{dates, val}, PlotStyle -> col]


text:
Q: git log from particular sha to head I have a script:
for sha1 in $(git log <BRANCH> --format=format:%H --no-merges)
do
    if [ "$sha1" == "<TRAGET_SHA>" ]
    then
        break
    fi
    echo $sha1
done | tail -r

What it does is from a particular BRANCH lists all no merge sha's (in 'reverse' order) starting from TRAGET_SHA to HEAD.
I spent 30 minutes trying to achieve the same with git command directly with no success.
Is this possible to achieve? How?


text:
Q: Fetch params from controller when nesting attributes 2 levels deep My Pack model has lines, which in turn contain items, and both pack and lines accept nested attributes for the collection they contain.
Here are the models:
Class Pack < ApplicationRecord
   has_many :pack_lines, dependent: :destroy
   accepts_nested_attributes_for :pack_lines, allow_destroy: true
end

Class PackLine < ApplicationRecord
   belongs_to :pack
   has_many :pack_line_items, dependent: :destroy
   accepts_nested_attributes_for :pack_line_items, allow_destroy: true
end

Class PackLineItem < ApplicationRecord
   belongs_to :pack_line
end

It took me a long time finding the right syntax to use to permit the nested nested parameters in my controller.

A: You can permit nested attributes like this.
params.require(:pack).permit(
  :name,
  pack_lines_attributes: [
    :id, :_destroy, pack_line_items_attributes: [
         :id, :_destroy
    ]
  ]
)

They work similarly for has_many and has_one. You might have to singularize in case of has_one like pack_line_attributes [:id]

A: After much head-scratching and docs-reading, here is what I came up with:
# In controllers/packs_controller.rb
def pack_params
   params.require(:pack).permit(
      :name,
      pack_lines_attributes: [
         :id,
         :_destroy,
         {
           pack_line_items_attributes: [
             :id,
             :_destroy
           ]
         }
      ]
   )
end

Hope that helps!


text:
Q: Should I use Datatables backend plugin in MVC framework I'm using an MVC PHP framework and I managed to write all models then I completed all backend staff. Later on on the frontend development to make everything easier and faster I found my self in-need to use Datatables plug-in, but this compels me to send response back in a specific format, so I wrote a plug-in that changes the returned values from models to the format needed in Datatables.
Example 1 - Model with my own plugin:
$this->myModel->setCostRange(50, 93);
$this->myModel->setCustomerId(123);
$results = $this->myModel->search();

// Then I use my plugin this way to change the response format
$results = $this->_buildGrid($results);

That was my solution, although Datatables provide many backend plugins to make queries instead of model, but as I believe this conflicts code separation principle and MVC logic.
Example 2 - no model use:
$g = new \Data\Grid("tableName");
$g->addColumn(
    "name",
    "Name"
 );
 $g->addColumn(
     "userEmail",
     "Email"
 );
 $g->render($_POST);

Any advises!

A: I think yes, you should call your plugin into your controller or where the business logic is written.You are using plugin to convert the data return from the database, you are just adding one layer over to your database model. It will be break the code separation logic of MVC if you write some core queries in Model or write conversion logic into the Model. But, If you think so, you can you use third party Libraries like doctrine or Active Records also, which will just need to be instantiated in your model and separates the login of data extraction layer and conversion logic from the model, there are lots of framework use those libraries to separate the data extraction logic with business logic and converts data from in proper format needed by your framework, on the basis of this you need to make some changes in you presentation layer also. Hope this will help you out :).


text:
Q: Matplotlib: draw a series of radial lines on PolarAxes I'm trying to replicate a certain plot using matplotlib: it should look something like this.

I have seen that it it possible to use the PolarAxes to draw radial points: for istance i've made a really simple polar plot with the following snippet:
import matplotlib.pyplot as plt
fig = plt.figure()
# Set the axes as polar
ax = fig.add_subplot(111, polar=True)
# Draw some points
ax.plot([0],[1], 'o')
ax.plot([3],[1], 'o')
ax.plot([6],[1], 'o')

# Go clockwise
ax.set_theta_direction(-1)
# Start from the top
ax.set_theta_offset(1.570796327)

plt.savefig('test.png')

And i get something like this:

So my question is: is there a way to draw the lines as in the first figure, and to adjust the width in order to fit in the whole circonference? Also some hints on how to handle the colors would be much appreciated.
UPDATE: the data that has to be plotted is quite simple: each track is an array of floats whose range is between 0 and 9 (and the color is derived from the colormap RdYlGn). The array length are multiple of 96.
UPDATE 2: that's the snipped that i have used
# mydata is a simple list of floats
a = np.array([[x for i in range(10)] for x in mydata])

# construct the grid
radius = np.linspace(0.2,0.4,10)
theta = np.linspace(0,2*np.pi,len(a))
R,T  = np.meshgrid(radius,theta)

fig = plt.figure()
ax = fig.add_subplot(111, polar = True)

# plot the values using the appropriate colormap
ax.pcolor(T,R,a,cmap=cm.RdYlGn)

A: Without more information about how your data is organized it is difficult to say what the best way to recreate this plot would be. It is easy to draw lines of different widths and colors on a polar plot. Though if you need as many as in your example, things may get slow. I have also provided an example of a polar pseudo-color plot.
import numpy as np
import matplotlib.pyplot as plt

#Create radius and theta arrays, and a 2d radius/theta array
radius = np.linspace(0.2,0.4,51)
theta = np.linspace(0,2*np.pi,51)
R,T  = np.meshgrid(radius,theta)

#Calculate some values to plot
Zfun = lambda R,T: R**2*np.cos(T)
Z = Zfun(R,T)

#Create figure and polar axis
fig = plt.figure()
ax = fig.add_subplot(111, polar = True)

ax.pcolor(T,R,Z)    #Plot calculated values

#Plot thick red section and label it
theta = np.linspace(0,np.pi/4,21)
ax.plot(theta,[1.23 for t in theta],color='#AA5555',linewidth=10)   #Colors are set by hex codes
ax.text(np.pi/8,1.25,"Text")

ax.set_rmax(1.25)   #Set maximum radius

#Turn off polar labels
ax.axes.get_xaxis().set_visible(False)
ax.axes.get_yaxis().set_visible(False)


text:
Q: Expected cv::UMat for argument 'src' I'm trying to apply the canny function on an image and here's the full code but it shows the error only if i put the steps within a function, but doesn't show when leaving all the code outside of any functions. Code:
import cv2
import numpy as np

def canny(image):
    gray = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY)
    blur = cv2.GaussianBlur(gray, (5,5), 0)
    canny = cv2.Canny(blur, 50, 150) #sick
    return canny

sourceimage = cv2.imread('lane.jpg')
img = np.copy(sourceimage)
canny = canny(img)
cv2.imshow("result", canny)
cv2.waitKey(0)

And here is the error i get: (python 3.6.8)
kream@KRIMZON:~/Desktop/finding-lanes-linux$ python3 lane.py
Traceback (most recent call last):
  File "lane.py", line 12, in <module>
    cannyer = canny(img)
  File "lane.py", line 5, in canny
    gray = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY)
TypeError: Expected cv::UMat for argument 'src'
kream@KRIMZON:~/Desktop/finding-lanes-linux$

A: When I just run the code, it also complains Expected cv::UMat for argument 'src'. Because there is no lane.jpg in my PC, so cv2.imread return NoneType, and np.copy return np.array(None, dtype=object). If you just pass such a variable to cv2, it will complain Expected cv::UMat for argument 'xxx'.

Yes, you should check your image exists and loaded successfully!

And notice, another bad practice is: your variable name canny is the same with your function name canny(). So when you call canny = canny(img), the function canny() object is replaced by variable canny. If you call canny() next time, it will fail like this:TypeError: 'numpy.ndarray' object is not callable.

Then use different names.

>>> src = cv2.imread("noexist.png")
>>> img = np.copy(src)
>>>
>>> type(src)
<class 'NoneType'>
>>> cv2.cvtColor(src, cv2.COLOR_BGR2GRAY)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
cv2.error: OpenCV(4.0.1) d:\build\opencv\opencv-4.0.1\modules\imgproc\src\color.cpp:181: error: (-215:Assertion failed) !_src.empty() in function 'cv::cvtColor'

>>>
>>> img
array(None, dtype=object)
>>> cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: Expected cv::UMat for argument 'src'
>>>
>>> img()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'numpy.ndarray' object is not callable


text:
Q: How to refresh layers and ui elements in google earth engine app? I want to create a Google Earth Engine app. When a user selects something from the dropdown element and clicks on the load button I want it to load that particular layer and its label displayed on map.
The problem I am facing is that when user clicks on Display button again and again, it loads the same layer number of times the button is clicked. Also, I want to hide the other layers that were loaded first when any other element from the list is selected.
This is my code https://code.earthengine.google.com/882a81c42e593ddaa8461e65b98f269c
var srtm = ee.Image("USGS/SRTMGL1_003");
var modis_ndvi = ee.ImageCollection("MODIS/061/MOD13A2").first();
// Select Element
var variables = ['SRTM','MODIS NDVI'];
var Selector = ui.Select({
  items: variables,
  placeholder: 'Select',
  style:{position: 'top-left', width:'150px'}
  })

var button = ui.Button({
  label:'Display',
  style: {margin:'15px 0 0 0'},
})
var panel_selector = ui.Panel({
    widgets: [Selector, button],
    layout: ui.Panel.Layout.Flow('horizontal'),
    style: {position: 'top-right'},
  });
Map.add(panel_selector)

var loadComposite = function() {
  var gv = Selector.getValue();
  if(gv=="SRTM"){
  Map.addLayer(srtm,{min:200, max:4000, palette:['yellow','orange','red']},'SRTM');
  var label_srtm = ui.Label({value:'SRTM 30m'})
  Map.add(label_srtm)
  }
  else if(gv=="MODIS NDVI"){
    Map.addLayer(modis_ndvi,{},'MODIS NDVI');
    var label_modis = ui.Label({value:'MODIS 1NDVI km'})
    Map.add(label_modis)
  }

};

button.onClick(loadComposite);

How to fix it?
I have tried ui.root.clear and but that hides everything

A: Use Map.clear() which will clear all previously loaded layers.


text:
Q: How can I make a "color map" plot in idl? I would like to be able to make a graph as produced by the code shown below (but using logarithmic axes). I have a 2D matrix containing the data and I know the separation positions between one cell and the other (equispaced if viewed in logarithmic scale). The code that I report below simulates what I would like obtain but it use Hist_2D and therefore I do not think it is usable in my case.
An example of my data:
data is a Matrix 9*9
   data [0.000     0.000     0.000     0.000     0.000     0.000     0.000     0.000     0.000
0.429     0.143     0.000     0.000     0.048     0.000     0.000     0.000     0.000
0.857     0.810     0.667     0.429     0.429     0.286     0.190     0.286     0.143
0.952     0.952     0.905     0.857     0.857     0.905     0.857     0.762     0.810
1.000     1.000     0.952     0.952     0.952     0.952     0.952     0.952     1.000
1.000     1.000     1.000     1.000     1.000     1.000     1.000     1.000     1.000
1.000     1.000     1.000     1.000     1.000     1.000     1.000     1.000     1.000
1.000     1.000     1.000     1.000     1.000     1.000     1.000     1.000     1.000
1.000     1.000     1.000     1.000     1.000     1.000     1.000     1.000     1.000]

x e y are two vector of length 10
x [0.189036 0.484322 0.779609 1.07489 1.37018 1.66547 1.96075 2.25604 2.55133]

y [ -1.06208 -0.584192 -0.106299 0.371593 0.849485 1.32738 1.80527 2.28316 2.76105]

code
PRO Plot2
x = cgScaleVector(Randomn(-3L, 100000)*3., -10, 10)
y = cgScaleVector(Randomn(-5L, 100000)*10., 0, 100)

xrange = [Min(x), Max(x)]
yrange = [Min(y), Max(y)]
xbinsize = 0.25
ybinsize = 3.00
cgDisplay
density = Hist_2D(x, y, Min1=xrange[0], Max1=xrange[1], Bin1=xbinsize, Min2=yrange[0], Max2=yrange[1], Bin2=ybinsize)

maxDensity = Ceil(Max(density)/1e2) * 1e2
scaledDensity = BytScl(density, Min=0, Max=maxDensity)

cgLoadCT, 33
TVLCT, cgColor('gray', /Triple), 0
TVLCT, r, g, b, /Get
palette = [ [r], [g], [b] ]

cgImage, scaledDensity, XRange=xrange, YRange=yrange, /Axes, Palette=palette, $
  XTitle='Concentration of X', YTitle='Concentration of Y', $
  Position=[0.125, 0.125, 0.9, 0.8]

thick = (!D.Name EQ 'PS') ? 6 : 2
cgContour, density, LEVELS=maxDensity*[0.25, 0.5, 0.75], /OnImage, $
   C_Colors=['Tan','Tan', 'Brown'], C_Annotation=['Low', 'Avg', 'High'], $
   C_Thick=thick, C_CharThick=thick

cgColorbar, Position=[0.125, 0.875, 0.9, 0.925], Title='Density', $
   Range=[0, maxDensity], NColors=254, Bottom=1, OOB_Low='gray', $
   TLocation='Top'
END ;*****************************************************************

Plot2

END

Thanks for your help!

A: In the code you have posted, Hist_2D computes the density map that is then displayed by cgImage. Since you already have the matrix you want to display (data), you can simply run:
cgImage, data, /axes, /scale, /keep, xrange=[0.04,2.70], yrange=[-1.30,3.00]


text:
Q: Get File Path of a File Being Passed into MyApp Objective-C Mac I'm using -(void)application:(NSApplication *)sender openFiles:(NSArray *)filenames to preform an action when a file with .myfiletype at the end of the file name.
I am also using NSString *fileThing = [NSString stringWithContentsOfFile:@"/Users/baileyseymour/Desktop/myfile.myfiletype"
encoding:NSUTF8StringEncoding error:nil];
to get the contents of a file but with a absolute path.
How can I make it so that I can get the path to the file being opened instead of the absolute path?

A: Are you looking for each filename in the filenames array? Like this:
-(void)application:(NSApplication *)sender openFiles:(NSArray *)filenames {
    for (NSString *filename in filenames) {
        NSString *fileThing = [NSString stringWithContentsOfFile:filename
                                                        encoding:NSUTF8StringEncoding
                                                           error:nil];
    }
}


text:
Q: Android Google Maps compose how to show multiple InfoWindows at same time I would like to display multiple, in this case 2, info windows at the same time.
I am using the Google Maps Compose library.
This is what I have tried so far:
GoogleMap(
    modifier = Modifier.fillMaxSize(),
    cameraPositionState = cameraPositionState,
    uiSettings = uiSettings,
    properties = properties
) {

  val markerState = rememberMarkerState(position = someLocation)
  markerState.showInfoWindow()
  MarkerInfoWindow(
      state = markerState,
      icon = BitMapUtils.bitmapDescriptor(context, R.drawable.ic_own_position),
      content = {
          Text("Test")
      }
  )

  val markerState2 = rememberMarkerState(position = someLocation2)
  markerState2.showInfoWindow()
  MarkerInfoWindow(
      state = markerState2,
      icon = BitMapUtils.bitmapDescriptor(context, R.drawable.ic_own_position),
      content = {
              Text("Test")
      }
  )

}

When I run the app the InfoWindows show and then hide immediately and this keeps on going until the Memory is gone and an OutOfMemory Excpetion is thrown. Also the performance is very bad
I also tried to execute showInfoWindow() in a coroutine. This solves the performance issues but then only one InfoWindow is permanently visible.
Is there a way to show both InfoWindows at the same time?


text:
Q: How can I remove the Featured Image in Woocommerce? I've searched the forums, but I think the code is too old now.  How can I remove the Featured Image in Woocommerce?  Thank you!

A: Try this plugin and then  use a function to show the second image of the  gallery. Otherwise it will show the empty space that the featured image left.
Second option, try this snippet:

function my_post_image_html( $html, $post_id, $post_image_id ) {
if(is_single()) {
return '';
} else

return $html;
}
add_filter( 'post_thumbnail_html', 'my_post_image_html', 10, 3 );

More useful info and options here.


text:
Q: What action triggers onItemSelected in a ListView? I have a ListView of Medications that use a CursorAdapter. My goal is to obtain a reference to the Cursor of the selected item when the user presses the submit button, but I keep getting a null value. Here is my current code:
mSubmitButton.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        Cursor selectedMedication = (Cursor) mMedicationListView.getSelectedItem();
        if(selectedMedication != null)
        {
            MedicationSelectionListener activity = (MedicationSelectionListener) getActivity();
            activity.onMedicationSelected(new Medication(selectedMedication));
        } else{
            Toast.makeText(getActivity(), "Must select a medication.", Toast.LENGTH_SHORT).show();
        }
    }
});

When this executes, selectedMedication is always null. I have implemented a drawable selector.xml file that changes the background color of the item when it is pressed, and that works fine, so I was under the impression that clicking the item was enough.
I have also tried the following, by setting the selected medication variable each time an item is clicked:
mMedicationListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        Cursor c = (Cursor) mMedicationListView.getItemAtPosition(position);
        if(c.moveToFirst())
            mSelectedMedication = new Medication(c);
    }
});

This worked fine, but I felt it preformed a bunch of pointless operations when all I am interested in is the final selected item. Should clicking an item trigger mMedicationListView.onItemSelected()? If not, what action is used to ensure that happens?

A:
so I was under the impression that clicking the item was enough.

Clicks are not selections with a ListView. A selection will occur either when:

*

*you set a selection programmatically, or

*the user uses a five-way navigation option (e.g., D-pad, trackball, arrow keys) and presses up/down on that to move a highlight bar around

all I am interested in is the final selected item

A ListView is a command widget by default. When the user taps on a row in a ListView, your app should go do something, usually getting rid of the ListView along the way.
If, OTOH, the user is choosing something, where the list and choice remain on-screen (e.g., master-detail pattern, choosing a state/province as part of filling in an address), then you should be using a choice mode. That could be a single-choice mode (usually represented with radio buttons down the right edge), multiple-choice mode (usually represented with checkboxes down the right edge), or multiple-choice-modal mode (usually represented by an "activated" state setting a persistent highlight, usually reserved for master-detail sorts of scenarios).
Do not attempt to overload "selection" to mean "choice". It sounds like you are presenting a ListView as part of something larger, where the user is making a choice, so use a choice mode for that.


text:
Q: Java reflection and metaprogramming I've an array of beans and use reflection to retrieve the values within them through their getter methods. All the beans are of the same type, so instead of using reflection for every object, is there any way of generating code(or object) which will have the calls and I can regenerate this object for a different type of bean? I've heard of something like this in Lisp macros, is it possible in Java?

A: You could take a look at JAXP (http://download.oracle.com/javase/tutorial/jaxp/index.html) where you can generate beans from xml definitions. For heavy reflection work I find BeanUtils (http://commons.apache.org/beanutils/) helpful.

A: Generics may help you in reducing code repetition before you compile and release the class.
You can also compile and deploy class at run-time, see How can I compile and deploy a java class at runtime?

A: Yes, You can use Velocity (and other tools) to generate the code.  However unless performance is critical, it 10x simpler to use reflection.


text:
Q: How are declarations in a SML program separated? In SML's grammar

Programs
prog ::=   dec core declaration
           functor fctbind functor declaration
           signature sigbind signature declaration
           empty
           prog1 ⟨;⟩ prog2 sequence

fctbind ::= id1 ( id2 : sig ) ⟨:⟨>⟩ sig⟩ = str ⟨and fctbind⟩    plain
id ( spec ) ⟨:⟨>⟩ sig⟩ = str ⟨and fctbind⟩ opened
sigbind    ::= id = sig ⟨and sigbind⟩ signature

Why
val a = 1
val b = 2;

a
b

has error between a and b, but not between the two val declarations?
$sml < main.sml
Standard ML of New Jersey v110.78 [built: Thu Aug 31 03:45:42 2017]
- val a = 1 : int
val b = 2 : int
= stdIn:4.1-5.2 Error: operator is not a function [tycon mismatch]
  operator: int
  in expression:
    a b

Thanks.

A: In
val a = 1
val b = 2

All you've done is bind two variables, corresponding to the rules
dec ::= val ⟨var⟩(,) valbind, dec ::= dec1 ⟨;⟩ dec2, and at top level,
prog ::= dec.
Then in
a
b

You're actually attempting to apply a to b (exp ::= exp1 exp2    (application)). It might be simpler to see it as the equivalently written
a b

However, a doesn't have a function type, hence the error operator is not a function. It's unclear what you're actually attempting to do with a and b.


text:
Q: transform:translateX vs transition on left property. Which has better performance? CSS I'm making a slide out menu with HTML and CSS3 - especially transitions.
I would like to know what is best practice / best performance to slide a relatively positioned div horizontally. When i click a button it adds a class to my div. Which class is better? (Note I can add all the browser prefixes later and this site only targets modern browsers).
//option 1
.animate{
    -webkit-transition:all ease 0.3s;
    -webkit-transform:translateZ(200px);
}

//option 2
.animate{
    -webkit-transition:all ease 0.3s;
    left:200px;
}

Thanks

A: translateX and translateY is much smoother than left, right, top, bottom and jQuery animate versions.
See this for much deeper details with demo:
http://www.paulirish.com/2012/why-moving-elements-with-translate-is-better-than-posabs-topleft/

A: Transitions via translate performs MUCH better on mobile devices!
Edit:
Here are a live demo. Transitions with translateX and translateY are much smoother than top, bottom, left and right.
jsFiddle Demo for mobile devices


text:
Q: How can I read multiple problems from a file? I have to read a txt file which has the first line to describe the problem. It can be either a or b, then I have some ints and as matrix. My program works for both, but there are files that after the first problem may have another with the same format. I don't know how to do this.
sample of txt:
5 5 A(B) 1
0 3 (start point)´
1 5 6 5 9
5 8 6 3 1
8 6 9 5 3
5 6 9 3 0
2 3 9 3 8

then another problem, or more, with this format
while(!feof(fp)){
  fscanf(fp, "%d %d %c %d", &L, &C, &variante, &pontos);

  mapa=(int **)malloc(L*sizeof(int*));
  for(i=0; i<L; i++){
    mapa[i]=(int*)malloc(C*sizeof(int));
  }
  for(i=0; i<L; i++){
    for(j=0; j<C; j++){
      mapa[i][j]=0;
    }
  }

  if(variante == 'A') {
    fscanf(fp, "%d %d", &Linit, &cinit);
    for(i=0; i<L; i++){
      for(j=0; j<C; j++){
        fscanf(fp, "%d", &mapa[i][j]);
        printf("%d-", mapa[i][j]);
      }

      printf("\n");
    }
    possivel=varianteA(mapa, L, C, Linit, cinit, &custo);
    printf("%d\n",custo);
  }
  if(variante== 'B'){
    line=(int*)malloc(pontos*sizeof(int));
    col=(int*)malloc(pontos*sizeof(int));
    for(k=0; k<pontos; k++){
      line[k]=0;
      col[k]=0;
    }
    for(k=0; k<pontos; k++){
      fscanf(fp, "%d %d", &line[k], &col[k]);
    }
    for(i=0; i<L; i++){
      for(j=0; j<C; j++){
        fscanf(fp, "%d", &mapa[i][j]);
        printf("%d-", mapa[i][j]);
      }
      printf("\n");
    }
      possivel=varianteB(mapa, L, C, &custo, pontos, line, col);
      printf("%d %d\n", possivel, custo);
      free(line);
      free(col);
  }

  for(i=0; i<L; i++){
    int *linha;
    linha=mapa[i];
    free(linha);
  }
  free(mapa);
}
//  free(variante);
  fclose(fp);

now I have this, but it does one more problem that is not in the file. and valgrind gives me an error in: possivel=varianteA(..). It says that address is 0 bytes after block of size 24 alloc'd

A: When tackling this sort of problem (or any programming task, really), it's often beneficial to write some pseudo-code, just in words about what the program needs to do.
Do Problem

*

*Open the file

*While file has remaining content

*

*read a line of text

*

*extract the width from that line

*extract the height from that line

*extract the problem-type "A" or "B" from that line

*IF problem-type is "A"

*extract the ??? last number from the line

*IF problem-type is "B"

*extract the remaining 2+ numbers from the line

*read a line of text

*

*extract the start-point-x from that line

*extract the start-point-y from that line

*read height lines of text from the file

*

*With each line, extract width numbers for array_data

*read a blank line

(EDIT: It looks like I maxed-out the indentation levels, but you get the idea)
So now the problem is broken up into smaller, hopefully more manageable problems.

A: Here is some sample sudo code on how it may be possible to structure your program.  You will have to modify things heavily but you said you just needed to read the second problem.
#define MAX_SIZE (100) //or whatever it is
#define UNIQUE_IDENTIFIER "=" //or whatever it is

FILE * fp = NULL;
int problem_counter = 0;
char * line = malloc(sizeof(char)*MAX_SIZE);

if(!(fp = fopen("problem.txt","r"))){
  do_error_handling();
}

do{
printf("This is the %dth problem", ++problem_counter); //dont need to printf this but you can start counting here.
if(fgets(line,MAX_SIZE,fp) == NULL){
  break;
}
if(strstr(line,UNIQUE_IDENTIFIER){
  //start of problem.  maybe read in all the lines here and build up the problem you have to solve
  read_problem(line); //does special stuff based of the first line read
  solve_problem(); //solve the problem based on the stuff you extracted from reading the problem
}
while(!feof(fp));


text:
Q: How to display a pic that I uploaded to my controller using my directive Well, honestly this is my first attempt of working with pic upload in JS. I am working with an Angular project that needs to upload a pic from user and display it on a page. (Very much like we upload our profile pic on facebook, only difference being, this page will be downloaded as pdf later).
I was disappointed to see ng-model do not work with file type. I  tried many things and finally made a directive that brings file to my controller (got help from here).
Now that I have file in my $scope.myPic variable. How do I go around using this file. How do I display it.
. I tried binding the variable directly {{myPic}}, which didn't work
. I tried using (#id).value(). Storing this in variable and binding, which   didn't work.
There are other couples of thing I tried, but could not help myself out.
Can someone provide the way of binding image that are uploaded by users from their systems into HTML page in Angular.
Any good links are more than appreciated ...
FYI:
My directive fn:
function uploadPicFn($parse) {
    return {
        restrict: 'A',
        link: function(scope, element, attrs) {
            var model = $parse(attrs.picModel);
            var modelSetter = model.assign;

            element.bind('change', function(){
                scope.$apply(function(){
                    modelSetter(scope, element[0].files[0]);
                });
            });
        }
    };
};

my html :

         That's me:{{home.myPic}}

         <input class="pd_txtarea" type="file" pic-model="home.myPic"/>

A: This can be done, for example, with File Reader.
You've mentioned that you got help from here. So I updated jsfiddle from that article with very basic code example of how FileReader can be used. Take a look - jsfiddle
        link: function(scope, element, attrs) {
          var model = $parse(attrs.fileModel);
          var modelSetter = model.assign;
          var img = element.parent().children()[2];
          var reader = new FileReader();
          reader.onload = function (e) {
            angular.element(img).attr('src', e.target.result);
          }

          element.bind('change', function(){
            scope.$apply(function(){
                modelSetter(scope, element[0].files[0]);
            });
            reader.readAsDataURL(element[0].files[0]);
        });
    }


text:
Q: How can we add dynamic data into our SMS messages that is send via the API We want to send SMS messages via the API (/sms/v1/messageContact/XXXXXX/send). The SMS messages contain dynamic data like timestamps. So for example we have the following message:
'We will arrive between TIME1 and TIME2'
TIME1 and TIME2 are variables. How can we achieve this with the API? Is something like this possible? (beneath is just an example what to achieve):
{
    "mobileNumbers": [
    "31612345678"
    ],
    "Subscribe": true,
    "Resubscribe": true,
    "keyword": "TRANSACTIONAL",
    "Override": true,
    "time1": "9/20/2021 14:00:00",
     "time2": "10/21/2021 16:00:00",
    "messageText": "We will arrive between %%=v(@time1)=%% and %%=v(@time2)=%%"

}


text:
Q: How to group all commits in a row of the same author? Consider a repository with a large amount of commits (more than 20 thousand) in a single branch without any merges (a straight chain of commits). I'd like to squash all commits of the same author in a row in a single commit, for all authors, creating a new shorter story. Example:

*

*commit 09 - Author BBBB

*commit 08 - Author BBBB

*commit 07 - Author AAAA

*commit 06 - Author AAAA

*commit 05 - Author AAAA

*commit 04 - Author CCCC

*commit 03 - Author CCCC

*commit 02 - Author AAAA

*commit 01 - Author BBBB

It'd ended up like:

*

*commit 05 - Author BBBB

*commit 04 - Author AAAA

*commit 03 - Author CCCC

*commit 02 - Author AAAA

*commit 01 - Author BBBB

How to script it with git?

A: Based on this answer https://stackoverflow.com/a/46403701/926064, I ended up with this one. It really worked like a charm:
$ GIT_EDITOR='cat' \
GIT_SEQUENCE_EDITOR='todofile=$1; awk '"'"'{if ($1 != "#" && $1 != "") { author=$3; if (lastauthor != author) { lastauthor=author; printf "pick %s %s\n", $2, $3 } else { printf "squash %s %s\n", $2, $3 }}}'"'"' $todofile>$todofile.temp; mv -f $todofile.temp $todofile; cat $todofile' \
git -c "rebase.instructionFormat=%ae" rebase -i $(git log --oneline --reverse --pretty=format:%H  | head -n1)

Notes:
The first one, GIT_EDITOR ensures that the squash commit message would be preserved like the default git squash messages, don't touching them - they will be concatenated messages.
The second one, GIT_SEQUENCE_EDITOR will do the desired work, the filter, saying which commit will be squashed based on the author. But it depends of the author's email, so when we call git rebase we must format the "rebase instructions" asking git to put the author's email on the list.
The third and last one is the git rebase, but we have to format the "rebase instruction" to put on them every information we will need when processing (editing) the rebase instructions list.
Just for convenience below is the formatted awk script inlined in GIT_SEQUENCE_EDITOR variable:
{
    if ($1 != "#" && $1 != "") {
        author=$3;
        if (lastauthor != author) {
            lastauthor=author;
            printf "pick %s %s\n", $2, $3
        } else {
            printf "squash %s %s\n", $2, $3
        }
    }
}

A: There is no built in way to do this.
As nologin effectively noted in a comment, if you achieve the desired set of commits, you have a new history, incompatible with the original history.  If that's OK, there is a process—not built in, but not extremely difficult—by which you can achieve the desired set of commits.  First, though, be sure about what you want.
Edit: the rest of this applies only to the question as originally phrased.  The caveat below does not apply to the updated question, which now says that the commits are in fact linear.  See Luciano's answer for a nice way to use git rebase -i with a few simple tools to achieve the desired result.
ou describe commits as linear, and they might actually be linear, but they might not.  They will be linear in some areas.  But commits form a Directed Acyclic Graph or DAG.  This graph is the history in the repository.  In those parts where it is linear, it's pretty simple:
... <-F <-G <-H   <-- master

Here, the branch name master identifies, or points to, commit H.  More precisely, the name master stores the hash ID of commit H.  Commit H, meanwhile, stores the hash ID of H's parent commit G, which stores the hash ID of its parent F, and so on.  By starting at the end and working backwards, git log shows you these commits, and that is the history.
Some commits, however, are merge commits.  Such a commit has two (or more, but usually just two) parents.  We can draw them this way:
       I--J
      /    \
...--H      M   <-- dev
      \    /
       K--L

Here the branch name dev points to commit M, but M points back to both J and L.  J points back to I; L points back to K; and I and K both point back to the commit from which the two sub-branches within the branch formed, namely commit H (to which the name master presumably points: commits H and earlier are on both master and dev).
If commits I, L, and M are all made by author BBBB, but J and K are by author AAAA, what do you intend to do here?  If you keep M (by BBBB), and keep J because it's by a different author AAAA, you must also keep L even though it's by BBBB.  However, if all of I-J and K-L and M are by AAAA, you might choose to collapse them all into a single commit whose parent is H:
...--H--M'  <-- dev

So it's your job to figure out which commits you want to keep, and what you want to do about merge commits.  You must keep merge commits if you need to keep the structure (the fork-and-merge at H and M).  If you want to eliminate the branch-and-merge structure, you must discard merge commits, but then you must figure out what to do with oddball commits like I and L if they're by some other author.
Whatever you decide, when you're finally done, the way to achieve the result you want is:

*

*Start with a list of all commits (by hash ID) that you wish to retain and/or all commits that you wish to discard.  (Either suffices, since we'll assume that you're going to hold the universe of All Commits steady while you do this—i.e., not add new commits to the repository while you're computing these lists and making changes to the repository.)

*Then run git filter-branch.  Choose at least the --commit-filter.  You may want additional filters, depending on what other history-data you're intent on discarding here.  (For instance, each commit has a log message: do you want to combine all the log messages, or throw away the ones from commits whose snapshot you're throwing away?  That is what you're doing: you're producing a fictional history.  You can make up as much of it as you like, keeping only whatever you like from the original history, discarding the rest.  What you keep and what you discard is up to you.  Your new repository is incompatible with the old repositories: changing even a single bit anywhere in history renders the remaining history invalid and incompatible.  So you might as well go as far as you like: it's really all-or-nothing!)
In your commit filter—read the git filter-branch documentation for details—use skip_commit to skip the commits you don't want and git commit-tree "$@" to make the commits that you wish to keep.  To decide, just see if $GIT_COMMIT is in the keep or discard list.
The filter-branch command will take care of enumerating each commit, one at a time, in the correct order so that you can emit or exclude the commit from the history you're creating as you go.  After it's invoked your commit filter on each such commit, it will write the hash ID of the last copied commit into the hash name.  The original history is now effectively gone (but still findable via the refs/original/refs/head/branch name; this name won't be in any new clones, and you can discard it when you're ready; again, see the documentation).


text:
Q: Installing pip on Mac OSX password issue I am learning Python and trying to install PIP. However, I keep reaching a password issue in the terminal. There seems to be a key symbol and does not allow me to type in my computer password. I'd appreciate any help.
The python password issue

A: In a terminal when inputting your password it does not echo. Double check your typing as well.
If you really cannot get sudo to work, then boot the system into single user mode (COMMAND+S) and repeat your command.


text:
Q: c_str() vs std::string - what's the real difference in this piece of small code? Why does the code below print "NO"?
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

void main()
{
    const std::string abc = "hello";

    if (abc.c_str() == "hello")
    {
        cout << "\nYES";
    }
    else
    {
        cout << "NO";
    }
}

The .c_str() returns const char* whereas "hello" should be interpreted as either const char* or std::string, both are valid. But why doesn't it print "YES". strcmp() does print "YES", when used instead. But my question is on the code above, is this a compiler bug?

A:
"hello" should be interpreted as either const char* or std::string both are valid.

No. "hello"  is never interpreted as std::string. It has the type const char[6], which in this case is converted to const char*. This conversion for arrays is called decaying.

But why doesn't it print YES.

When you compare two pointers, you compare whether they point to the same object. The pointers that you use compare unequal because the string literal, and the buffer of the std::string are not the same object.

is this a compiler bug?

No. It is a bug in your code.

so what would you suggest as the right approach with using c_str() and std::string?

The correct way is to compare the content of null terminated character arrays is std::strcmp.
Alternatively, you could use the comparison operator with the std::string directly, without using the pointer returned by c_str. The comparison operator of std::string compares with the content of a null terminated string.

A: It's not a compiler bug. abc.c_str() is giving you the value of a pointer to the std::string data buffer and since C++11, it's impossible for that to be the same address as the address of the literal "hello" as that standard forbids copy-on-write semantics for std::string. (I believe this was theoretically possible in C++03 and earlier, out of interest.)
If you want to compare a literal with a std::string, use
if (abc == "hello")
as std::string has an appropriate overload for the == operator.

A: abc.c_str() is a pointer to the internal buffer of the abc object, you're then doing a pointer comparison with the string literal "hello" which returns false.

A: You are comparing the wrong way, try:
Instead of:
if (abc.c_str() == "hello")

use:
if (!strcmp(abc.c_str(), "hello"))


text:
Q: Android private styles using Trying to inherit Widget.TextView.ListSeparator style, but now aapt doesn´t allow to do this:

No resource found that matches the given name
  'Widget.TextView.ListSeparator

because google made it private. But how can I combine two styles : ListSeparator and margins?
Style 1
<style name="settings_plain_text">
<item name="android:layout_marginTop"> 10sp </item>
<item name="android:layout_marginBottom"> 10sp </item>
<item name="android:textSize"> 18sp </item>

Style 2
style="?android:attr/listSeparatorTextViewStyle"

A: I copy the answer from this link:

Hello all. I did some investigating with the frameworks team who's in charge of aapt.
  What is happening is that some styles, like WindowTitle are not public (you won't find them in android.R.style). You should not be extending non public resources. aapt used to let you do that but it was a bug which was fixed in platform-tools r6.
The issue is that once compiled, resources are assigned an integer. In this case your custom style is assigned an integer and its parent is referenced through the parent integer.
For the framework, only public resources are guaranteed to only have the same integer, build after build. The integer of private resources integer will change from build to build.
This means that your custom style is referencing a parent that will not be valid once installed on a device. It'll referenced either another resources or none at all, and it won't do what you want.
If you wish to reuse a style that is private, you should copy the content of that style into your own instead of extending it.

The style I have found googling is that one:
<style name="Widget.TextView.ListSeparator">
    <item name="android:background">@android:drawable/dark_header_dither</item>
    <item name="android:layout_width">match_parent</item>
    <item name="android:layout_height">wrap_content</item>
    <item name="android:textStyle">bold</item>
    <item name="android:textColor">?textColorSecondary</item>
    <item name="android:textSize">14sp</item>
    <item name="android:gravity">center_vertical</item>
    <item name="android:paddingStart">8dip</item>
</style>

From that you can modify margins.


text:
Q: List as value from map cannot be parsed by reduceByKey in Spark I am quite new to coding on Spark using python
My map input is a key-value pair and output is a key-value pair with value as a list of floats.
In the reducer, I want to add the corresponding values in lists for matching keys. Something like this:
    map(lambda <some_pair>: (<some_key>,<list_of_floats>)).reduceByKey(lambda list1,list2: [list1[0]+list2[0],list1[1]+list2[1],list1[2]+list2[2]]).collect()

However, when I do this, I get the error:
    TypeError: 'float' object has no attribute '__getitem__'

Any ideas how to solve this?


text:
Q: VSCode: How to prevent editor expansion while double checking on upper tab When using split screen in vscode, double clicking on the superior tab kinda expands the current editor.
I find that a little annoying sometimes, my mouse double clicks more often than I'd like it to...I know I should probably get a new mouse but come on...Is there a way to disable this feature?
I've already tried all kinds of settings and still couldn't find a way


text:
Q: How to upload files logged in as a user to the app creator's drive? Hi all App Maker Gurus,
I am trying to create an app using Google App Maker that when published, allows a user to upload files to the app creator's google drive. For example, User A creates this app and shares it with User B, giving User B permission to use the app. User B uploads a file via Google Drive picker, and the file is saved onto User A's Google Drive. Does Google App Maker have the ability to configure a "centralized" drive where users with access to the app can all upload files there?
Thank you.


text:
Q: Could not calculate build plan: Plugin org.apache.maven.plugins:maven-jar-plugin:2.3.2 or one of its dependencies could not be resolved I got the following error message when I tried to create a Maven project in eclipse. Many have posted about proxies in settings.xml file and also flush the .m2 folder forcing it to download a new one. None of this is working for me. I'm at work, with proxy settings active in the internet options.
The error message:
Could not calculate build plan: Plugin org.apache.maven.plugins:maven-resources-plugin:2.5 or one of its dependencies could not be resolved:
Failed to read artifact descriptor for org.apache.maven.plugins:maven-resources-plugin:jar:2.5
Plugin org.apache.maven.plugins:maven-resources-plugin:2.5 or one of its dependencies could not be resolved:
Failed to read artifact descriptor for org.apache.maven.plugins:maven-resources-plugin:jar:2.5

POM.XML:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.blahhhhhhhhhhhhhhhhh</groupId>
  <artifactId>HelloRESTEasy</artifactId>
  <version>0.0.1-SNAPSHOT</version>
</project>

settings.xml:
  <proxies>
    <proxy>
      <id>optional</id>
      <active>true</active>
      <protocol>http</protocol>
      <username>proxyuser</username>
      <password>proxypass</password>
      <host>proxyserver.company.com</host>
      <port>8080</port>
      <nonProxyHosts>local.net|some.host.com</nonProxyHosts>
    </proxy>
  </proxies>

A: I solved it now. However it only is solved in Netbeans. Not sure why eclipse still won't take the settings.xml that is changed. The solution is however to remove/comment the User/Password param in settings.xml
Before:
<proxies>
    <proxy>
      <id>optional</id>
      <active>true</active>
      <protocol>http</protocol>
      <username>proxyuser</username>
      <password>proxypass</password>
      <host>proxyserver.company.com</host>
      <port>8080</port>
      <nonProxyHosts>local.net|some.host.com</nonProxyHosts>
    </proxy>
  </proxies>

After:
<proxies>
    <proxy>
      <id>optional</id>
      <active>true</active>
      <protocol>http</protocol>
      <host>proxyserver.company.com</host>
      <port>8080</port>
      <nonProxyHosts>local.net|some.host.com</nonProxyHosts>
    </proxy>
  </proxies>

A: Mainly this occurs during Eclipse upgrade.
I Solved using:
-> Right Click Project-> Maven->Update Project-> Select all (checkbox)
Old or out-dated, projects got refreshed with the updated jar files, and the required plugins. No more errors were visible.

A: For me, this problem occurs in Eclipse when the Maven installation is not well configured. By default the Maven installation is embedded in Eclipse. The .settings.xml file is set wherever the Eclipse installation points.
In my case this file was not auto-generated. I choose my own Maven installation - an external one. But if you don't explicitly choose where settings.xml is then Eclipse tries to get this file from the path set in the embedded installation. If the file is not autogenerated you have to choose the correct location.
Go to windows/preferences/Maven/Installation/user settings and choose the correct location of your settings.xml.

A: I also faced the above error. I used Eclipse.
After followed the below solution, it works fine for me.
Solution is,

*

*Right click project "pom.xml" in eclipse and select Maven Install.

*Right click on the project -> Maven -> Update Project.

*Refresh

A: Try cleaning the local .m2/repository/ folder manually using rm -rf and then re build the project. Worked for me after trying every possible other alternative(reinstalling eclipse, pointing to the correct maven version in eclipse, proxy settings etc)

A: Right click project "pom.xml" in eclipse and select Maven Install.
Right click on the Project -> Maven -> Update Project.
Then Refresh.

A: I have had this issue and I resolved it by following the next step:
1- Close Eclipse.
2- Go to user directory and delete the .m2 directory.
3- Open Elipse.
4- Right click on the project -> Run as -> maven install

A: I have had this issue, and removing the .m2/repository/ has not solved it in my case. Seems that eclipse is unable to download the maven-plugin or dependency needed. Therefore you need to install it yourself.
I have finally solved it downloading both jar and pom files from the Maven Repository and installing it using the command (better than copying to the folder directly):
mvn install:install-file -Dfile=<path-to-file> -DpomFile=<path-to-pomfile>
(In my case: mvn install:install-file -Dfile=maven-war-plugin-2.2.pom -DpomFile=maven-war-plugin-2.2.pom)

A: In my case the error was: CoreException: Could not calculate build plan: Plugin org.apache.maven.plugins:maven-compiler-plugin:2.3.2 ....
With eclipse luna from console in the pom.xml folder
mvn clean
mvn install

With Juno I had to had this to my pom.xml
  <build>
    <pluginManagement>
      <plugins>
        <plugin>
          <groupId>org.apache.maven.plugins</groupId>
          <artifactId>maven-compiler-plugin</artifactId>
          <version>2.3.2</version>
          <configuration>
            <!-- put your configurations here -->
          </configuration>
        </plugin>
      </plugins>
    </pluginManagement>
  </build>

And then
mvn install

And then from eclipse right click>maven>update project
* Once the plugin is donwloaded you can remove the plugin from your pom.xml

A: Jotting down some steps which help:
Writing answer from eclipse perspective as base logic will remain the same whether done by Intellij or command line

*

*Rt click your project -> Maven -> Update project -> Select Force update -> Click OK

*Under properties tag , add :

>  <maven.compiler.source>1.8</maven.compiler.source>
> <maven.compiler.target>1.8</maven.compiler.target>

*In some instance , you will start seeing error as we tried force update , saying , failure to transfer X dependency from Y path , resolutions will not be reattempted , bla bla bla
  **In such case quickly fix it by cd to .m2/repository folder and run following command :

for /r %i in (*.lastUpdated) do del %i**

A: I was able to solve the same problem with different solution.
The solution that worked for me was to Right click project "pom.xml" in eclipse and select "Maven Install".

A: I also had the same problem. I used next way:
1.Added settings.xml file (~/.m2/settings.xml) with next content
<proxies>
   <proxy>
      <active>true</active>
      <protocol>http</protocol>
      <host>qq-proxya</host>
      <port>8080</port>
      <username>user</username>
      <password>passw</password>
      <nonProxyHosts>www.google.com|*.example.com</nonProxyHosts>
    </proxy>
  </proxies>

3. Using cmd go to folder with my project and wrote mvn clean and after that mvn install !

*After that updated project in the Eclipse(Alt + F5) or right click on project -> Maven -> Update project

P.S. after that, when I add new dependency to my project I have to compile project using cmd(mvn compile). Because if I do it using eclipse plugin, I get error connecting with proxy connection.

A: I had this error, I follwed below three steps to solve,
1). check proxy settings in settings.xml refer,
2). .m2 diretory to release cached files causing problems
3) Point your eclipse to correct JDK installation.
Refer No compiler is provided in this environment. Perhaps you are running on a JRE rather than a JDK? to know how

A: I also faced same problem... I follow the following steps...u can try it
1. Right click on maven project
2. Take cursor in Maven
3. Click on Update Maven project or (alt+F5).
it will take some time then most probably problem will solved..

A: There could be multiple reasons, i fixed with following steps:

*

*delete .m2 folder and re launch eclipse. (Find m2 folder in
windows: c:\Users\Your_User_Name\ .m2
or  to search in Mac : ~/.m2

*make sure settings.xml is configured as #JustinBieber mentioned.

*provide settings.xml path in eclipse (windows->preferences->maven->user settings) User Settings must locate settings.xml file.

save changes and relaunch the eclipse..!! it should work.

A: Excellent i got solution:
Just clearing (.m2) complete folder and starting a new maven project problem solved for me.
Note:: .m2 folder located in os installed disk only.
If you want the exact location, check in Eclipse:
Eclipse-->window-->preferences-->maven-->user settings
There local repository path is for .m2
Delete entire .m2 folder and restart your eclipse.

A: I had same issue while creating new spring project in eclipse using Maven.

The main reason for this issue is that the proxy settings was not there.

I used the following approach to reslove it:
1) create settings.xml with  the below content
    <settings xmlns="http://maven.apache.org/SETTINGS/1.0.0"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xsi:schemaLocation="http://maven.apache.org/SETTINGS/1.0.0
                          https://maven.apache.org/xsd/settings-1.0.0.xsd">
      <localRepository/>
      <interactiveMode/>
      <usePluginRegistry/>
      <offline/>
      <pluginGroups/>
      <servers/>
      <mirrors/>
      <proxies>
        <proxy>
            <active>true</active>
            <protocol>http</protocol>
            <host>Your proxy</host>
            <port>Your port</port>
        </proxy>
      </proxies>
      <profiles/>
      <activeProfiles/>
    </settings>
2) Save the settings.xml file under local C:\Users\<<your user account>>\.m2
3) Then Right click project pom.XML in eclipse and select "Update Project". It always give precedence to settings.XML

A: I have summarised what I did for my issue.
1) Delete .m2 folder.
2) Change the apache-maven-3.5.4\conf\settings.xml as follow
<proxies>
<proxy>
  <id>optional</id>
  <active>true</active>
  <protocol>http</protocol>
  <host>proxyserver.company.com</host> --> Please change it according to your proxy
  <port>8080</port> -->Please change it accordingly
  <nonProxyHosts>local.net|some.host.com</nonProxyHosts>
</proxy>

3) Try again in cmd. It will work.
4) For eclipse, delete the existing maven project and go to
window ->prefernces -> maven -> user settings -> browse -> configure this path apache-maven-3.5.4\conf\settings.xml

5) Delete .m2 folder.
6) Restart the eclipse and try creating new maven project.
These steps worked for me.

A: Maybe your network is slow, so that jar isn't downloaded completely.
There are two methods:
a. find your .m2 folder, you can find some path like this 'org/apache/maven/plugins/maven-resources-plugin', you need only delete this foldler 'maven-resources-plugin', because others are downloaded well.
Then maven build your project.
If other problem occures, repeat this process again.
b. you can change a more quick maven source.
Firstly, you should find maven's settings file(window ->prefernces -> maven -> user settings). If it is empty, you can create a new one (any path, for example, .m2/settings).
Secondly, add sth like this (From https://blog.csdn.net/liangyihuai/article/details/57406870). This example uses aliyun's maven.
<settings xmlns="http://maven.apache.org/SETTINGS/1.0.0"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xsi:schemaLocation="http://maven.apache.org/SETTINGS/1.0.0
                          https://maven.apache.org/xsd/settings-1.0.0.xsd">

      <mirrors>
        <mirror>
            <id>alimaven</id>
            <name>aliyun maven</name>
            <url>http://maven.aliyun.com/nexus/content/groups/public/</url>
            <mirrorOf>central</mirrorOf>
        </mirror>
      </mirrors>
</settings>

Thirdly, maven build again. (before this, you should delete your .m2 folder's files)

A: Force update works for me.
Select the force update option as per image in update maven project.

A: run:
mvn -U dependency:go-offline

It works for me.


text:
Q: Javascript library for code syntax highlighting I came across Syntax highlighting code with Javascript, which explains very well how to do syntax highlighting on the client side.
Right now, I'm scraping sites and would like to do the syntax highlighting on the server side, as I'm scraping. We're using node.js cheerio to get some of the basic jQuery features as we're scraping. Is there a simple javascript library that works with cheerio (not a full-fledged jQuery) that lets me do something along the lines of:
var highlightedCode = JsCodeSyntaxHighlighter.highlightCode(...);

where ... is raw HTML.
Or, can I accomplish that with prettify or jQuery syntax highlighter (i.e. does jQuery syntax highlighter only rely on functionality that cheerio provides?).
The reason I need to do this server-side and not client-side is because we load thousands of code divs on the client at once (mostly hidden, but still), and running jQuery syntax highlighter on thousands of  snippets takes a few seconds, which is too slow.

A: Don't know if this is what you want, but on my blog I use Alex Gorbatchev's Syntax Highlight which is pretty awesome. It's javascript, but I use it as a client side script. I've never used server side JS (read NodeJS) and I don't know how compatible they can be, but you should give it a shot and see if you like it.
Hope I can help!

A: you can use prettier.
requirements
const chreerio=require("cheerio"),
prettier=require("prettier")
$=cheerio.load(`

Apple

Orange

Pear

`)

var response = prettier.format($.root(), {  parser: "html" });
console.log(response);

Additionally In production, formatting code on the server side is a bad idea.
This will increase the content size and will take more internet to load the page.
And also Why do you need to format the code?

A: There are many libraries to do this like rainbowjs, highlightjs, prismjs, etc. All of these provide custom spans and default spans for popular languages.


text:
Q: Can MFMailComposeViewController attach an XML doc to an HTML message? I am creating an email in MFMaiilComposeViewController and if I simply create some html snippets and assign them to the message body - all is well. The resulting email (in GMail and Yahoo) looks like the original HTML I sent.
 [mailMan_ setMessageBody:body isHTML:YES];

On the other hand, if I also include an XML attachment, my email reader renders everything as plain text … including, the XML inlined. IE: my mail client (GMail, Yahoo) shows the raw HTHML and XML tags - including html tags that I didn't supply - ie: the html, head, body tags the iPhone provides around the content:
 NSData *opmlData = [[NSData alloc] initWithData:[opml dataUsingEncoding:NSUTF8StringEncoding]];
 NSString *fileName = [NSString stringWithFormat:@"%f.opml", [NSDate timeIntervalSinceReferenceDate]];
 [mailMan_ addAttachmentData:opmlData mimeType:@"text/xml" fileName:fileName];

I pop3'd the mails to see what was happening and found that WITHOUT an attachment, the resulting html section of the email contains this block:
--0-1682099714-1273329398=:59784
Content-Type: text/html; charset=us-ascii

<h2 style="b

while on the other hand, WITH the XML attachment, the iPhone is sending this:
--0-881105825-1273328091=:50337
Content-Type: text/plain; charset=us-ascii

<h2 style="bac

Notice the difference? Look at the Content-Type … text/html vs text/plain. It looks like when I include an XML attachment, the iPhone is errantly tagging the HTML version of the body as plain text! Just to clarify, technically, both with and without the attachment, the iPhone also includes this:
--0-881105825-1273328091=:50337
Content-Type: text/plain; charset=us-ascii

Notebook
Carpentry
Bathroom floor tile
Bathroom wall tile
Scrape thinset

But this obviously isn't where the problem lies.
Am I doing something wrong? What must I do to actually "attach" XML without the iPhone labeling the entire HTML body as plain text. I tried reversing the assignments (attachment first and then body) but no luck.
For what it's worth, the email looks perfect from the iPhone's sending interface. Indeed, the HTML renders correctly and the attachment looks like a little icon at the bottom of the message. This problem has more to do with what the iPhone is actually sending.

A: Turns out - this problem is specific to Yahoo.
On the iPhone, if I change my provider to my Gmail account instead of my Yahoo account, the resulting email has more sections, is much more specific and renders correctly.
Moral of the story - be careful sending attachments from your iPhone via different providers.


text:
Q: Deploy Microsoft.ACE.OLEDB.12.0 provider with WPF package I have WPF application which I use Access Database engine 12.0 to read excel file.
In order to work this application correctly this database engine needs to be installed in the user machines. I want to install that if user hasn't install that in their machine.
How Can I achieve that with the click once deployment.

A: Have you tried using WiX Toolset? (http://wixtoolset.org/)
You can accomplish what you're trying to do in a very simple way, and it's really easy to use.


text:
Q: API Returns OK in API but no Data I'm trying to return an object in a model through another API I've made but when I fetch my API with GET on PostMan it only returns 200 OK but an empty array.
This is what I'm trying to get:
[
  {
    "productId": 0,
    "quantity": 0
  }
]

And this is what I'm getting in PostMan
[]

by calling with this API URL:
http://localhost:5700/api/Orders/basket/firstId

Here is my controller and the respective GET method on which I'm calling upon in Postman:
[HttpGet("basket/{identifier}")]
public async Task<IEnumerable<BasketEntryDto>> FetchBasketEntries(string identifier)
{
    var httpRequestMessage = new HttpRequestMessage(
       HttpMethod.Get,
       $"https://localhost:5500/api/Basket/{identifier}")
    {
        Headers = { { HeaderNames.Accept, "application/json" }, }
    };

    var httpClient = httpClientFactory.CreateClient();

    using var httpResponseMessage =
        await httpClient.SendAsync(httpRequestMessage);

    var basketEntires = Enumerable.Empty<BasketEntryDto>();

    if (!httpResponseMessage.IsSuccessStatusCode)
        return basketEntires;

    using var contentStream =
        await httpResponseMessage.Content.ReadAsStreamAsync();

    var options = new JsonSerializerOptions { PropertyNameCaseInsensitive = true };

    var basketDTO = await JsonSerializer.DeserializeAsync
            <BasketDto>(contentStream, options);

    //basketDTO = new NewBasketDTO.ItemDTO
    //{
    //    ProductId = basketDTO.ProductId,
    //    Quantity = basketDTO.Quantity
    //};

    basketEntires = basketDTO.Entries.Select(x =>
        new BasketEntryDto
        {
            ProductId = x.ProductId,
            Quantity = x.Quantity
        }
    );

    return basketEntires; // 200 OK
}

Here is my BasketDTO:
public class BasketDto
{
    public string Identifier { get; set; }
    public IEnumerable<BasketEntryDto> Entries { get; set; } = new List<BasketEntryDto>();
}

and my BasketEntryDto:
public class BasketEntryDto
{
    public int ProductId { get; set; }
    public int Quantity { get; set; }
}

and this is the original API in JSON:
{
    "identifier": "mrPostMan",
    "items": [
        {
            "productId": 1,
            "quantity": 1
        }
    ]
}

in which I want to get the items array and its object.
Is there something I'm doing wrong? Why is it returning an empty array? Thanks in advance for any help..

A: As I mentioned in the comments, you need to change the Entries property in BasketDTO to Items to match with the JSON property name.
public class BasketDto
{
    public string Identifier { get; set; }
    public IEnumerable<BasketEntryDto> Items { get; set; } = new List<BasketEntryDto>();
}

Alternatively, you could also explicitly mention the JSON Property name by using JsonPropertyNameAttribute
public class BasketDto
{
    public string Identifier { get; set; }

    [JsonPropertyName("items")]
    public IEnumerable<BasketEntryDto> Entries { get; set; } = new List<BasketEntryDto>();
}

A: Well this will work when there are more than 0 items (basket is not empty) but not when the basket is empty as:
basketEntires = basketDTO.Entries.Select(x =>
        new BasketEntryDto
        {
            ProductId = x.ProductId,
            Quantity = x.Quantity
        }
    );

there are no items, select will not work. so you can do like this:
if(basketEntires.Count == 0)
{
     basketEntires = new BasketEntryDto
         {
              ProductId = 0,
              Quantity  = 0
         }
}

return basketEntires; // 200 OK

And don't forget to add .ToList():
basketEntires = basketDTO.Entries.Select(x =>
    new BasketEntryDto
    {
        ProductId = x.ProductId,
        Quantity = x.Quantity
    }
).ToList();

You should not return IEnumerable, instead you should return list (or array).