text:
Q: History of uninformative prior theory I am writing a short theoretical essay for a Bayesian Statistics course (in an Economics M.Sc.) on uninformative priors and I am trying to understand which are the steps in the development of this theory.
By now, my timeline is made three main steps: Laplace's indifference principle (1812), Non-Invariant priors (Jeffreys (1946)), Bernardo reference prior (1979).
From my literature review, I've understood that indifference principle (Laplace) was the first tool used to represent lack of prior information but the missing requirement of invariance has led to its abandonment until the 40s, when Jeffreys introduced his method, which has the desired property of invariance. The arise of paradoxes of marginalization due to the careless use of improper prior in the 70s pushed Bernardo to elaborate his reference prior theory to deal with this issue.
Reading the literature, every author cites different contributes: Jaynes' maximum entropy, Box and Tiao's data-translated likelihood, Zellner, ...
In your opinion, what are the crucial steps I am missing?
EDIT: I add my (main) references, if someone needs:
1) The selection of prior by formal rules, Kass, Wasserman
2) A catalogue of non informative priors, Yang, Berger
3) Noninformative Bayesians Priors Interpretation and Problems with Construction and Applications
EDIT 2: Sorry for the 2 year delay but here you can find my essay here

A: A few comments about flaws of noninformative priors (uninformative priors) are probably a good idea since the investigation of such flaws helped development of the concept of noninformative prior in history.
You may want to add some comments about the drawbacks/flaws of adopting noninformative priors. Among many criticisms I point out two.
(1) Generally the adoption of noninformative priors has consistency problems especially when the model distribution has multi-modal behavior.
This problem is not unique to noninformative priors but is shared by many other Bayesian procedures as pointed out in the following  paper along with its discussions.
Diaconis, Persi, and David Freedman. "On the consistency of Bayes estimates." The Annals of Statistics (1986): 1-26.
Nowadays the noninformative prior is no longer a research focus. It seems that there is more interest in more flexible choices of prior in nonparametric settings. Examples are the Gaussian process prior in nonparametric Bayes procedure or a flexible model like a mixture of Dirichlet priors, as in
Antoniak, Charles E. "Mixtures of Dirichlet processes with applications to Bayesian nonparametric problems." The annals of statistics (1974): 1152-1174.
But again such a prior has its own consistency problems.
(2) Most so-called "noninformative priors" are not well-defined.
This is probably the most evident problem associated with noninformative priors during their development.
One example is that the limit definition of noninformative prior as a limit of a sequence of proper priors will lead to a marginalization paradox. As you mentioned, Bernardo's reference prior also has the problem that Berger never proved that its formal definition is independent from its construction/partition. See the discussion in
Berger, James O., José M. Bernardo, and Dongchu Sun. "The formal definition of reference priors." The Annals of Statistics (2009): 905-938.
One best definition about Jeffreys' prior that is well-defined is that it is chosen to be a prior such that it is invariant under certain parallel translation over the Riemannian manifold equipped with Fisher information metric, but even that does not solve the first problem.
Also you may want to read my explanation about marginalization paradox.

A: I would have posted in the comments, but I guess I do not have the reputation yet.  The only missing thing, not in the comments already marked, is a special case of noninformative priors whose origins that I have tried to hunt down and have not found.  It may precede Jeffreys paper.
For the normal distribution, I have seen the Cauchy distribution used as a noninformative prior for data with a normal likelihood.  The reason is that the precision of the Cauchy distribution is zero, where precision is one divided by the variance.  It creates a rather peculiar set of contradictory concepts.
The formula for the Cauchy is $$\frac{1}{\pi}\frac{\Gamma}{\Gamma^2+(x-\mu)^2}.$$
Depending on how you define the integral there is either no defined variance or it goes to infinity about the median, which implies the precision goes to zero.  In conjugate updating, which wouldn't apply here, you add the weighted precisions.  I think this is why this idea of a proper prior with a perfectly imprecise density formed.  It is also equivalent to Student's t with one degree of freedom, which could also be the source.
This is a strange idea in the sense that the Cauchy distribution has a well defined center of location and inter-quartile range, which is $2\Gamma$.
The two earliest references to the Cauchy distribution are as likelihood functions.  The first in a letter from Poisson to Laplace as an exception to the Central Limit Theorem.  The second was in 1851 journal articles in a battle between Bienayme' and Cauchy over the validity of ordinary least squares.
I have found references to its use as a noninformative prior back into the 1980's but I cannot find a first article or book.  I also have not found a proof that it is noninformative.  I did find a citation to Jeffreys' 1961 book on probability theory, but I have never requested the book via interlibrary loan.
It may be simply weakly informative.  The 99.99% highest density region is 1272 semi-interquartile ranges wide.
I hope it helps.  It is a weird special case, but you see it come up in a number of regression papers.  It satisfies the requirements for a Bayes action by being a proper prior, while minimally influencing location and scale.

A: What you seem to be missing is the early history. You can check the paper by Fienberg (2006) When Did Bayesian Inference Become "Bayesian"?. First, he notices that Thomas Bayes was the first one who suggested using a uniform prior:

In current statistical language, Bayes' paper introduces a uniform
  prior distribution on the binomial parameter, $\theta$, reasoning by
  analogy with a "billiard table" and drawing on the form of the
  marginal distribution of the binomial random variable, and not on the
  principle of "insufficient reason," as many others have claimed.

Pierre Simon Laplace was the next person to discuss it:

Laplace also articulated, more clearly than Bayes, his argument for
  the choice of a uniform prior distribution, arguing that the posterior
  distribution of the parameter $\theta$ should be proportional to what
  we now call the likelihood of the data, i.e.,
$$ f(\theta\mid x_1,x_2,\dots,x_n) \propto f(x_1,x_2,\dots,x_n\mid\theta) $$
We now understand that this implies that the prior distribution for
  $\theta$ is uniform, although in general, of course, the prior may not
  exist.

Moreover Carl Friedrich Gauss also referred to using an uninformative prior, as noted by David and Edwards (2001) in their book Annotated Readings in the History of Statistics:

Gauss uses an ad hoc Bayesian-type argument to show that the posterior
  density of $h$ is proportional to the likelihood (in modern
  terminology):
$$ f(h|x) \propto f(x|h) $$
where he has assumed $h$ to be uniformly distributed over $[0,
 \infty)$. Gauss mentions neither Bayes nor Laplace, although the
  latter had popularized this approach since Laplace (1774).

and as Fienberg (2006) notices, "inverse probability" (and what follows, using uniform priors) was popular at the turn of the 19th century

[...] Thus, in retrospect, it shouldn't be surprising to see inverse
  probability as the method of choice of the great English statisticians
  of the turn of the century, such as Edgeworth and Pearson. For
  example, Edgeworth (49) gave one of the earliest derivations of what
  we now know as Student's $t$-distribution, the posterior distribution
  of the mean $\mu$ of a normal distribution given uniform prior
  distributions on $\mu$ and $h =\sigma^{-1}$ [...]

The early history of the Bayesian approach is also reviewed by Stigler (1986) in his book The history of statistics: The measurement of uncertainty before 1900.
In your short review you also do not seem to mention Ronald Aylmer Fisher (again quoted after Fienberg, 2006):

Fisher moved away from the inverse methods and towards his own
  approach to inference he called the "likelihood," a concept he claimed
  was distinct from probability. But Fisher's progression in this regard
  was slow. Stigler (164) has pointed out that, in an unpublished
  manuscript dating from 1916, Fisher didn't distinguish between
  likelihood and inverse probability with a flat prior, even though when
  he later made the distinction he claimed to have understood it at this
  time.

Jaynes (1986) provided his own short review paper Bayesian Methods: General Background. An Introductory Tutorial that you could check, but it does not focus on uninformative priors. Moreover, as noted by AdamO, you should definitely read The Epic Story of Maximum Likelihood by Stigler (2007).
It is also worth mentioning that there is no such thing as an "uninformative prior", so many authors prefer talking about "vague priors", or "weekly informative priors".
A theoretical review is provided by Kass and Wasserman (1996) in The selection of prior distributions by formal rules, who go into greater detail about choosing priors, with extended discussion of usage of uninformative priors.


text:
Q: First integral for non-linear system of equations. I have the dynamics
\begin{align}
x'&=y\\
y'&=-y-x-x^2\tag1
\end{align}
which represents a one-dimensional mechanical system with velocity $y$ and coordinate $x$, or in other words the second order equation
$$x''=-y-x-x^2 \Longleftrightarrow x''+g(x)=0 \tag2$$
where $g(x)=y+x+x^2.$ Since the origin is an asymptotically stable equilibrium point, I want to find its region of attraction using an appropriate Lyapunov function $V(x,y)$. So in the book they give the formula
$$V(x,y)=\text{Kinetic energy}+\text{Potential energy}=\frac{y^2}{2}+\int_0^xg(z)dz, \tag3$$
plugging in my expression for $g(z)$ I get
$$V(x,y)=\frac{y^2}{2}+\int_0^xy+z+z^2 \ dz=\frac{y^2}{2}+\frac{x^2}{2}+\frac{x^3}{3}+xy.\tag4$$
However, according to the book the $xy$ should not be at the end. I assume it is because they get their $g(x)$ to be $g(x)=x+x^2$. How come?

A: There is no $y$ in $g(x)$, the idea is wrong from the start. As $y$ is not an argument of $g$, the variable $y$ can not appear in $g$.
Thus it is correct to write $g(x)=x+x^2$ so that the potential energy is $G(x)=\frac{x^2}2+\frac{x^3}3$.
Using that in the Lyapunov function gives
$$
\frac{d}{dt}(\frac{y^2}2+\frac{x^2}2+\frac{x^3}3)=-y^2
$$
and it is easy to check that there are no solutions that move along the $x$ axis except the stationary solutions with $y=0$, $x=-1$ or $x=0$. This means that this energy function is continuously decreasing. If a solution starts in the valley around the origin, it will descend towards the origin.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Xcode / GitHub - Committing Interface Setting Files What do you normally do when Xcode tries to commit user setting files to git like this ones:

xcuserdata/username.xcuserdatad/xcschemes
xcuserdata/username.xcuserdatad
UserInterfaceState.xcuserstate

If I push the files to the GitHub server, aren't they going to end up on another team members computer ?
What would be the best practice? Is there a way to omit commitment on this types of files, or omit the push to the remote server ?
What do you normally do?

A: You use the .gitignore file - either at the repo level or the machine level - to tell git to ignore files, folders, etc... In this specific case, you would add xcuserdata/ to the .gitignore and git will start ignoring those files. Note that if you've already committed anything within the xcuserdata/ folder at least once, git will continue to track the file(s) even after you update the .gitignore.
Github maintains a repository of common .gitignore files for various languages, IDEs, etc..., which is available here.
There's also an Xcode-specific .gitignore example in that repo here.


text:
Q: Python XML + Java XML interoperability I need a recommendation for a pythonic library that can marshall python objects to XML(let it be a file).
I need to be able read that XML later on with Java (JAXB) and unmarshall it.
I know JAXB has some issues that makes it not play nice with .NET XML libraries so a recommendation on something that actually works would be great.

A: As Ignacio says, XML is XML.  On the python side, I recommend using lxml, unless you have more specific needs that are better met by another library.  If you are restricted to the standard library, look at ElementTree or cElementTree, which are also excellent, and which inspired (and are functionally mostly equivalent to) lxml.etree.
Edit: On closer look, it seems you are not just looking for XML, but for XML representations of objects.  For this, check out lxml.objectify, or Amara.  I haven't tried using them for interoperability with Java, but they're worth a try.  If you're just looking for a way to do data exchange, you might also try custom JSON objects.

A: The issue your are probably having is the default format of the Python and Java libraries you are using to marshal your objects. Any decent libraries including JAXB allows customisation of how objects should be represented in XML.
You need to decide what the structure of your XML should be then use your libraries features to consume and emit your XML structure rather than relying on the defaults which would never be the same across different libraries in different programming languages.


text:
Q: IntentService STICKY and sensor monitoring stops when it shouldn't in Android In my application onCreate I check some conditions and then I start an Activity like this:
Intent startIntent = new Intent(getApplicationContext(), EnableLocationProviderActivity.class);
startIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
getApplicationContext().startActivity(startIntent);

From that Activity I start an IntentService which register some listeners for the sensors, it is started as STICKY meaning it should be stopped explicitly. That IntentService monitors the sensors.
My problem is that when I come back to the first Activity the sensors are not sensing anymore (I put a Log.v in onSensorChanged (the start showing data, and then it stops).
Why it could be that it stops if I didn't stopped it explicitly?
Moreover I see sometimes OnDestroy of the IntentService being called, but again, How can it being called if it's STICKY and I didn't call stopself() and didn't stopped in any other way?
Thanks! Guillermo.
EDIT
This is the code of the IntentService (which should be running all the time, despite if the cellphone goes to sleep or the home button is pressed (I know about battery and everything else, the user will be warned about this and will have the oportunity to close the application when he wants.
The service is called from MainActivity like this:
Intent startIntent = new Intent(GdpTesisApplication.getInstance().getApplicationContext(), SensingService.class);
startService(startIntent);

And the service code is this one:
public class SensingService extends IntentService implements SensorEventListener {
    private float[] mAccelerationValues;
    private SensorManager mSensorManager = null;
    String sensorType = "";

    public SensingService(String name) {
        super(name);
        setIntentRedelivery(true);
    }

    public SensingService() {
        super("SensingService");
        setIntentRedelivery(true);
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.v(ApplicationName,"SensingService.onStartCommand");
        super.onStartCommand(intent, flags, startId); // If this is not written then onHandleIntent is not called.
        return START_STICKY;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        Log.v(ApplicationName, "SensingService.onCreate");
        initialize();
    }

    private void initialize() {
        mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE); // This must be in onCreate since it needs the Context to be created.
        mAccelerationValues = new float[3];

        Log.v(ApplicationName, "Opening Location Service from Sensing Service");
        LocationService myLocation = new LocationService();
        myLocation.getLocation(this, locationResult);
    }

    @Override
    public void onDestroy() {
        Log.v(ApplicationName, "SensingService.onDestroy");
        super.onDestroy();
        if (mSensorManager != null) {
            mSensorManager.unregisterListener(this);
        }
    }

    @Override
    protected void onHandleIntent(Intent intent) {
        Log.v(ApplicationName, "SensingService.onHandleIntent");
        if (mSensorManager != null) {
            registerListeners();
        }
    }

    public LocationResult locationResult = new LocationResult() {
        @Override
        public void gotLocation(final Location location) {
            if (location != null) {
                Log.v(ApplicationName, "Location != null : (" + location.getLatitude() + "," + location.getLongitude() + ")");
            } else {
                Log.v(ApplicationName, "Location == null : (0,0)");
            }
        }
    };

    public void onAccuracyChanged(Sensor sensor, int accuracy) {
    }

    public void onSensorChanged(SensorEvent currentEvent) {
        if (currentEvent.accuracy == SensorManager.SENSOR_STATUS_UNRELIABLE) {
            return;
        }

        synchronized (this) {
            float[] accelVals = null;
            float totalForce = 0.0f;

            int sensor = currentEvent.sensor.getType();
            System.arraycopy(currentEvent.values, 0, mAccelerationValues, 0, 3); // We use System.arraycopy because of this:
            switch (sensor) {
            case Sensor.TYPE_ACCELEROMETER:
                sensorType = "Accelerometer";
                totalForce = SensorsHelpers.getTotalForceInGs(mAccelerationValues);
                break;
            case Sensor.TYPE_LINEAR_ACCELERATION:
                sensorType = "LinearAcceleration";
                totalForce = SensorsHelpers.getTotalForceInGs(mAccelerationValues) + 1;
                break;
            case Sensor.TYPE_GRAVITY:
                totalForce = SensorsHelpers.getTotalForceInGs(mAccelerationValues);
                sensorType = "Gravity";
                break;
            }
            Log.v(ApplicationName,DateHelper.GetUTCdatetimeFromDate(new Date()) + " - from sensingService");
        }
    }

    private void registerListeners() {
        Log.v(ApplicationName, "Registering sensors listeners");
        mSensorManager.registerListener(this, mSensorManager.getDefaultSensor(Sensor.TYPE_LINEAR_ACCELERATION), SensorManager.SENSOR_DELAY_UI);
        mSensorManager.registerListener(this, mSensorManager.getDefaultSensor(Sensor.TYPE_GRAVITY),SensorManager.SENSOR_DELAY_UI);
        mSensorManager.registerListener(this, mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER), SensorManager.SENSOR_DELAY_UI);
    }
}

UPDATE 2
Now I've added this on the method onCreate:
int NOTIFICATION_ID = 1;
Intent intent = new Intent(this, MainActivity.class);
PendingIntent pi = PendingIntent.getActivity(this, 1, intent, 0);
Notification notification = new Notification(R.drawable.ic_dialog_info, "Running in the Foregound", System.currentTimeMillis());
notification.setLatestEventInfo(this, "Title", "Text", pi);
notification.flags = notification.flags | Notification.FLAG_ONGOING_EVENT;
startForeground(NOTIFICATION_ID, notification);

to start it as startForground, but it puts the icon in the notification bar, then onDestroy is called in the service and the notification icon goes away.
I'm desperate now! Please help in this one!
Thanks! Guillermo.

A: As per IntentService documentation:

the service is started as needed, handles each Intent in turn using a
  worker thread, and stops itself when it runs out of work

Also, according to the same documentation, you're not supposed to override onStartCommand() and onDestroy() in your IntentService, I assume because it implements its own special behavior as specified above. Maybe you need to extend Service instead of IntentService.

A: Ok, I saw a reply to another question, and there is a guy who said it's a bug in Android, I followed his suggestion to move the code to onCreate instead of onHandleIntent and it worked! So, if no one show to me it's a problem with my code, for me it will be a bug. Thanks!


text:
Q: Generate a Date series between transaction dates I have a table which contains transaction dates and the balances of those transactions. Example Below:
select id, transaction_bal1, transaction_bal2, transaction_date
from transactions

Which results in
ID | transaction_bal1 | transaction_bal2 | transaction_date
1  | -10000           | 1000             | 2017.01.02
2  | 4000             | 1000             | 2017.02.02
3  | 4000             | 1000             | 2017.03.02
etc...

What I want to do is to generate a series with '1 day'::interval so that I select all days between the transaciton dates and that the rows in the above table falls under the right day. Something like this:
Gen_series | ID | transaction 1 | transaction 2 | transaction_date
2017.01.01 |null| 0             | 0             | null
2017.01.02 |1   | -10000        | 1000          | 2017.01.02
2017.01.03 |null| 0             | 0             | null
...
2017.02.01 |null| 0             | 0             | null
2017.02.02 |1   | 4000          | 1000          | 2017.01.02
2017.02.03 |null| 0             | 0             | null
etc...

I use Postgresql(dont know which version) but I use PgAdmin 4 3.2 (if that is of any help)
Feel free to ask any questions if I need to flesh out anything.


text:
Q: flatten a dictionary of dictionaries in to a list in python I have a dictionary of dictionaries and need to flatten it into a list. My goal here is to have it in a form that I can send to a MySQL database. The dictionary is in the form
{
 'Customer 1':
   {'Vitamin A': 0, 'Calcium': 1, 'Protein': 1, 'B vitamins': 0, 'HPMR': 0},
 'Customer 2':
   {'Vitamin A': 0, 'Calcium': 0, 'Protein': 1, 'B vitamins': 1, 'HPMR': 0}
 }

I want it to end up like:
('Customer 1', 'Vitamin A', 0), ('Customer 1', 'Calcium', 1)
...
('Customer 2', 'Vitamin A', 0), ('Customer 2', 'Calcium', 0)`

Thanks for your help

A: customers = {'Customer 1': {'Vitamin A': 0,
                            'Calcium': 1,
                            'Protein': 1,
                            'B vitamins': 0,
                            'HPMR': 0},
             'Customer 2': {'Vitamin A': 0,
                            'Calcium': 0,
                            'Protein': 1,
                            'B vitamins': 1,
                            'HPMR': 0}}
all_orders = []
for customer, order in customers.items():
    customer_orders = [(customer, vitamin, quantity) for vitamin, quantity in order.items()]
    all_orders.append(customer_orders)

all_orders = [[('Customer 2', 'Calcium', 0),
               ('Customer 2', 'Vitamin A', 0),
               ('Customer 2', 'HPMR', 0),
               ('Customer 2', 'Protein', 1),
               ('Customer 2', 'B vitamins', 1)],
              [('Customer 1', 'Calcium', 1),
               ('Customer 1', 'Vitamin A', 0),
               ('Customer 1', 'HPMR', 0),
               ('Customer 1', 'Protein', 1),
               ('Customer 1', 'B vitamins', 0)]]

A: In [6]: dic={'Customer 1': {'Vitamin A': 0, 'Calcium': 1, 'Protein': 1, 'B vitamins': 0, 'HPMR': 0}, 'Customer 2': {'Vitamin A': 0, 'Calcium': 0, 'Protein': 1, 'B vitamins': 1, 'HPMR': 0}}

In [7]: [tuple([x]+list(y)) for x in dic for y in dic[x].items() ]

Out[7]:
[('Customer 2', 'Calcium', 0),
 ('Customer 2', 'Vitamin A', 0),
 ('Customer 2', 'HPMR', 0),
 ('Customer 2', 'Protein', 1),
 ('Customer 2', 'B vitamins', 1),
 ('Customer 1', 'Calcium', 1),
 ('Customer 1', 'Vitamin A', 0),
 ('Customer 1', 'HPMR', 0),
 ('Customer 1', 'Protein', 1),
 ('Customer 1', 'B vitamins', 0)]

or using itertools.chain():
In [8]: from itertools import chain

In [9]: [tuple(chain(*([x],y))) for x in dic for y in dic[x].items() ]
Out[9]:
[('Customer 2', 'Calcium', 0),
 ('Customer 2', 'Vitamin A', 0),
 ('Customer 2', 'HPMR', 0),
 ('Customer 2', 'Protein', 1),
 ('Customer 2', 'B vitamins', 1),
 ('Customer 1', 'Calcium', 1),
 ('Customer 1', 'Vitamin A', 0),
 ('Customer 1', 'HPMR', 0),
 ('Customer 1', 'Protein', 1),
 ('Customer 1', 'B vitamins', 0)]

A: [(k, k2, v) for k in dct for k2, v in k.items()]

A: dictio = {'Customer 1': {'Vitamin A': 0, 'Calcium': 1, 'Protein': 1, 'B vitamins': 0, 'HPMR': 0}, 'Customer 2': {'Vitamin A': 0, 'Calcium': 0, 'Protein': 1, 'B vitamins': 1, 'HPMR': 0}}
a = []
for key in dictio.keys():
    for key_ in dictio[key].keys():
        a.append((key,key_,dictio[key][key_]))

print a

Output:
[('Customer 2', 'Calcium', 0), ('Customer 2', 'Vitamin A', 0), ('Customer 2', 'HPMR', 0), ('Customer 2', 'Protein', 1), ('Customer 2', 'B vitamins', 1), ('Customer 1', 'Calcium', 1), ('Customer 1', 'Vitamin A', 0), ('Customer 1', 'HPMR', 0), ('Customer 1', 'Protein', 1), ('Customer 1', 'B vitamins', 0)]
Also what you are inserting are tuples to the list, not lists.

A: I too thought of a list comprehension like others:
cust = {'Customer 1': {'Vitamin A': 0, 'Calcium': 1, 'Protein': 1, 'B vitamins': 0, 'HPMR': 0}, 'Customer 2': {'Vitamin A': 0, 'Calcium': 0, 'Protein': 1, 'B vitamins': 1, 'HPMR': 0}}
cust_flat = [ (k, k2, v2) for k2, v2 in v.iteritems() for k, v in cust.iteritems() ]

Result looks like:
[('Customer 2', 'Calcium', 1),
 ('Customer 1', 'Calcium', 1),
 ('Customer 2', 'Vitamin A', 0),
 ('Customer 1', 'Vitamin A', 0),
 ('Customer 2', 'HPMR', 0),
 ('Customer 1', 'HPMR', 0),
 ('Customer 2', 'Protein', 1),
 ('Customer 1', 'Protein', 1),
 ('Customer 2', 'B vitamins', 0),
 ('Customer 1', 'B vitamins', 0)]


text:
Q: Package requires NuGet client version '2.12' I am trying to install 'WindowsAzure.Storage 8.0.1' in visual studio 2012, but getting the error

package requires NuGet client version '2.12' or above, but the current NuGet version is '2.8.60318.667'.

on running command "Install-Package NuGet.Client"
Attempting to resolve dependency 'NuGet.Versioning (≥ 3.5.0)'.
Attempting to resolve dependency 'NuGet.Packaging (≥ 3.5.0)'.
Attempting to resolve dependency 'NuGet.Common (≥ 3.5.0)'.
Attempting to resolve dependency 'NuGet.Packaging.Core (≥ 3.5.0)'.
Attempting to resolve dependency 'NuGet.Packaging.Core.Types (≥ 3.5.0)'.
Attempting to resolve dependency 'NuGet.Frameworks (≥ 3.5.0)'.
Attempting to resolve dependency 'NuGet.Repositories (≥ 3.5.0)'.
Attempting to resolve dependency 'NuGet.RuntimeModel (≥ 3.5.0)'.
Attempting to resolve dependency 'Newtonsoft.Json (≥ 6.0.4)'.
Attempting to resolve dependency 'NuGet.ContentModel (≥ 3.5.0)'.
'NuGet.Client 3.5.0' already installed.

But still I am getting the error.

The 'WindowsAzure.Storage 8.0.1' package requires NuGet client version '2.12' or above, but the current NuGet version is '2.8.60318.667'.

A: Update your NuGet Package Manager extension. Go to Tools->Extensions and Updates and select Updates->Visual Studio Gallery. Update the NuGet Package Manager extension. Then try to install the package after Visual Studio gets restarted.

A: NuGet 2.12 only supports Visual Studio 2013 and later. If you're on Visual Studio 2012 you're out of luck.

A: I struggled with this issue in Visual Studio 2010 when I was trying to add NewtonSoft.Json nuget package into my project. When I try to run the latest version of the nuget package from nuget package manager console:
PM> Install-Package Newtonsoft.Json

It results in the same error as mentioned by OP:

package requires NuGet client version '2.12' or above, but the current
  NuGet version is '2.8.60318.667'.

So I thought I would update the NuGet extension in Visual Studio first to latest version. But when I went into Tools -> Extensions and Updates window the Updates tab wasn't showing any update for Nuget extension. So it seems NuGet client version 2.12 isn't available/supported in Visual Studio 2010 at all. I was running out of options now.
So finally, I tried to install a specific lower version (6.0.3) of Newtonsoft.Json package deliberately this way:
PM> Install-Package Newtonsoft.Json {Your Project Name} 6.0.3

This worked successfully.
Latest version of this package at the time of writing this post is 10.0.3 instead.
So, it might be the case that newer version of a nuget package is compatible with only latest version of nuget package manager. So sometimes explicitly installing a lower version of the package might help you. Older version of a nuget package will of course be compatible with older nuget extension in Visual Studio if it is not up-to-date.
The only caveat in this solution is that the functionalities present in lower version of the nuget package you target should suffice your current project needs. Good luck!
Note: Although I've elaborated this solution w.r.t. Visual Studio 2010 but you can try this work around for any Visual Studio version for that matter.

A: try
nuget update -self

my result:
Checking for updates from https://www.nuget.org/api/v2/.
Currently running NuGet.exe 2.8.7.
Updating NuGet.exe to 5.3.1.
Update successful.

A: I find out the solution for this problem.
Basically you have a .nuget folder at solution level, that folder contains a nuget.exe file that probably is old. A lot of packages might need new version of that file.

*

*Open this link: https://www.nuget.org/downloads

*Download latest version of nuget.exe

*Replace your .nuget/nuget.exe with this new version.

And try again, I'm confident it will work.

A: This fix worked for me(I am using vs 2013, not sure if it will work for the rest), Go to Tools --> Extensions and Updates, then look for NuGet package manager for visual studio 2013, uninstall it. In the left pane select online which will take you to visual studio gallery, in the right pane search for NuGet package manager for visual studio 2013, it will bring you the right version to install. Install that and you are good to go, hope this sorts someone out.

A: Install-Package Newtonsoft.Json -Version 6.0.3

A: I got the same issue and I just clicked on "Restore NuGet package for this solution". In my case this solved the problem. Hope it will help.

A: I try everything but nothing helps me. Than I change Visual Studio version from 2012 to 2015 everything is working Like a charm now.

A: You are updating the wrong package. Update your Nuget Package Manager and the error will be gone.
Update-Package NuGet.VisualStudio

https://www.nuget.org/packages/NuGet.VisualStudio

A: I solved this problem, and my steps are as below:
1.Do what as "Mathivanan KP" said;

2.Delete the folder ".nuget", which is below your solution folder;

3.Rebuild your solution;

4.Back to your solution folder, and press "Ctrl + Z", then rebuild your solution again.

If the problem still there, i think you should clone the code from version manager to a new folder, and do the steps as before.
Hope it helpful to you.


text:
Q: NSDateFormatter relative date formatting with custom format So my intention is to put out dates that would look like the following:
Today, August 28
Tomorrow, August 29
Friday, August 30
...etc

The issue is that it seems I can only get so close.
When I setDoesRelativeDateFormatting:YES and setDateStyle to Full and setTimeStyle to None, it yields results like this:
Today
Tomorrow
Friday, August 30, 2013

This yields the year and does not yield month and date for today and tomorrow.
The other code I've tried is this:
[NSDateFormatter dateFormatFromTemplate:@"eeeedMMM" options:0
                                                     locale:[NSLocale currentLocale]];

and that yields the following:
Wednesday, August 28
Thursday, August 29
Friday, August 30

Seemingly, the dateStyle and timeStyle, or the relative date formatting overrides the custom format.
Is there a way to accomplish this date format without going into a custom implementation?
Thanks in advance!

A: Based on the documentation about NSDateFormatter I think that the only solution for your issue is to present two date strings for the days you would like to be relatively shown. You should keep in mind that in different languages there are differences in the relative dates. From the documentation:

If a date formatter uses relative date formatting, where possible it replaces the date component of its output with a phrase—such as "today" or "tomorrow"—that indicates a relative date. The available phrases depend on the locale for the date formatter; whereas, for dates in the future, English may only allow "tomorrow," French may allow "the day after the day after tomorrow".

I believe that if you define that you're going to show relatively for example yesterday, today and tomorrow you can use 2 NSDateFormatters. With the first one you will show the relative value and with the second you will display the actual date. For the non-relative dates you will display only the non-relative value.

A: It seems there is no way to accomplish this kind of date formatting without going into a custom implementation. So, the short answer to this question is 'No'.
However, the problem still exists, so below is my own solution to the problem.
Make a subclass of NSDateFormatter and implement custom init and override stringFromDate: method.
- (instancetype)initWithDateFormat:(NSString *)dateFormat
{
    self = [super init];
    if (self) {
        NSLocale *locale = [NSLocale currentLocale];
        self.locale = locale;

        self.timeStyle = NSDateFormatterNoStyle;
        self.dateStyle = NSDateFormatterShortStyle;
        self.doesRelativeDateFormatting = YES;

        self.dateFormat = dateFormat;
    }
    return self;
}

- (NSString *)stringFromDate:(NSDate *)date
{
    NSString *dateFormat = self.dateFormat;
    self.dateFormat = nil;

    BOOL didRelativeDateFormatting = self.doesRelativeDateFormatting;
    self.doesRelativeDateFormatting = YES;

    NSString *result = [super stringFromDate:date];

    if ([result rangeOfCharacterFromSet:[NSCharacterSet decimalDigitCharacterSet]].location != NSNotFound) {
        self.dateFormat = dateFormat;
        self.doesRelativeDateFormatting = NO;
        result = [super stringFromDate:date];
    }

    self.dateFormat = dateFormat;
    self.doesRelativeDateFormatting = didRelativeDateFormatting;

    return result;
}

Since doesRelativeDateFormatting and dateFormat are mutually exclusive we try to use relative formatting first. Given that we set self.dateStyle = NSDateFormatterShortStyle in the init method, we know the date will contain decimal numbers unless it is replaced with words meaning 'today', 'tomorrow' and anything that may appear in other languages. If we did not spot any numbers we accept this result.
If there are digital numbers in the string we assume the relative formatting did not happen, so we apply our own date format.

A: I use this approach in Swift 3:
struct SharedFormatters {
    private static let dateWithRelativeFormatting: DateFormatter = {
        let df = DateFormatter()
        df.dateStyle = .medium
        df.doesRelativeDateFormatting = true
        return df
    }()
    private static let dateWithoutRelativeFormatting: DateFormatter = {
        let df = DateFormatter()
        df.dateStyle = .medium
        df.doesRelativeDateFormatting = false
        return df
    }()
    private static let longDateWithoutYear: DateFormatter = {
        let df = DateFormatter()
        df.dateFormat = "MMMM d"
        df.doesRelativeDateFormatting = false
        return df
    }()
    static func string(from date: Date) -> String {
        let val = dateWithRelativeFormatting.string(from: date)
        let val2 = dateWithoutRelativeFormatting.string(from: date)
        return val == val2 ? longDateWithoutYear.string(from: date) : val
    }
}


text:
Q: How to pass Link id between pages in react? I'm making an application using the MERN stack where I have different chats that a user is a part of and the user can click on one of the chat links to go to that chat page. I don't want to create a page for each chat, so instead, what I'm doing is I use the id of the chat (I have a map call where I assign an id to each Link that corresponds to a chat) to get the chat, and then return the display the chat data to the screen. However, I need to know which chat the user clicked on to make this work. Is there some way I can do this?

A: You need to pass id of every item to Link in Router:
<Route path=`link/${chatID}` component = {ChatComponent}/>


text:
Q: Downloading a PDF file In my application, the user needs to download PDF file from an url and store it on sdcard.
But the catch here is I can only use DefaultHttpClient to access the url.
I found couple of solutions but none used DefaultHttpClient.
After downloading the PDF, I would also likie to view the PDF in my application.

A: //use this method to download the pdf file
 public void downloadPdfContent(String urlToDownload){

             try {

                 String fileName="xyz";
             String fileExtension=".pdf";

//           download pdf file.

                URL url = new URL(urlToDownload);
                HttpURLConnection c = (HttpURLConnection) url.openConnection();
                c.setRequestMethod("GET");
                c.setDoOutput(true);
                c.connect();
                String PATH = Environment.getExternalStorageDirectory() + "/mydownload/";
                File file = new File(PATH);
                file.mkdirs();
                File outputFile = new File(file, fileName+fileExtension);
                FileOutputStream fos = new FileOutputStream(outputFile);
                InputStream is = c.getInputStream();
                byte[] buffer = new byte[1024];
                int len1 = 0;
                while ((len1 = is.read(buffer)) != -1) {
                    fos.write(buffer, 0, len1);
                }
                fos.close();
                is.close();

               System.out.println("--pdf downloaded--ok--"+urlToDownload);
            } catch (Exception e) {
                e.printStackTrace();

            }
    }

//    for viewing the pdf use this method
private void onPdfClick()
    {

//      String pdfFile = Environment.getExternalStorageDirectory()+ File.separator + AstroManager.file.getName();

         Intent intent = new Intent(Intent.ACTION_VIEW);
         intent.setDataAndType(Uri.fromFile(new File("/sdcard/mydownload/xyz.pdf"), "application/*");

         startActivity(intent);
    }

A: If you have to open pdf file, pdf reader must have to be installed in your device.Otherwise it will show blank screen.
Also here is good example to download pdf from server and view its contents.

A: see http://developer.android.com/reference/org/apache/http/client/methods/HttpGet.html for retreiving data from a url with a DefaultHttpClient


text:
Q: Where can I find a good example of FastScrollView? I have a long "cities" list.  I was looking for an equivalent to
sectionIndexTitlesForTableView in the iphone world.  It provides a way to "jump" to a particular point in long lists without having to scroll through all the elements.  I think FastScrollView implements this but it's not part of the API and I can't find any documentation on how to use it.  It appears in the baked in contacts application of the device.  I want to use this functionality within an AlertDialog.  Is this possible?

A: Fast scroll can be used for any list; the most common being the alphabetical lists. You can write your own custom SectionIndexer for other fast scrolling operations such as moving to a list based on some other attribute of your list item (e.g. name, address - where section indexer will be alphabetical, and phone number, address etc where it can be numerical)
P.S. This is more of a comment aimed at matto1990's answer.

A: Fast scroll is something you can only use in alphabetical lists really. The view which pops up (to show where you are) can only provide space for a single letter. I've looked in the source code for ways to extend it, however lots of the methods needed are protected and can only be used by classes in the same package (the core framework one).
The only thing I can think to do is to just write it all yourself. It's annoying but until Google make it possible for us to extend it via an API that's the best that's possible.
My similar question


text:
Q: How to retrieve the value in GridView when I click on LinkButton of GridView I am using gridview to display of data from database, in each row of the gridview I am having delete and edit link button. How can I get value of "NAME" and "DESCRIPTION" when I click on Delete or Edit Button in gridview.
The following is my code.
List.aspx
        <div align="center" style="margin-top:50px">
          <asp:GridView ID="gvDetails" runat="server" AutoGenerateColumns="false" CellPadding="5" runat="server">
             <Columns>
                <asp:BoundField HeaderText="Report Name" DataField="NAME" />
                <asp:BoundField HeaderText="Report Description" DataField="DESCRIPTION" />
                <asp:BoundField HeaderText="Report Group" DataField="REPORT_GROUP" />
                <asp:TemplateField>
                <ItemTemplate>
                        <asp:LinkButton ID="btnDelete" Text="Delete" runat="server"  OnClick="Btn_Delete_Click" />
                        <asp:LinkButton ID="btnEdit" Text="Edit" runat="server" />
                </ItemTemplate>
                </asp:TemplateField>
             </Columns>
             <HeaderStyle BackColor="#df5015" Font-Bold="true" ForeColor="White" />
             </asp:GridView>
        </div>

List.aspx.cs
    protected void Btn_Delete_Click(object sender, EventArgs e)
    {

    }

A:
use command argument like this

<ItemTemplate>
   <asp:LinkButton ID="btnDelete" Text="Delete" runat="server" CommandArguman='<%# Eval("Name")+","+Eval("DESCRIPTION") %>' OnClick="Btn_Delete_Click" />
   <asp:LinkButton ID="btnEdit"  Text="Edit" runat="server" CommandArguman='<%# Eval("Name")+","+Eval("DESCRIPTION") %>' OnClick="btnEdit_Click" />
</ItemTemplate>

in onclick

protected void Btn_Delete_Click(object sender, EventArgs e)
    {
         string strName=((LinkButton)sender).CommandArgument.Split(',')[0];
         string strDescription=((LinkButton)sender).CommandArgument.Split(',')[1];
    }

protected void btnEdit_Click_Click(object sender, EventArgs e)
    {
         string strName=((LinkButton)sender).CommandArgument.Split(',')[0];
         string strDescription=((LinkButton)sender).CommandArgument.Split(',')[1];
    }


text:
Q: Trying to swap values in 2d array inside nested for loops I have been struggling with this for a while. Hopefully someone can help. Here goes. I have 2 dimensional array that is initialized in a nested for loop. If the dimensions of the array mod (%) 2 is even (d%2 == 0), I want to swap the element 2 and element 1 in the array matrix with one another.
Another idea I am struggling with is this, instead of perform a swap I could just simply explicit assign the 1 and 2 to the index of the array inside the for loop.
Here is the code I have so far.. I appreciate any inputs that will assist me to arriving at the right solution..
if (d % 2 == 0)
{
    for (row_i = 0; row_i < d; row_i++)//loops through rows
    {
        for(col_j = 0; col_j < d; col_j++) //loops through column
        {
            board[row_i][col_j] = multi_dim--;
            if(board[row_i][col_j] == 2 && board[row_i][col_j] == 1)
            {
                int hold = board[d][d -2];
                board[d][d - 2] = board[d][d - 1];
                board[d][d - 1] = hold;
            }
            printf(" %2d ", board[row_i][col_j]);
        }
        printf("\n");
    }
}

A: if(board[row_i][col_j] == 2 && board[row_i][col_j] == 1)

This test is always false.  You're asking the same variable 'board[row_i][col_j]' to be 2 and 1 at the same time.


text:
Q: Mercurial no color in commands after doing su First noticed in 12.04 still persists in 14.04
This happens when to change to a system user (www-data, postgres, etc) and not for a user which has a desktop profile setup.
What I have tried:

*

*Copy .profile and .bashrc from a user to the www-data user which shows colors in the ls command but still no color in mercurial

Reproducing the problem (colors show for the first hg stat command but not the second):
sudo su -
hg stat
su - www-data
hg stat

A: Sounds like a simple configuration issue. You successfully got colored ls output after copying suitable .bashrc and .profile files to the other user's (e.g., www-data) home directory. Obtaining colored output in mercurial should presumably be as simple as additionally copying a suitable .hgrc file.
Also see the mercurial man page.


text:
Q: rotate two adjacent elements I have two adjacent elements:

*

*Hero Div, with a background image

*A 60px high element beneath that

I gave the Hero Div a clip-path, to angle the bottom right corner of the image slightly up. I need the div below that to match the angle, so I gave it a transform: rotate(x) property. Only issue is that as the hero div scales with its percentages the transformed div doesn't scale with it, leaving white spaces to the left or right depending on the size.
I am sure this is an easy task for a lot, but I can't think of a way that is suitable for production.
div(id="front")
    section(class="hero overlay")
        main
            h1 xxx
    div(class="angled")

Imagine the bottom right corner of this gray box above as slanted upwards, so as to create the effect of the box being tilted.

A: I solved it this way:
.hero {
        background-image: url(../images/hero.png);
        background-position: center;
        background-repeat: no-repeat;
        background-size: cover;
        height: 250px;
        width: 100%;
}

.angled {
        background-color: #fff;
        border-top: 60px solid color('one');
        padding-bottom: 40px;
        margin-top: -40px;
        transform: rotate(-2.5deg);
        width: 110vw;
        z-index: 99;
}

As a classical mobile first approach, the background hero image only gets 250px of a height. The angled div is where the money is at. The padding-bottom along with the z-index prevents the hero image from spilling out on the bottom (hides it). The negative margin-top value pulls the div upwards and aligns it with the bottom left corner of the hero image.
I had the hero image itself angled but decided to take it out so that I don't have to worry about two elements with the same responsive angles.
Hope others see this and take a similar mobile-first approach.


text:
Q: Get Magento Mage_Core_Model_Store_Group from backend into frontend array How do get the property of a Mage_Core_Model_Store_Group object into an array?  I need the _storeIds and _storeCodes into respective arrays.
$theobjectthathasdataiwant = Mage::getSingleton('adminhtml/system_store')->getGroupCollection();
var_dump($theobjectthathasdataiwant);

results in:
object(Mage_Core_Model_Store_Group)[129]
protected '_cacheTag' => boolean true
protected '_eventPrefix' => string 'store_group' (length=11)
protected '_eventObject' => string 'store_group' (length=11)
protected '_stores' =>
array (size=3)
  7 =>
   .....
protected '_storeIds' =>
array (size=3)
  7 => string '7' (length=1)
  4 => string '4' (length=1)
  5 => string '5' (length=1)
protected '_storeCodes' =>
array (size=3)
  7 => string 'rg' (length=2)
  4 => string 'xray' (length=4)
  5 => string 'zoe' (length=3)
protected '_storesCount' => int 3

Thank you in advance!

A: Got it!  As follows:
$theobjectthathasdataiwant = Mage::getSingleton('adminhtml/system_store')->getGroupCollection();
$Group = $theobjectthathasdataiwant[5]; //<-- [5] is the group of my desired store array
$storearrayiwant = $Group->getStoreIds();
$var_dump($storearrayiwant);

Finally, my store id array:
array (size=3)
  7 => string '7' (length=1)
  4 => string '4' (length=1)
  5 => string '5' (length=1)


text:
Q: template argument of template class I have some template class Pool:
template<int a>
class Pool{}

Now, I have another class where I pass Pool's object pointer as argument:
template<int a, Pool<a> &pool>
class Point{}

or
template<typename PoolT, PoolT &pool>
class Point{}

Can I somehow avoid first argument? E.g.:
template<Pool<?> &pool>
class Point{}

Here is example what I am doing:
#include <iostream>
#include <stdlib.h>     /* malloc, free, rand */
using namespace std;

template<int i>
struct Pool{
    int id;
};

struct FE{
    static Pool<1> pool;
};

Pool<1> FE::pool;

template<typename T, T &_p>
struct C{
    int id;
    void* operator new(size_t size){
        std::cout<<"new";
        return malloc(size);
    }

    void test(){
        std::cout << _p.id;
    }
};

int main() {
    FE::pool.id = 120;
    C<Pool<1>, FE::pool> c;
    c.test();
    return 0;
}

http://ideone.com/1BRUos

A: Can't you just use a static const member to store the template parameter of Pool?
#include <stdio.h>

template<int i>
struct Pool
{
    static const int stored = i;
};

int main(int argc, char* argv[])
{
    printf("%d\n", Pool<5>::stored);
    return 0;
}

A: Partial specialization can unpack the argument 1 from the type Pool, but there is no way to declare a template that takes a reference to any object and deduces the type. A function can deduce a type given an object, but such an object cannot be used as a non-type template argument.
The best factoring here is probably to make the client type nested within the pool type.
template<int i>
struct Pool{
    int id;

    // i and the Pool type are already defined at least within this context.

    template< Pool & p >
    struct C{
        int id;
        void* operator new(size_t size){
            std::cout<<"new";
            return malloc(size);
        }

        void test(){
            std::cout << _p.id;
        }
    };
};

int main() {
    FE::pool.id = 120;
    Pool<1>::C< FE::pool> c;
    c.test();
    return 0;
}

The name Pool<1>::C< FE::pool> as illustrated still contains the same ugly information, but this factoring is more amenable to a typedef, or adding code to the allocator type where relevant information is conveniently in scope.


text:
Q: Risk Premium Formula I was once served the formula below for calculating the risk premium in insurance. The intent is to model the risk premium in two steps, first "capping" claims larger than a certain limit, and then modelling these separately.

Frequency*{Severity Claims + Probability for big Claim *
  (New Big Claim model) }

So Frequeny and Severity Capped Claims are modelled with Poisson and Gamma regression and new Big Claim model is another distribution.
First, is this formula correct? Does not seem intuitive to me... Second, any place I can self study this exact formula?


text:
Q: Form work's with web but not iOS, event.target returns 'undefined' I've written a login form that works in the browser, but not on Expo Client for iOS.
The event.target.id and event.target.value in the changeHandler method returns 'undefined' on iOS, while it returns the correct values in the browser.
Can anybody explain why?
class AdminPanel extends Component {

  constructor(props){
    super(props)

    this.state = {
      isLoggedIn: false,
      username: null,
      password: null
    }

    this.changeHandler = this.changeHandler.bind(this)
    this.loginHandler = this.loginHandler.bind(this)
  }

  changeHandler(event){
    let name = event.target.id;
    let value = event.target.value;

    this.setState({[name]: [value]})
  }

  loginHandler(event){
    if(this.state.isLoggedIn){
      this.setState({isLoggedIn: false, username: null})
    }else{
      if(this.state.username == "adm" && this.state.password == "123"){
        this.setState({isLoggedIn: true, password: null})
      }else{
        alert("Login failed")
      }
    }
  }

  render(){
    if(this.state.isLoggedIn){
      return (
        <View>
        <Text>Hi {this.state.username}!</Text>
        <input type="submit" value="Logout" onClick={this.loginHandler} />
        <StatusBar style="auto" />
        </View>
      )
    }else{
      return (
        <View>
          <Text>Welcome to the admin panel.</Text>
          <Input id="username" onChange={this.changeHandler} placeholder="Username" />
          <Input id="password" onChange={this.changeHandler} placeholder="Password" />
          <Button title="Login" onPress={this.loginHandler} />
          <StatusBar style="auto" />
        </View>
      );
    }
  }
}

A: I worked around the problem by using onChangeText instead of onChange, and passing two parameters containing name and text to my new method, inputHandler.
inputHandler(id, text){
    this.setState({[id]: [text]})
}

...
<Input name="username" onChangeText={ (text) => { this.inputHandler('username', text) }} placeholder="Username" />
<Input name="password" onChangeText={ (text) => { this.inputHandler('password', text) }} placeholder="Password" secureTextEntry={true} />

I'm unsure why event.target.name and event.target.value aren't accessible from iOS, but something tells me that event's work different in native than from web.


text:
Q: C++ operator overloading called as function I'm experimenting with operator overloading and found something that I cannot explain:
WeekDays.h
using namespace std;
enum DAYS
{
    MON,
    TUE,
    WED,
    THU,
    FRY,
    SAT,
    SUN
};

DAYS operator+(DAYS&a,DAYS &b)
{
    printf("Binary+ called\n");
    return (DAYS)(((unsigned int)a+(unsigned int)b)%7);
}

//Increment 3
DAYS operator+(DAYS&a)
{
    printf("Unary+ called\n");
    return (DAYS)(((unsigned int)a+3)%7);
}

ostream& operator<<(ostream&o, DAYS &a)
{
    switch(a){
    case MON: o<<"MON"; break;
    case TUE: o<<"TUE"; break;
    case WED: o<<"WED"; break;
    case THU: o<<"THU"; break;
    case FRY: o<<"FRY"; break;
    case SAT: o<<"SAT"; break;
    case SUN: o<<"SUN"; break;
    }
    return o;
};

Main.cpp
#include <iostream>
#include "WeekDays.h"
using namespace std;

void main()
{
    DAYS a=MON; //=0
    DAYS b=TUE; //=1
    cout<< +a       <<endl;
    cout<< +b       <<endl;
    cout<< +(a,b)   <<endl;
    cout<< (a+b)    <<endl;
    cin.get();
}

Output is
Unary+ called
3
Unary+ called
4
Unary+ called
4
Binary+ called
1

Why is +(a,b) evaluated as unary operator +b ? I've failed to explain this.
Link to relevant thread Operator overloading .
I'm Using VisualStudio 2012.

A: With (a,b) you happen to invoke the odd "comma" operator, which evaluates first a, then b, and finally returns b.
You could call your operator by spelling it out as operator+(a,b). (Here the comma is a separator for the parameters, and not the comma operator).

A: Please take a look at the link http://en.cppreference.com/w/cpp/language/operator_arithmetic
unary plus, aka +a
T::operator+() const;
T operator+(const T &a);

addition, aka a + b
T::operator+(const T2 &b) const;
T T operator+(const T &a, const T2 &b);

With your overloaded operator+(a,b) you should get at least this warning:
warning: left operand of comma operator has no effect [-Wunused-value]


text:
Q: Are there other ways to introduce a new property/method to a variable in django template? I am looking at one of sentry's templates and it is giving me an error INVALID CONTEXT VARIABLE: MESSAGE.GET_STATUS_DISPLAY. The template looks like this:
<span class="status status-{{ message.status }}">
    {{ message.get_status_display }}
</span>

The django docs says that when it encounters a dotted name after a variable like message.get_status_display, it will resolve it in this order:

*

*Dictionary lookup

*Attribute lookup

*Method lookup

*List-index lookup

I have scoured the source code and I have discovered that message is a model object and it doesn't contain anything resembling get_status_display. It, however, has a message.status. Can someone provide hints on how the dispatch to get_status_display is implemented ?

A: status has choices, therefore get_status_display() is created by the ORM.


text:
Q: how to explain this code : if (strstr(line, *argv) != EOF) != except Its in K&R.
#include <stdio.h>
#include <string.h>
#define MAXLINE 1000

int getline(char *line, int max);

int main(int argc, char *argv[])
{

     char line[MAXLINE];
     long lineno = 0;
     int c, except = 0, number = 0, found = 0;

     while(--argc > 0 && (*++argv)[0] == '-')
        while(c = *++argv[0])
          switch(c) {
             case 'x':
                  except = 1;
                  break;
             case 'n':
                  number = 1;
                  break;
             default:
                  printf("find: illegal option %c\n", c);
                  argc = 0;
                  found = -1;
                  break;
          }
    if (argc != 1)
        printf("Usage : find -x, -n, pattern\n");
     else
    while(getline(line, MAXLINE) > 0) {
       lineno++;
        if ((strstr(line, *argv) != NULL) != except) {
           if (number)
              printf("%ld", lineno);
           printf("%s", line);
              found++;
      }
    }
}

I have no idea what this statement means: if (strstr(line, *argv) != EOF) != expect) there was some mistakes before and i correctd it.
However, when i try to understand it ,i have some troubles.
Here is what i think: find -x -n. So, the argc = 3. argv[0] = find. argv[1] = -x. argv[2] = -n. argv[3] = NULL. After the first while loop, shouldn't the argc = 0. so i am confused.

A: This code is wrong in many ways. But specially because it is comparing a pointer to an integer. The strstr() function returns a pointer, and EOF is an integer. The parameters are fine, if the comparison was made with NULL instead it would be testing if the first value argv points to, contains the text in line. Remember that the argv can be incremented to point to the next element in each iteration.

A: The example is from K&R 2nd Edition, section 5.10 "Command-line Arguments".
The example is given to illustrate strstr(), pointer handling, and adding some options to a command line program:

The standard library function strstr(s,t) returns a pointer to the
  first occurrence of the string t in the string s, or NULL if
  there is none. It is declared in <string.h>.
The model can now be elaborated to illustrate further pointer
  constructions. Suppose we want to allow two optional arguments. One
  says "print all the lines except those that match the pattern;" the
  second says "precede each printed line by its line number."

To answer your specific question about the meaning of:
if ((strstr(line, *argv) != NULL) != except)  // note: NULL, not EOF

The answer is that the strstr() call will return a non-NULL pointer if the string passed as a command line argument is found in the line and NULL otherwise. So the sub-expression
(strstr(line, *argv) != NULL)

evaluates to:
true    - argument is found (a 'match')
false   - argument is not found (a 'non-match')

The variable except is set via an option with the following meaning:
true    - print non-matching lines
false   - print matching lines (the default)

So, the full expression determines if the line should be printed or not according to whether it contains the argument and whether the option to print matching or non-matching lines is given.

A: This code is wrong. Though I don't have K&R, I rewrite it.
#include <stdio.h>
#include <string.h>

#define MAXLINE 1000

// Dummy Array
static char fooString[2][MAXLINE] = {
   "abcdefg\n",
   "hijklm\n"
};

// dummy function
int myGetline(char **line, int maxline) {
    static int i = 0;
    char *tmp = fooString[i++];
    if (strlen(tmp) > maxline) {
        *line = '\0';
        return 0;
    }
    *line = tmp;
    return strlen(tmp);
}

int main(int argc, char *argv[]) {
    // Mod Start ---
    //char line[MAXLINE];
    char *line = NULL;
    // Mod End   ---
    long lineno = 0;
    size_t length = 0;
    int c, except = 0, number = 0, found = 0;
    // Mod start ---
    //while (--argc > 0 && (*++argv)[0] == '-') {
    // equals ...
    int idx_i = 0;
    int idx_j = 0;
    while (--argc > 0 && argv[++idx_i][0] == '-') {
    // Mod End   ---
        // Mod start ---
        //while (c = *++(argv[0])) {
        // equals ...
        idx_j = 0;
        while (c = argv[idx_i][++idx_j]) {
        // Mod End   ---
            switch (c) {
            case 'x':
                except = 1;
                break;
            case 'n':
                number = 1;
                break;
            default:
                printf("find : illigal option %c\n", c);
                found = -1;
                break;
            }
        }
    }
    if (argc != 1) {
        printf("Usage: find -x -n pattern\n");
    }
    else {
        while (myGetline(&line, MAXLINE) > 0) {
            // Mod start ---
            //if ((strstr(line, *argv) != NULL) != except) {
            // equals ...
            if ((strstr(line, argv[idx_i]) != NULL) != except) {
            // Mod End ---
                if (number) {
                    printf("%ld:", lineno);
                }
                printf("%s", line);
                found++;
            }
        }
    }
    return (found ? 0 : -1);
}

Complie:
$ gcc -o find.exe find.c

Result:
$ ./find.exe -n -x abc
0:hijklm

X means EXCEPT, not expect...
if ((strstr(line, *argv) != NULL) != except) equals the code below.
if ((strstr(line, *argv) != NULL) {
    if (except) {

A: Add the pattern in the end of 'find -x -n'. if missed, then argc=0, it will print the sentence: Usage: find -x -n pattern.


text:
Q: URL Start menu entry missing on Windows 10 although installed I have a "normal" Setup and a "Pro" Setup of the same application. They have many things in common, so I use an
#include "CommonThings.iss"

Both versions can be installed in parallel, because they have a different AppId.
In the common definition, I have
[Icons]
Name: {group}\Online documentation; Filename: "http://example.com/"

but only one of them shows up in the Windows Start menu:

Looking at the file system under
C:\ProgramData\Microsoft\Windows\Start Menu\Programs\Example
C:\ProgramData\Microsoft\Windows\Start Menu\Programs\Example Pro

the Online Documentation Internet Shortcut is available for both programs.
To me, it seems like a bug of Windows, since I don't do any fancy stuff with my installer, just copy some files.
I have tried:

*

*I am not suffering from the 512 start menu items limitation, since I test my installer on a clean Windows 10 with no other apps installed (except the ones that come with Windows itself).

*The problem persists after a restart

Is there a fix possible in Inno Setup for this kind of issue?

A: I can reproduce your problem too on Windows 10 (not on Windows 7).
Windows 10 seems to filter identical URLs form the Start menu.
A solution seems to be to make the URLs unique, e.g. by:
[Icons]
Name: {group}\Online documentation; \
    Filename: "https://www.example.com/?uniq={#SetupSetting("AppId")}"

Though note that it's against Windows 10 guidelines to put more than one shortcut per application to the Start Menu. Links to open documentation and similar, should now be contained in the application itself only.


text:
Q: Django save() method filling a certain field with None when saving with same id I have this model.
class Country(models.Model):

countryname = models.TextField(null=True)
countryincharge = models.ForeignKey(Employees, on_delete=models.CASCADE,null = True)
createdby = models.TextField(null=True)
createdtime = models.TextField(null=True)
modifiedby = models.TextField(null=True)
modifiedtime = models.TextField(null=True)
deletedby = models.TextField(null=True)
deletedtime = models.TextField(null=True)
isdeleted = models.IntegerField(null=True)
tenantid = models.TextField(null=True)

And create and update functions as following.
#Create
def countrycreate(request):

if request.user.is_authenticated:

    if request.method == 'POST':
        id = request.POST.get('id')

        modelwithdata = Country(
            countryname=request.POST.get('countryname'),
            countryincharge_id=request.POST.get('countryincharge'),
            createdtime = timezone.now(),
            createdby = request.user.id

        )
        if Country.objects.filter(countryname=request.POST.get('countryname')).exists():
            messages.info(request, 'Country already exists!')
            return HttpResponseRedirect(request.META.get('HTTP_REFERER'))

        else:
            modelwithdata.save()

        return redirect('/admin/countrylistview')

 #Update
 def countryupdate(request):

if request.user.is_authenticated:

    if request.method == 'POST':
        id = request.POST.get('id')
        modelwithdata = Country(
            countryname=request.POST.get('countryname'),
            countryincharge_id=request.POST.get('countryincharge'),
            modifiedtime = timezone.now(),
            modifiedby = request.user.id
        )

        modelwithdata.id = id
        modelwithdata.save()
        return redirect('/admin/countrylistview')

The problem is when a record is created the createdtime value is saved as intended. But when running the update function the createdtime value is set to None. For unknown reasons. Other fields are working fine. The db is SQLite. Same behaviour happens when use DateTimeField(auto_now_add=True, null=True) and DateTimeField(auto_now=True, null=True).

A: The problem is you are creating a new object, first grab the original and change only what is required.
#Update
// Change this to get the object
modelwithdata = get_object_or_404(Country, pk=id)

// Change only the fields you need to
modelwithdata.countryname=request.POST.get('countryname')

modelwithdata.countryincharge_id=request.POST.get('countryincharge')
modelwithdata.modifiedtime = timezone.now()
modelwithdata.modifiedby = request.user.id

//Dont need this
//   modelwithdata.id = id
//Save the new model
modelwithdata.save()

A: You should use PUT or PATCH method to update the data instead of POST
For your code we can also use .update()
# Update

def countryupdate(request):
    if request.user.is_authenticated:
        if request.method == 'POST':
            Country.objects.filter(pk=request.POST.get('id')).update(
                countryname=request.POST.get('countryname'),
                countryincharge_id=request.POST.get('countryincharge'),
                modifiedtime = timezone.now(),
                modifiedby = request.user.id
            )
            return redirect('/admin/countrylistview')


text:
Q: Django Rest Framework Tokens Are Not Being Automatically Generated I am (trying) to use Django Rest Framework's Token-based authentication. I have the following in my app's models.py
from django.db.models.signals import post_save
from django.dispatch import receiver
from rest_framework.authtoken.models import Token
from django.conf import settings

@receiver(post_save, sender=settings.AUTH_USER_MODEL)
def create_auth_token(sender, instance=None, created=False, **kwargs):
    if created:
        Token.objects.create(user=instance)

Whenever I create a new account (either through 'createsuperuser' or by using my registration form), the user is correctly added to the 'auth_user' table. However, although the 'authtoken_token' table is created, there is nothing added to it. This leads me to believe that my @reciever may not be working properly.
I can however manually create tokens using the Django shell. Those tokens will be properly added to the authtoken_token table.
Any help on this would be greatly appreciated,
Thanks

A: Things to check:

*

*Is the receiver even running? Add a print or log inside to check that it is called in the first place

*If AUTH_USER_MODEL is not defined, you may need to use get_user_model() instead

*Make sure that this code is inside the models.py file of an app that is in settings.INSTALLED_APPS
I've used DRF for several years and never had this problem. One of the above is likely your culprit.


text:
Q: Tensorflow 2 TextVectorization - how to get the word frequencies Question
Is word frequency available from the TextVectorization instance? TextVectorization documentation says it determines the frequency of each string but it looks there is no method to get how many times a word appeared in the corpus it adapted.

it will analyze the dataset, determine the frequency of individual string values, and create a 'vocabulary' from them.

If the TextVectorization instance has already analysed and has the word frequencies, we can use them for statistics e.g. for negative sampling. It can be done but prefer using already available information especially the corpus is large.
from collections import Counter
corpus = "..."
total = len(words:=corpus.split())
probabilities = {word: (count / total) for (word, count) in Counter(words).items()}


text:
Q: Как перевести код с pyton на php Есть код на python
data = {"test": "123"}
digest = hashlib.sha256(json.dumps(data).encode()).digest()
base64 = base64.b64encode(digest).decode("utf-8")
// base64 | FU/k0/TF9apOoP+3fRjXg1Kxe2ME5dD7vVOQgOip3LA=

Как его перевести на php?
Пишу такой код:
$data = ["test" => "123"];
$base64 = base64_encode(hash('sha256',json_encode($data),true));
// base64 | QPlNWg2hr7S0jLVHLdBEBxI9vWCgyKswzysAscnqQvQ=


text:
Q: Jinja2 not work on flask/glitch.me deployment I have a deployment of a tiny Flask app on Glitch. It seems to be working... sort of. However, the Jinja2 template engine is clearly not working, since all Jinja2 tags are being read into the browser as text. The application, which I have up on my GitHub page, works fine on the localhost. Can I fix this somehow?

A: I'm not a python expert but while your glitch project has the same code as localhost, your local machine is executing the code through a different path. In this case because there are no instructions for Glitch to start your project from mesostic.py it's just treating your project as a static website. (hence why the template tags are just being rendered out as text).
It might help to look at other python projects on glitch to get a sense of how to execute your .py file. e.g. checkout start.sh on https://glitch.com/edit/#!/python3-morepath. I'm not sure but you may also need a requirements.txt to tell Glitch that this is a python project.
Hope this gives you a place to start debugging from

A: Seems like this was not a problem with earlier versions of Flask and Python.

Firstly, adding the following  debug  option in the  server.py  file.

app.debug = True

Secondly, add some code as follows:

@app.after_request
def apply_kr_hello(response):
    """Adds some headers to all responses."""
    ...
    response.headers['Cache-Control'] = 'no-cache'
    return response

Thirdly, do a  Ctrl-Shift-R  on the specific browser tab where your application is being rendered.
That is it! Now, when you make changes to static file, they should be reflected in your app.
I presume one might also benefit from reading https://stackabuse.com/serving-static-files-with-flask as well.


text:
Q: ClearDB on Heroku throws an error when running a migration to create a new table that has a `details` field of type `json` I am running a Rails 5.2.2 and ruby 2.6.3 app on Heroku backed by ClearDB database.
NOTE: Locally this all works fine
my gem file has the mysql2 version as such:
gem 'mysql2', '>= 0.4.4', '< 0.6.0'
When I attempt to run a migration to create a new table that has a details field of type json it fails with a syntax error.
Mysql2::Error: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'json'
Removing the details field of type json and re-running the migration succeeeds.
Here is an example of the contents of the migration.
class InitTables < ActiveRecord::Migration[5.2]
  def change
    create_table :services do |t|
      t.string :public_id, null: false, index: { unique: true }
      t.json :details
    end
  end
end

This is the error message:
Mysql2::Error: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'json'

A: I faced same issues with ClearDB (Ignite plan). Switched to JAWS_DB (free plan) and migration was run successfully.

A: According to the ClearDB support, 5.7 version of MySQL is required to be compatible with my migration to use a field of json type.
The Heroku Ignite, Punch, Drift and Scream plans shared resource plans are currently only available on clusters running 5.5 or 5.6 (5.6 in Europe) versions of MySQL and I AM ON the Heroku Ignite plan.
To solve this issue I'll need a dedicated resource(instance) plans that can be configured to use 5.5, 5.6, or 5.7 version of MySQL.


text:
Q: What is the power consumption of HP Proliant SAS 15k hard disks? I have been looking at improving the power footprint of our server architecture and one way to achieve this might be to replace our current 15k SAS HDDs with SSD drives.
However, I have been unable to find the typical power consumption figures of these drives from the HP documentation.
What is an average power consumption of a 2.5" 15k SAS drive?

A: Seems like a 2,5" 15k SAS disk would use about 9 watt on average, compared to SSD which use almost nothing at idle and 2watt at load
http://www.seagate.com/gb/en/internal-hard-drives/enterprise-hard-drives/hdd/enterprise-performance-15k-hdd/#specs


text:
Q: VB.NET Temporarily modify loop's starting value? Suppose I have the following code:
For intA As Integer = 1 To 5
    For intB As Integer = 1 To 50
        For intC As Integer = 1 to 100
            ...
        Next intC
    Next intB
 Next intA

I want to save progress to a db table so that I can continue later on. So, suppose intA is currently 2, intB is currently 14 and intC is currently 54.
Those get saved in a table like so:
 intA     intB     intC
========================
  2        14       54

Simple enough.
When I want to continue, how can I go about setting each loop to the current, saved value?
I can't simply set the initial loops' starts to the saved values, because that would alter the entire loops' "run".
I could probably use a flag to signal a value has been stored and do something like this:
booSavedC As Boolean = IsSavedC  'This resides outside all loops, so "single shot"

For intC As Integer = 1 to 100
    If booSavedC Then
        intC = GetSavedC   'or intC = GetSavedC + 1
        booSavedC = False
    End If

    ...
Next intC

However, this renders checking the booSavedC variable every single interation, as well as checking the outer loops' (booSavedB and booSavedA) variables too, etc.
Is there a better, less "expensive" way?

A: Based on my comment above:

You would need to use variables for the start value of the loop
  counters and you can set them to the values from the database. Inside
  each loop, simply set the relevant variable to 1, so the loop will
  start at 1 again on the next iteration of the parent loop.

here is an example:
Module Module1

    Sub Main()
        Console.WriteLine("iMin=1, jMin=1, kMin=1")
        RunLoops(1, 1, 1)

        Console.WriteLine()

        Console.WriteLine("iMin=2, jMin=3, kMin=4")
        RunLoops(2, 3, 4)

        Console.ReadLine()
    End Sub

    Sub RunLoops(iMin As Integer, jMin As Integer, kMin As Integer)
        For i = iMin To 5
            iMin = 1

            For j = jMin To 5
                jMin = 1

                For k = kMin To 5
                    kMin = 1

                    Console.WriteLine($"i={i}, j={j}, k={k}")
                Next
            Next
        Next
    End Sub

End Module

You don't necessarily need to reset iMin as that loop is only run through once.  It's there for completeness though.
EDIT:
Based on the comment below by @the_lotus and the fact that resetting the start value for the outermost loop is unnecessary, here's some modified code:
Sub RunLoops(iMin As Integer, jMin As Integer, kMin As Integer)
    For i = iMin To 5
        For j = jMin To 5
            For k = kMin To 5
                Console.WriteLine($"i={i}, j={j}, k={k}")
            Next

            kMin = 1
        Next

        jMin = 1
    Next
End Sub


text:
Q: Deserialize JSON Date to C# Object with DateTime Returning 01/01/0001 I'm using Newtonsoft to translate a JSON string that presents a date
"[{\"Name\":\"Learning\",\"Start Date\":\"2022-03-01\",\"End Date\":\"2022-04-30\"]"

And I want to deserialize it to this custom object
public class MyObject
{
    public string Name { get; set; }
    public DateTime StartDate { get; set; }
    public DateTime EndDate { get; set; }
}

By doing this
var myObject = JsonConvert.DeserializeObject<List<MyObject>>(jsonRecords,
            new IsoDateTimeConverter { DateTimeFormat = "yyyy-MM-dd" });

But the StartDate and EndDate objects are always coming out as 01/01/0001, while I'd want them to show in this format: dd/MM/yyyy
I also tried to use new IsoDateTimeConverter { DateTimeFormat = "dd/MM/yyyy" } but that didn't work either (and I think you need to use the format in which the date is coming from json?)
What am I doing wrong?

A: Add [JsonProperty("Start Date")] above public DateTime StartDate { get; set; } and similar above public DateTime EndDate { get; set; }:
public class MyObject
{
    public string Name { get; set; }
    [JsonProperty("Start Date")]
    public DateTime StartDate { get; set; }
    [JsonProperty("End Date")]
    public DateTime EndDate { get; set; }
}

The problem was that json property names ('Start Date') and class property names ('StartDate') were not the same so it defaulted to 01/01/0001.
This will work without the need for IsoDateTimeConverter.

A: Well, if your properties don't match the JSON properties, that's normal.
You have spaces between "Start Date" so you need to use JsonProperty attribute to specify the JSON property that you want to use:
public class MyObject
     {
        public string Name { get; set; }

        [JsonProperty(PropertyName ="Start Date")]
        public DateTime StartDate { get; set; }

        [JsonProperty(PropertyName = "End Date")]
        public DateTime EndDate { get; set; }
    }

You see that 01/01/0001 because it's the Date time default and your values are not mapped.


text:
Q: Set date to yesterdays date I have this piece of code which sets the date to 360 days later,
I would like to know how to change this piece of code to make the date yesterdays date, 28/3/2016
$tmpdate = new DateTime(date("Y-m-d"));
            $tmpdate->add(new DateInterval('P360D'));
            $Available = $tmpdate->format('Y-m-d');

A: You can do that:
date("Y-m-d", strtotime("-1 day")); // yesterday (based on server date)

For any other date you can use strtotime:
strtotime("30-12-9999");

I hope it helps you!
Regards.

A: Yesterday:
echo date("Y m d h:i",time() -60*60*24); // 24 hours ago.
echo date("Y m d",time() -60*60*24); // yesterday as in date.

As mark pointed out below I did not think of daylight savings. So...
$date = new DateTime(null, new DateTimeZone('Europe/Stockholm')); // Change to suit
$Heretime = $date->format('H');
$date->setTimezone(new DateTimeZone('UTC'));
$Difftime = $date->format('H') - $Heretime;

echo date("Y m d h:i",time() -60*60*(24-$Difftime)); // 24 hours ago in UTC.
echo date("Y m d",time() -60*60*(24-$Difftime)); // yesterday as in date in UTC.

And from there you can convert it back I guess... Or maybe I'm completely lost?


text:
Q: Dynamically change localization in Polymer app I have a Polymer app with many templates, in which I would like to manage localization. I use app-localize-behavior for that. I found a nice way of managing localization from a single file. The solution proposed there uses behaviors, and requires little additions in each template, with a unique json data file.
My problem is that I would like to be able to change the language dynamically, and probably store it in a app-localstorage-document element, which I manage from another file. How can I set this language property from outside this file?
<link rel="import" href="../../bower_components/polymer/polymer.html">
<link rel="import" href="../../bower_components/app-localize-behavior/app-localize-behavior.html">

<script>
  MyLocalizeImpl = {
    properties: {
      language: {
        value: 'fr'
      }
    },

    attached: function() {
      this.loadResources(this.resolveUrl('../locales.json'));
    },
  };

  MyLocalize = [MyLocalizeImpl, Polymer.AppLocalizeBehavior];
</script>

A: OK I adapted the app-localize-behavior demo code. The template which changes the language has to override the language property, including "notify: true":
  properties: {
    language: {
      value: 'en',
      type: String,
      notify: true
    },
  },

Then I bound all other elements' language property with this:
<element language="{{language}}"></element>

Templates which use localize must of course link the localize script:
<link rel="import" href="localize.html">

… and add the behavior in the script part:
Polymer({
  is: "my-page",

  behaviors: [
    MyLocalize
  ]

Bonus: how to use a different json file for every language: https://abendigo.github.io/2016/08/03/lazyloading_localization.html


text:
Q: Javascript array in combo boxes I have been given an array in the following format and need to put it into two drop down boxes one with make and the other with model based on the first selection. (the actual array is huge, but I have just included the first few)
var aMember = [{
    "Make": "other",
    "Models": ["other"]
}, {
    "Make": "Boat",
    "Models": ["Over 21 ft.", "Under 21 ft."]
}, {
    "Make": "Motorcycle",
    "Models": ["Over 600cc", "Under 600cc"]
}];

I need to have a make combo box with Other, Boat and Motorcycle, which when selected populates the second combo box with the options.
I have done almost no JavaScript before, but have tried the following, which does not work.
I really don't know if I am anywhere near to what I need.
<html>
<head>
<script>
var cars =[{"Make":"other","Models":["other"]},{"Make":"Boat","Models":["Over 21 ft.","Under 21 ft."]},{"Make":"Motorcycle","Models":["Over 600cc","Under 600cc"]}];

function populateDropdown(drop, items) {
   drop.empty();
   for(var i = 0; i < items.length; i++) {
      drop.append('<option value=' + i + '>' + items[i].Make + '</option>');
   }
   drop.show();
}

populateDropdown( $('#Makes'), cars );

$('#Models').change(function() {
   var modelIndex = $(this).val();
   var model = Models[modelIndex ];

   populateDropdown( $('#Models'), cars.Models);

});

</script>
</head>
<body onload = "populateDropdown( $('#Makes'), cars );">
<form>

MAKE:
<select name = 'Makes'>
</select>
MODEL:
<select name = 'Models'>
</select>

</select>
</form>
</body>
</html>

Thanks

A: the $(#Makes) searches for the ID! not for the name! change the select name='Makes' to id='makes'

A: Give this a try:
<html>
<head>
<script>
var cars =[{"Make":"other","Models":["other"]},{"Make":"Boat","Models":["Over 21 ft.","Under 21 ft."]},{"Make":"Motorcycle","Models":["Over 600cc","Under 600cc"]}];

function populateDropdown(drop, items) {
   drop.empty();
   for(var i = 0; i < items.length; i++) {
      drop.append('<option value=' + i + '>' + items[i].Make + '</option>');
   }
   drop.show();
}

$(document).ready(function() {
    populateDropdown( $('#makes'), cars );

    $('#makes').change(function() {
       var index = $(this).val();
       var make = cars[index];

       populateDropdown( $('#models'), make.Models);
    });
});

</script>
</head>
<body>
<form>

MAKE:
<select id="make">
</select>

MODEL:
<select id="models">
</select>

</form>
</body>
</html>

A: *

*You can use $.grep to filter out the current make, and then fetch the models of that make.

*You can use $.map to map the array with all data to an array of makes.

*$.each can be used.

*You can use $("<option>").val(...).text(...) to build the option a little cleaner.

*You need $(function() {...}) to wait until the DOM is ready.

*drop.show() is not needed since both selects are already visible

*You're populating Models on Models's change event. I think you mean to run that on Makes's change event.

*You're using name instead of id. Also you should not use spaces around the = in HTML attributes.

This is a corrected version: http://jsfiddle.net/zJTnw/1/.
$(function(){
    var cars = [
        {"Make":"other",
         "Models": ["other"]},

        {"Make":"Boat",
         "Models": ["Over 21 ft.","Under 21 ft."]},

        {"Make":"Motorcycle",
         "Models": ["Over 600cc","Under 600cc"]}
    ];

    function populateDropdown(drop, items) {
        drop.empty();

        $.each(items, function(i, v) { // `i` is index, `v` is element
            drop.append($("<option>").val(v).text(v));
        });
    }

    populateDropdown($('#Makes'), $.map(cars, function(x) {
        return x.Make; // map `cars` to an array of makes
    }));

    $('#Makes').change(function() {
        var make = $(this).val();

        var item = $.grep(cars, function(x) { // get item of this make
            return x.Make === make;
        });

        populateDropdown($('#Models'), item[0].Models); // populate with models
    });
});


text:
Q: Use union of arg types instead of supertype for generic variadic function I have a generic function one_of that may return any of its (variable) arguments. Its return type may be the supertype of all of its arguments; however, I'd like to annotate its usage locations with the union of their types instead.
from typing import TypeVar
import random

T = TypeVar("T")

def one_of(*args: T) -> T:
    return random.choice(args)

def int_or_str() -> int | str:
    return one_of(1, "one")

This is the error mypy provides:
vararg_type.py:11: error: Incompatible return value type (got "object", expected "Union[int, str]")
Found 1 error in 1 file (checked 1 source file)

I figured that I can cast the return value of one_of at each of its call sites, but is there another way to better use the typechecker?

A: I don't know if this is "better", but mypy only uses object because it's chosen not to default to int | str. So you could tell it to use int | str. Just hinting one is sufficient
def int_or_str() -> int | str:
    one: int | str = "one"
    return one_of(1, one)

There may be a neater way of writing that.


text:
Q: discord.js TypeError: can not read property 'id' of undefined & Making a fail system So this command worked just a second ago then the next a error came out of nowhere. Is there a fix to this?
Here is the code
run: async (client, message, args) => {
    const cooldown = cooldowns.get(message.author.id);
    if (cooldown) {
        const remaining = humanizeDuration(cooldown - Date.now(),{ units: ['m', 's'],round: true });
        let cEmbed = new MessageEmbed()
        .setColor("RANDOM")
        .setTitle("Slow down, cmon!")
        .setDescription(`You will be able to work in \`${remaining}\` just you wait!\n\nWhile you wait why not follow our [Twitter](https://twitter.com/switchoffical)`)
        return message.channel.send(cEmbed)
        .catch(console.error);

    } else {
        let member = message.mentions.users.first() || client.users.cache.get(args[0]);
        let user = message.mentions.members.first()
        let targetuser = await db.fetch(`money_${user.id}`) // fetch mentioned users balance
        let author = await db.fetch(`money_${message.author.id}`) // fetch authors balance
        let uBalance = balance[member.id].balance;
        let TuBalance = balance[user.id].balance;
        let random = Math.floor(Math.random() * 200) + 1; // random number 200-1, you can change 200 to whatever you'd like
        let curBal = balance[message.author.id].balance
        balance[message.author.id].balance = curBal + random;
        let crurBal = balance[message.author.id].balance
        balance[user.id].balance = crurBal - random;

        if (!user) {
            return message.channel.send('Sorry, you forgot to mention somebody.')
            if (uBalance < 500) { // if the authors balance is less than 250, return this.
                return message.channel.send(':x: You need at least 500$ to rob somebody.')
            }

            if (TuBalance < 0) { // if mentioned user has 0 or less, it will return this.
                return message.channel.send(`:x: ${user.user.username} does not have anything to rob.`)
            }

            message.channel.send(`${message.author} you robbed ${user} and got away with ${random}!`)

            cooldowns.set(message.author.id, Date.now() + 900000);
            setTimeout(() => cooldowns.delete(message.author.id), 900000);

            db.subtract(`money_${user.id}`, random)
            db.add(`money_${message.author.id}`, random)
        }
    }
}

The error that is made is
(node:7574) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'id' of undefined
at Object.run (/app/commands/economy/rob.js:37:47)
at module.exports (/app/events/guild/message.js:10:33)
    at Client.emit (events.js:196:13)
    at MessageCreateAction.handle (/rbd/pnpm-volume/5936e237-314d-4884-9101-9ef8b43cdb53/node_modules/.registry.npmjs.org/discord.js/12.2.0/node_modules/discord.js/src/client/actions/MessageCreate.js:31:14)
    at Object.module.exports [as MESSAGE_CREATE] (/rbd/pnpm-volume/5936e237-314d-4884-9101-9ef8b43cdb53/node_modules/.registry.npmjs.org/discord.js/12.2.0/node_modules/discord.js/src/client/websocket/handlers/MESSAGE_CREATE.js:4:32)
    at WebSocketManager.handlePacket (/rbd/pnpm-volume/5936e237-314d-4884-9101-9ef8b43cdb53/node_modules/.registry.npmjs.org/discord.js/12.2.0/node_modules/discord.js/src/client/websocket/WebSocketManager.js:386:31)
    at WebSocketShard.onPacket (/rbd/pnpm-volume/5936e237-314d-4884-9101-9ef8b43cdb53/node_modules/.registry.npmjs.org/discord.js/12.2.0/node_modules/discord.js/src/client/websocket/WebSocketShard.js:436:22)
    at WebSocketShard.onMessage (/rbd/pnpm-volume/5936e237-314d-4884-9101-9ef8b43cdb53/node_modules/.registry.npmjs.org/discord.js/12.2.0/node_modules/discord.js/src/client/websocket/WebSocketShard.js:293:10)
    at WebSocket.onMessage (/rbd/pnpm-volume/5936e237-314d-4884-9101-9ef8b43cdb53/node_modules/.registry.npmjs.org/discord.js/12.2.0/node_modules/discord.js/node_modules/ws/lib/event-target.js:125:16)
    at WebSocket.emit (events.js:196:13)
(node:7574) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
(node:7574) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

Now to my next question for the fail system I want it to subtract $500 away from the author and give the 500 to whom they were robbing from. I have the code but it broke the command and there is just too much going on in the code where the system will not fit that I have. SO I completely trashed the fail portion. For the fail rate it is pretty high and there is about a 10% chance you will actually rob someone. is there a efficient way to do this with the big code I have.

A: There are 2 issues here :
Issue 1:
By using
let user = message.mentions.members.first()`

The variable user can be undefined if there are no mentions in the message.
You were right to check for !user, however, you forgot to move the line just before :
let user = message.mentions.members.first()`
// [...]
balance[user.id].balance = crurBal - random;
if (!user) {

Should be :
let user = message.mentions.members.first()`
// [...]
if (!user) {
    balance[user.id].balance = crurBal - random;

Issue 2:
Keep in mind that a message does not always have an author. A webhook message has no author, as you can see in the documentation with the return type being ?User (? here means that it can also be null). Here is the related code.
So you also need to check for an author to the recieved message.


text:
Q: How to use arrow functions with main class 'this' properties? I was racking my brain to make an algorithm in nodeJS work. I got a file with that function bellow where some properties are tied to this and some functions are tied to prototype.
function Main(controller) {
        this.tipo = "string";
        this.controller = controller;
        this.debug = controller.debug;
        this.db = controller.db;
        this.util = require('util');
        this.utils = require('../utils.js');
        this.moment = require('moment');
}

Main.prototype.funcX = (dados) => {
        // doing stuffs
}

Somehow, the properties of this were not being recognized in functions tied to prototype and there was always an TypeError.
Then, I've found a solution after reading this question, where I noticed that arrow function has its own this context. Then, changing this code snippet
Main.prototype.funcX = (dados) => {
    // doing stuffs
    console.log(typeof this.db) // TypeError: cannot read property 'info' of undefined
};

To this
 Main.prototype.funcX = function (dados) {
     // doing stuffs
     console.log(typeof this.db) // prints my db instance
 };

made everything works well.
But I do not want to use function keyword to these functions at all.
Q: What is the best way to use arrow functions accessing the Main's this properties?

A: There is literally no way to access the correct this in an arrow function attached to a constructor prototype.
"use strict";
function Main() {};
Main.prototype.foo = () => console.log(this);
var m = new Main();
m.foo(); // undefined
m.foo.call(m); // still undefined
m.foo.bind(m)(); // you get the idea

Arrow functions' this is closed over in the lexical scope like a normal var, and in this case it's the global (or top-level module) scope. If you remove the "use strict" you'll just get window instead of undefined.
You have a few alternatives:
Don't define on the prototype (don't actually do this):
function Main() {
  this.foo = () => console.log(this);
}

m = new Main();
m.foo(); // correct this!

This works because the arrow function closes over the correct this in the lexical scope of the constructor. But here you lose the advantages of having only one function object shared between instances (since you aren't using the prototype).
Use a normal function
That's already posted in your question, so no need to repeat.
Define a class with method
class Main {
  foo () {
    console.log(this);
  }
}

m = new Main();
m.foo(); // correct this

A: Well, as you said, you can't use context with arrow functions. I guess that the next best bet would be to create an enclosed scope to use inside the arrow function:
{ // that
    let db = something;

    Main.prototype.funcX = (dados) => {

        console.log(db + "is only available from inside that block");

    };
}

But still, as pointed out in the comments, you're missing the point of arrow functions.


text:
Q: Minor difficulties with Ajax and PHP interaction I working in CodeIgniter and I am trying to spit out all of the items I have in a table and order them as they should be using the dropdown. I want it to happen without page reload and without submit buttons, so I am using this jQuery function to make  immediately react, when it is changed:
$(document).ready(function() {
    $(".order-by-select").click(function() {var orderValue = this.value;
    $.post("<?php echo base_url() ?>welcome/index", {val: orderValue}, function(data) {
        alert(data);
    });
});

Inside you can see the $.post method, with wich I am trying to send the data to php script (orderValue).
After that, I am getting an alert (not even sure, why do I need it (Maybe to check if everything is ok there))
In PHP, I am receiving the chosen select option and assigning a variable ($data['people']) to the results of MySQL query (that is placed in the model) to  be able to access it withing the view. This - $_POST['val'] represents, how can I order the list (select * from people order by $theorder" ($theother is just a variable inside the query function. It recieves the value of $_POST['val'])).
if(isset($_POST['val'])) {
    $data['people'] = $this->database->listPeople($_POST['val']);
    exit;
}

After that I recieve this variable in the view and I am running foreach loop to take different parts of the array(name of the person, his age, etc..) and placing it in the way they should be.
The problem is - if I do that without ajax, when I have static order by value - everything works fine. I did not mean that was the problem :D, the problem basically is that is doesn't work with ajax... I was trying to recieve the array in the js callback and create a layout using
$.each(eval(data), function() {
  $('#container').text('
' + eval(res).name + '
');
});

But that was also a failure...
How should I organize and create my code to make everything work properly?
I am kinda new to Ajax, so I hope I'll really learn how to do that from you guys. I already searched through the whole internet and have seen a lot of ajax tutorials and other kind of material (e. g. StackOverflow), but I still can't get, how can I do all of that in my particular situation. I have wasted already about 12 hours trying to solve the problem and couldn't do that, so I hope You will tell me if there is any useful salvation.
Thank you for your consideration.

A: Hi the skinny is you need 3 parts to make ajax work,

*

*serverside code to generate the page

*ajax ( clientside ) to make the call and respond

*seperate serverside to receive it.

Also it will be easier to replace the table completely then to pick out elements.  But that is up to you.
So say we have the page with our ajax call

Now you seem to have some json response I'll assume you get this from the alert above;
 [{"id":"1","name":"Nick","age":"18"},{"id":"2","name":"John","age":"23"}]

I'll also assume that this comes from something like
echo json_encode( array( array('id'=>1, ...), array('id'=>2 ...) .. );

It's important before doing the echo that you tell the server that this is json, you do this using a header, but you cannot output anything before the header, and after the json header all output must be in the json format or it wont work, it's like telling the browser that this is html, or an image etc. what the content is.
  Header("Content-Type: application/json");
  echo json_encode( ....

You can get away without doing this sometimes, but often you'll need to use eval or something, by telling the browser its json you don't need that.  Now doing an alert is great and all but if you see the string data [{"id": .. your header is wrong, you should get something like [object] when you do the alert.
No once we have a factual Json object we can make use of all that wonderful data

This should loop through all the data and do 2 alerts, first the id then the name, right.  Next it's a simple matter of replacing the content using .text() or .append()