text:
Q: What does the Akaike Information Criterion (AIC) score of a model mean? I have seen some questions here about what it means in layman terms, but these are too layman for for my purpose here. I am trying to mathematically understand what does the AIC score mean.
But at the same time, I don't want a rigor proof that would make me not see the more important points. For example, if this was calculus, I would be happy with infinitesimals, and if this was probability theory, I would be happy without measure theory.
My attempt
by reading here, and some notation sugar of my own, $\text{AIC}_{m,D}$ is the AIC criterion of model $m$ on dataset $D$ as follows:
$$
\text{AIC}_{m,D} = 2k_m - 2 \ln(L_{m,D})
$$
where $k_m$ is the number of parameters of model $m$, and $L_{m,D}$ is the maximum likelihood function value of model $m$ on dataset $D$.
Here is my understanding of what the above implies:
$$
m = \underset{\theta}{\text{arg max}\,} \Pr(D|\theta)
$$
This way:

*

*$k_m$ is the number of parameters of $m$.

*$L_{m,D} = \Pr(D|m) = \mathcal{L}(m|D)$.

Let's now rewrite AIC:
$$\begin{split}
\text{AIC}_{m,D} =& 2k_m - 2 \ln(L_{m,D})\\
=& 2k_m - 2 \ln(\Pr(D|m))\\
=& 2k_m - 2 \log_e(\Pr(D|m))\\
\end{split}$$
Obviously, $\Pr(D|m)$ is the probability of observing dataset $D$ under model $m$. So the better the model $m$ fits the dataset $D$, the larger $\Pr(D|m)$ becomes, and thus smaller the term $-2\log_e(\Pr(D|m))$ becomes.
So clearly AIC rewards models that fit their datasets (because smaller $\text{AIC}_{m,D}$ is better).
On the other hand, the term $2k_m$ clearly punishes models with more parameters by making $\text{AIC}_{m,D}$ larger.
In other words, AIC seems to be a measure that:

*

*Rewards accurate models (those that fit $D$ better) logarithmically. E.g. it rewards increase in fitness from $0.4$ to $0.5$ more than it rewards the increase in fitness from $0.8$ to $0.9$. This is shown in the figure below.

*Rewards reduction in parameters linearly. So decrease in parameters from $9$ down to $8$ is rewarded as much as it rewards the decrease from $2$ down to $1$.

In other words (again), AIC defines a trade-off between the importance of simplicity and the importance of fitness.
In other words (again), AIC seems to suggest that:

*

*The importance of fitness diminishes.

*But the importance of simplicity never diminishes but is rather always constantly important.

Q1: But a question is: why should we care about this specific fitness-simplicity trade-off?
Q2: Why $2k$ and why $2 \log_e(\ldots)$? Why not just:
$$\begin{split}
\text{AIC}_{m,D} =& 2k_m - 2 \ln(L_{m,D})\\
 =& 2(k_m - \ln(L_{m,D}))\\
\frac{\text{AIC}_{m,D}}{2} =& k_m - \ln(L_{m,D})\\
\text{AIC}_{m,D,\text{SIMPLE}} =& k_m - \ln(L_{m,D})\\
\end{split}$$
i.e. $\text{AIC}_{m,D,\text{SIMPLE}}$ should in y view be equally useful to $\text{AIC}_{m,D}$ and should be able to serve for relatively comparing different models (it's just not scaled by $2$; do we need this?).
Q3: How does this relate to information theory? Could someone derive this from an information theoretical start?

A: AIC is an estimate of twice the model-driven additive term to the expected Kullback-Leibler divergence between the true distribution $f$ and the approximating parametric model $g$.
K-L divergence is a topic in information theory and works intuitively (though not rigorously) as a measure of distance between two probability distributions. In my explanation below, I'm referencing these slides from Shuhua Hu. This answer still needs a citation for the "key result."
The K-L divergence between the true model $f$ and approximating model $g_{\theta}$ is
$$ d(f, g_{\theta}) = \int f(x) \log(f(x)) dx -\int f(x) \log(g_{\theta}(x)) dx$$
Since the truth is unknown, data $y$ is generated from $f$ and maximum likelihood estimation yields estimator $\hat{\theta}(y)$. Replacing $\theta$ with $\hat{\theta}(y)$ in the equations above means that both the second term in the K-L divergence formula as well as the K-L divergence itself are now random variables. The "key result" in the slides is that the average of the second additive term with respect to $y$ can be estimated by a simple function of the likelihood function $L$ (evaluated at the MLE), and $k$, the dimension of $\theta$:
$$ -\text{E}_y\left[\int f(x) \log(g_{\hat{\theta}(y)}(x)) \, dx \right] \approx  -\log(L(\hat{\theta}(y))) + k.$$
AIC is defined as twice the expectation above (HT @Carl), and smaller (more negative) values correspond to a smaller estimated K-L divergences between the true distribution $f$ and the modeled distribution $g_{\hat{\theta}(y)}$.

A: A simple point of view for your first two questions is that the AIC is related to the expected out-of-sample error rate of the maximum likelihood model. The AIC criterion is based on the relationship (Elements of Statistical Learning equation 7.27)
$$
-2 \, \mathrm{E}[\ln \mathrm{Pr}(D|\theta)] \approx -\frac{2}{N} \, \mathrm{E}[\ln L_{m,D}] + \frac{2k_m}{N} = \frac{1}{N} E[\mathrm{AIC}_{m,D}]
$$
where, following your notation, $k_m$ is the number of parameters in the model $m$ whose maximum likelihood value is $L_{m,D}$.
The term on the left is the expected out-of-sample "error" rate of the maximum likelihood model $m = \{ \theta \}$, using the log of the probability as the error metric. The -2 factor is the traditional correction used to construct the deviance (useful because in certain situations it follows a chi-square distribution).
The right hand consists of the in-sample "error" rate estimated from the maximized log-likelihood, plus the term $2k_m/N$ correcting for the optimism of the maximized log-likelihood, which has the freedom to overfit the data somewhat.
Thus, the AIC is an estimate of the out-of-sample "error" rate (deviance) times $N$.

A: This question by caveman is popular, but there were no attempted answers for months until my controversial one. It may be that the actual answer below  is not, in itself, controversial, merely that the questions are "loaded" questions, because the field seems (to me, at least) to be populated by acolytes of AIC and BIC who would rather use OLS than each others' methods. Please look at all the assumptions listed, and restrictions placed on data types and methods of analysis, and please comment on them; fix this, contribute. Thus far, some very smart people have contributed, so slow progress is being made. I acknowledge contributions by Richard Hardy and GeoMatt22, kind words from Antoni Parellada, and valiant attempts by Cagdas Ozgenc and Ben Ogorek to relate K-L divergence to an actual divergence.
Before we begin let us review what AIC is, and one source for this is Prerequisites for AIC model comparison and another is from Rob J Hyndman. In specific, AIC is calculated to be equal to
$$2k - 2 \log(L(\theta))\,,$$
where $k$ is the number of parameters in the model and $L(\theta)$ the likelihood function. AIC compares the trade-off between variance ($2k$) and bias ($2\log(L(\theta))$) from modelling assumptions. From Facts and fallacies of the AIC, point 3  "The AIC does not assume the residuals are Gaussian. It is just that the Gaussian likelihood is most frequently used. But if you want to use some other distribution, go ahead." The AIC is the penalized likelihood, whichever likelihood you choose to use. For example, to resolve AIC for Student's-t distributed residuals, we could use the maximum-likelihood solution for Student's-t. The log-likelihood usually applied for AIC is derived from Gaussian log-likelihood and given by
$$ \log(L(\theta)) =-\frac{|D|}{2}\log(2\pi) -\frac{1}{2} \log(|K|) -\frac{1}{2}(x-\mu)^T K^{-1} (x-\mu), $$
$K$ being the covariance structure of the model, $|D|$ the sample size; the number of observations in the datasets, $\mu$ the mean response and $x$ the dependent variable. Note that, strictly speaking, it is unnecessary for AIC to correct for the sample size, because AIC is not used to compare datasets, only models using the same dataset. Thus, we do not have to investigate whether the sample size correction is done correctly or not, but we would have to worry about this if we could somehow generalize AIC to be useful between datasets. Similarly, much is made about $K>>|D|>2$ to insure asymptotic efficiency. A minimalist view might consider AIC to be just an "index," making $K>|D|$ relevant and $K>>|D|$ irrelevant. However, some attention has been given to this in the form of proposing an altered AIC for $K$ not much larger than $|D|$ called AIC$_c$ see second paragraph of answer to Q2 below. This proliferation of "measures" only reinforces the notion that AIC is an index. However, caution is advised when using the "i" word as some AIC advocates equate use of the word "index" with the same fondness as might be attached to referring to their ontogeny as extramarital.
Q1: But a question is: why should we care about this specific fitness-simplicity trade-off?
Answer in two parts. First the specific question. You should only care because that was the way it was defined. If you prefer there is no reason not to define a CIC; a caveman information criterion, it will not be AIC, but CIC would produce the same answers as AIC, it does not effect the tradeoff between goodness-of-fit and positing simplicity. Any constant that could have been used as an AIC multiplier, including one times, would have to have been chosen and adhered to, as there is no reference standard to enforce an absolute scale. However, adhering to a standard definition is not arbitrary in the sense that there is room for one and only one definition, or "convention," for a quantity, like AIC, that is defined only on a relative scale. Also see AIC assumption #3, below.
The second answer to this question pertains to the specifics of AIC tradeoff between goodness-of-fit and positing simplicity irrespective of how its constant multiplier would have been chosen. That is, what actually effects the "tradeoff"? One of the things that effects this, is to degree of freedom readjust for the number of parameters in a model, this led to defining an "new" AIC called AIC$_c$ as follows:
$$\begin{align}AIC_c &= AIC + \frac{2k(k + 1)}{n - k - 1}\\
&= \frac{2kn}{n-k-1} - 2 \ln{(L)}\end{align} \,,$$
where $n$ is the sample size. Since the weighting is now slightly different when comparing models having different numbers of parameters, AIC$_c$ selects models differently than AIC itself, and identically as AIC when the two models are different but have the same number of parameters.
Other methods will also select models differently, for example, "The BIC [sic, Bayesian information criterion] generally penalizes free parameters more strongly than the Akaike information criterion, though it depends..." ANOVA would also penalize supernumerary parameters using partial probabilities of the indispensability of parameter values differently, and in some circumstances would be preferable to AIC use. In general, any method of assessment of appropriateness of a model will have its advantages and disadvantages. My advice would be to test the performance of any model selection method for its application to the data regression methodology more vigorously than testing the models themselves. Any reason to doubt? Yup, care should be taken when constructing or selecting any model test to select methods that are methodologically appropriate. AIC is useful for a subset of model evaluations, for that see Q3, next. For example, extracting information with model A may be best performed with regression method 1, and for model B with regression method 2, where model B and method 2 sometimes yields non-physical answers, and where neither regression method is MLR, where the residuals are a multi-period waveform with two distinct frequencies for either model and the reviewer asks "Why don't you calculate AIC?"
Q3 How does this relate to information theory:
MLR assumption #1. AIC is predicated upon the assumptions of maximum likelihood (MLR) applicability to a regression problem. There is only one circumstance in which ordinary least squares regression and maximum likelihood regression have been pointed out to me as being the same. That would be when the residuals from ordinary least squares (OLS) linear regression are normally distributed, and MLR has a Gaussian loss function. In other cases of OLS linear regression, for nonlinear OLS regression, and non-Gaussian loss functions, MLR and OLS may differ. There are many other regression targets than OLS or MLR or even goodness of fit and frequently a good answer has little to do with either, e.g., for most inverse problems. There are highly cited attempts (e.g., 1100 times) to use generalize AIC for quasi-likelihood so that the dependence on maximum likelihood regression is relaxed to admit more general loss functions. Moreover,  MLR for Student's-t, although not in closed form, is robustly convergent. Since Student-t residual distributions are both more common and more general than, as well as inclusive of, Gaussian conditions, I see no special reason to use the Gaussian assumption for AIC.
MLR assumption #2. MLR is an attempt to quantify goodness of fit. It is sometimes applied when it is not appropriate. For example, for trimmed range data, when the model used is not trimmed. Goodness-of-fit is all fine and good if we have complete information coverage. In time series,  we do not usually have fast enough information to understand fully what physical events transpire initially or our models may not be complete enough to examine very early data. Even more troubling is that one often cannot test goodness-of-fit at very late times, for lack of data. Thus, goodness-of-fit may only be modelling 30% of the area fit under the curve, and in that case, we are judging an extrapolated model on the basis of where the data is, and we are not examining what that means. In order to extrapolate, we need to look not only at the goodness of fit of 'amounts' but also the derivatives of those amounts failing which we have no "goodness" of extrapolation. Thus, fit techniques like B-splines find use because they can more smoothly predict what the data is when the derivatives are fit, or alternatively inverse problem treatments, e.g., ill-posed integral treatment over the whole model range, like error propagation adaptive Tikhonov regularization.
Another complicated concern, the data can tell us what we should be doing with it. What we need for goodness-of-fit (when appropriate), is to have the residuals that are distances in the sense that a standard deviation is a distance. That is, goodness-of-fit would not make much sense if a residual that is twice as long as a single standard deviation were not also of length two standard deviations. Selection of data transforms should be investigated prior to applying any model selection/regression method. If the data has proportional type error, typically taking the logarithm before selecting a regression is not inappropriate, as it then transforms standard deviations into distances. Alternatively, we can alter the norm to be minimized to accommodate fitting proportional data. The same would apply for Poisson error structure, we can either take the square root of the data to normalize the error, or alter our norm for fitting. There are problems that are much more complicated or even intractable if we cannot alter the norm for fitting, e.g., Poisson counting statistics from nuclear decay when the radionuclide decay introduces an exponential time-based association between the counting data and the actual mass that would have been emanating those counts had there been no decay. Why? If we decay back-correct the count rates, we no longer have Poisson statistics, and residuals (or errors) from the square-root of corrected counts are no longer distances. If we then want to perform a goodness-of-fit test of decay corrected data (e.g., AIC), we would have to do it in some way that is unknown to my humble self. Open question to the readership, if we insist on using MLR, can we alter its norm to account for the error type of the data (desirable), or must we always transform the data to allow MLR usage (not as useful)? Note, AIC does not compare regression methods for a single model, it compares different models for the same regression method.
AIC assumption #1. It would seem that MLR is not restricted to normal residuals, for example, see this question about MLR and Student's-t. Next, let us assume that MLR is appropriate to our problem so that we track its use for comparing AIC values in theory. Next we assume that have 1) complete information, 2) the same type of distribution of residuals (e.g., both normal, both Student's-t) for at least 2 models. That is, we have an accident that two models should now have the type of distribution of residuals. Could that happen? Yes, probably, but certainly not always.
AIC assumption #2. AIC relates the negative logarithm of the quantity (number of parameters in the model divided by the  Kullback-Leibler divergence). Is this assumption necessary? In the general loss functions paper a different "divergence" is used. This leads us to question if that other measure is more general than K-L divergence, why are we not using it for AIC as well?
The  mismatched information for AIC from Kullback-Leibler divergence is "Although ... often intuited as a way of measuring the distance between probability distributions, the Kullback–Leibler divergence is not a true metric." We shall see why shortly.
The K-L argument gets to the point where the difference between two things the model (P) and the data (Q) are
$$D_{\mathrm{KL}}(P\|Q) = \int_X \log\!\left(\frac{{\rm d}P}{{\rm d}Q}\right) \frac{{\rm d}P}{{\rm d}Q} \, {\rm d}Q \,,$$
which we recognize as the entropy of ''P'' relative to ''Q''.
AIC assumption #3. Most formulas involving the Kullback–Leibler divergence hold regardless of the base of the logarithm. The constant multiplier might have more meaning if AIC were relating more than one data set at at time. As it stands when comparing methods, if $AIC_{data,model 1}<AIC_{data,model 2}$ then any positive number times that will still be $<$. Since it is arbitrary, setting the constant to a specific value as a matter of definition is also not inappropriate.
AIC assumption #4. That would be that AIC measures Shannon entropy or self information." What we need to know is "Is entropy what we need for a metric of information?"
To understand what "self-information" is, it behooves us to normalize information in a physical context, any one will do. Yes, I want a measure of information to have properties that are physical. So what would that look like in a more general context?
The Gibbs free-energy equation ($\Delta G = ΔH – TΔS$) relates the change in energy to the change in enthalpy minus the absolute temperature times the change in entropy. Temperature is an example of a successful type of normalized information content, because if one hot and one cold brick are placed in contact with each other in a thermally closed environment, then heat will flow between them. Now, if we jump at this without thinking too hard, we say that heat is the information. But is it the relative information that predicts behaviour of a system. Information flows until equilibrium is reached, but equilibrium of what? Temperature, that's what, not heat as in particle velocity of certain particle masses, I am not talking about molecular temperature, I am talking about gross temperature of two bricks which may have different masses, made of different materials, having different densities etc., and none of that do I have to know, all I need to know is that the gross temperature is what equilibrates. Thus if one brick is hotter, then it has more relative information content, and when colder, less.
Now, if I am told one brick has more entropy than the other, so what? That, by itself, will not predict if it will gain or lose entropy when placed in contact with another brick. So, is entropy alone a useful measure of information? Yes, but only if we are comparing the same brick to itself thus the term "self-information."
From that comes the last restriction: To use K-L divergence all bricks must be identical. Thus, what makes AIC an atypical index is that it is not portable between data sets (e.g., different bricks), which is not an especially desirable property that might be addressed by normalizing information content. Is K-L divergence linear? Maybe yes, maybe no. However, that does not matter, we do not need to assume linearity to use AIC, and, for example, entropy itself I do not think is linearly related to temperature. In other words, we do not need a linear metric to use entropy calculations.
It has been said that, "In itself, the value of the AIC for a given data set has no meaning." On the optimistic side models that have close results can be differentiated by smoothing to establish confidence intervals, and much much more.


text:
Q: ASP.NET - Having a common script for both client-side and server-side? I am working on a web application and I come to this calculation method that is going to take a string and returns the number of SMS messages.(It's a pure function and doesn't need any external resources to do its job)
I need this function to work both in client-side and server-side.While in client-side user can see the number of SMSs of his message so far and when in server-side i have to calculate how much does the message cost.
I thought that I had to have a C# version of this function for server-side and a javascript one for client-side but then I thought DRY - what if I could run javascript functions in server-side too ?
I am not sure if it's possible or not ?
So here's the question : can we run a javascript function in server-side (or in my case from a class library)?

A: I think you're looking at this from the wrong way. Instead of trying to run javascript server side (which is not possible I think), you should create a C# function to calculate whatever it is you want calculated and pass the result to your client. This function can be invoked by the client through e.g. an ajax call, or passed in through a viewmodel etc.

A: Solution:
1. You should write API in C# and since it is pure method to calculate, its number of parameters are fixed. Now Client side code can make ajax (or xmlHttpRequest) to this API and response to which can be handled at client side.
2. Use Node for server side javascript something like, https://www.npmjs.com/package/sandbox, or use native node js VM module.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Jira Startup failed with unloaded plugins I was deploying a Jira report plugin with SDK 3.10 and ran into this:
The following plugins are required by JIRA, but have not been started:
Gadget Directory Plugin (com.atlassian.gadgets.directory)
Atlassian JIRA - Plugins - Project Config Plugin (com.atlassian.jira.jira-project-    config-plugin)
Atlassian OAuth Admin Plugin (com.atlassian.oauth.admin)
Embedded Gadgets Plugin (com.atlassian.gadgets.embedded)
Atlassian JIRA - Plugins - Shared Application Access Layer (SAL) Plugin(com.atlassian.sal.jira)
Gadget Dashboard Plugin (com.atlassian.gadgets.dashboard)
Atlassian JIRA - Plugins - Look And Feel Logo Upload Plugin (com.atlassian.jira.lookandfeel)
Atlassian JIRA - Plugins - Gadgets Plugin (com.atlassian.jira.gadgets)
Atlassian REST - Module Types (com.atlassian.plugins.rest.atlassian-rest-module)
FishEye Plugin (com.atlassian.jirafisheyeplugin)
Gadget Spec Publisher Plugin (com.atlassian.gadgets.publisher)
Atlassian JIRA - Plugins - REST Plugin (com.atlassian.jira.rest)
Atlassian OAuth Service Provider Plugin (com.atlassian.oauth.serviceprovider)
Opensocial Plugin (com.atlassian.gadgets.opensocial)

RemarK: i do not have Jira installed on my laptop. is that a problem? also, I am using Java SE 1.6

A: I think you have to provide more information, for example pom.xml base pom and dependencies, and maybe some logs. JIRA SDK produces compilation log file, that you could include.
Another thing, you could skip harness test. Try to build plugin with:
mvn clean package -Patlassian -Dmaven.test.skip=true


text:
Q: Как повысить привилегии приложения (UAC) Делаю приложение, которое запускается на Windows 7/10 от пользователя с правами администратора. При этом запускается оно в обычном режиме (с ограниченными правами). Приложению этих прав хватает на всё, кроме одной редко используемой операции. Вопрос: можно ли как-то во время исполнения приложения запросить повышение привилегий для его процесса без перезапуска (создания нового) процесса? Т.е. как в некоторых стандартных диалогах Windows есть функции, помеченные значком щита, при вызове которых появляется стандартный запрос UAC на повышение прав доступа.

A: Без создания нового процесса - нельзя, без перезапуска - можно.
Алгоритм действия такой (для того, что бы не делать перезапуск):

*

*Cоздаём процесс с повышенными привелегиями, можно вызвать свой же модуль, но с параметром, по-которому наша программа "переключится" на запасной режим работы, например через runas (читать UAC).

*Ждём отклика от процесса (пока пользователь в диалоге UAC разрешит)

*Передаем новому процессу параметры для вызова одной АПИ (DuplicateHandle, WriteProcessMemory, CreatePipe, Write и т п)

*Передаём процессу сигнал запустить функцию

*Ждём ответа процесса (пока ф-ция отработает) ( с помощью WaitForSingleObject например).

*Считываем ответ (ReadProcessMemory, Read)

*Замораживаем нить процесса, что бы повторно использовать.

*По завершению работы программы так же завершаем процесс с админскими привелегиями (или через TerminateProcess, или передаём сигнал процессу).

При этом визуально не будет понятно, что основной процесс создал дополнительный.


text:
Q: css rotate introduces outline when using SVG clip-path or mask Is there a way to stop this outline in firefox?

#blob { background: red; width: 500px; height: 500px; clip-path: url(#myClip); transform: rotate(20deg);}

<svg>
    <defs>
        <path d="M320.403196,424.677624 C426.787532,365.585154 447.310044,306.188587 433.45394,197.28033 C419.597836,88.3720737 316.997962,53.8862578 227.347416,40.9086547 C144.650118,28.9375873 104.472702,88.6407456 69.862267,131.812053 C15.52584,199.588564 48.3439099,300.905451 80.8563197,361.757908 C110.80391,417.809872 214.018859,483.770094 320.403196,424.677624 Z" id="path-1"></path>

        <clipPath id="myClip"><use href="#path-1"></use></clipPath>

    </defs>
</svg>

This renders correctly in other browsers, just need some work around for this firefox bug
same outline appears using either clip-path or mask

A: As a workaround you could rotate the clipPath instead:

#blob {
  background: red;
  width: 500px;
  height: 500px;
  clip-path: url(#myClip);
}

<svg viewBox="0 0 397 409">
    <defs>
        <path d="M320.403196,424.677624 C426.787532,365.585154 447.310044,306.188587 433.45394,197.28033 C419.597836,88.3720737 316.997962,53.8862578 227.347416,40.9086547 C144.650118,28.9375873 104.472702,88.6407456 69.862267,131.812053 C15.52584,199.588564 48.3439099,300.905451 80.8563197,361.757908 C110.80391,417.809872 214.018859,483.770094 320.403196,424.677624 Z" id="path-1" />
        <clipPath id="myClip" transform="rotate(20)" transform-origin="center">
          <use href="#path-1"></use>
        </clipPath>
    </defs>
</svg>


text:
Q: This operation requires the page to be asynchronous (the Async attribute must be set to true). I'm trying to execute an asynchronous task on my Azure hosted webpage inside the Page_Load method. However I'm getting the above error. I have set the Async property of the page to true in the aspx file and still no luck.
ASP Header Code:
<%@ Page Title="" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="SalesAndCCFAQ.FAQ" Async ="true"%>

Page_Load Code:
    protected void Page_Load(object sender, EventArgs e)
    {
        RegisterAsyncTask(new PageAsyncTask(test));
        Page.ExecuteRegisteredAsyncTasks();
        //Only need to fill catDropDown when the page is first directed to
        if (!Page.IsPostBack)
        {
            fillCatDropDown();
            //Show who is currently logged in
            currentUserLabel.Text += HttpContext.Current.User.Identity.Name;
        }
        if (GlobalUse.external == true)
            {
                whichApproved = "approvedExternal = 1";
                greenKeyImage.Visible = false;
                greenKeyLabel.Visible = false;
                yellowKeyImage.Visible = false;
                yellowKeyLabel.Visible = false;
                redKeyImage.Visible = false;
                redKeyLabel.Visible = false;

            }
            else
            {
                whichApproved = "approvedInternal = 1";
            }
        //String to be added to main query if a category is selected
        filterCatQuery = "cid = (SELECT cid FROM Category WHERE name = '" + catDropDown.Text + "')";
    }

Page_PreInit Code:
    protected void Page_PreInit()
    {
        if (!Page.IsPostBack)
        {
            if (GlobalUse.external == true)
            {
                this.MasterPageFile = "~/SiteExternal.Master";
            }
        }
    }

Asynchronous function that is called:
    protected async Task test()
    {
        if (GlobalUse.external != null)
            return;
        await GlobalUse.isUserExternalGroup(); //This method sets GlobalUse.external
        Response.Redirect("~/Default.aspx"); //Refresh to call the PreInit Code again
    }

A: Set Async to true as below in the page.
<%@ Page Title="" Language="C#" Async="true" MasterPageFile="~/XXX.Master" AutoEventWireup="true"
CodeBehind="XXX.aspx.cs" Inherits="XXX"
ValidateRequest="false" meta:resourcekey="XXX" %>

A: The reason this error was being thrown is because it was my Default page. The way I fixed it was by creating a blank Default page which then redirects to my desired homepage upon it being loaded. I will leave this here as it may be of use to someone and I believe it is quite a unique case.

A: You can write  this.AsyncMode = true; under page load to allow Async tasks execution.


text:
Q: AngularJS - trying to get background color to change with ng-switch and ng-click This is my first question - and it is really just more of a frustration. I've went through about 12 different stack overflow questions that are similar and have copied their code and I still can't get the bloody background color to change on click. So I assume I'm missing something.
https://codepen.io/Dawsraki/pen/XRGBLW

    <

Listen to Music

    >

     <

Share it with friends

    >

Here is my code pen - I want the background color to change when I click on the arrow and I have seen so many simple solutions but they just arn't working and I've no idea why. If anyone wants to help an AngularJS noob out there will be much love and biscuits <3 (DISCLAIMER: biscuits will not be provided)

A: This problem is due to ng-switch, as it creates its own scope.
Use $parent.myStyle={background:'red'}" in your anchor tag to fix this


text:
Q: Using GetSchemaTable() to retrieve only column names Is it possible to use GetSchemaTable() to retrieve only column names?
I have been trying to retrieve Column names (only) using this method, is it possible.
  DataTable table = myReader.GetSchemaTable();

  foreach (DataRow myField in table.Rows)
  {
      foreach (DataColumn myProperty in table.Columns)
      {
          fileconnectiongrid.Rows.Add(myProperty.ColumnName + " = "
                            + myField[myProperty].ToString());
      }
  }

This code retrieves a lot of table data unwanted, I only need a list containing
column names!:

A: You need to use ExecuteReader(CommandBehavior.SchemaOnly)):
DataTable schema = null;
using (var con = new SqlConnection(connection))
{
    using (var schemaCommand = new SqlCommand("SELECT * FROM table", con))
    {
        con.Open();
        using (var reader = schemaCommand.ExecuteReader(CommandBehavior.SchemaOnly))
        {
            schema = reader.GetSchemaTable();
        }
    }
}

SchemaOnly:

The query returns column information only. When using SchemaOnly, the
  .NET Framework Data Provider for SQL Server precedes the statement
  being executed with SET FMTONLY ON.

The column name is in the first column of every row. I don't think that it's possible to omit the other column informations like ColumnOrdinal,ColumnSize,NumericPrecision and so on since you cannot use reader.GetString but only reader.GetSchemaTable in this case.
But your loop is incorrect if you only want the column names:
foreach (DataRow col in schema.Rows)
{
    Console.WriteLine("ColumnName={0}", col.Field<String>("ColumnName"));
}

A: Change your code to below if all you want is to display the column names. Your original code was trying to not only display column names, but also trying to display the actual data values as well.
DataTable table = myReader.GetSchemaTable();

foreach (DataRow myField in table.Rows)
{
    foreach (DataColumn myProperty in table.Columns)
    {
        fileconnectiongrid.Rows.Add(myProperty.ToString());
    }
}

A: This will give you all column names, you can place them in a string[] and do with them what you like.
foreach(var columnName in DataTable.Columns)
{
  Console.WriteLine(columnName);
}

A: //Retrieve column schema into a DataTable.
schemaTable = reader.GetSchemaTable();

int index = schemaTable.Columns.IndexOf("ColumnName");
DataColumn columnName = schemaTable.Columns[index];

//For each field in the table...
foreach (DataRow myField in schemaTable.Rows)
  {
    String columnNameValue = myField[columnName].ToString();
    Console.WriteLine("ColumnName " + columnNameValue);
  }

A: I use same technics to add MAX-STRING-LENGTH constraint on custom TextBox in my VB.Net program.
I use a SQL SELECT command to get 4 column's values
    SELECT code_pays
          ,nom
          ,code_pays_short
          ,default_devise
      FROM pays
      ORDER BY nom

I use the result returned by an IDataReader object to fill a DataGridView.
And finally, I display each row's field in a Panel that contains 4 TextBox.
To avoid that SQL UPDATE command used to save some record's changes done in TextBox return error message due to column value too long, I have added a property in custom Textbox to inform directly user that value's size is overlapped.
Here is my Form

Here is VB.Net code used to initialize MaxStringLength properties
    Private Sub PushColumnConstraints(dr As IDataReader)
        Dim tb As DataTable = dr.GetSchemaTable()

        Dim nColIndex As Integer = -1

        For Each col As DataColumn In tb.Columns
            If col.ColumnName = "ColumnSize" Then
                nColIndex = col.Ordinal
                Exit For
            End If
        Next

        If nColIndex < 0 Then
            oT.ThrowException("[ColumnSize] columns's index not found !")
            Exit Sub
        End If

        txtCodePays.MaxStringLength = tb.Rows(0).Item(nColIndex)
        txtPays.MaxStringLength = tb.Rows(1).Item(nColIndex)
        txtShortCodePays.MaxStringLength = tb.Rows(2).Item(nColIndex)
        txtDefaultDevise.MaxStringLength = tb.Rows(3).Item(nColIndex)
    End Sub

In For loop, program search index of field contained in ColumnSize column's value.
MaxStringLength property is assigned using following syntax
tb.Rows(%TEXT-BOX-INDEX%).Item(nColIndex)

.Rows(%TEXT-BOX-INDEX%) is used to identify column's metadata in SQL SELECT !
.Item(nColIndex) is used to get a specific column's metadata value
Item(n) can return a String or an Integer but VB.Net do implicit conversion when necessary.
This line of code can also be written shortly
tb.Rows(%TEXT-BOX-INDEX%)(nColIndex)
tb(%TEXT-BOX-INDEX%)(nColIndex)

but it is not readable !
Caution: MaxStringLength is a custom property. It is not part of normal TextBox.
In print screen above, you can see that program indicates to user that length is too big for Code Pays (3 lettres) TextBox.
Error's message is displayed in StatusBar at bottom of Form.
This information is displayed before clicking on SAVE button that generates an SQL UPDATE command.
Code used that call PushColumnConstraints method is following
    Public Sub FillPanel()

        SQL =
    <sql-select>

        SELECT code_pays
              ,nom
              ,code_pays_short
              ,default_devise
          FROM pays
          ORDER BY nom

    </sql-select>

        Dim cmd As New NpgsqlCommand(SQL, cn)
        Dim dr As NpgsqlDataReader

        Try
            dr = cmd.ExecuteReader()
        Catch ex As Exception
            ThrowException(ex)
        End Try

        Call PushColumnConstraints(dr)


text:
Q: nhibernate complex projection expression I'm trying to use nhibernate to retrieve data from mysql db. However I need the projection to run some calculations. Nhibernate doesn't seem to like that. It works great with linq to sql.
        var purchases = _session.QueryOver<Purchase>()
                        .Where(validPID<Purchase>(portfolioID))
                        .SelectList(list => list
                            .SelectGroup(c => c.currency)
                            .SelectSum(c => c.shares * c.price - c.commission))

I get "Could not determine member from ((c.shares * c.price) - c.commission)" as error.
How can I write this to work?
Thanks

A: What library of Linq extensions are you using that has SelectList, SelectGroup and SelectSum? They're not the standard methods for those operations, and they're not NH-provided extensions. As such, NHibernate probably has no clue what to do with them. As a rule, when constructing a Linq2NH query, you cannot use any custom extension methods; if it didn't come from System.Linq or NHibernate.Linq, you can't use it (one of the very few exceptions is IEnumerable.Contains() which translates to an IN query)
Try inserting an AsEnumerable() call after the Where method. This will basically force evaluation of the Queryable expression tree, and all further operations will be performed in-memory on the objects (or their NH proxies, populated as necessary).

A: Why dont you use HQL instead. I am not sure how to translate your query to HQl cos I cant make head or tail of it, but your artihematic operations will be supported in HQL.
If you can explain what you are doing i cou;d probably help you with the query.

A: I actaully ended up summing up in code like this
        var purchases = (from p in _session.QueryOver<Purchase>()
                                    .Where(validPID<Purchase>(portfolioID)).List().ToList()
                         group p by p.currency into currencies
                         select new object[2] {
                            currencies.Key,
                            currencies.Sum(f => -1*f.price*f.shares - f.commission)
                        }).ToList();


text:
Q: Need help with Pearson criterion (chi-square) to check if the distribution is uniform Let's assume we have X - a random variable, and its values are 1, 2, and 3. We also have frequencies for each of the values, which equal to 51, 40, and 65 respectively.
So, this will look like this:

X
1
2
3

n
51
40
65

And the question is whether the variable X has uniform distribution. I am to use Pearson criterion to check it.
I actually do know how to solve it, but I have stumbled across one problem: the number of degrees of freedom is equal to zero, hence, I cannot use tables with critical values for chi-squared, since there is no zero degrees of freedom. What do I do? Is it even possible at all to solve this task using this criterion?

A: If your distribution was uniform you should have had $156/3=52$ observations each value. Now apply chi-squared test
$$\chi^2=\frac{(51-52)^2}{52}+\frac{(40-52)^2}{52}+\frac{(65-52)^2}{52}$$
and then check the result with your tables with 2 d.o.f.


text:
Q: Best practice for updating production database? I am new to programming. I am using Rails 4 and Postgres as database in production. When I change my database structure, what is the best practice to update production database when deploying using Capistrano? I want to keep all the data in production intact.
I noticed sometimes when I changed schema and deploy to production, some of the existing data records are lost.

A: Normally when making alterations to your schema you'll use rails g migration to produce new migrations and then do things like this:
class AddUsersDiscountToken < ActiveRecord::Migration
  def change
    add_column :users, :discount_token, :string
  end
end

This migration will add a discount_token column to the users table and can be applied with:
rake db:migrate

Within Capistrano there's a task that will do this for you once the deploy is successful. No data should be lost, no records altered apart from introducing this new field. If anything else happens you've got something very odd going on in your migrations.
Remember, a few rules:

*

*Always back-up your data before applying any migrations using the proper tool. mysqldump is a good place to start. Copying the binary MySQL data files is not adequate and will not work reliably, if at all.

*Always test your back-ups and ensure everything is there. The backup process may have terminated early for some reason and failed to properly back up all the tables and data.

*Never deploy migrations on your live production database without testing on a copy first. This is where the backup comes in handy, you get a chance to restore it, run the migrations, and test the results.

This is why having a staging server is often handy, even if it's just a temporary one, or not as powerful as your production server. It allows you to test your migrations on actual, production data without running the risk of interrupting service. Run your new production code with your newly migrated production database and verify that the new features you've added are functioning correctly and also check you haven't broken any old code with regressions.
Remember, migrations that alter the schema of large tables, such as those with millions of rows, may take some time to complete, especially on servers with non-SSD backed databases. When testing on your staging system make a note of how long it takes to complete as you may need to give your users advance notice for scheduled maintenance or make alterations to your plans to be less disruptive in terms of migrations.

A: Unless you are deleting a table or removing a column migrations will never cause you any issues.
To avoid some migration-related issues make sure you are following this:

*

*If possible try to rename the table or column than deleting and creating a table with identical structure.

*Check if your migration is reversible in case you need to rollback

*If you are writing a script to update the database make sure you have counter-script ready.

*Most important understand what the migration is exactly doing cross verify it on staging environment to make sure you are not loosing your data - By @CraigRinger


text:
Q: Joining two tables where one of them has 2 possible values I except my code to give following output:
I'm trying to select some info from my users table, where the id equals "user", which i've specified in the first part where it says "as user". But it wont use the output from user in the part below?
Here's what i've tried:
SELECT (CASE WHEN user_1 = '103' THEN user_2 ELSE user_1 END) as user FROM contacts
                                        UNION ALL
                                        SELECT NULL AS user FROM users WHERE id = user
                                        LIMIT 5


text:
Q: How to tell which set is larger. If I am given two infinite sets A and B which do not have a bijection between them I know that one set would be larger than the other .
But, how could I tell which set is larger? What additional properties would I need to know about the sets to tell which is larger and which is smaller?

A: You can't know that one is larger than the other. The standard example is any of the uncountably infinite ordinal numbers (as long as they're not too large) versus the real numbers. Cantor drove himself mad trying to figure this out, and we know now that in standard (ZF) set theory, they are incomparable.
Even with the axiom of choice, which implies that there is some ordinal number with a bijection to $\Bbb R$, exactly which one is still impossible to assert.

A: Without an injection you need cardinality inequalities.

*

*If there's an injection $f:A \to B$  then $|A| \le |B|$

*If there's a surjection $f:A \to B$ then $|B| \le |A|$.
When you know there isn't a bijection then you can say it's a strict inequality. As mentioned in Arthur's solution, establishing a strict inequality is not always decidable in ZFC.
Examples
$f:\mathbb{Q} \to \mathbb{R}$ defined by $f(q)=q$ is injective therefore $|\mathbb{Q}| \le |\mathbb{R}|$.
$f:\mathbb{R}^n \to \mathbb{Z}$ defined by $f(\vec{x})= \textbf{floor}(x_1)$ is onto so $|\mathbb{R}^n| \ge |\mathbb{Z}|$
It's actually even more handy when you have the theorem $|A|=|B|$ iff $|A|\le |B|$ and $|A| \ge |B|$.

A: "which do not have a bijection between them I know that one set would be larger than the other"
You actually don't know that unless you know a bijection is impossible.  It's not enough just to not have one; you have to know one is impossible.
The options are:
You know a bijection $f: A\to B$ exists.  $|A| = |B|$.
You are told that a bijection $f: A\to B$ is impossible but you know nothing else then $|A| \ne |B|$ but ... we know nothing more.
You don't know if an bijection does or does not exist and you don't know anything about other functions then ... you don't know a thing.
Basically:
If you have an injection $g:A\to B$ then $|B| \ge |A|$.
If you have a surjection $h:A\to B$ then $|A| \ge |B|$.
If you know an injection $g:A\to B$ is impossible then you know $|A| > |B|$.
If you know a surjection $h:A \to B$ is impossible then you know $|B| > |A|$.
If you have any of knowledge  combination of knowledge and ignorance you may or may not know more details.
But to prove things are not the same size you must prove certain mappings are impossible.


text:
Q: In Nimbus, how to paint TextField when MouseOver? I recently studied to override the defaults of Nimbus.
In the page of Nimbus Defaults for the TextField, there is no key TextField[MouseOver].borderPainter while there is Button[MouseOver].backgroundPainter.
I desired to paint TextField when MouseOver as I can do for JButton.
How can I achieve that? Thanks for your help.

A: A button is different than a text field. Even in the default metal LAF the button supports a change of border on a mouse over while a text field doesn't. So I guess it is no surprise that the Nimbus text field doesn't support this property.
You can implement this behaviour yourself by adding a MouseListener to the text field. Then you handle the mouseEntered and mouseExited events to change the border.


text:
Q: Make Slicknav menu close when outside click on IOS devices I'm using the Slicknav mobile menu script: http://slicknav.com/
And it's working great except I can't figure out how to get it to close when one clicks outside of the menu on ios devices. It closes fine when clicking outside when I test it on desktop and Android, but on my Ipad it's not working. Here's the current code. Any insight? Thank you!

Home

Link1

Link2

A: On my site the right menu uses slicknav. It closes fine when i click outside on iOS thanks to this code. Demonstration : http://www.crealisationweb.fr
Replace this:
$('.slicknav_menu').focusout(function(event){
    $('.menu').slicknav('close');
});

With this :
$("div, html").on("click", function (event) {
    if(!$(event.target).hasClass(".menu a") &&
    !$(event.target).hasClass("ul.slicknav_nav li a") &&
    !$(event.target).hasClass("slicknav_menutxt") &&
    !$(event.target).hasClass("slicknav_icon") &&
    !$(event.target).hasClass("slicknav_icon-bar") &&
    !$(event.target).hasClass("slicknav_btn")) {
        $(".menu").slicknav('close');
    }
});

A: I used something like this
$(window).on("touchstart", function(e) {
    var container = $("#menu");
if (!container.is(e.target) // if the target of the click isn't the container...
    && container.has(e.target).length === 0) // ... nor a descendant of the container
{
    $('#menu').slicknav('close');
}
});

A: I remember creating my first mobile website and this issue killed so much time. iOS has a known issue with :hover state when clicked.
Read up here - it should fix your issue.


text:
Q: Problem with value assignment inside a for loop There is silly bug in my code. I would appreciate to any help. I know this is language (C) specific (because I have some experience with Python & JS).
I'm trying to split source array into two parts.
When I try to assign value of current index of source array to another array, it works fine but only until the end of for loop. After loop completion these arrays turns out with completely different values.
Please check out my code below:
#include <stdio.h>
//#include <cs50.h>

int merge_sort(int unsorted_array[], int size_of_arr);

int main(void)
{
    int unar[] = {9, 8, 7, 6, 5, 4, 3, 2, 1};     // unsorted array
    int len_of_arr = sizeof(unar) / sizeof(int);  // finding lenght of array
    merge_sort(unar, len_of_arr);
}

int merge_sort(int unsorted_array[], int size_of_arr)
{
    // dividing
    int ls_len; // lenght of left side of an array
    int rs_len; // lenght of right side of an array

    if (size_of_arr % 2 == 0) // if lenght of an array is even then lenght of each half equals: lenght of arr / 2
    {
        ls_len = size_of_arr / 2;
        rs_len = size_of_arr / 2;
    }
    else                      // else lenght of arr / 2 and right half++
    {
        ls_len = size_of_arr / 2;
        rs_len = size_of_arr / 2 + 1;
    }

    int unsorted_ls[ls_len]; // unsorted_array_length // 2
    int unsorted_rs[rs_len]; // if array_len is odd ? array_len / 2 + 1 : array_len / 2
    printf("left half len: %i\nRight half len: %i\n", ls_len, rs_len);

    for (int i = 0; i < size_of_arr; i++)
    {
        if (i < ls_len)
        {
            unsorted_ls[i] = unsorted_array[i];
            printf("Current value of original array: %i\n", unsorted_array[i]);
            printf("Currently assigned value of left half: %i\n\n", unsorted_ls[i]);       // current
        } else
        {
            unsorted_rs[i] = unsorted_array[i];
            printf("Current value of original array: %i\n", unsorted_rs[i]);
            printf("Currently assigned value of right half: %i\n\n", unsorted_array[i]);
        }
    }

    printf("Left half outside of for loop: ");
    for (int i = 0; i < ls_len; i++)
    {
        printf("%i", unsorted_ls[i]);
    }
    printf("\n");

    printf("Right half outside of for loop: ");
    for (int i = 0; i < rs_len; i++)
    {
        printf("%i", unsorted_rs[i]);
    }
    printf("\n");

    // sorting                                                       // not implemented yet
    // int sorted_left_side[] = merge_sort(unsorted_left_half);
    // int sorted_right_side[] = merge_sort(unsorted_right_half);

    // merging                                                       // not implemented yet
    // // for (int i = 0; )

    // return sorted_array;
    return 0;
}

A: This assignment statement
unsorted_rs[i] = unsorted_array[i];

invokes undefined behavior because there is an attempt to access memory beyond the array unsorted_rs when the value of the index i is greater than or equal to ls_len.
You should write
unsorted_rs[i - ls_len] = unsorted_array[i];

Pay attention to that instead of this if-else statement
if (size_of_arr % 2 == 0) // if lenght of an array is even then lenght of each half equals: lenght of arr / 2
{
    ls_len = size_of_arr / 2;
    rs_len = size_of_arr / 2;
}
else                      // else lenght of arr / 2 and right half++
{
    ls_len = size_of_arr / 2;
    rs_len = size_of_arr / 2 + 1;
}

you could just write
ls_len = size_of_arr / 2;
rs_len = size_of_arr - ls_len;


text:
Q: Bluetooth IC performance improves after resoldering/heating This is a very general question and I'm trying to brainstorm and get some insight into potential issues, things to watch out for etc. Unfortunately, I can't share the schematic or the datasheet.
My design uses a Realtek RTL8822CS WLAN and Bluetooth transceiver which pairs with a remote control.
Using a nrf52 dongle I am able to measure the RSSI of the DUT in a test chamber. Below are the results from a good unit (one which pairs successfully to a remote).

And here are the results from a bad unit, which does not pair to a remote. In this one case you can see the degraded performance on the lower frequency channels, but this isn't always the case. Some bad units have degraded performance on other channels.

Simply resoldering the same chip and/or after heating the chip with a heat gun, the performance across all channels improves to nominal levels and I am again able to pair my remote.
Could heating potentially cause the IC to exit some latch up state it's been stuck in? (Edit: power cycling the DUT does not solve the issue).
Additionally, there is a 40MHz oscillator which drives the IC for its PLL circuitry. Because the degradation seems to be frequency related I was thinking that it could be related to the stability of the oscillator.
I would really appreciate any ideas.


text:
Q: Parsing JSON array for certain strings in Python I'm trying to get certain strings from a website but having difficulty. This is the array (blocking out certain values)
{
    "ts": 1468156734285,
    "inbox": "email",
    "created": 302,
    "expire_in": 86098,
    "last_eml": 1468156432,
    "emls": [{
        "eml": "this is the email id",
        "eml_hash": "email hash",
        "eml_destroy_hash": "3319b480",
        "subject": "Welcome to your new temporary inbox",
        "from_address": "welcome@mytemp.email",
        "from_name": "welcome",
        "status": "read",
        "received": 302,
        "size": 0
     }]
}

In the 'emls' array, I'm trying to get 'eml' and 'eml_hash' as a python string. This is my code so far:
response = requests.get(url)
data = response.json()
print data
emal = data['emls']
eml_hash = data['eml_hash']

But it can't find these values
Traceback (most recent call last):
File "test.py", line 40, in <module>
emal= data['eml']

KeyError: 'eml'
Thanks

A: This code
response = requests.get(url)
data = response.json()
print data
emls = data['emls'] # emls = [{'status': 'unread','received': 0,...}]

Makes emls equal the list with a dictionary inside. So you need to take the first (0th) item of that list. Then you can use the keys eml and eml_hash.
eml = emls[0]['eml']
eml_hash = emls[0]['eml_hash]

If emls has more than one email in, simply loop over it:
eml = [] # List of all eml, email IDs.
eml_hash = [] # list of all eml_has, email hashes

for email in emls:
    eml += [email['eml]]
    eml_hash = [email['eml_hash']]

A: This should be pretty straightforward, given that data is the dictionary you provided:
data = {
"ts": 1468156734285,
"inbox": "email",
"created": 302,
"expire_in": 86098,
"last_eml": 1468156432,
"emls": [{
    "eml": "this is the email id",
    "eml_hash": "email hash",
    "eml_destroy_hash": "3319b480",
    "subject": "Welcome to your new temporary inbox",
    "from_address": "welcome@mytemp.email",
    "from_name": "welcome",
    "status": "read",
    "received": 302,
    "size": 0
}]}

for email in data['emls']:
    print(email['eml'])
    print(email['eml_hash'])

A: What you are doing is actually indexing the root of the dictionary, data, again. Therefore, you wouldn't get the expected output:
response = requests.get(url)
data = response.json()
print data
emal = data['emls']
# You should not be indexing data again. Note that emls is a list too.
eml_hash = data['eml_hash']

So your code would be:
response = requests.get(url)
data = response.json()
print data
eml = data['emls']
eml_hash = data['emls'][0]['eml_hash']

Or:
response = requests.get(url)
data = response.json()
print data
eml = data['emls']
eml_hash = eml[0]['eml_hash']

Outputs:
>>> eml
[{u'status': u'read', u'received': 302, u'from_name': u'welcome', u'from_address': u'welcome@mytemp.email', u'eml': u'this is the email id', u'eml_destroy_hash': u'3319b480', u'eml_hash': u'email hash', u'size': 0, u'subject': u'Welcome to your new temporary inbox'}]
>>> eml_hash
u'email hash'


text:
Q: Circle through focii of ellipse A circle passes through the focii of an ellipse.
Circle intersects ellipse at points A and B. Tangents and normals are drawn to the ellipse at A & B such that tangents intersect at P and normals intersect at Q. Then what is PQ is equal to ?
Is this a property that when a circle passes through focii of ellipse, the tangents meet at P and normals meet at Q and PQ is one of the diameters of the circle?

A: Consider the ellipse with foci $F_1$ and $F_2$ as shown below,
with a circle through $F_1$ and $F_2$ intersecting the ellipse at $A$.
Furthermore we have the tangent to the ellipse at $A$,
intersecting the circle at $S$,
and the perpendicular to the tangent at $A$,
intersecting the circle at $R$.

Knowing that $\angle F_1AR = \angle \angle F_2AR,$
what can you conclude about circular arcs $F_1R$ and $F_2R$?
Knowing that $\angle RAS$ is a right angle, what can you conclude about the line segment $RS$?
It can be shown that $R$ and $S$ are the points where the minor axis of the ellipse intersects the circle.
Therefore if we repeat this construction at another intersection point of the ellipse and circle, for example $B$ in this figure, the tangent and perpendicular lines will again intersect the circle at two points on the minor axis of the ellipse, which therefore are the same points $R$ and $S,$ which therefore are the two points $P$ and $Q.$
In this case the construction works equally well at any of the four intersection points between the circle and ellipse.
If we alter the shape or positions of the ellipse and/or circle so that there are only two intersections, the construction is still valid for those two points.


text:
Q: Code to show a string of text I'm in my first semester of college, and we're doing C#. I have to make a Winforms app that can convert between Celsius and Fahrenheit. I have all the code down (basically), but I need to have the result output to a label. I can send the answer to the label with lblOutput = Output.ToString(); but I need a message like "[input] Celsius will is [output] Fahrenheit". I tried putting in between the brackets after "ToString" but I was getting an error.
I have everything else coded except for this. I have been looking for the last couple days to figure it out, but I can't find an answer. Any help is greatly appreciated.
Edit:
The code that I have set up appears inside of a button. I have two radio buttons that saying that the value put into a text box is either Far -> Cels or Cels -> Far.
This is what I have coded in my button. If there is any way to improve upon it, please let me know.
private void btnConvert_Click(object sender, EventArgs e)
{
    decimal Input = Convert.ToDecimal(txtInput.Text); //grabs the input that the user entered

    if (rbtnCelsius.Checked == true) //Test to see if the Celsius radio button is checked
    {
        decimal Output = ((Input - 32) * 5) / 9; //If yes, it uses this formula to convert the input from Farenheit to Celsius
        txtOutput.Text = Output.ToString(); //Outputs the message to the user, showing the Celsius end point
    }
    else //Says that the Celsius Radio Button is not checked, meaning that the Farenheit radio button is
    {
        decimal Output = (Input * 9) / 5 + 32; //Moves onto this formula, converts Celsius to Farenheit
        txtOutput.Text = Output.ToString(); //outputs the message to the user, showing the Farenheit end point
    }

    //txtOutput.Text = Output.ToString();
    //Commented out because it gives an error saying that "Output does not exist in current context"
}

A: int fahrenheit, celsius;
// your code to set the two variables
string yourLabelText = String.Format("{0} Celcius is {1} Fahrenheit", celsius.ToString(), fahrenheit.ToString());

yourLabel.Text = yourLabelText;

Here is a reference for String.Format().  (thanks to Lukazoid!)

A: I'm not sure what your question is about but if you need to format your output into a set phrase you can do this.
private void btnConvert_Click(object sender, EventArgs e)
{
    decimal Input = Convert.ToDecimal(txtInput.Text); //grabs the input that the user entered
    // declare this outside the loop so you can use it later.
    decimal output = 0M;
    if (rbtnCelsius.Checked == true) //Test to see if the Celsius radio button is checked
    {
        output= ((Input - 32) * 5) / 9; //If yes, it uses this formula to convert the input from Farenheit to Celsius

    }
    else //Says that the Celsius Radio Button is not checked, meaning that the Farenheit radio button is
    {
        output= (Input * 9) / 5 + 32; //Moves onto this formula, converts Celsius to Farenheit

    }

    txtOutput.Text =string.Format("{0} Celsius will is {1} Fahrenheit",input,output);
}`

p.s. Do remember to use a try parse method to ensure that the txtInput is definitely convertible to decimal.

A: I don't know if you care about that, but for some cases you can get something like 12.243333333 by calling Output.ToString(), to make it more user-friendly, you can make it like this
Output.ToString("F2")

Which will change it to 12.24. You can use this together with string.Format like folks suggested.

A: you can use string.format to replace tokens like {0} or {1} in a string, or you can directly use string concatenation.  I'd like to avoid directly giving you the answer since you said this is homework, but if you look for c# examples of this you should be able to find your way.


text:
Q: How can I check if a charfield result is something specific? I want to check if Category in this method is Toys. Here is the method:
class Product(models.Model):
    CATS = (
        ("T", "Toys"),
        ("C", "Clothes"),
        ("B", "Baby essentials")
    )
    Title = models.CharField(max_length=100)
    Description = models.TextField()
    Colours = models.CharField(max_length=200)
    Category = models.CharField(max_length=1, choices=CATS)
    Price = models.IntegerField(default=1)
    image_one = models.ImageField(upload_to='media', default='def.jpg')
    image_two = models.ImageField(upload_to='media', default='def.jpg')
    image_three = models.ImageField(upload_to='media', default='def.jpg')

What I did in the HTML template:
{% extends "ecomm/base.html" %}
{% block content %}
{% for p in products%}
    {% if p.Category==Toys %}

 {{p.Title}}

 {{p.Price}}

 {{p.Description}}

    {% endif %}
{% endfor %}
{% endblock %}

A: I suggest you change the comparison to something like this, using the key and not the description of the category, and also putting the T as a string:
{% for p in products %}
    {% if p.Category == 'T' %}

{{ p.Title }}

{{ p.Price }}

{{ p.Description }}

    {% endif %}
{% endfor %}

This is because the field Product.Category holds the string value T, not the whole label Toys; the label Toys is added by Django code when rendering the HTML pages.


text:
Q: Query least one item of array Elasticsearch Suppose I have documents like this:
{
   "name":"Foo",
   "interests":{
      "movies":[
         1,
         2,
         3
      ],
      "music":[
         8,
         9,
         10
      ]
   }
}

How do I query for documents that match at least one of array items given an integer number?
Example: How to query all documents that interests.movie has 1?
All query examples I had tried turned into an exclusive match.

A: Pretty much how you described:
GET movies/_search
{
  "query": {
    "match": {
      "interests.movies": "1"
    }
  }
}


text:
Q: Luci cbi - How to get section name in ListValue How do I add all name of a section in a ListValue in Luci using CBI?
I know how to do this for a list of options. For example if I have the config below.
config mysection 'foo'
    option key1 'abc'
    option key2 'def'

config mysection 'bar'
    option key1 '123'
    option key2 '456'

I can easily make a list of options key1 like so:
lv = s:option(ListValue, "xxx", "whatever");
m.uci:foreach("myconfig","mysection",
        function(i)
                lv:value(i.key1, i.key1)
        end)

This provides a drop down list with 'abc' and '123'
Now I need the same but using the name of the section. i.e. A list with 'foo' and 'bar'.

A: This link gave me the answer.
lv = s:option(ListValue, "xxx", "whatever");
m.uci:foreach("myconfig","mysection",
        function(i)
                lv:value(i['.name'], i['.name'])
        end)

Interesting how editing a question helps you solving it.


text:
Q: Why is it not possible to use foreach in async function? Why can't I use foreach when using async functions? I always thought they just do the same thing.
 let query = try? await store.collection("feedposts").getDocuments()
 let documents = query?.documents ?? []

This works perfectly:
for document in documents {
            try? await store.collection("feedposts").document(document.documentID).collection("locked").document(uid).delete()
        }

While this doesn't:
documents.forEach { document in
            try? await store.collection("feedposts").document(document.documentID).collection("locked").document(uid).delete()
        }

A: for x in y is a language feature and executes in the current scope. So the await is also executed in the current scope.
But the forEach method is, well, a method that takes a specific argument:
func forEach(_ body: (Self.Element) throws -> Void) rethrows

You pass it a block, and if you look at the signature of body you see that it's lacking the async keyword. The block is thus not (guaranteed to be) executed in an async environment. But you can only use await in an async scope, which body is not guaranteeing to the compiler and it thus doesn't allow you to use await here.
If you want a forEach method that supports async/await, you need to implement it yourself. Whether Swift is going to provide an async forEach is debated in the Swift project.


text:
Q: What algorithm should I use to find the shortest path in this graph I have a problem about the calculation of shortest paths on an unweighted and undirected graph.
Which algorithm I use to calculate the shortest path between a node A and node B that passing through a node C on an undirected and unweighted graph?

A: You can split the solution into 2 steps, first find a path from A to C, and then find one from C to B and concatenate them.
To find the individual paths you'll want to use Dijkstra (given that unweighted likely means there is no heuristic to get for A*).

A: Like ratchet freak pointed out, you'll have to split the solution into finding a path from A to C and then from C to B.
However, Dijkstra is not needed since the graph doesn't have any weight. A simple Breadth First Search (BFS), slightly easier to implement, is enough.
Also, if you were to implement A*, no weight doesn't mean that you cannot find a heuristic. You could still favor paths that go through nodes with a certain property as a heuristic.


text:
Q: It's not easy to know what each Stack Exchange site is for I have joined multiple sites on Stack Exchange e.g. Meta, Programmer, SO etc. On each of this site there is no place where the kind of questions that can be asked, or category of users the site is for, are displayed. All the site looks alike except for color change, theme etc.
Is there any place one can know that? This will help to ask relevant question in that particular section

A: If you're a new user (exactly the type of person you'd want to reach), you don't need to click on any links: it's right in the sidebar.

I'm not 100% on who gets to see the sidebar, but I'm relatively certain you should at least see it the first time you visit any Stack Exchange site.
Additionally, the "Ask a Question" page describes the site topic (briefly, but still) in the sidebar and the prefilled title help text, like so:

A: You should have pointed out that there is an "About" link at the top of every page. That was what I was asking for.

Thanks

A: Each site's FAQ makes it very clear what the site is about and what kind of questions are expected.
For example, Stack Overflow's FAQ says

Stack Overflow is for professional and enthusiast programmers, people
  who write code because they love it. We feel the best Stack Overflow
  questions have a bit of source code in them, but if your question
  generally covers …
a specific programming problem a software algorithm software tools
  commonly used by programmers practical, answerable problems that are
  unique to the programming profession … then you're in the right place
  to ask your question!

while something like IT Security's FAQ says:

IT Security - Stack Exchange is for Information Security professionals
  to discuss protecting assets from threats and vulnerabilities. Topics
  include, but are not limited to:
web app hardening network security social engineering, including
  phishing risk management policies penetration testing security tools
  using cryptography incident response Questions on setting up your home
  PC antivirus may be more appropriate over at superuser.com; and
  questions on the deeper aspects of cryptography belong on crypto.SE.


text:
Q: Qt compilation error unicode/uloc.h I'm trying to compile Qt x64 libraries with the following configure command
D:\Qt\Qt5.0.0src>configure -prefix %CD%\qtbase -release -opensource -icu -platform win32-msvc2010 -opengl desktop

following this guide
http://www.holoborodko.com/pavel/2011/02/01/how-to-compile-qt-4-7-with-visual-studio-2010/#comment-7546
then launching the jom.exe file (extracted into D:\Qt\Qt5.0.0src) with
jom.exe -j7 /P

but I'm getting the following error:
Generating Code...
qlocale_win.cpp
tools\qstring.cpp(3841) : warning C4309: 'argument' : truncation of constant value
tools\qstring.cpp(3842) : warning C4309: 'argument' : truncation of constant value
qstringbuilder.cpp
Generating Code...
qlocale_icu.cpp
tools\qlocale_icu.cpp(48) : fatal error C1083: Cannot open include file: 'unicode/uloc.h': No such file or directory
qharfbuzz.cpp
Generating Code...
jom: D:\Qt\Qt5.0.0src\qtbase\src\corelib\Makefile.Release [.obj\release_shared\qelapsedtimer_win.obj] Error 2
jom: D:\Qt\Qt5.0.0src\qtbase\src\corelib\Makefile [release] Error 2
jom: D:\Qt\Qt5.0.0src\qtbase\src\Makefile [sub-corelib-make_first] Error 2
jom: D:\Qt\Qt5.0.0src\qtbase\Makefile [sub-src-make_first] Error 2
jom: D:\Qt\Qt5.0.0src\Makefile [module-qtbase-make_first] Error 2

The main point is:
fatal error C1083: Cannot open include file: 'unicode/uloc.h': No such file or directory

this file is located into "D:\Qt\icu\include\unicode" and I added both D:\Qt\icu and D:\Qt\icu\bin64 to the Path environment variable.
Why can't the makefile find it?

A: Solved -> I hadn't installed Windows SDK 7.1 before


text:
Q: The density of diagonal isotropic ternary quadratic forms with respect to discriminant Let $q(x,y,z) = ax^2 + by^2 + cz^2$ be a non-singular diagonal ternary quadratic form with integer coefficients. The discriminant $\Delta(q)$ of $q$ is then equal to $abc$, and for any positive number $X$ there are finitely many non-singular diagonal quadratic forms of discriminant at most $X$. Indeed, the number of non-singular diagonal ternary quadratic forms with $|\Delta(q)| \leq X$ is approximated by the integral
$$\displaystyle 8\iiint_{\substack{1 \leq uvw \leq X \\ u,v,w \geq1}} dudvdw = 8X (\log X)^2 + O(X \log X).$$
A quadratic form $q \in \mathbb{Z}[x,y,z]$ (not necessarily diagonal) is isotropic if the equation
$$\displaystyle q(x,y,z) = 0$$
has a solution $(x,y,z) \in \mathbb{Z}^3$. Define
$$\displaystyle N(X) = \#\{q = ax^2 + by^2 + cz^2 : a,b,c \in \mathbb{Z} \setminus \{0\}, |\Delta(q)| \leq X, q \text{ is isotropic}\}.$$
Define
$$\displaystyle R(X) = \frac{X (\log X)^2}{N(X)}.$$
Is there an asymptotic relation for $R(X)$? Alternatively, how dense are isotropic diagonal ternary quadratic forms among all diagonal ternary quadratic forms?

A: The density must be zero: for each prime $p$,
the probability that $q$ is not $p$-adically isotropic is
$3/2p + O(1/p^2)$ (when one of $a,b,c$ is a multiple of $p$,
and the product of the other two is $-1$ times a quadratic nonresidue);
thus for any finite set $P$ of primes, the probability is
$$
\prod_{p \in P} \left( 1 - \frac3{2p} + O(1/p^2) \right)
= \exp \left[- \sum_{p \in P} \bigl( 3/(2p) + O(1/p^2) \bigr)\right];
$$
and $\sum_{p \in P} 3/(2p)$ can be made arbitrarily large, while
$\sum_{p \in P} O(1/p^2)$ is bounded.


text:
Q: changing font size of \caption* I want to change the font size of the \caption* command, which is not listed in the list of figures.
I have the following code so far:
\documentclass{article}
\begin{figure}[h!]
   This is a figure
\caption{Time Line for an Event Study}
\caption*{Source: own diagram based on \cite{campbell1997}}
\end{figure}

I would like to have the Source text in a smaller font, as well as left aligned with the Figure 1 caption.
Also: i need to make sure that the \cite{} command works in the caption


text:
Q: How to make PL/Python tracebacks more verbose? Currently in case of error I have such traceback in psql for PL/Python procedure, that imports Python module and calls some function from it:
ERROR:  AssertionError:
CONTEXT:  Traceback (most recent call last):
  PL/Python function "tempo_timeintervalset_contains", line 6, in <module>
    TimeIntervalSet.from_json(timeintervalset))
  PL/Python function "tempo_timeintervalset_contains", line 209, in __contains__
  PL/Python function "tempo_timeintervalset_contains", line 106, in _walk
  PL/Python function "tempo_timeintervalset_contains", line 41, in _evaluate
  PL/Python function "tempo_timeintervalset_contains", line 200, in callback
  PL/Python function "tempo_timeintervalset_contains", line 91, in __contains__
PL/Python function "tempo_timeintervalset_contains"

I've tried to set log_error_verbosity = verbose in postgresql.conf and set this environment variables PYTHONVERBOSE=1 PYTHONDEBUG=1. Nothing helped.
Who knows, how to actually set it to be more verbose if it's possible at all?

A: I know this is old,  but I find this works well.
create function python_version()
returns text
language plpythonu
as $$

import sys
import traceback

try:
    return sys.version
except:
    error = sys.exc_info()[0]
    details = traceback.format_exc()
    plpy.error('%s: %s' % ( error, details ) )
$$;


text:
Q: How to create MongoDB collection with TTL? I create a collection of objects
public class User
{
public User(string fullname, string email)
{
Fullname = fullname;
Email = email;
}

    public string Fullname { get; }
    public string Email { get; }
}

And create the index and some docs
var collection = _database.GetCollection("bar");
collection.Indexes.CreateOne(new CreateIndexModel
(new BsonDocument("lastModifiedDate", 1), new CreateIndexOptions { ExpireAfter = new TimeSpan(0, 0, 30) }));

            var user = new User("Vasya", "billgates@ms.com");
            collection.InsertOne(user.ToBsonDocument());
            var user1 = new User("Petya", "Petya@ms.com");
            collection.InsertOne(user1.ToBsonDocument());
            var user2 = new User("Kolya", "Kolya@ms.com");
            collection.InsertOne(user2.ToBsonDocument());
            count = collection.CountDocuments(new BsonDocument());

But when I see http://localhost:8081/db/dbtest/ then I do not see any TTL and documents do not expire after 30 secs.
What I do wrong? How to create collection or documents in it with TTL?

A: Your user object doesn't have the field you specified on the index
public class User
{
    public User(string fullname, string email, DateTime lastModifiedDate)
    {
        Fullname = fullname;
        Email = email;
        LastModifiedDate = lastModifiedDate;
    }

    public string Fullname { get; }
    public string Email { get; }
    public DateTime LastModifiedDate { get; }
}

Also, the default convention for serialization in MongoDB C# Driver is not camel case so you'll need to update your index to the following:
var collection = _database.GetCollection("bar");
collection.Indexes.CreateOne(new CreateIndexModel
(new BsonDocument("LastModifiedDate", 1), new CreateIndexOptions { ExpireAfter = new TimeSpan(0, 0, 30) }));

You might also want to embrace the type safety that C# and the MongoDB Driver gives you by using your User type instead of the BsonDocument. Below is an example of how to do this.
using MongoDB.Driver;

var client = new MongoClient();
var database = client.GetDatabase("test");
var collection = database.GetCollection<User>("users");
await collection.Indexes.CreateOneAsync(
    Builders<User>.IndexKeys.Ascending(x => x.LastModifiedDate),
    new CreateIndexOptions { ExpireAfter = new TimeSpan(0, 0, 30) });

var user = new User("Vasya", "billgates@ms.com", DateTime.UtcNow);
collection.InsertOne(user);
var user1 = new User("Petya", "Petya@ms.com", DateTime.UtcNow);
collection.InsertOne(user1);
var user2 = new User("Kolya", "Kolya@ms.com", DateTime.UtcNow);
collection.InsertOne(user2);

for (var i = 0; i < 10; i++)
{
    var count = await collection.CountDocumentsAsync(Builders<User>.Filter.Empty);
    Console.WriteLine($"Count: {count} @ {DateTime.UtcNow}");
    await Task.Delay(10000);
}

// Count: 4 @ 02/01/2022 11:42:13
// Count: 4 @ 02/01/2022 11:42:23
// Count: 4 @ 02/01/2022 11:42:33
// Count: 4 @ 02/01/2022 11:42:43
// Count: 4 @ 02/01/2022 11:42:53
// Count: 1 @ 02/01/2022 11:43:03
// Count: 1 @ 02/01/2022 11:43:13
// Count: 1 @ 02/01/2022 11:43:23
// Count: 1 @ 02/01/2022 11:43:33
// Count: 0 @ 02/01/2022 11:43:43

public class User
{
    public User(string fullname, string email, DateTime lastModifiedDate)
    {
        Fullname = fullname;
        Email = email;
        LastModifiedDate = lastModifiedDate;
    }

    public string Fullname { get; }
    public string Email { get; }
    public DateTime LastModifiedDate { get; }
}

You might notice that the documents don't get deleted at once but as said in the MongoDB docs

The background task that removes expired documents runs every 60 seconds. As a result, documents may remain in a collection during the period between the expiration of the document and the running of the background task.
https://docs.mongodb.com/manual/core/index-ttl/#timing-of-the-delete-operation


text:
Q: Is it possible to connect a PHPmyAdmin database using Angular and Postman? this is my first time using StackOverflow and I don't know how this works but I'll be quick and short. So, I'm in an internship and I'm learning Angular and I only know the basics. They told me to make a simple project so I can understand the basics of Angular by making a task manager and using as Database PHPmyAdmin and of course PHP language. I did the database and I'm using Postman to get the HTTP request as the company colleagues told me to use. I want to understand if it is possible to make the database connection to Angular and how.

A: No because there's no such thing as a "phpmyadmin database".
Phpmyadmin is a tool for interacting with a mysql/mariadb database management system which will contain one or more databases.
Meanwhile angular is a toolkit/framework/library for writing JavaScript code to run in a browser. Browsers communicate with servers using http. Mariadb and mysql don't speak http. You need to build something serverside to bridge the http to the DBMS. You appear to be using PHP serverside already for this but there are lots of other languages.


text:
Q: Watin test hang application while uploading file I have an issue with  watin test that should browse for pdf and upload it to a web page. This test runs  smoothly on my machine, always find pdf, click submit and wait 30 sec for upload completed.
But when I try to run this test on build machine (teamcity), happens that test hang at the point when it should wait for upload. The problem is that test don't timeout, even if I set timeout at nunit on 1 minute for whole test,  or trying to reload page. The test just froze whole site at upload step.
Testing this functionality is really important, but since those tests with uploading hang whole build we have to do it manually and that isn't really out idea of test automation.
Does anyone have idea how to solve this upload problem? Or at least manage to timeout this test.
stack trace = at System.RuntimeType.InvokeDispMethod(String name, BindingFlags invokeAttr, Object target, Object[] args, Boolean[] byrefModifiers, Int32 culture, String[] namedParameters)
  at System.RuntimeType.InvokeMember(String name, BindingFlags bindingFlags, Binder binder, Object target, Object[] providedArgs, ParameterModifier[] modifiers, CultureInfo culture, String[] namedParams)
  at System.RuntimeType.ForwardCallToInvokeMember(String memberName, BindingFlags flags, Object target, Int32[] aWrapperTypes, MessageData& msgData)
  at mshtml.DispHTMLBaseElement.click()
  at WatiN.Core.InternetExplorer.IEElement.ClickOnElement()
  at WatiN.Core.Element.Click()
  at WatiN.Core.FileUpload.Set(String fileName)

A: I think the problem here is that your unit test depends on too many external resources, such as your the file system of your development machine, the network, etc.
Ask yourself what the importance of the test is: is there any business logic involved you can put into a separate class? Then you can write tests for this class. What you basically need is to test all the logic of the upload process without actually uploading a file or going to the network.

A: The issue was that WatiN used sendkeys to set the file(name) to upload. In WatiN 2.0 beta 1 this is changed to using some API calls. This solved the issue of hanging tests when automating a dialog which does require text input.


text:
Q: How to get artifacts in the response from Azure DevOps REST API call that lists all releases? I am using Azure DevOps rest API to get list all releases and artifact build ID's associated with each release. The call function:
GET https://vsrm.dev.azure.com/{organization}/{project}/_apis/release/releases?api-version=7.1-preview.8
list all releases. From there, I can get the release IDs, which I input manually into the call function:
GET https://vsrm.dev.azure.com/{organization}/{project}/_apis/release/releases/{releaseId}?api-version=7.1-preview.8
The response from this call has artifacts, and I can get the build ID of that artifact through artifacts/definitionReference/version/id
Is there any way to get to artifacts through the list releases call? I have used $expand=$artifactsadded to the first list function, but no artifact appeared in the response.
Any advice would be appreciated.

A:
How to get artifacts in the response from Azure DevOps REST API call that lists all releases?

You could loop the release IDs from the first list function to get all the artifacts by the ForEach ($ReleaseId in $ReleaseIds ).
$connectionToken="PAT"
$base64AuthInfo= [System.Convert]::ToBase64String([System.Text.Encoding]::ASCII.GetBytes(":$($connectionToken)"))

$url = "https://vsrm.dev.azure.com/{organization}/{project}/_apis/release/releases?api-version=7.1-preview.8"
$ReleaseInfo = (Invoke-RestMethod -Uri $url -Method Get -UseDefaultCredential -Headers @{Authorization=("Basic {0}" -f $base64AuthInfo)})

$ReleaseIds= $ReleaseInfo.value.id

Write-Host "ReleaseIds is = $($ReleaseIds | ConvertTo-Json -Depth 100)"

[string[]]$ReleaseIds = $ReleaseInfo.value.id

ForEach ($ReleaseId in $ReleaseIds )

{

    $ArtifactsInfo= "https://vsrm.dev.azure.com/{organization}/{project}/_apis/release/releases/$ReleaseId?api-version=7.1-preview.8"

    $TestplanInfo = (Invoke-RestMethod -Uri $ArtifactsInfo -Method Get -UseDefaultCredential -Headers @{Authorization=("Basic {0}" -f $base64AuthInfo)})

    ....

}


text:
Q: Android Emulator in Android Studio does not show my app I'm currently working on an android application using Android Studio. When I run my code on a Nexus 5 API 21 x86 emulator, the emulator does not show the application that I am trying to debug. I went into all applications, but I still cannot find the app I am trying to test. However, the emulator does still show an app from a previous project that I was working on. The log doesn't show any errors either when compiling the gradle and starting up the emulator.
From researching other posts, I believe it may have something to do with the version of the emulator I am running. I am not sure if that is the case and if it is how I would fix it. I have pasted a copy of my manifest below and my gradle.build. Please let me know what is wrong, this problem has been irritating me for the last several days.
 <manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.jamescho.androidgame"
    android:versionCode="1"
    android:versionName="0.5" >

    <uses-permission android:name="android.permission.WAKE_LOCK" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="17" />

    <application
        android:icon="@drawable/bxbx_char"
        android:label="Bxbx">
        <activity
            android:name="com.Bxbx.BxbxGame.Game"
            android:configChanges="keyboard|keyboardHidden|orientation"
            android:label="Bxbx"
            android:screenOrientation="portrait">
             <intent-filter>
                 <action android:name="android.intent.action.MAIN"/>
                 <category android:name="android.intent.category.LAUNCHER"/>
             </intent-filter>
        </activity>
    </application>

</manifest>

And the build.gradle
apply plugin: 'com.android.application'

android {
    compileSdkVersion 17
    buildToolsVersion "19.1.0"

    defaultConfig {
        applicationId "com.jamescho.androidgame"
        minSdkVersion 8
        targetSdkVersion 17
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.txt'
        }
    }
}

dependencies {
    compile 'com.android.support:support-v4:18.+'

A: From Android Studio, go to the AVD manager (Tools>Android>AVD). Locate your virtual device, and then under actions, select the downward triangle and hit Wipe Data. This should remove the old test APK.
If the old app is still there, try just deleting the old virtual device and creating a new one. If it is still there, you are probably selecting the wrong virtual device when starting your app.
You should also try clearing the default testing device. Under Run>Edit Configurations, select the default run configuration. On the General tab, go to the bottom under Deployment Target Options and select Open Select Target Deployment Dialog, then save and try again.

A: I got the Solution.
You have to change the adb.exe file
Download the adb.exe
File Location: C:\Users[USER]\AppData\Local\Android\sdk\platform-tools
Enjoy


text:
Q: Eclipse Scala interpreter (REPL) - proper use and debugging I would like to know what are best practises of using Eclipse Scala interpreter (Eclipse Scala IDE).
Let's say I have application with breakpoint in it. Is it possible to debug an application in such a way, that I can execute/evaluate expressions inside REPL at the specific breakpoint? If yes how can I achieve it?
Another thing that made me wonder is what's the difference between opening the interpreter as Run configuration or opening it trough Window -> Show view -> Scala interpreter.
Do you know any other uses cases of Eclipse Scala interpreter that are interesting to know about, like for example Ctrl+Shift+X to run selected expression?

A: Maybe it is an obvious advice, but in addition to merely starting REPL in Scala IDE you can run selected expression in it: just select the expression and press Ctrl+Shift+X (default hotkey).
Update
There is a comprehensive reference for Scala interpreter (thanks Mirco Dotta).
It is also worth to mention that in near future Scala interpreter is going to be enhanced significantly: integration with Scala debugger and implementation of a concept known as worksheet are on the way.


text:
Q: Android web-client (phone, table) bad works with IIS 7 I have a IIS7 web-site on Windows 2008.
From java-script I write mp3-file by http-handler:
var audio = document.getElementById("audio");
audio.src = GetMultimedia.ashx?F=" + filename;
audio.load();
audio.play();

GetMultimedia.ashx:
 Response.ClearHeaders();
 Response.ClearContent();
 Response.Clear();
 Response.ContentType = "audio/mp3";
 Response.AddHeader("content-length", FileLength().ToString());
 Response.AddHeader("Connection", "keep-alive");
 Response.BufferOutput = true;

   GetFile(ref FileBuffer);  // I get buffer of mp3-file for writing to Response
   if (FileBuffer != null)
   {
     ms = new MemoryStream(FileBuffer, 0, FileBuffer.Length, true);
     if (Response.IsClientConnected == true)
     {
       ms.CopyTo(Response.OutputStream);
       Response.Flush();
      }
   }

Problem: on Windows any browsers work fine, but on Android (Opera, internal browser) http-handler works 12 times (log below). IIS write retcode 200 0 64, after this handler calling 11 times. So, mp3-file in Response different from original because http-handler calling multiple time.
2012-11-11 15:54:13 GET /GetMultimedia.ashx V=f.mp3 HTTP/1.1 stagefright/1.2+(Linux;Android+4.0.3) 200 0 64 1069317 261 8626
2012-11-11 15:54:13 GET /GetMultimedia.ashx V=f.mp3 HTTP/1.1 stagefright/1.2+(Linux;Android+4.0.3) 200 0 0 2236677 261 8330
2012-11-11 15:56:15 GET /GetMultimedia.ashx V=f.mp3 HTTP/1.1 stagefright/1.2+(Linux;Android+4.0.3) 200 0 0 255 284 140
2012-11-11 15:56:18 GET /GetMultimedia.ashx V=f.mp3 HTTP/1.1 stagefright/1.2+(Linux;Android+4.0.3) 200 0 0 255 284 140
2012-11-11 15:56:22 GET /GetMultimedia.ashx V=f.mp3 HTTP/1.1 stagefright/1.2+(Linux;Android+4.0.3) 200 0 0 255 284 296
2012-11-11 15:56:25 GET /GetMultimedia.ashx V=f.mp3 HTTP/1.1 stagefright/1.2+(Linux;Android+4.0.3) 200 0 0 255 284 124
2012-11-11 15:56:29 GET /GetMultimedia.ashx V=f.mp3 HTTP/1.1 stagefright/1.2+(Linux;Android+4.0.3) 200 0 0 255 284 249
2012-11-11 15:56:32 GET /GetMultimedia.ashx V=f.mp3 HTTP/1.1 stagefright/1.2+(Linux;Android+4.0.3) 200 0 0 255 284 171
2012-11-11 15:56:35 GET /GetMultimedia.ashx V=f.mp3 HTTP/1.1 stagefright/1.2+(Linux;Android+4.0.3) 200 0 0 255 284 140
2012-11-11 15:56:38 GET /GetMultimedia.ashx V=f.mp3 HTTP/1.1 stagefright/1.2+(Linux;Android+4.0.3) 200 0 0 255 284 140
2012-11-11 15:56:41 GET /GetMultimedia.ashx V=f.mp3 HTTP/1.1 stagefright/1.2+(Linux;Android+4.0.3) 200 0 0 255 284 140
2012-11-11 15:56:44 GET /GetMultimedia.ashx V=f.mp3 HTTP/1.1 stagefright/1.2+(Linux;Android+4.0.3) 200 0 0 255 284 109


text:
Q: Validation Spring3 + Hibernate I try validate a BigDecimal field as the next:
@DecimalMin(value = "0.00", message = "message error validation")
private BigDecimal saldoFechaDefunProducto;
But I get the next error:
javax.validation.ConstraintViolationException: validation failed for classes...
Can anybody help me please?

A: you can validate like this :
@Digits(integer=0, fraction=2)
@Column(name = "saldoFechaDefunProducto")
private BigDecimal saldoFechaDefunProducto;

and this like can help you Hibernate Validator


text:
Q: SQL query to get the status of all the job in SQL Server I need a SQL query which should give me the latest status of all the jobs in SQL server.
Below Query i have tried to get the status but it will not give the status of all the jobs in SQL server.
SELECT  DISTINCT name AS [Job Name],
    CASE WHEN enabled=1 THEN 'Enabled'
        ELSE 'Disabled'
    END [Job Status],
    CASE    WHEN SJH.run_status=0 THEN 'Failed'
            WHEN SJH.run_status=1 THEN 'Succeeded'
            WHEN SJH.run_status=2 THEN 'Retry'
            WHEN SJH.run_status=3 THEN 'Cancelled'
    ELSE 'Unknown'
    END [Job Outcome],
    sjh.run_date,
    sjh.run_time
FROM    SYSJobs sj
LEFT    JOIN    SYSJobHistory sjh
ON      sj.job_id = sjh.job_id
WHERE   (
    sjh.run_date IN (
                    SELECT  MAX(sjh1.run_date)
                    FROM    SYSJobHistory sjh1
                    WHERE   sjh.job_id = sjh1.job_id
                    )
    OR sjh.run_date IS NULL
    )
AND     (
    sjh.run_time IN (
                    SELECT  MAX(sjh1.run_time)
                    FROM    SYSJobHistory sjh1
                    WHERE   sjh.job_id = sjh1.job_id
                    )
    OR  sjh.run_time IS NULL
    )
 ORDER  BY [Job Name]

A: Use this
select distinct j.Name as "Job Name",
case jh.run_status
when 0 then 'Failed'
when 1 then 'Successful'
when 2 then 'Retry'
when 3 then 'Cancelled'
when 4 then 'In Progress'
end as Job_Execution_Status
from sysJobHistory jh, sysJobs j
where j.job_id = jh.job_id

A: try using Row_Number()
;With Cte
as
(
    SELECT  name AS [Job Name],
        CASE WHEN enabled=1 THEN 'Enabled'
            ELSE 'Disabled'
        END [Job Status],
      CASE    WHEN SJH.run_status=0 THEN 'Failed'
        WHEN SJH.run_status=1 THEN 'Succeeded'
        WHEN SJH.run_status=2 THEN 'Retry'
        WHEN SJH.run_status=3 THEN 'Cancelled'
        ELSE 'Unknown'
        END [Job Outcome],
        sjh.run_date,
        sjh.run_time,Row_Number() Over(Partition by name Order By sjh.run_date desc,sjh.run_time desc) as rn
    FROM    SYSJobs sj
    LEFT    JOIN    SYSJobHistory sjh
    ON      sj.job_id = sjh.job_id
)

select * from cte where rn=1

If You din't Understand the scenario, then just look at the Row_Number()


text:
Q: Return entity without database Nelmio Symfony I use Nelmio to generate automatically my api doc. I would like to return an object in responseMap which is a simple class (entity without a database associated) like this :
/**
* @ApiDoc(
*  description = "Get informations from user.",
*   responseMap = {
*     200 = { "\AppBundle\Entity\MyUserInfos" },
*   },
* )
*
* @Rest\View(statusCode=Response::HTTP_OK)
* @Rest\Get("/my_user_infos")
*/
public function getMyUserInfosAction(Request $request) {
...
}

namespace AppBundle\Entity;

/**
 * MyUserInfos
 */
class MyUserInfos
{
 /**
 * @var string
 */
private $username;

/**
 * @var string
 */
private $email;

+getters and setters
}

But response object is not displayed in my api doc. Can anyone help me ?
Thanks.

A: Remove the leading backslash on you class name
/**
* @ApiDoc(
*  description = "Get informations from user.",
*   responseMap = {
*     200 = { "AppBundle\Entity\MyUserInfos" },
*   },
* )
*
* @Rest\View(statusCode=Response::HTTP_OK)
* @Rest\Get("/my_user_infos")
*/
public function getMyUserInfosAction(Request $request) {
...
}

See:https://github.com/nelmio/NelmioApiDocBundle/blob/2d70b0802144fd2c868783c46fa1be4a774967d4/Resources/doc/swagger-support.rst#multiple-response-models


text:
Q: Functional Square Root of Derivative The derivative can be seen as a linear operator $\frac{d}{dx} : C^1(\mathbb{R}) \rightarrow C^0(\mathbb{R})$. Does there exist another linear operator $ D : C^1(\mathbb{R}) \rightarrow C^0(\mathbb{R}) $ such that the composition of $D$ with itself gives the derivative operator? (That is, $D \circ D = \frac{d}{dx}$)
My inclination would be that such an operator would not exist, but I haven't been able to prove this.

A: That is called Fractional Calculus. You can even differentiate $\sqrt{2}$ times.


text:
Q: Is it possible to build Apache HtmlEmail from string representation? I'm building a ImageHtmlEmail in order to download and embed all the images from given HTML into a multipart email. I need to store that email for sending later.
Problem is, I can get the resulting email text and content-type, but I see no means to construct an ImageHtmlEmail back from a text and a content-type. Is it possible at all? Or should I go with raw javax.mail for actual sending?

A: I was able to create javax.mail.internet.MimeMessage out of String representation of an email (ASCII dump as one one get on downloading original email from gmail). However not been very successful in constructing Email subclasses like HtmlEmail from it yet.
MimeMessage mimeMessage  =  MimeMessageUtils.createMimeMessage(Session.getDefaultInstance(new Properties()), new ByteArrayInputStream(oneEmail.toString().getBytes()));

It does give me most of the things I can think of as useful using its getter methods.

A: Not sure what you mean with "building HtmlEmail from string", but constructing an ImageHtmlMail should be fairly easy, see the sample at http://commons.apache.org/email/userguide.html, all you need to provide is some html-text via setHtmlMsg()
import org.apache.commons.mail.HtmlEmail;
...

// load your HTML email template
String htmlEmailTemplate = ....

// define you base URL to resolve relative resource locations
URL url = new URL("http://www.apache.org");

// create the email message
HtmlEmail email = new ImageHtmlEmail();
email.setDataSourceResolver(new DataSourceResolverImpl(url));
email.setHostName("mail.myserver.com");
email.addTo("jdoe@somewhere.org", "John Doe");
email.setFrom("me@apache.org", "Me");
email.setSubject("Test email with inline image");

// set the html message
email.setHtmlMsg(htmlEmailTemplate);

// set the alternative message
email.setTextMsg("Your email client does not support HTML messages");

// send the email
email.send();