Constructing a coefplot from a data frame

Question: I would like to construct a coefficient plot from a data frame. With below code however I am running into the following error.
Error: $ operator is invalid for atomic vectors

Example code
library(coefplot)
model1 <- lm(price ~ carat + cut, data=diamonds)
df <- coefplot:::buildModelCI(model1)
> df
                  Value Coefficient   HighInner    LowInner  HighOuter   LowOuter  Model
cut^4          74.59427       cut^4    90.83386    58.35469   107.0734    42.1151 model1
cut.C         367.90995       cut.C   388.12410   347.69579   408.3383   327.4816 model1
cut.Q        -528.59779       cut.Q  -505.46541  -551.73018  -482.3330  -574.8626 model1
cut.L        1239.80045       cut.L  1265.90049  1213.70040  1292.0005  1187.6004 model1
carat        7871.08213       carat  7885.06176  7857.10251  7899.0414  7843.1229 model1
(Intercept) -2701.37602 (Intercept) -2685.94495 -2716.80710 -2670.5139 -2732.2382 model1
coefplot(df)
Error: $ operator is invalid for atomic vectors

Answer: After much trial and error I worked out how to edit the source code for the coefplot multiplot function.
Creating our test datasets.
library(coefplot)

model1 <- lm(price ~ carat + cut, data=diamonds)
model2 <- lm(price ~ carat + cut + color, data=diamonds)
model3 <- lm(price ~ carat + color, data=diamonds)
dflist <- list(buildModelCI(model1), buildModelCI(model2), buildModelCI(model3))
dflist

Now below is the adjusted code for the multiplot function that will take the dflist data frame containing the coefficients rather then a list of models.
#edited version of buildModelCI.default for parsing the dataframes
modelfunc <- function(model, outerCI=2, innerCI=1, intercept=TRUE, numeric=FALSE,
                     sort=c("natural", "magnitude", "alphabetical"),
                     decreasing=TRUE, name=NULL, ...)
{
  modelCI <- model
  sort <- match.arg(sort)
  ## possible orderings of the coefficients
  ordering <- switch(sort,
                     natural=order(1:nrow(modelCI), decreasing=decreasing),   # the way the data came in
                     magnitude=order(modelCI$Value, decreasing=decreasing),     #  size order
                     alphabetical=order(modelCI$Coefficient, decreasing=decreasing),    # alphabetical order
                     order(1:nrow(modelCI))     # default, the way it came in
  )

  # implement the ordering
  modelCI <- modelCI[ordering, ]
  modelCI$Coefficient <- factor(modelCI$Coefficient, levels=modelCI$Coefficient)

  return(modelCI)
}

#new function for multiplot coeffcient plots
mymultiplot <- function (..., title = "Coefficient Plot", xlab = "Value", ylab = "Coefficient",
                         innerCI = 1, outerCI = 0, lwdInner = 1, lwdOuter = 0, pointSize = 3,
                         dodgeHeight = 1, color = "blue", shape = 16, linetype = 1,
                         cex = 0.8, textAngle = 0, numberAngle = 90, zeroColor = "grey",
                         zeroLWD = 1, zeroType = 2, single = FALSE, scales = "fixed",
                         ncol = length(unique(modelCI$Model)), sort = c("natural",
                                                                        "normal", "magnitude", "size", "alphabetical"), decreasing = TRUE,
                         names = NULL, numeric = FALSE, fillColor = "grey", alpha = 1/2,
                         horizontal = FALSE, factors = NULL, only = NULL, shorten = TRUE,
                         intercept = TRUE, interceptName = "(Intercept)", coefficients = NULL,
                         predictors = NULL, strict = FALSE, newNames = NULL, plot = TRUE,
                         drop = FALSE, by = c("Coefficient", "Model"), plot.shapes = FALSE,
                         plot.linetypes = FALSE, legend.position = "right", secret.weapon = FALSE)
{
  if (tryCatch(is.list(...), error = function(e) FALSE)) {
    theDots <- list(...)[[1]]
    if (is.null(names(theDots))) {
      names(theDots) <- sprintf("Model%s", 1:length(theDots))
    }
  }
  else {
    theDots <- list(...)
  }
  theArgs <- unlist(structure(as.list(match.call()[-1]), class = "uneval"))
  if (is.null(names(theArgs))) {
    theNames <- theArgs
  }
  else {
    theNames <- theArgs[names(theArgs) == ""]
  }
  if (is.null(names(theDots))) {
    names(theDots) <- theNames
  }
  sort <- match.arg(sort)
  by <- match.arg(by)
  legend.position <- match.arg(legend.position)
  if (secret.weapon) {
    by <- "Model"
    horizontal <- TRUE
  }
  if (by == "Model" & length(coefficients) != 1) {
    stop("If plotting the model along the axis then exactly one coefficient must be specified for plotting")
  }
  #new code to parse data frames
  modelCI <- plyr:::ldply(theDots, modelfunc, outerCI = outerCI,
                          innerCI = innerCI, intercept = intercept, numeric = numeric,
                          sort = sort, decreasing = decreasing, factors = factors,
                          shorten = shorten, coefficients = coefficients, predictors = predictors,
                          strict = strict, newNames = newNames)
  #oldcode to parse models
  #modelCI <- plyr:::ldply(theDots, .fun = buildModelCI, outerCI = outerCI,
  #                 innerCI = innerCI, intercept = intercept, numeric = numeric,
  #                 sort = sort, decreasing = decreasing, factors = factors,
  #                 shorten = shorten, coefficients = coefficients, predictors = predictors,
  #                 strict = strict, newNames = newNames)
  modelCI$Model <- modelCI$.id
  modelCI$.id <- NULL
  if (!is.null(names)) {
    names(names) <- theNames
    modelCI$Model <- names[modelCI$Model]
  }
  if (drop) {
    notNA <- daply(modelCI, .variables = "Model", function(x) {
      !all(is.na(x$Coef))
    })
    modelCI <- modelCI[modelCI$Model %in% names(which(notNA ==
                                                        TRUE)), ]
  }
  if (!plot) {
    return(modelCI)
  }
  p <- coefplot:::buildPlotting.default(modelCI = modelCI, title = title,
                                        xlab = xlab, ylab = ylab, lwdInner = lwdInner, lwdOuter = lwdOuter,
                                        pointSize = pointSize, dodgeHeight = dodgeHeight, color = color,
                                        shape = shape, linetype = linetype, cex = cex, textAngle = textAngle,
                                        numberAngle = numberAngle, zeroColor = zeroColor, zeroLWD = zeroLWD,
                                        outerCI = outerCI, innerCI = innerCI, zeroType = zeroType,
                                        numeric = numeric, fillColor = fillColor, alpha = alpha,
                                        multi = TRUE, value = "Value", coefficient = by, horizontal = horizontal,
                                        facet = FALSE, scales = "fixed")
  theColorScale <- list(Coefficient = scale_colour_discrete("Model"),
                        Model = scale_color_manual(values = rep(color, length(unique(modelCI$Model))),
                                                   guide = FALSE))
  theShapeScale <- list(NoShapes = scale_shape_manual(values = rep(shape,
                                                                   length(unique(modelCI$Model))), guide = FALSE), Shapes = scale_shape_manual(values = 1:length(unique(modelCI$Model))))
  theLinetypeScale <- list(NoShapes = scale_linetype_manual(values = rep(linetype,
                                                                         length(unique(modelCI$Model))), guide = FALSE), Shapes = scale_linetype_manual(values = 1:length(unique(modelCI$Model))))
  p + theColorScale[[by]] + theShapeScale[[plot.shapes + 1]] +
    theLinetypeScale[[plot.linetypes + 1]] + theme(legend.position = legend.position) +
    if (!single)
      facet_wrap(~Model, scales = scales, ncol = ncol)
}

Now we plot the graphs with the new function
mymultiplot(dflist)

Answer: library(arm)
data(diamonds)
model1 <- lm(price ~ carat + cut, data=diamonds)
model2 <- lm(price ~ carat + carat, data=diamonds)

You cannot directly build a coefplot from a df since the arguments passed into the coefplot function have to be "fitted objects-lm, glm, bugs and polr, or a vector of coefficients"
However, you may call your coef from df like this
# df with model1 and model2 coefs
df <- as.data.frame(cbind(model1[[1]], model2[[1]]))
coefplot(model1, coefs = as.vector(df[,1]))

if you want to display multiple model coefs, you may use
par(new=TRUE)
# display coefs of model2
coefplot(model1, coefs = as.vector(df[,2]))


$\forall a \in \mathbb{Z} : a^2 \geq 0$

Question: Can we decide whether this statement would be True or False or would that be meaningless?
The mathematical statement translates to For all $a$ in the set of Integers such that the square is greater than or equal to zero.
Comment: It depends on the structure youre interpreting the statement in but in case you're wondering if it is possible in some case to decide whether this statement would be true or false the answer is yes.
Comment: If that is supposed to be a proposition that *the squares of all integers are non-negative*  then it is true
Comment: How are you supposed to know it is a proposition. I thought it was a set of $\mathbb{Z}$.
Answer: It is true. A square of an integer is indeed non-negative.
Comment: This is not a helpful answer, despite being a literal "answer" to the "question" OP asked. I would refrain from answering such questions.
Answer: I see two possible interpretations of what you have said: one is true and one is incomplete.
If you wanted to say this: "For every integer, its square is non-negative", i.e. $$(\forall a\in\mathbb{Z})a^2\ge 0$$
then this is true.
If you wanted to say this: "For every integer whose square is non-negative...", i.e. $$(\forall a\in\mathbb{Z}: a^2\ge 0)$$
this is an incomplete sentence. (For every integer whose square is non-negative - what?) You can complete it (e.g. by adding something that could be true about that integer), after which it will make sense, and depending on what you've written it may be true or false. For example:
$$(\forall a\in\mathbb{Z}: a^2\ge 0) a\ge 0$$
("Every integer whose square is non-negative, is itself non-negative") - this is a sentence which happens to be false.
Logically, the sentence $(\forall a\in\mathbb{Z}:a^2\ge 0)P(a)$ is equivalent to $(\forall a\in\mathbb{Z})(a^2\ge 0\implies P(a))$, whatever predicate $P$ you choose.

$\forall a \in \mathbb{Z} : a^2 \geq 0$


Burlando encurtadores com python

Question: Eu necessito para meu projeto, alguma função usando Python 2.7 que entre em um URL, e pegue o URL seguinte dele.
-> Exemplo:
goo.gl/LAKFXG = https://pt.stackoverflow.com/
bit.ly/2D3SEnZ = https://pt.stackoverflow.com/
Não quero usar o API destas URLS, e sim algo que realmente entre na url e me devolva a URL final. Porém, estou sem ideias.
Alguma biblioteca? Lembrando que não quero usar as API de encurtadores.
Comment: Como não trabalho com Python, vou deixar uma dica que talvez lhe ajude. Utilize o comando `cURL` do Python para acessar essa url. Porém, ao invés de retornar o "body", você retorna apenas os "headers". Tendo os headers, basta filtrar por *location*, *followlocation*, etc.
Comment: O que está a implementar é algo do tipo _URL unshortener_?
Answer: <code>import urllib2
r = urllib2.urlopen(url="https://shorturl.com")
print 'URL redirecionada:', r.url
</code>
Comment: Heey! Consegui acabar com o erro. 403 forbidden! pastebin.com/5tyzikbD
Obrigado frank!
Comment: urllib2.HTTPError: HTTP Error 403: Forbidden
O que faço neste caso?
Comment: Qual URL você tentou?
Segundo os códigos de estado, isso é um erro de proibição: https://pt.wikipedia.org/wiki/Lista_de_códigos_de_estado_HTTP#403_Proibido

```>>> r = urllib2.urlopen(url="https://goo.gl/LAKFXG")
>>> r.url
'https://pt.stackoverflow.com/'```
Comment: Não os headers. Qual URL você tentou? Para que eu possa replicar o erro.
Comment: Agora man. Eu aconselharia fortemente o uso da biblioteca requests e python3. Se você não tiver com algum projeto em ambiente de produção claro.
Comment: Em que o requests + python3 atrapalharia ambientes em produção @FranklinTimóteo ?
Comment: Ele está utilizando python2, o que eu quis dizer é que ele pode trocar para python3 e usar a biblioteca requests, porém se ele estiver usando python2 com projeto em produção, concorda que seria difícil fazer essa troca da noite para o dia? A questão é: mude para python3 o mais rápido possível, mas se já utiliza python2 e não quer perder tempo com retrabalho, continue com python2 até ter tempo para fazer a devida modificação.
Comment: A própria documentação do urllib2 recomenda o uso de requests. https://docs.python.org/2/library/urllib2.html . Ahh mas isso é só para obter uma URL final, porque usar uma biblioteca mais robusta? Verdade, não faz sentido. Mas se pensarmos no futuro onde você queria aprimorar seu programa?!

Burlando encurtadores com python


nondecreasing f prove integrable with upper and lower sums

Question: I have been given a question as such:
If $f$ is nondecreasing on $[0,1]$ use upper and lower sums to prove $f$ is Riemann Integrable.
So I know that using upper and lower sums to prove a riemann integral I have to show that the upper sum equals the lower sum and I know that
the upper sum = $\sum_{j=1}^{n} M_j(x_j-x_{j-1})$
the lower sum = $\sum_{j=1}^{n} m_j(x_j-x_{j-1})$
Where the x's are the size of the intervals and the big M is the upper height and little m is lower height. I'm just not so sure how I should go about using the fact f is non decreasing to prove the lower and upper sums equal each other.
Answer: If $f$ is non decreasing you can give explicit expressions in terms of $f$ for $M_i$ and $m_i$.
Comment: Ok, so I'm pretty sure I can say $m_i \le f(x) \le M_i$ because $f$ is nondecreasing, and that satisfies one of the properties of the Riemann Integral. I can also probably say $m_i(x_i - x_{i-1}) \le f(x)$, and $M_i(x_i - x_{i-1}) \ge f(x)$, correct? Is this enough to prove the function is Riemann integrable? Is it even correct? I've just been introduced to these sums so I'm still trying to gain some intuition on the topic.
Comment: $m_i\le f(x)\le M_i$ holds wether $f$ is decreasing or not. Another hint: if $f$ decreases in $[x_{i-1},x_i}]$, what is the maximum value it can have? At which $x$ does it take that maximum value?
Answer: If $f$ is nondecreasing, then the lower sums would be strictly increasing and bounded above by the upper sums. Simply apply the monotone convergence theorem from there.


What statistical test to use for multiple variables?

Question: I am trying to find out what test should I use to prove or not if There is positive and significant relationship between consumers' environmental values/awareness and consumers' view on Coca-Cola and Pepsi.
In order to do so I use the responses I got from a questionnaire, they are all categorical data
question 5, 7, 8, 9, 10, 11, relates to the consumers' environmental values and question 13, 14, 15, 16, 17, 18 relates to consumers' view on Coca-Cola and Pepsi.
That is quite a lot of variables, therefore I don't know what test to use with SPSS!! anyone could help please?
Many thanks,
Comment: Welcome to the site. First, questions about code are off topic here, so if you just want SPSS code, you need to ask elsewhere. But it seems like there is a statistics question here, but it's unclear. My blog post [how to ask a statistics question](https://statisticalanalysisconsulting.com/how-to-ask-a-statistics-question/) may help you formulate it so it can be answered.
Answer: You might construct a multidimensional contingency table and test for independence of the two groups of variables. I do not know SPSS. Canonical correlation would also be an option for continuous variables, which is not the case.


How can I run a command using python2 as the interpreter if I have Anaconda 3?

Question: Im trying tto emulate an android device on my linux computer. I decided to go with androidviewclient and Culebra.
However, I think both are designed for python2, because when I run
culebra --version

I get the error:

File "/home/user/anaconda3/envs/mobile/bin/culebra", line 155
print progname, version
^ SyntaxError: Missing parentheses in call to 'print'. Did you mean print(progname, version)?

I installed it using pip within and Anaconda 3 environment. I have installed python2.7 but when I run python it still uses python3. I can however run python2 using /usr/bin/python2.7.
When I run culebra, I guess it still runs it using python3, hence the error with the brackets. How can I run the culebra command using python2?
Answer: To install or upgrade the python3 compatible version (which is a pre-release) you can run
$ pip3 install --pre androidviewclient --upgrade

and it will install 20.x.y.


Difference in  using normalized gradient and gradient

Question: In general setting of gradient descent algorithm, we have $x_{n+1} = x_{n} - \eta * gradient_{x_n}$ where $x_n$ is the current point, $\eta$ is the step size and $gradient_{x_n}$ is the gradient evaluated at $x_n$.
I have seen in some algorithm, people uses normalized gradient instead of gradient. I wanted to know what is the difference in using normalized gradient and simply gradient.
Comment: Can I ask a question? how can I calculate the normalized gradient if I have already obtained the gradient vector? If the gradient vector is numeric large, I need to normalize the gradient. Could you give some intuitive examples about normalizing gradient? Thank you!
Answer: In a gradient descent algorithm, the algorithm proceeds by finding a direction along which you can find the optimal solution. The optimal direction turns out to be the gradient. However, since we are only interested in the direction and not necessarily how far we move along that direction, we are usually not interested in the magnitude of the gradient. Thereby, normalized gradient is good enough for our purposes and we let $\eta$ dictate how far we want to move in the computed direction. However, if you use unnormalized gradient descent, then at any point, the distance you move in the optimal direction is dictated by the magnitude of the gradient (in essence dictated by the surface of the objective function i.e a point on a steep surface will have high magnitude whereas a point on the fairly flat surface will have low magnitude).
From the above, you might have realized that normalization of gradient is an added controlling power that you get (whether it is useful or not is something upto your specific application). What I mean by the above is:
1] If you want to ensure that your algorithm moves in fixed step sizes in every iteration, then you might want to use normalized gradient descent with fixed $\eta$.
2] If you want to ensure that your algorithm moves in step sizes which is dictated precisely by you, then again you may want to use normalized gradient descent with your specific function for step size encoded into $\eta$.
3] If you want to let the magnitude of the gradient dictate the step size, then you will use unnormalized gradient descent.
There are several other variants like you can let the magnitude of the gradient decide the step size, but you put a cap on it and so on.
Now, step size clearly has influence on the speed of convergence and stability. Which of the above step sizes works best depends purely on your application (i.e objective function). In certain cases, the relationship between speed of convergence, stability and step size can be analyzed. This relationship then may give a hint as to whether you would want to go with normalized or unnormalized gradient descent.
To summarize, there is no difference between normalized and unnormalized gradient descent (as far as the theory behind the algorithm goes). However, it has practical impact on the speed of convergence and stability. The choice of one over the other is purely based on the application/objective at hand.
Comment: You could take a intermediate approach where you normalize based on the first gradient, for example.  This would still make the relative gradient size matter in terms of step size.
Answer: Which method has faster convergence will depend on your specific objective, and generally I use the normalized gradient.  A good example of why you might want to do this is a simple quadratic: $f(x) = x^Tx$.  In this case the ODE that describes a given gradient descent trajectory (as step sizes approaches zero) can be determined analytically: $y(t) = x_0/||x_0|| * e^{-t}$.  So, the norm of the gradient decreases exponentially fast as you approach the critical point.  In such cases it's often better to bounce back and forth across the min a few times than to approach it very slowly.  In general though, first order methods are known to have very slow convergence around the critical points so you should not really be using them if you really care about accuracy.  If you can't compute the Hessian of your objective analytically you can still approximate it (BFGS).
Answer: What really matters is how $\eta$ is selected.  It doesn't matter whether you use the normalized gradient or the unnormalized gradient if the step size is selected in a way that makes the length of $\eta$ times the gradient the same.


How does 5 Limit tuning get its ratios?

Question: I want to know how 5 Limit Tuning calculates ratios.
I am currently reading Harmonic Experience by W.A. Mathieu and in some of the beginning pages he says something about "five-limit lattice", which I am assuming has to do with five limit tuning, although I'm finding it really difficult to grasp my head on how the tuning system works and how it compares with other tuning systems, like 12 Tone Equal Temperament.
Comment: Did you try a Google search of "5-limit tuning", which, as its first result, gives the Wikipedia page for "Five-limit tuning", which in turn explains the system, including the lattice? If yes, then perhaps you could post a more specific question about where you're stuck.
Answer: Five-limit tuning gets its ratios from the observation that thirds and sixths are particularly pleasant when they are tuned according to the overtone series.  Most notably, when the major third is in tune with the fifth harmonic of the root, the ratio of the pitches is 5:4.
Other intervals may be derived from this interval and the basic interval of three-limit (better known as "Pythagorean") tuning, which is the perfect fifth with a ratio of 3:2, through inversion, composition (stacking intervals on top of each other) or complementation (finding the interval between two other intervals -- and inversion is in fact a special case of complementation where one of the two intervals is the octave).
To compose two intervals, multiply their ratios.  For example, the major seventh is the composition of the perfect fifth and the major third, so its ratio is 15:8.
To calculate the complement of one interval with respect to another, divide their ratios.  For example, the minor sixth is the inversion, or octave complement, of the major third, so its ratio is 8:5, and the minor third is the fifth's complement of the major third, so its ratio is 6:5.
The whole step or tone is the composition of two perfect fifths, octave adjusted, so 9:8, but the interval between 5:4 and 9:8, which is also a whole step, is 10:9, giving us two different sizes of whole step, known as the major tone and the minor tone.
Intervals may of course be calculated in more than one way, which sometimes gives the same result and sometimes does not.  The major sixth, for example, is the octave complement of the minor third (which gives 5:3) and the composition of the perfect fourth and major third or of the perfect fifth and minor tone (also 5:3).  But it's also a perfect fifth above the major second, which is a major tone, and combining those intervals gives a ratio of 27:16.
The ratio between 27:16 and 5:3 is the same as the ratio between 9:8 and 10:9, that is to say 81:80.  This is known as the syntonic or Ptolemaic comma.  It is slightly smaller than the (perhaps better known) Pythagorean comma.
The term "five limit" comes from the observation that building intervals in this manner from the major third, perfect fifth, and octave yields a system where the prime factors of the ratios are only 2, 3, and 5.  In other words, the prime factors are less than or equal to 5.
As to how this system compares to equal temperament, well, the major third is about 14 cents narrower, the minor third is about 16 cents wider, and the perfect fifth is about two cents wider.  Accordingly, if you try to tune a keyboard in 5-limit just intonation, some intervals will be very pure and well tuned, whereas others will be very badly out of tune (notably the 27:16 perfect fifth that usually appears between the second and sixth degrees of the major scale).  (Consequently, as Pythagorean tuning came to be seen as unsuitable for keyboards, it was replaced not with just intonation but with various meantone temperaments, but a discussion of meantone temperaments is beyond the scope of the question.)
Alternatively, if you use just intonation with singers or instruments that can alter the tuning of individual notes during a performance, you typically find that a given pitch has to be tuned differently in different harmonic contexts.
Comment: Should I be asking you to cite sources for each assertion in this answer?
Comment: @ToddWilcox I see no reason why you shouldn't ask.  I'm not sure how much it would add to the answer, though.  Many of the assertions seem self-evident to me or are developed in the answer itself (for example the proof of "intervals may of course be calculated in more than one way, which sometimes gives the same result and sometimes does not").  Are there particular assertions that you find particularly suspect, or at least less self evident than I might think?
Comment: @ToddWilcox or if you're asking for sources supporting the cent figures, they should be easy to find; they're also easy to calculate.  Should I add the formula?  I find the answer s bit too long as it is, and I just noticed that I completely failed to address the part of the question concerning the lattice.

How does 5 Limit tuning get its ratios?


Equivalence of two definitions of polar of polytope

Question: Let $a_i \in \mathbb{R}^n$. $P = \{ x_i \vert \  a_i \cdot x_i \leq 1 \ \forall x_i \in \mathbb{R}^n, i \in [1\dots n] \}$, P is bounded. Since P is a bounded polyhedra, it is a polytope (by Weyl-Minkowski).
Now, consider:
$$
\begin{align}
Q_1 &= \text{Conv}(a_1, a_2, \dots, a_n) \\
Q_2 &= \{ y  \mid  y \cdot p \leq 1, \forall y \in \mathbb{R}^n, \forall p \in P \}
\end{align}
$$
Prove that $Q_1 = Q_2$. We know that $Q_2$ is the standard definiton of polar. We wish to show equivalence to the first form. Roughly, we wish to show that the polar of a polytope is a polytope, with the new vertices being the hyperplane normals. Note that we are using a normalized polytope, with the constraints $\leq 1$.
Forward direction of proof ($Q_1 \subseteq Q_2$)
The rough sketch is as follows. Let $q \in Q_1$. Since $Q_1$ is the convex hull of $a_1, \dots, a_n$:
$$
q = \sum_i a_i \lambda_i \\
$$
Where $\lambda_i$ are of the form:
$$
\begin{align}
\lambda_i &\in \mathbb{R} \\
\lambda_i &\geq 0 \\
\sum_i \lambda_i &= 1
\end{align}
$$
$\forall p \in P$, consider $q \cdot p$.
$
q \cdot p =
(\sum_i a_i \lambda_i) \cdot p =
\sum (a_i \cdot p) \lambda_i
$
Each $a_i \cdot p \leq 1$, because $p \in P$, hence by definition of $P$ the inequality holds.
Therefore, $\sum (a_i \cdot p) \lambda_i \leq \sum 1 \lambda_i \leq \sum \lambda_i$.
We know that $\sum \lambda_i = 1$ by definition.
Hence, $\forall p \in P, q \cdot p \leq \sum \lambda_i \leq 1$.
Hence, $q \in Q_2$, and $Q_1 \subseteq Q_2$.
Backward Direction of Proof ($Q_2 \subseteq Q_1$)
I have gotten stuck when trying to prove this. The obstacle I face is this: given some point $q \in Q_2$, we need to actually describe such a point as a convex combination of $a_i$. I have no idea how to come up with the $\lambda_i$ coefficients.
Any proof strategy hints would be very welcome :)
Comment: Your definition of $P$ does not make sense due to the $\forall x_i$. Do you mean $P = \{ x \in \mathbb{R}^n : a_i \cdot x \leq 1 \forall i \in \{1,..,n\} \}$?
Answer: The following incomplete proof uses LP duality.
$$\begin{align}
Q_2 &= \{ y \in \mathbb{R}^n \mid y \cdot p \leq 1 \; \forall p : a_i \cdot p \leq 1 \} \\
&= \{ y \in \mathbb{R}^n \mid \max_p \{ y \cdot p \mid a_i \cdot p \leq 1 \} \leq 1 \} \\
&= \{ y \in \mathbb{R}^n \mid \min_{\lambda \in \mathbb{R}^n_+} \{ \sum \lambda_i \mid \sum_i \lambda_i a_i = y \} \leq 1 \} \\
&= \{ y \in \mathbb{R}^n \mid \exists \lambda \in \mathbb{R}^n_+ : \sum_i \lambda_i \leq 1, \sum_i \lambda_i a_i = y \}
\end{align}$$
This is almost correct, the only problem being the sum of $\lambda$ is not necessarily $1$. We have not used that $P$ is bounded.
Comment: It has to do with $0 \in Q_i$, and giving it weight $1-\sum_i \lambda_i$.
Comment: Thanks for the pointer. I'm actually unsure how you would control $\lambda_i$ using the fact that $P$ is bounded. May I have a hint or a full proof? I've never seen duality used within algebraic manipulation before :)


Attempting to add a widget with type GtkBox to a GtkWindow

Question: #include <gtk/gtk.h>
#include <stdbool.h>

int main ( int argc, char *argv[] )
{
  GtkWidget   *page;
  GtkWidget   *vbox;
  GtkWidget   *toolbar;
  GtkWidget   *Label1;

  GtkToolItem *new;
  GtkToolItem *open;
  GtkToolItem *save;
  GtkToolItem *exit;
  GtkToolItem *setting;
  GtkToolItem *about;

  void NEW_PROJECT ();
  void EXIT_FROM_SOFTWARE ();

  gtk_init ( &argc, &argv );

  /* Window configure */
  page = gtk_window_new ( GTK_WINDOW_TOPLEVEL );
  gtk_window_set_title        ( GTK_WINDOW(page), "Stack over flow" );
  gtk_window_set_default_size ( GTK_WINDOW(page), 800, 500 );
  gtk_window_set_resizable    ( GTK_WINDOW(page), FALSE );
  g_signal_connect            ( G_OBJECT (page), "destroy", G_CALLBACK (gtk_main_quit), NULL );
  /* Window configure */

  GtkWidget *button;
  button=gtk_frame_new ("An example of different info bars");
  /* Add the button to window */
  gtk_container_add(GTK_CONTAINER(page),button);

  /* Toolbar configure */
  vbox = gtk_box_new            ( TRUE, 0 );
  gtk_container_add             ( GTK_CONTAINER (page), vbox );
  toolbar = gtk_toolbar_new     ();
  gtk_toolbar_set_style         ( GTK_TOOLBAR (toolbar), GTK_TOOLBAR_ICONS );
  new = gtk_tool_button_new     ( gtk_image_new_from_icon_name ("tab-new-symbolic", GTK_ICON_SIZE_SMALL_TOOLBAR), NULL );
  gtk_toolbar_insert            ( GTK_TOOLBAR (toolbar), new, -1 );
  open = gtk_tool_button_new    ( gtk_image_new_from_icon_name ("emblem-default-symbolic", GTK_ICON_SIZE_SMALL_TOOLBAR), NULL );
  gtk_toolbar_insert            ( GTK_TOOLBAR (toolbar), open, -1 );
  save = gtk_tool_button_new    ( gtk_image_new_from_icon_name ("user-trash-symbolic", GTK_ICON_SIZE_SMALL_TOOLBAR), NULL );
  gtk_toolbar_insert            ( GTK_TOOLBAR (toolbar), save, -1 );
  gtk_toolbar_insert            ( GTK_TOOLBAR (toolbar), gtk_separator_tool_item_new(), -1 );
  about = gtk_tool_button_new   ( gtk_image_new_from_icon_name ("mail-mark-junk-symbolic", GTK_ICON_SIZE_SMALL_TOOLBAR), NULL );
  gtk_toolbar_insert            ( GTK_TOOLBAR (toolbar), about, -1 );
  setting = gtk_tool_button_new ( gtk_image_new_from_icon_name ("applications-system-symbolic", GTK_ICON_SIZE_SMALL_TOOLBAR), NULL );
  gtk_toolbar_insert            ( GTK_TOOLBAR (toolbar), setting, -1 );
  gtk_toolbar_insert            ( GTK_TOOLBAR (toolbar), gtk_separator_tool_item_new(), -1 );
  exit = gtk_tool_button_new    ( gtk_image_new_from_icon_name ("edit-delete-symbolic", GTK_ICON_SIZE_SMALL_TOOLBAR), NULL );
  gtk_toolbar_insert            ( GTK_TOOLBAR (toolbar), exit, -1 );
  gtk_box_pack_start            ( GTK_BOX (vbox), toolbar, FALSE, FALSE, 5 );
  //Signal Connection to the widghts
  g_signal_connect              ( G_OBJECT (exit), "clicked",
        G_CALLBACK              ( EXIT_FROM_SOFTWARE), NULL );
  g_signal_connect              ( G_OBJECT (new), "clicked",
        G_CALLBACK              ( NEW_PROJECT), NULL );
  /* Toolbar configure */

  gtk_widget_show_all           ( page );

  gtk_main                      ();
  return 0;
}

void NEW_PROJECT () {}
void EXIT_FROM_SOFTWARE () {}

I have GTKButton and gtk_box_new but when I run my code, only one of them is displayed.
And the compiler report:
$ gcc Setup.c -o Setup  `pkg-config --cflags --libs gtk+-3.0` -rdynamic && ./Setup

(Setup:3937): Gtk-WARNING **: 22:32:11.813: Attempting to add a widget with type GtkBox to a GtkWindow, but as a GtkBin subclass a GtkWindow can only contain one widget at a time; it already contains a widget of type GtkFrame

You see that:

But when I delete this block from source:
GtkWidget *button;
button=gtk_frame_new ("An example of different info bars");
gtk_container_add(GTK_CONTAINER(page), button);

The software runs like this:

As far as I understand, the library cannot display two widgets at the same time.
So in this case, how to make complex software?
Maybe I didn't write the code correctly, but in this case, the compiler would give an error.
I searched the internet but did not find a similar item on your website
There was no similar case in Google to solve my problem.
I use GTK3 in Fedora Gnome.
Comment: Sorry, I'm newbie in the Gtk, so it is may be the stupid question. Please answer and do not rate negative
Answer:
As far as I understand, the library cannot display two widgets at the same time.

Not correct. The only restriction is a GtkBin cannot contain more than one widget at a time.
We see here:
page = gtk_window_new ( GTK_WINDOW_TOPLEVEL );

That page is a GtkWindow which is a subclass of GtkBin.
You add button to page:
gtk_container_add(GTK_CONTAINER(page),button);

And then you try to add vbox to page:
gtk_container_add( GTK_CONTAINER (page), vbox );

This causes the error message:

Attempting to add a widget with type GtkBox to a GtkWindow, but as a GtkBin subclass a GtkWindow can only contain one widget at a time; it already contains a widget of type GtkFrame

Instead, try adding button to vbox instead of to page directly, because a GtkBox can hold multiple items at once but a GtkWindow cannot.


Evaluating behavior of a black-box sequence

Question: Suppose a black box produces a sequence of vectors $(x_k)$ in $\mathbb{R}^n$.
Suppose that sequence is not convergent.

What are good measures of nonconvergence/chaoticness etc. to evaluate nonconvergent sequences?

I am interested in measuring how much the sequence wanders/exploits $\mathbb{R}^n$, and whether or not it exhibits "chaotic behavior" etc. I could monitor $\|x_k\|$ to see whether or not it blows up. Any other measures (ideally with literature references) would be appreciated.
Comment: For chaoticity Lyapunov exponents are often measured. For example, start from [here](https://www.cs.colorado.edu/~lizb/chaos/wolf-notes.pdf).
Comment: @Evgeny this is fantastic - please make this a real answer as it might be useful for other folks as well.
Answer: It seems you have already got your answer in the comments. Nevertheless, I will add some more details.
Chaos itself is a vague concept and there does not exist a universally accepted definition for it. But from what I have seen, the most common way of detecting chaos is by calculating the Lyapunov exponents. Mathematically speaking

The Lyapunov exponent or of a dynamical system is a quantity that characterizes the rate of separation of infinitesimally close trajectories. For a sequence of vectors, one can assume that these vectors are the trajectory positions of a hypothetical system at discrete times.

The Lyapunov exponent can also be considered as a measure of stability, i.e. in a linear system, the Lyapunov exponents are equal to the eigenvalues of its characteristic matrix. In this case, they can be easily calculated. But in general, there doesn't exist any straightforward way to calculate them.
There are several algorithms for estimating the Lyapunov exponents. You may refer to this article for a short survey on some of these methods. One simple method, as noted in the comments, is Wolf's algorithm. Another popular approach is proposed by Eckmann et al. and later optimized by Rosenstein et al.
In practice $-$if you are familiar with Python, you can use the nolds package, which implements the Rosenstein method for computing the Lyapunov exponents. It has a simple interface:
import nolds
import numpy as np

rwalk = np.cumsum(np.random.random(1000))
h = nolds.lyap_e(rwalk)


Redirect to mobile page (not theme switching)

Question: I'm looking for a way to redirect mobile users to a mobile landing page (and I'm not looking for a theme switcher). I have a specific page that I'd like to redirect mobile users to: www.mysite.com/m/
Is there a way to utilize Mobile_Detect.php and specify a single page as the redirect target?
Answer: I suppose if you really wanted to, you could do something along the lines of this in a custom module:
function YOURMODULE_init() {

  if ($_SERVER['REQUEST_METHOD']=='GET' // most ajax/ahah etc use POST
      && arg(0)!='admin' // admin theme/backend
      && strpos($_GET['q'], 'sites/default/files')===FALSE // are we looking at anything under files that doesn't "really" exist, eg imagecaches that aren't created yet
      && $_GET['q']!='m') { // aren't already "here"

    include 'PATHTOSCRIPT/Mobile_Detect.php';
    $detect = new Mobile_Detect();

    if ($detect->isMobile()) {
      drupal_goto('m');
    }

  }

}

but they could never leave, or rather, be able to go to any other page on your site.
Addition:  per @MPD's comments, some further protections.
Comment: hook_init() runs on every request, including imagecache renders, AJAX, admin backend, etc.  Drupal 7 offers better alternatives for a lot of what we used hook_init() for in Drupal 6.  In this case, I don't think there are any better hooks you can use.  Just keep in mind that you may been some additional logic to prevent the redirection on your imagecahce, AJAX, etc if you need them.
Comment: I heard some performance issues about `hook_init` what you think ?
Comment: what performance issues have you heard about or are concerned with?  I've seen talk here ( http://drupal.stackexchange.com/questions/36265/alternatives-to-hook-init ) about some issues but none too too stressful.  Granted, hook_init() is run "last" so I suppose you could put this somewhere deeper/earlier into the stack, but, for what the user asked, I don't see that extra/double drupal bootstrapping to be a really big issue.  Opinions mine of course.  (And this is a quick and dirty solution as well :)
Comment: @Jimajamma thanks for that snippet. I don't suppose there is a way around this?
Answer: My preference when doing mobile redirection is to use a javascript solution instead of PHP. It doesn't impact the load times significantly, and can easily be adjusted for more complex logic if required (user-agent, platform, etc).


Conditional Expectation : How is E[E[xy|x]]=E[xE[y|x]]?

Question: I read that "The law of total expectations states E[xy]=E[E[xy|x]]. By linearity of conditional expectations, E[E[xy|x]]=E[xE[y|x]]" but I am not able to understand the part "E[E[xy|x]]=E[xE[y|x]]"
I would be really thankful if you could explain this.
Comment: A related Q with a more rigorous answer is at (https://stats.stackexchange.com/questions/501366/conditional-expectation-an-implication)
Answer: To supplement the other answers by Taylor and mhdadk, I find it has never led me astray to have absolute clarity on the probability distributions with respect to which one is computing expectations.
And if the properties being used by the other answers are unfamiliar, then it can be useful to return to the original definition of expectation and conditional expectation, and to see how these properties are merely abbreviations for what is going on with the integral.
In the continuous case, i.e. assuming that $X, Y \in \mathbb{R}$, we have a marginal density $f_X(x)$, conditional density $f_{Y | X}(y | x)$, and a joint density $f_{X, Y}(x,y)$. Omitting the range of integration $(-\infty, \infty)$ as well as formal technicalities, we have that
\begin{align}
\mathbb{E}_{X, Y}[XY] &= \iint xy f_{X, Y}(x, y) \space dy \space dx \\
&= \iint xy f_{Y|X}(y|x) f_X(x) \space dy \space dx \\
&= \int f_X(x) \int xy f_{Y|X}(y|x) \space dy \space dx  \space (= \mathbb{E}_X[\mathbb{E}_{Y|X}[XY \mid X]])\\
&= \int xf_X(x) \int y f_{Y|X}(y|x) \space dy \space dx\\
&= \mathbb{E}_{X} [X \space \mathbb{E}_{Y|X}[Y \mid X]]
\end{align}
From 1st to 2nd equality, I have the used fact that $f_{X, Y} = f_X \cdot f_{Y|X}$. From 2nd to 4th equality, both $f_X$ and $x$ can be factored out of the inner integral, because the inner integral is with respect to $y$. The final equality follows from the definitions. All integrals can be replaced with summations in the discrete case, which Xi'an has covered more generally and with a greater degree of rigour in the following thread:
Conditional expectation: an implication
Answer: \begin{align}
E[E[XY|X=x]] &= E[E[xY|X=x]] \\
&= E[xE[Y|X=x]]
\end{align}
In the first line, $X$ in the inner expectation is assumed to be constant, so it is replaced accordingly. In the second line, $E[aX] = aE[X]$ for any constant $a$ by the linearity of the expectation operator.
Answer: You can reduce this question to this: why is
$$
E[XY|X] = XE[Y|X]
$$
(with probability 1)? If this is true, then you can just take expectations on both sides.
The answer is "because of the (technical) definition of conditional expectation." Thinking of  it like the linearity property of nonconditional expectations can be helpful, too. If it is, stick with that.


What is the expected progression from being able to "play a piece" and "perfecting a piece"?

Question: I've played the piano as a hobby on and off for over 20 years. While I did take lessons for several years as a child/young-teen, it was always quite casual. Now, as an adult, I realize that I've never really learned pieces to perfection (*see note below); I typically find a new piece, practice it for a few weeks until I can play through it at tempo (mostly) and move on to another.
My questions are:

What is the expected amount of work or amount of time required to take pieces from "I can play this" to "I can play this perfectly*"?
What does this process look like?
As a hobby pianist, is it worth it? What is gained from this process? (I feel bad asking this one, but I mean it as a serious question, so I'll put it out there anyway in hopes I won't be judged too harshly.)

EDIT Note* I've left the question as originally stated and added this note explaining what I intended by the word "perfect":
There has been lots of discussion already about what is meant by the word "perfect" here. Of course there is room for interpretation by others, but I think some have given me better words to convey my meaning: perhaps "performance ready" or "polished" would have been better choices instead of "perfect".
My intended meaning is something like the difference between "I can play this piece through mostly at tempo with some hiccups" and "I would be surprised if I made any mistakes (wrong notes, restarts, unplanned-pauses)". Maybe some wouldn't consider a piece in the first statement as "learned", but as a hobby pianist, this is often where I get.
Besides just the notes, to get to "polished" or "performance ready" surely includes work on more subjective aspects of music. I'm grateful for guidance on this aspect too, but this was not the intended meaning of my question.
Sorry for the confusion. Appreciate the comments/answers so far. Hopefully that helps :)
Comment: What do you mean by "perfect"?
Comment: Does this answer your question? [How should one practice a piece that is learned, but not fully mastered?](https://music.stackexchange.com/questions/33443/how-should-one-practice-a-piece-that-is-learned-but-not-fully-mastered)
Comment: A criterion: if a piece can be played ten times in succession, with no hesitations or wrong notes, with correct dynamics, at the written tempo, then maybe, just maybe, it could be considered perfect. But there again...
Comment: Yeah, the term "perfect" is subjective and that may get this question closed. What is perfect? Does it mean every note must be struck with the exact same amount of force down to the decibel? Does the tempo have to be in line with an atomic clock pulse? Does a missed note disqualify one from perfection, or is it only if the missed note is noticed? Great underlying question, but we will need it edited to a more objective phrasing. (Just an idea: what about "playable" versus "concert-ready"?)
Answer: You asked three questions:

How long does it take to get to "perfect,"
How do I, and
Why should I?

Let's take them out of order, and first take some time to get a working definition of "perfect."
It's true, "perfect" isn't really a useful goal. It's as if astrophysicists ask "how long until we've learned everything we possibly can about the universe?" There's always something more. The saying "practice makes perfect" is absurd, as if you wake up one day and discover that you got your "Perfect Badge" and never need to practice again. Instead, we set ourselves a goal of playing at a certain level, and when we meet that we set a higher goal. E.g., Goal 1 is play all the notes correctly; Goal 2 might be to increase the interpretive and emotional nuance.
But there's nothing wrong with using the word "perfect" if this is in fact what we mean, "perfect enough for my current goal." Perhaps a useful definition for this discussion would be "good enough that I could play the piece for others and both they and I would enjoy it."

Ok, now that we've got a definition, let's start with the third question.

As a hobby pianist, is it worth it? What is gained from this process?

Presumably, you're playing "for fun," for your own enjoyment, not for money, for the congratulations of friends, or to accompany the school musical. Well, the only thing to be gained is new kinds and levels of enjoyment. (As to whether they're worth it, that's up to you.) If we take the analogy of visual art, there could be a certain enjoyment in making a quick charcoal sketch every day, and there's another enjoyment in spending weeks making a detailed oil painting with meticulous detail. Right now you're enjoying the "discovery" phase of learning a piece, and there's a lot to enjoy there. What you're missing is the satisfaction of "seeing" the finished product, as well as many secondary "discovery" phases in which you uncover new facets of a piece you thought you already new. There's also a heady thrill when you attempt something challenging and succeed. The first day you play completely through at performance speed is a bit like the moment from any superhero origin story in which a mild-mannered civilian discovers they have new powers. Young Clark Kent runs through the cornfield and catches air. Keanu Reeves opens his eyes and says "I know kung fu." And there's a related thrill, some time later, from being able to effortlessly kick the %$#@ of a piece that used to be impossible ("Puny god").

Second question:

What does this process look like?

Unfortunately, between "I know kung fu" and "We have a Hulk" comes a period of drudgery. This is the "practice" that makes "perfect" (if we allow generous scare-quotes). This is the portion that would be rendered as a training montage, but while we're rocking out to "Gonna Fly Now," Rocky still has to chug the raw eggs and run up the steps of the Philly art museum, and it takes him days and weeks rather than minutes. It's not all torture, though; this period is full of mini-milestones with mini-rewards.
For musicians, there's a familiar set of tools and techniques; see these Q/As and no doubt many other posts here about "how to practice." The metronome is your best friend. Start slow, build gradually. Isolate difficult bits, then recontextualize them. Turn off the metronome and work on expression. Record yourself and play it back.
Most of all, even if the only goal is personal fulfillment, you might want to create some informal performances. Performance for others is its own unique joy, and it provides a goal that motivates your work. It's often helpful to book some very small, low-stakes performances before a big one, as part of the learning process (e.g., before a recital, play in a coffeeshop, in a friend's living room, on the sidewalk for change).
And of course, if you're interested, the very best way to accelerate learning is to get lessons.

And finally, the first question:

What is the expected amount of work or amount of time required to take pieces from "I can play this" to "I can play this perfectly"?

Substituting "satisfactorily in a performance" for "perfectly"... well, as I'm sure you can guess, the answer is "It depends." Depends on how hard the piece is, whether you already have a head-start (is it one you played as a kid?), how long and often you practice, and on where you draw the line for "satisfactorily." If you've played for 20 years, you could probably play something out of a beginner piano book "perfectly" with hours if not minutes of practice. A Rachmaninoff concerto might be impossible to attain in a lifetime. But in general? Let's assume that you're at a level at which you play "real pieces," Bach inventions, Chopin etudes, etc. Let's assume that the piece in question is of only "medium" difficulty, and is around 5 minutes long. Let's assume you practice for about half an hour per day, 5 days a week. With those conditions, your experience might look something like:

First week: getting familiar with the notes. Can play most of the piece through, but have to slow down to muddle through some hard bits.
Next month or so (more if the piece is hard): Getting mastery over the hard bits. Can play through at a consistent tempo, sometimes without mistakes (if not always).
Next month: Success becomes more consistent. Start memorizing the piece. If you haven't already, perhaps you start attaining your goal tempo. In this period you pay a lot of attention to expression, nuance, and interpretation (though hopefully you've been working on them to some degree all along).
Last few weeks before "big performance": In this stage you are simply practicing performing; this is where you put the informal performances. Get used to stopping for nothing. Get used to the act of performing the piece. Get familiar with the patterns of what you think about in which moment, how you need to prepare for what comes next. Find out whether the dramatic and emotional gestures you want are actually coming through to your listeners.
"Big performance"
Weeks, months, and years later: Keep maintaining the piece by reviewing now and then. Play it for the sheer fun of being able to bust out something that you know cold. Keep it in your working memory so you have something to show off if called on. Keep discovering new secrets about it and new levels of mastery as the years go on.
Comment: Along with informal performance, you can record your self. That can be a real eye opener! Reviewing your recorded history can help track/encourage progress.
Answer: Perfect is unobtainable. I mean in the philosophical sense. In general use "perfect" means some very high level of performance.
As a hobby, amateur pianist (both of us, I'm an amateur too) I think it doesn't make sense to think about perfection. To play very well, yes. But, "perfection" seems contradictory to being an amateur. Realistically speaking, if we were approaching perfection, aren't we more than amateurs?

What is the expected amount of work or amount of time required to take pieces from "I can play this" to "I can play this perfectly"?

If you listen to the greatest pianists, they say it's a lifetime pursuit. But it's too broad a question. You need to consider the difficulty and length of the piece, your familiarity with the genre.
But, regarding time general, play daily and set weekly and monthly goals. Weekly goals could be the initial break down of learning a new piece, with a monthly goal of initially playing the full piece. Those are just suggestions, you can find other periods that work for you. The point is to set short/medium/long term goals. Work on your weak points. Make incremental improvements, then move on to the next practice goal. "Perfection" is most definitely not the focus with this approach. Identifying weaknesses and incremental improvement and the focus.
Thinking about your music library and repertoire would be good. Maybe to try to devote long term attention to a half dozen pieces while working up a decent performance of a new piece once a week. Then file the weekly pieces back into the library. Something like that strikes a nice balance between fresh material and a main repertoire. It's good to get time away from familiar material and then return to it. It can refresh and deepen your understanding of familiar stuff.
Sight reading should be part of daily practice.

What does this process look like?

I think you can approach this a few different ways. I won't get into basic technical practice, things like determining a fingering, practicing hands separately, etc. I assume of the mechanical and memorization stuff is something you know about. If not, perfection isn't even remotely the topic to think about.
Once past the mechanical/memory phase, I think a very good way to start "polishing" a performance (maybe that's a better word that "perfecting") is to play the piece in  various tempos and articulations. Some styles like Baroque don't indicate much detail in tempo/articulation so there is a lot of freedom. In other score with lots of indications, you still have room for variety. The point is less about how to articulate whatever markings may be in the score and more about exercising your performance control in the piece. Are you just able to "get through" with the one performance manageable, or can you at will change your expressive playing?
Another thing to try is a sort of "rehearsal marking" practice. From memory can you start up the piece at any arbitrary phrase? Are you only able to play from start to finish? If you really know the piece, you should know all the phrases without the queues of playing from the start. This is more of a memory thing. But, the more solid your memory of the musical structure, the more concentration you can devote to expressive details.
Another thing I have tried, but can be challenging for large or complex works, it transposing to another key. The challenge is both about memory and structural understanding of the music, but also about technical flexibility and changing fingerings for different keys. This too is more a technical challenge, but with the eventual goal of overcoming the technical to be able to concentrate on the expressive.
Answer: It's going to depend a lot on what your (or the piano player's) target is.
If it's to perform pieces at a concert in front of the public, if it's to be used in an examination situation, if it's just to experience a certain composer's style, if it's just to give the player a sense of satisfaction, etc.
'Perfect' in music is way too subjective. I might play a piece in several different ways, all of which could be deemed 'perfect' for those different situations. Solo, with one other muso, in an ensemble , for examples. Maybe you consider playing exactly as writ. is 'perfect'. If so, there are many concert pianists out there who are 'far from perfect' in their renditions!
'Interpretation' muddies that whole concept.
Answering the 1st question: just how long is that piece of string? How difficult is the piece? How much of an advanced player is playing? How quickly do you learn? Sorry, unanswerable.
Answering the 2nd question:the process can have many different looks. One may play through a few times and it's 'perfect', others may take 2 hrs a day and after 3 months it's still not learned well enough. Yet others may never reach that state with certain pieces. There are some that after 20 yrs, I still can't deliver well enough !
Answering the 3rd question: very dependent on what your aims actually are. Often, I use certain pieces to highlight a particular technique (a skill that needs honing). The fact that they're contained in a piece is by the by. It may/may not be interesting to learn or be able to play the whole piece well, but getting to grips with the technique is the target. If the rest of that piece is only 'o.k.', then that's good enough for me, as the teacher at that point.
Answer: It depends 100% on the song you're trying to learn, your own skill, and your own perception of the word "perfect".
Take Chopin's Waltz in a minor. It is quite easy to learn, but harder to get "perfect". Compare this performance with this. The first one is played "perfectly", while the other one is just a computer playing. The computer plays exactly the right notes at the exact perfect tempo, but without all those little ritardandos, accelerandos, etc.
Another good example for this is Beethoven's Moonlight Sonata, 1st Movement. Extremely easy chords, but playing it "perfect" is a little harder.
On the contrary to this, there are other songs that have only little room for improvising and are for that reason easier to master. These songs are mostly modern songs, or just generally songs that have multiple instruments and/or vocals, for example Nothing Else Matters

TD;DR
It depends on the song, and your interpretation of it. You may master a song that's hard to learn in just 10 minutes, and an easy one in 10 days.


What is the simplest way to show that $x\log(1+\frac{a}{x})$ is an increasing function of $x$?

Question: How to show that $x\log(1+\frac{a}{x})$ is an increasing function of $x$ for non-negative values of $x$? Actually its derivative is $$\log\left(1+\frac{a}{x}\right)-\frac{a}{a+x}$$ ($a$ is positive) where we can see that the second term is negative> so how to show that the derivative of $x\log(1+\frac{a}{x})$ is positive? Thanks in advance.
Comment: You knoe the second derivative is always negative so first derivative is decreasing. Calculate the limit as x tends to infinity of the first derivative. You will get the limit is positive. Thus the derivstive is always positive
Comment: Try to look at the second derivative
Comment: Is $a$ nonnegative as aswell?
Comment: The fact that there seems to be the limit definition of $e^a$ in there might be important
Comment: No $a$ is positive
Comment: @AndrewLi would you please that definition?
Comment: A very useful fact about the $\log$ function is that $\log(1+y) \leq y$ for all $y>-1$. It seems that can be used to evaluate your derivative.
Comment: @Patrick the second derivative is always negative and is equal to $$-\frac{a^2}{x(a+x)^2}$$. How to proceed further? I am not sure how to cater for all the possible values of $a$? Please guide me on this
Comment: @Patrick you are absolutely right. I can understand it for finite values of $a$ but will it be true for $a=\infty$ also?
Comment: I don't understand how you define the function for a infinity. It doesn't make any sense to me.
Comment: @Patrick wouldn't it come out to be zero, so nonnegative, but not positive?
Comment: @Patrick Ok maybe i have to add some line so that $a$ is always finite
Comment: @Frank Moses I think $a$ would have to be finite since it is a constant.
Comment: @Tyberius didn't calculate the limit myself as i'm on my phone. If the limit is zero, you can still argue the the derivative is non zero. If it's zero at some point x it has to be zero at all points t>x which cannot be true
Comment: @Patrick the limit of the first derivative as $x\to \infty$ is not positive. It is zero
Comment: @Patrck but if we limit the values of $x$ to a certain finite positive value then using your comment we can say that the derivative is always positive uptill that finite value of $x$.
Comment: @Frank Moses I think this gets at the subtle point of increasing vs strictly increasing. Strictly increasing means that the derivative is always positive over some interval, while increasing just means it is nonnegative, so this should still satisfy your problem.
Answer: I think the most parsimonious way to do this is via the integral representation of the logarithm. To start, note that
$$\begin{split}\frac{\ln(1+t)}{t}&=\frac{1}{t}\int_1^{1+t}\frac{\mathrm{d}t'}{t'}\\
&=\frac{1}{t}\int_0^{t}\frac{\mathrm{d}u}{1+u}\\
&=\int_0^{1}\frac{\mathrm{d}v}{1+tv}\text{.}
\end{split}$$
Substitute $t\leftarrow a/x$ and multiply both sides by $a$. Then
$$x\ln(1+a/x)=\int_0^{1}\frac{ax\mathrm{d}v}{x+av}$$
so
$$\frac{\mathrm{d}}{\mathrm{d}x}\left(x\ln(1+a/x)\right)=\int_0^{1}\frac{a^2v\mathrm{d}v}{(x+av)^2}$$
which is manifestly positive.
Comment: Thank you great explanation.
Answer: The function $g(u) = (1 + u)\log(1 + u) - u$ is increasing for $u > 0$. Indeed,
$$
g^{\prime}(u) = \log(1 + u) + \dfrac{1 + u}{1 + u} - 1 = \log(1 + u) \geq 0 \quad \text{to} \quad u \geq 0
$$
But, $g(0) = 0$. Thus, $g(u) > g(0) = 0$ if $u > 0$ or
$$
(1 + u)\log(1 + u) > u \quad \Rightarrow \quad \log(1 + u) - \dfrac{u}{1 + u} > 0
$$
for $u > 0$. For $u = a/x$, we have
$$
\log\biggl(1 + \dfrac{a}{x}\biggr) - \dfrac{a/x}{1 + a/x} > 0 \quad \Rightarrow
$$
$$
f^{\prime}(x) = \log\biggl(1 + \dfrac{a}{x}\biggr) - \dfrac{a}{a + x} > 0 \quad \Rightarrow
$$
$f$ increasing.
Answer: Using the integral definition of $\log$,
$\begin{array}\\
(x\log(1+\dfrac{a}{x}))'
&=\log\left(1+\frac{a}{x}\right)-\dfrac{a}{a+x}\\
&=\int_1^{1+\frac{a}{x}}\dfrac{dt}{t}-\dfrac{a}{a+x}\\
&=\int_0^{\frac{a}{x}}\dfrac{dt}{1+t}-\dfrac{a}{a+x}\\
&=\int_0^{\frac{a}{x}}\dfrac{dt}{1+t}-\dfrac{a/x}{1+a/x}\\
&=\int_0^{\frac{a}{x}}\left(\dfrac{1}{1+t}-\dfrac{1}{1+a/x}\right)dt\\
&=\int_0^{\frac{a}{x}}\left(\dfrac{(1+a/x)-(1+t)}{(1+t)(1+a/x)}\right)dt\\
&=\int_0^{\frac{a}{x}}\left(\dfrac{a/x-t}{(1+t)(1+a/x)}\right)dt\\
&\ge 0
\qquad\text{since } \frac{a}{x} \ge t\\
\end{array}
$


Enable a single CGI script for Apache within the document root?

Question: Is it possible to enable a single CGI script stored within the Apache 2.4 document root ?
I was hoping something like the following might be possible :
<VirtualHost *:80>
    DocumentRoot "PATH/TO/htdocs/localhost"
    ServerName localhost
    ErrorLog "logs/localhost/errors.log"
    CustomLog "logs/localhost/access.log" common

    ScriptAlias "/python/" "PATH/TO/htdocs/localhost/python/index.py"
    <Files "PATH/TO/htdocs/localhost/python/index.py">
      Options +ExecCGI
      AddHandler cgi-script .py
      Require all granted
    </Files>
</VirtualHost>

OR should I really be placing this within CGI-bin ?
Answer: Apache really discourages the placement of scripts within ones htdocs. In my case this is for a fallback virtual host on a local development machine, so I can get away with the following :
PATH/TO/htdocs/localhost/index.html
PATH/TO/scripts/localhost/index.py

Specifying a DirectoryIndex indicates my preference for the python file over the static html file. The former then moved to a new location as indicated above.
<VirtualHost *:80>
    DocumentRoot "PATH/TO/htdocs/localhost"
    ServerName localhost
    ErrorLog "logs/localhost/errors.log"
    CustomLog "logs/localhost/access.log" common

    DirectoryIndex index.py index.php index.html

    ScriptAlias "/python/" "PATH/TO/scripts/localhost/python/index.py"
    <Files "PATH/TO/scripts/localhost/python/index.py">
      Options +ExecCGI
      AddHandler cgi-script .py
      Require all granted
    </Files>
</VirtualHost>

Comment: I'll leave this as unanswered for the moment in case some one has a better suggestion. I'd be interested in any alternatives.


Flow in Datasource or Repository?

Question: Where should I emit data with the flow? Repository or Datasource? Why?
Answer: Depending on your specific use case and design, you can use Flow in both a repository and a data source in Android.
In a repository, you might use Flow to expose a stream of data to the rest of your app. For example, you might have a repository that retrieves a list of users from a database or API.
In a data source, you might use Flow to asynchronously stream data from a data source to the repository or the UI layer. For example, you might have a data source that retrieves a large dataset from a remote API.
Which one is common?
Using Flow in a repository is more common in Android development. This is because a repository is often used as an abstraction layer between the data sources and the rest of the app, and it provides a clean API for accessing and modifying data.
Using Flow in a repository can make it easy to observe changes to the data and handle asynchronous operations, such as network requests or database queries, in a clean and efficient way

Flow in Datasource or Repository?


How to debug memcached "SERVER HAS FAILED AND IS DISABLED UNTIL TIMED RETRY" errors?

Question: I have a two server memcached setup. When memcached write fails, I receive an email notification. About once per day "SERVER HAS FAILED AND IS DISABLED UNTIL TIMED RETRY" error comes and I have no idea how to find the reason.
I am using PHP Memcached client.
I am not using too long keys. I tried adding -v flag, but it does not help, the log remains empty.
If I include output of getStats to the error notification, I receive the following info:
Array
(
    [192.168.0.3:11211] => Array
        (
            [pid] => 28167
            [uptime] => 3671962
            [threads] => 4
            [time] => 1358714713
            [pointer_size] => 64
            [rusage_user_seconds] => 24516
            [rusage_user_microseconds] => 130981
            [rusage_system_seconds] => 86246
            [rusage_system_microseconds] => 675512
            [curr_items] => 1616352
            [total_items] => 118339822
            [limit_maxbytes] => 2684354560
            [curr_connections] => 8
            [total_connections] => 78108681
            [connection_structures] => 356
            [bytes] => 981522779
            [cmd_get] => 1561752945
            [cmd_set] => 158718324
            [get_hits] => 1383072575
            [get_misses] => 178680370
            [evictions] => 0
            [bytes_read] => 138113231690
            [bytes_written] => 1091741700765
            [version] => 1.4.15
        )

    [192.168.0.4:11211] => Array
        (
            [pid] => -1
            [uptime] => 0
            [threads] => 0
            [time] => 0
            [pointer_size] => 0
            [rusage_user_seconds] => 0
            [rusage_user_microseconds] => 0
            [rusage_system_seconds] => 0
            [rusage_system_microseconds] => 0
            [curr_items] => 0
            [total_items] => 0
            [limit_maxbytes] => 0
            [curr_connections] => 0
            [total_connections] => 0
            [connection_structures] => 0
            [bytes] => 0
            [cmd_get] => 0
            [cmd_set] => 0
            [get_hits] => 0
            [get_misses] => 0
            [evictions] => 0
            [bytes_read] => 0
            [bytes_written] => 0
            [version] =>
        )

)

Answer: MEMCACHED_SERVER_TEMPORARILY_DISABLED or "SERVER HAS FAILED AND IS DISABLED UNTIL TIMED RETRY" is generated by libmemcached library. I'm unable to confirm how pecl_memcached handles this error, but I imagine it would be treated as a standard connectivity error. This message would be issued when a connection exceeds time-out and/or retry limit. (see  I/O Options)
Naturally, as this is a temporary issue, you would architect your PHP application to fall-over to the next cache server, or pull affected server out of server list.
Comment: So you are saying there is no way to get rid of such errors? Why do they occur then? There should be a reason.
Answer: In my case turning off the behavior option tcp_nodelay made it work.
This seems to be an option of pylibmc, which is a python wrapper around the libmemcached, but the docs says, that this option belongs to the ones directly configurable in libmemcached.
For more info see pylibmc docs http://sendapatch.se/projects/pylibmc/behaviors.html
Answer: I my case, I changed localhost to '127.0.0.1' in my code. and i am able to resolve error 'SERVER HAS FAILED AND IS DISABLED UNTIL TIMED RETRY'
hope that helped
'options' => array(
            'servers' => array('127.0.0.1', 11211),

Answer: In my case the reason for this error message was an incorrect server name.
Somehow the code preparing the configuration string for use was messed up, and a space character went in front of one of the memcache server names. This results in the above mentioned error message when reading from the server.
I am using PHP and the Memcached extension. Adding the server name with the space worked without any complaint, i.e. there is no internal validation for them. The are only checked at the time a connection to the server has to be made.


Uniqueness of the initial topology

Question: The Initial Topology $\tau_X $(as defined below) and its uniqueness is characterised by two certain properties.
I would like to know, what happens to the uniqueness of $\tau_X $, if you remove one or even both properties? Possibly $\tau_X $ is then no longer unique. How would/could such topologies then look like?
Given: A set $X$ and $(Y_i)_{i \in \ I}$ topological spaces and maps $f_i : X \rightarrow Y_i$
There is then an unique topology $\tau_X$ with:

All $f_i$ are continuous
Given a topological space $Z$ and a map $g: Z \rightarrow X$, then:
$g$ continuous $\Leftrightarrow f_i \circ g: Z \rightarrow Y_i $ continuous $\forall i \in I$

$\tau_X$ defined above is called the Initial Topology or the Cofinal Topology with respect to the $f_i$.
Comment: Well, if you do not assume 2, then any topology on $X$ finer than $\tau_X$ is possible.
Answer: If you just assume 1. we could just take the discrete topology on $X$ and this would make all functions continuous on it.
Usually the initial topology is defined as the intersection of all topologies that make all $f_i$ continuous. This intersection is non-empty (the discrete topology is one of these topologies as we saw) and the intersection of topologies is again a topology. The property 2. then follows, once you observe that we can also say that $X$ is the topology generated by the subbase $\mathcal{S}=\{f_i^{-1}[O]: i \in I, O \subseteq Y_i\}$.
The nice part is that property 2 implies that $X$ must carry this topology. I write more on this in this answer.
In fact, property 2. implies property 1, because $g= \mathrm{id}_X$ is always continuous. So just property 2 alone characterises the initial topology.

Uniqueness of the initial topology


Using and Abusing wikipedia/investopedia as a source. Is it an issue?

Question: Im interested in improving my answering methods for this site.
For the most part I'm sourcing most of my answers either from Wikipedia or Investopedia, sometimes even just copying and pasting and would really like to know if original answers are necessary for this site and want to know how I can improve the quality of my answers (ie. a format or set of instructions).
Comment: If you happen to have access to the [Palgrave Dictionary of Economics](http://www.dictionaryofeconomics.com/dictionary), that is a much better source of articles than Wikipedia. Also, I would use journal articles or working papers as much as possible.
Answer: There are two issues here, regarding answers:
1) Correctness
Wikipedia and Investopedia have, in general, a positive record as regards the correctness of what their Economics and Econometrics lemmas include (although incomplete in many cases), but it would be advisable to use them as sources only if you can feel certain that the lemma you are sourcing from is indeed correct. This leads to the following general suggestion:

We should not answer questions just because we can find an answer in an
  online encyclopedia - we should answer questions we already know something
  about.

2) Originality
In a site such as ours that asks for answers based on mathematics, data and relevant scientific literature, "originality" has to do mainly with how the answerer will combine knowledge and sources to provide help for the OP and long-lasting high-quality content for the site. Then "copy-pasting" sources (irrespective of whether one acknowledges the act or not), is not very "original", except when we do feel that the exact passage summarizes very well the issues, or when what we want is to relay information about, say, the contents of a book.
Still, in such cases my suggestion would be to explicitly quote and come up with a commentary after the quote, even if it is only something like "I don't think I can summarize the issue better than the above quote", or "from how the author discusses the contents of his book, we see that he focuses mainly on..., leaving perhaps less space for...". This creates originality in the answer, a characteristic that is seen to be different from original material strictly defined.
Caveat: I may have not always "follow my own advice" in every single answer I have posted on this site as regards "copy-pasting" from sources. But my suggestions stand, and I better make sure that I will follow them in the future.
Comment: +1 I would just add that, if we answer a question we already know something about from a textbook or academic paper, a supporting reference from Wikipedia or Investopedia, which are readily accessible to all, is sometimes more helpful than one to the textbook or paper.  People may not have that textbook (or that edition of it) to hand, and for some the paper may be behind a paywall.
Comment: @AdamBailey  Thank you, this is a very good and helpful point you are making.


opengl strange behavior when using two shaders

Question: I have two shaders, one for instancing, one for just plotting a line. They correspond to two segments of code (segment1 for instancing and segment2 for a line) respectively. And the programing behaviour is weird:

When I put segment2 behind segment1, then the segment1 work just dispeared. Then I comment the code of segment2, segment1 works. Then I uncomment segment2 code and put it before segment1. Then both segments works. This is strange.
So I just put segment2 before segment1 to let it work. But what I want is that when pressing some keys, the view will move. But here is the thing:

a. when both segments uncommented, the instancing will move as expected, but the line just stays at where it borns.
b. then I comment the segment2 code, then the line will move as expected when keys pressed.

There must be some connections of the two problems. Here is some of the code, it's not runnable, I will provide full runnable code if necessary.
#include <stdio.h>
#include <stdlib.h>
#include <glad/glad.h>
#include <iostream>
#include <vector>
#include <algorithm>
#include <GLFW/glfw3.h>
#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtx/norm.hpp>
#include <thread>
#include <queue>
#include <mutex>
#include <glm/gtx/string_cast.hpp>
#include "../common/shader.hpp"

GLFWwindow *window;
using namespace glm;
using std::cout, std::endl;

int run_websocket(); // another thread run this function to get data into the queue
extern std::queue<std::tuple<unsigned long, float, float, bool>> queue1;
extern std::mutex m;

const int MaxParticles = 100000;
const int MaxLine = 1000;
int index = 0;
int width = 1024;
int height = 768;
float deltaTime = 0.0f;
float lastFrame = 0.0f;

void framebuffer_size_callback(GLFWwindow *window, int width1, int height1) {
    width = width1;
    height = height1;
    glViewport(0, 0, width1, height1);
}

void processInput(GLFWwindow *window) {
    if (glfwGetKey(window, GLFW_KEY_ESCAPE) == GLFW_PRESS)
        glfwSetWindowShouldClose(window, true);

    float f1 = 10000;
    float f_up_down = 10;
    float cameraSpeed = deltaTime;
    if (glfwGetKey(window, GLFW_KEY_N) == GLFW_PRESS)
        cameraPos += cameraSpeed * (cameraFront * f_up_down);
    if (glfwGetKey(window, GLFW_KEY_M) == GLFW_PRESS)
        cameraPos -= cameraSpeed * (cameraFront * f_up_down);
    if (glfwGetKey(window, GLFW_KEY_A) == GLFW_PRESS)
        cameraPos -= glm::normalize(glm::cross(cameraFront, cameraUp)) * (cameraSpeed * f1);
    if (glfwGetKey(window, GLFW_KEY_D) == GLFW_PRESS)
        cameraPos += glm::normalize(glm::cross(cameraFront, cameraUp)) * (cameraSpeed * f1);
    if (glfwGetKey(window, GLFW_KEY_W) == GLFW_PRESS)
        cameraPos += glm::normalize(cameraUp) * (cameraSpeed * f_up_down);
    if (glfwGetKey(window, GLFW_KEY_S) == GLFW_PRESS)
        cameraPos -= glm::normalize(cameraUp) * (cameraSpeed * f_up_down);
}

glm::vec3 cameraPos = glm::vec3(0.0f, 0.0f, 10.0f);
glm::vec3 cameraFront = glm::vec3(0.0f, 0.0f, -1.0f);
glm::vec3 cameraUp = glm::vec3(0.0f, 1.0f, 0.0f);

unsigned long x0 = 0;
float y00 = 0.0f;

int main(void) {
    // Initialise GLFW
    std::thread t1(run_websocket);
    if (!glfwInit()) {
        fprintf(stderr, "Failed to initialize GLFW\n");
        getchar();
        return -1;
    }

    glfwWindowHint(GLFW_SAMPLES, 4);
    glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
    glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
    glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);

    // Open a window and create its OpenGL context
    window = glfwCreateWindow(width, height, "title", NULL, NULL);
    if (window == NULL) {
        fprintf(stderr,
                "Failed to open GLFW window. If you have an Intel GPU, they are not 3.3 compatible. Try the 2.1 version of the tutorials.\n");
        getchar();
        glfwTerminate();
        return -1;
    }
    glfwMakeContextCurrent(window);
    glfwSetFramebufferSizeCallback(window, framebuffer_size_callback);

    // glad: load all OpenGL function pointers
    // ---------------------------------------
    if (!gladLoadGLLoader((GLADloadproc) glfwGetProcAddress)) {
        std::cout << "Failed to initialize GLAD" << std::endl;
        return -1;
    }

    glEnable(GL_BLEND);
    glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
    glfwSetInputMode(window, GLFW_STICKY_KEYS, GL_TRUE);
    glfwPollEvents();
    glClearColor(0.0f, 0.0f, 0.0f, 0.0f);

    GLuint programID = LoadShaders("Particle.vertexshader",
                                   "Particle.fragmentshader");
    GLuint shader2 = LoadShaders("line.vertexshader",
                                 "line.fragmentshader");

    GLuint ViewProjMatrixID = glGetUniformLocation(programID, "VP");
    GLuint ViewProjMatrixID2 = glGetUniformLocation(shader2, "VP2");
    static GLfloat *g_particule_position_size_data = new GLfloat[MaxParticles * 4];
    static GLfloat *g_line_data = new GLfloat[MaxLine * 4];
    static const GLfloat g_vertex_buffer_data[] = {
            -1.0f, -1.0f,
            1.0f, -1.0f,
            -1.0f, 1.0f,
            1.0f, -1.0f,
            -1.0f, 1.0f,
            1.0f, 1.0f,
    };
    // vao of segment2
    GLuint LineVertexArrayID;
    glGenVertexArrays(1, &LineVertexArrayID);
    glBindVertexArray(LineVertexArrayID);
    GLuint line_buffer;
    glGenBuffers(1, &line_buffer);
    glBindBuffer(GL_ARRAY_BUFFER, line_buffer);
    glBufferData(GL_ARRAY_BUFFER, MaxLine * 4 * sizeof(float), NULL, GL_STREAM_DRAW);
    glEnableVertexAttribArray(0);
    glVertexAttribPointer(
            0,
            2,
            GL_FLOAT,
            GL_FALSE,
            2 * sizeof(float),
            (void *) 0
    );
    glBindVertexArray(0);
    // vao of segment2 ends

    // vao of segment1
    GLuint VertexArrayID;
    glGenVertexArrays(1, &VertexArrayID);
    glBindVertexArray(VertexArrayID);
    GLuint billboard_vertex_buffer;
    glGenBuffers(1, &billboard_vertex_buffer);
    glBindBuffer(GL_ARRAY_BUFFER, billboard_vertex_buffer);
    glBufferData(GL_ARRAY_BUFFER, sizeof(g_vertex_buffer_data), g_vertex_buffer_data, GL_STATIC_DRAW);
    glEnableVertexAttribArray(0);
    glVertexAttribPointer(
            0,
            2,
            GL_FLOAT,
            GL_FALSE,
            2 * sizeof(float),
            (void *) 0
    );
    GLuint particles_position_buffer;
    glGenBuffers(1, &particles_position_buffer);
    glBindBuffer(GL_ARRAY_BUFFER, particles_position_buffer);
    glBufferData(GL_ARRAY_BUFFER, MaxParticles * 4 * sizeof(GLfloat), NULL, GL_STREAM_DRAW);
    glEnableVertexAttribArray(1);
    glVertexAttribPointer(
            1,
            4,
            GL_FLOAT,
            GL_FALSE,
            4 * sizeof(float),
            (void *) 0
    );
    glVertexAttribDivisor(1, 1);
    glBindVertexArray(0);
    // vao of segment1 ends

    do {
        glClear(GL_COLOR_BUFFER_BIT);
        float currentFrame = glfwGetTime();
        deltaTime = currentFrame - lastFrame;
        lastFrame = currentFrame;
        processInput(window);

        glm::mat4 projection = glm::mat4(1.0f);
        glm::mat4 view = glm::lookAt(cameraPos, cameraPos + cameraFront, cameraUp);
        projection = glm::perspective(glm::radians(90.0f), 1000.0f, 0.1f, 1000.0f);
        glm::mat4 ViewProjectionMatrix = projection * view;
        glm::mat4 ViewProjectionMatrix2 = projection * view;
        glUniformMatrix4fv(ViewProjMatrixID, 1, GL_FALSE, &ViewProjectionMatrix[0][0]);
        glUniformMatrix4fv(ViewProjMatrixID2, 1, GL_FALSE, &ViewProjectionMatrix2[0][0]);

        // why move segment2 behind segment1 then segment1 will not show ???
        ///// segment2
        int lineNum = 1;
        int line_index = 0;
        glUseProgram(shader2);
        glBindVertexArray(LineVertexArrayID);
        glBindBuffer(GL_ARRAY_BUFFER, line_buffer);
        g_line_data[line_index * 2 + 0] = -1.0f;
        g_line_data[line_index * 2 + 1] = 0;
        line_index = 1;
        g_line_data[line_index * 2 + 0] = 1.0f;
        g_line_data[line_index * 2 + 1] = 0;
        glBufferData(GL_ARRAY_BUFFER, MaxLine * 4 * sizeof(GLfloat), NULL, GL_STREAM_DRAW);
        glBufferSubData(GL_ARRAY_BUFFER, 0, lineNum * sizeof(GLfloat) * 4, g_line_data);
        glDrawArrays(GL_LINES, 0, 2);
        glBindVertexArray(0);
        glBindBuffer(GL_ARRAY_BUFFER, 0);
        ///// segment2

        // printing some here to make sure the Math is correct
//        vec4 p1 = ViewProjectionMatrix * vec4(-1.0f, 0, -0.1, 1.0);
//        vec4 p2 = ViewProjectionMatrix * vec4(1.0f, 0, -0.1, 1.0);
//        cout << "p1 y " << p1.y / p1.w << " , p2 y " << p2.y / p2.w << endl;

        //// segment1
        {
            std::lock_guard<std::mutex> lck(m);
            while (!queue1.empty()) {
                auto &t = queue1.front();
                unsigned long x_raw = std::get<0>(t);
                float y = std::get<1>(t);
                if (x0 == 0) {
                    x0 = x_raw;
                    y00 = y;
                    cameraPos += glm::vec3(0, 0, 0);
                }
                x_raw -= x0;
                y -= y00;
                float x = float(x_raw);
                float s = std::get<2>(t);
                bool is_sell_b = std::get<3>(t);
                float is_buy = 1.0f - static_cast<float>(is_sell_b);
                g_particule_position_size_data[index * 4 + 0] = x;
                g_particule_position_size_data[index * 4 + 1] = y;
                g_particule_position_size_data[index * 4 + 2] = s / 100;
                g_particule_position_size_data[index * 4 + 3] = is_buy;
                index++;
                queue1.pop();
            }
        }
        glUseProgram(programID);
        glBindVertexArray(VertexArrayID);
        glBindBuffer(GL_ARRAY_BUFFER, particles_position_buffer);
//        glBufferData(GL_ARRAY_BUFFER, MaxParticles * 4 * sizeof(GLfloat), NULL, GL_STREAM_DRAW); // Buffer orphaning, a common way to improve streaming perf. See above link for details.
        glBufferSubData(GL_ARRAY_BUFFER, 0, index * sizeof(GLfloat) * 4, g_particule_position_size_data);
        glDrawArraysInstanced(GL_TRIANGLE_STRIP, 0, 6, index);
        glBindVertexArray(0);
        glBindBuffer(GL_ARRAY_BUFFER, 0);
        //// segment1

        glfwSwapBuffers(window);
        glfwPollEvents();

    } // Check if the ESC key was pressed or the window was closed
    while (glfwGetKey(window, GLFW_KEY_ESCAPE) != GLFW_PRESS &&
           glfwWindowShouldClose(window) == 0);

    delete[] g_particule_position_size_data;

    // Cleanup VBO and shader
    glDeleteBuffers(1, &particles_position_buffer);
    glDeleteBuffers(1, &billboard_vertex_buffer);
    glDeleteProgram(programID);
//    glDeleteTextures(1, &Texture);
    glDeleteVertexArrays(1, &VertexArrayID);
    // Close OpenGL window and terminate GLFW
    glfwTerminate();
    return 0;
}

Answer: glUniform* sets a uniform variable in the default uniform block of the currently installed program.
Install the program with glUseProgram before setting the uniform:
glUseProgram(programID);
glUniformMatrix4fv(ViewProjMatrixID, 1, GL_FALSE, &ViewProjectionMatrix[0][0]);
glUseProgram(shader2);
glUniformMatrix4fv(ViewProjMatrixID2, 1, GL_FALSE, &ViewProjectionMatrix2[0][0]);

Or use glProgramUniformMatrix4fv:
glProgramUniformMatrix4fv(programID, ViewProjMatrixID, 1, GL_FALSE, &ViewProjectionMatrix[0][0]);
glProgramUniformMatrix4fv(shader2, ViewProjMatrixID2, 1, GL_FALSE, &ViewProjectionMatrix2[0][0]);


Using datetime to set xticks of matplotlib

Question: I have a function that takes a month and year and I want to set the xticks of a plot to the month and year that is inputted.
For example if user enters 5 as the month and 2019 as the year I want to make the first xtick 5/2018, the second one 6/2018, and so on. If it reaches 12/2018, the next tick should be 1/2019.
I was reading about datetime but I'm not sure how I would use it for this problem.
I tried this but it doesn't work and I'm pretty sure this is not the way to tackle this.
<code>cityPlot(self, year, month):

   myDates = [datetime(int(year), month, 1]
   plt.plot(myDates)
</code>
Comment: where is you code?
Answer: matplotlib.pyplot.xticks is probably what are you looking for. You should look at this too


Notation regarding linearization near equilibrium point of dynamical system

Question: Suppose we have $\frac{dx}{dt} = \dot{x} = f(x)$ with equilibrium point $x_e$ such that $f(x_e) = 0$. Then for the linearized approximation of the differential equation near $x_e$ we hope to use the solution of $\dot{\delta x} = Df(x_e)\delta x$ where $\delta x = x(t) - x_e$.
I'm having trouble figuring out how to set up $Df(x_e)$. Consider a concrete case of the pendulum equation $ml^2\ddot{\theta} = -lmg\sin\theta$ which can be rewritten using $$ x = \left[ \begin{array}{c} \theta \\ \dot{\theta} \end{array} \right] $$ as $$ \dot{x} = \left[ \begin{array}{c} x_2 \\ -(g/l)\sin x_1 \end{array} \right] $$ with equilibrium point $x=0$.
In this case, I know that $Df(x_e)$ should be $$ Df(0) = \left[ \begin{array}{c c} 0 & 1 \\ -g/l & 0 \end{array} \right]$$
but I can't quite figure out the various variables that make up $Df$. I think I am having trouble figuring out all the indirect notation, and seeing this example worked out would really help.
Answer: My confusion stemmed from mixing up $x$ and $\theta$ as well as not remembering to take $Df(x)$ as $x = x_e = 0$.
Worked out:
From the expression for $\dot{x}$ it is clear that $$ f([x_1 \ x_2]^T) = \left[ \begin{array}{c} x_2 \\ -\frac{g}{\ell}\sin x_1 \end{array} \right] $$ so
$$\begin{align*}
Df(x_e) &= \left[ \begin{array}{cc} \frac{\partial f_1}{\partial x_1} & \frac{\partial f_1}{\partial x_2} \\ \frac{\partial f_2}{\partial x_1} & \frac{\partial f_2}{\partial x_2} \end{array} \right] \\  &= \left[ \begin{array}{cc} 0 & 1 \\ -\frac{g}{\ell}\cos x_1 & 0 \end{array} \right] \\ &= \left[ \begin{array}{cc} 0 & 1 \\ -\frac{g}{\ell} & 0 \end{array} \right] \quad \textrm{substituting in the value for $x_{e}$} \end{align*} $$
as desired.


sql query for latest record in a table

Question: I have a table like following:
EmployeeName -----    date       ------ seqno

  A            10-02-2014                2
  B            10-02-2014                1
  C            10-01-2014                1
  D            10-02-2013                2
  E            10-02-2013                1

Now whenever a new employee is added on the same date the seq no is added to 1 more.. suppose one more employee is added for 10-02-2014 the seq num becomes 3 .. so i need the latest record with max sequence number .. i was able to do to this using rownum as:
select * from employee where rownum=1 order by date,seqno DESC;

Is this correct ??
Is there a way to do this without using rownum ?
Comment: Do you want the record for max sequence number for each date or at all?
Comment: @hamlet no not for each date but the latest date
Answer: Yes, using a subquery
select * from employee e
where date =
     (Select Max(date)
      from employee)
   and seqno =
     (Select Max(seqno)
      from employee
      where date = e.date)

The query you show should specify desc for both date and seqNo....
(If you don't specify, the query processor assumes ascending.)
select * from employee
where rownum=1
order by date desc, seqno DESC;

Answer: You can use the rownum by this approach. The rownum is formed in FROM clause thus ordering will change the number sequence. You must use subquery to get correct result.
SELECT * FROM
(
   SELECT *
   FROM employee
   ORDER BY date DESC, seqno DESC
) A
WHERE rownum = 1

sql query for latest record in a table


Parent zone does not provide glue for nameservers

Question: We have two domains:

gignouser.com
clouds.host

we have created two A records:

ns1.eu.clouds.host
ns2.eu.clouds.host

Both of these servers host the DNS for both domains, and are listed a nameservers on the domain.
Through our registrar, we have created two host entries for the two DNS servers and pointed them towards their real IP addresses.
The issue we are facing is that when running a report on gignouser.com we are getting the following error:
Parent zone does not provide glue for nameservers

I don't understand why this is happening as we have created all the normal DNS entries. My guess is that it is because the name servers are 1 level down, under .eu and that is where the DNS report is looking for the glue records. This seems odd however as I can't create those records without delegating the domain, and its all run on same DNS server.
Any ideas?
Answer: The parent zone is not obligated to provide glue records for a delegation if the delegated-to host names is not under the delegated name. Glue records are only needed if a delegation points to something that the delegation would need to be followed for to be useful.
Since you are delegating gignouser.com to name servers under eu.clouds.host, that is not the case and glue records are thus not required to be returned by the name servers hosting the delegation to gignouser.com -- meaning the com TLD DNS servers.
If you look at the delegation of clouds.host you will see that the delegation from the nic.host DNS servers does include glue records.
I do however notice something that may contribute to problems:
You are serving NS RRs with a 0 TTL, for both domains. This can be problematic. If you want to minimize the time that DNS servers cache the delegation data (why you'd want to do that to such an extent I don't know), then serve it with some small but non-zero TTL. I suggest using a minimum of 10 seconds TTL to give resolvers and proxies a chance to do their thing even if they abide by TTLs internally during the recursive resolution process.
I would fix the TTLs first, and see if the problem goes away. It's certainly possible that the report tool you are using is being confused by the zero TTLs.
I also notice that it appears that you are running both name servers on the same subnet -- specifically, on adjacent IP addresses -- which presents a massive single point of failure. If that is the case, strongly consider getting an off-site slave DNS server, especially if you want to serve zone authority data with very short TTLs. While "everything else will be down anyway" is a valid point on the face of it, which error would you rather the users get if your servers are unavailable; "the host name www.gignouser.com was not found" or "the server did not respond"? I would absolutely prefer the latter, even if the end result at that moment is the same in that your web site is unavailable.
Comment: thanks for the response, and the tip regarding the 0 TTL.. seems to be a bug in the Microsoft DNS Manager! .. anyway have updated. Also aware of servers on same subnet, if that location goes offline, then everything is down anyway!
Answer: Have you created NS entries in the domain configuration file ? Like that :
gignouser.com.        IN      NS      ns1.eu.clouds.host.
gignouser.com.        IN      NS      ns2.eu.clouds.host.


Como conseguir a localização do GPS de quem acessar o website?

Question: Olá
Preciso desenvolver um website que cria rotas, estou utilizando a Google API's JavaScript. Preciso conseguir a localização do usuário, porem a mesma deve ser do GPS caso o usuário esteja acessando através de um dispositivo mobile,  e não por IP como a função do HTML5.
É possível acessar os dados do GPS através de uma aplicação web? Como desenvolvo isso?
Answer: Você não consegue acessar as configurações de hardware de um dispositivo pelo navegador. O máximo que você pode fazer é utilizar o HTML5 Geolocation, mediante a aceitação do usuário, para obter as coordenadas de localização do usuário.
Como pode ser visto na documentação da mozilla, o geolocation não é baseado, isoladamente, no IP. Se o dispositivo possuir um GPS, ele irá utilizar o GPS para calcular a localização, o que pode ocasionar uma demora maior para obter os dados.
Abaixo está um exemplo de como utilizar a Geolocation, retirado da w3School.

Click the button to get your coordinates.

<button onclick="getLocation()">Try It</button>

Agora, se realmente deseja utilizar o GPS do dispositivo, você precisará desenvolver um aplicativo e solicitar a permissão do usuário antes. Essa permissão é definida no APP.

Para ver o funcionamento acesse o site do exemplo, pois existem bloqueios de conexões seguras (HTTPS).
Comment: @EliardoMarini O problema é que você não tem como fazer o que deseja sem desenvolver um app para essa finalidade. Outra, o Chrome (à partir da versão 50) aceita a utilização [mediante endereços confiáveis](https://developers.google.com/web/updates/2016/04/geolocation-on-secure-contexts-only), ou seja, endereços com HTTPS e não HTTP.
Comment: Mas com o HTML5 a localização será através do IP. o que não poderá ser utilizado nesta aplicação, pois ocorre um erro de localização relativamente grande. Além disso o google chrome não está nem exibindo a mensagem para permitir compartilhar a localização. Mesmo assim agradeço.


Standardization of latent variables in mean-comparison between groups

Question:
Hi!
The above image is from "Latent Variable Models" by Loehlin and Beaujean (p.154).
There are two groups: high stressor group and low stressor group.
The image describes the path diagram for high stressor group but basically its the same for the low stressor group.
The triangle 1 was added to compare the means of the latent variables between two groups.
Accordingly, the paths g and f were set to 0 in the low stressor group while estimated in the high stressor group.
But the part I don't understand is that the two latent variables, D and R were standardized (variance = 1) in the low stressor group, but its variances were estimated in the high stressor group.
I mean why can't I just fix the latent variables' variance to 1 in both groups?
Because 1 in the triangle is a constant, it does not affect the variance of any latent or manifest variable.
Is there any reason that I must fix the latent variables' variances to 1 in the first group but estimate them in the second group?
Answer: It's all about model identification.
You don't say, but presumably a-e were constrained to be equal across groups. (Or some of a-e).
If you constrain the variances to be equal, you're making the assumption (which is easily testable) that the variances are equal. If that's not true, your model is wrong.
If you don't constrain either, then the model isn't identified, and it's not possible to fit it.
Comment: So It's not a "must". Thank you so much!
Comment: Yes. The more normal approach (IMHO) would be to constrain the first loading to 1.0 (i.e. a and c). That would also identify the model.


Filter taxonomy terms in common to nodes related to the viewed node

Question: I want to filter taxonomy terms in common to nodes related to the viewed node, but I cannot figure out how. What I am getting are all the terms that the related nodes have (with repeated terms too). Please take a look at this recipe page, side block STAG RICETTA
I am filtering seasonality terms (months) in common to ingredients nodes (the ones related to the node being viewed) used in a recipe node (the viewed one).
How can I achieve this?
Comment: I don't completely understand what you're trying to show. What do you mean by "filtering"? How are the nodes related to one another?
Comment: I'll try to clarify, maybe it's my poor english, sorry. I would be able to prepare that recipe only when all ingredients are available! thus I want to show the month in which ingredients needed (1st block in the sidebar, from top) are all available but I get all the month in which any of the ingredients is available.
Comment: ingredients are related to recipes by a "recipe_uses_ingredient" relation. seasonality of the ingredients is a taxonomy vocabolary having months as terms.
Comment: So you want to show, when viewing a recipe, a list of the seasons on its ingredients? Am I understanding correctly now?
Answer: To show a list of season terms on the ingredient nodes related to the recipe node:

Create a view of taxonomy terms of type season.
Add a relationship: Taxonomy term: Content with term
Add a relationship: Entity Reference: Referencing entity (A bridge to the entity that is referencing Content via field_recipe_uses_ingredient) via the relationship created in step 2.
Check "require this relationship".
Save.
Comment: thank you beth,  step 3: relationship not found... is it that I'm using 'relation' module, not 'reference' module? why do I need to relate to the User? how do I relate with the viewed node?
Comment: Oops, the 'user' thing was a cut and paste error. Use the content entity that applies, not a user.
Comment: thanks beth; your method (I edited it introducing relations) returns all the months that any product has, not the ones in common to all the products, as needed. would you suggest any alternative method or modification?
Comment: You'll have to add the relevant contextual filters as needed.
Comment: sure, i did it even if i didn't mention (gathering recipe's NID), but it doesn't help as a recipe may have more that one associated ingredient :(
Comment: I think you have to pass in the NIDs of the ingredients as multiple contextual filters to accomplish that.