Sustained note out of tune with short note

Question: I have a Schecter C1 Classic with D'dario XL EJ22 strings, down tuned to dropped A# (A#, F, A#, D#, G, C). The strings are relatively new, but broken in (a couple of weeks old, and I don't play every day). I use a BOSS TU-3 to tune it.
When I tune the guitar, I've noticed that for about the first half second after I pluck the string, the tuning is sharp by about a 1/4 step, then it drops into place at the correct tuning. This occurs more on the lower strings (4, 5, & 6), and happens regardless of how softly I pluck the string.
This concerns me because I play both fast and slow notes, so I want the tuning to be consistent whether I'm playing 1/16 notes or letting it ring out.
What could be causing this problem and how can I fix it?
Comment: Oh wow - i totally missed the bit about the drop tuning! Yes, if you're dropping that much, you will be much more likely to have a problem with this.
Comment: It's entirely normal for a string to decrease in pitch as it decays. Normally this is 5-10 cents though - just enough to hear. 1/4 semitone out (if that's what you mean by 'step') is quite a lot. It also wouldn't be normal for this to happen even when plucked softly. Do you have any recordings of this happening?
Comment: @topomorto Nope, no recordings. I'll take a closer look at the output of the tuner so I can be more specific about how far off the tuning is. I'll do a bit of reading about cents too, because I'm not familiar with those. I did mean "semitone" when I said "step".
Comment: I'd make a couple suggestions.  First, a heavier gauge of string will have less of the effect that user37401 described, as the tension will be more appropriate for the guitar.  You can also tune the strings based on your picking.  The harder you pick, the higher the frequency, so if you're picking hard, you can tune it slightly lower.  But the freq change is less drastic as the note rings out, so you may want to tune your strings after letting it ring out for a moment.  The best solution I can suggest is the most costly, which is to get yourself a baritone guitar.
Comment: https://www.youtube.com/watch?v=F8S-F3DKA-8
Comment: Are you HEARING this, or just reading it off a tuner?   It's normal behaviour of a plucked string, maybe exacerbated by your unusually slack tuning.
Comment: To be precise, any string that is not infinitely elastic (that is, any string made of matter) will be higher in pitch, the greater its displacement.  This is independent of its thickness: a thicker string will be louder for a given displacement, but it will go just as sharp as a thinner string if you displace it the same amount.
Answer: You have the lowest string tuned to A# instead of E: that's a whole augmented fourth lower than designed.  That's rather loose.
As a result, the string's tendency to straighten out the "kink" from plucking the string is lower than usual, and while the string is kinky, its overall tension is larger than when it is swinging in sinoidal manner, making it a bit higher pitched.
If you want to decrease the effect, try starting with less of a kink.  Use a softer pick and/or attack, and play closer to the middle of the effective string than you usually would.  Harmonics should settle faster than regular notes as they tend to kill off the kinkier bits of action.
Comment: A# to E is a Tritone, not a M3
Comment: As Basstickler says, the strings are 6 frets lower than standard, not 4. Which exacerbates the problem. Heavier strings will sort out most of it, and also put back the tension in the neck, which may by now be relieving itself the wrong way, due to lack of tension in the strings. As Todd says, a baritone is a better answer if you need to play that low.
Comment: It sounds like you're saying that there's not a whole lot I can do to the guitar to reduce, and I just need to adjust my picking technique to accommodate it. Does that sound about right?
Answer: This is completely normal behavior of plucked and hammered strings. The average tension is slightly higher when the physical amplitude of the string's vibration is greater. The higher tension leads to a higher restitution force which leads to a shorter period which is the same as a higher frequency which means a sharp note. As the amplitude of vibration dies down, the average tension decreases and the note flattens back down.
What creates the greatest pitch deviation is a greater relative tension. That means if the resting absolute tension is higher, the relative tension difference created by plucking will be less, leading to a lower pitch change. Also, greater resting tension will reduce the physical amplitude of the string, leading to a lower average tension increase.
In short, use thicker strings to minimize the pitch variation that occurs when you pluck the strings.
Comment: Thicker strings will minimize the pitch variation for a given volume level, but they will actually have more pitch variation (because of increased stiffness) for the same displacement, if they are of the same material and construction.


Why is $\lim_{n\rightarrow \infty}\sqrt[n]{n!} = \infty$?

Question: Why is $$\lim_{n\rightarrow \infty}\sqrt[n]{n!} = \infty$$
if :
$$\lim_{n\rightarrow \infty}\frac{n!}{n^n} = 0 \implies n^n >n! \quad\text{for "big" n}$$
I don't understand it.
Comment: But $\sqrt[n]{n^n}\to\infty$ as well, so $n^n>n!$ proves nothing about the limit of $\sqrt[n]{n!}$.
Comment: $\lim_\limits{n\to\infty} \sqrt [n] {n^n} =\infty$
Comment: $n^n > n!$ always. No fancy limit argument needed. And the $n$th root of $n^n$ is just $n$.
Comment: It is true that $n! > (n/e)^n$. Might be easier to show that $ n! > (n/3)^n$.
Comment: If $f(n) \geq g(n) \geq 0$, then $f(n) \to 0$ implies that $g(n) \to 0$. However, it is not true that $f(n) \to \infty$ implies that $g(n) \to \infty.$
Comment: @DougM I fixed it.
Comment: I thought that any exponent less than $n$ gives the limit of n-th root equal to $1$
Answer: Let $a_n = n!$.
The limit $\lim \sqrt[n]{a_n}$ is related to the root test for series convergence.
In this context, it is well known that if $\lim \dfrac{a_{n+1}}{a_n}$ exists, then so does $\lim \sqrt[n]{a_n}$ and they are equal. Let's compute the ratios then:
$$
\lim \frac{a_{n+1}}{a_n} = \lim (n+1) = \infty
$$
Therefore, $\lim \sqrt[n]{a_n}= \infty$.
Comment: Adapted from https://math.stackexchange.com/a/1769591/589


Are there methods to cluster based on pair wise dissimilarity measures?

Question: I am facing a problem of learning clusters from a pairwise dissimilarity matrix. The measures i try are not metrics(not symmetric,no triangular equality), like KL-divergence for example.
Are there Clustering methods i can use to find clusters from these kinds of matrices?
If i have labels available, what kind of cluster validation techniques can i use?
Answer: Classic hierarchical cluster analysis requires the proximity matrix to be symmetric. So, you have to symmetricize your matrix, for example, averaging elements above and below the diagonal.
If it lacks triangular inequality, you can't use methods such as Ward, centroid, median, which are called "geometric" ones because they need distances be euclidean, - or metric at worst. Other methods, such as nearest neighbour, farthest neighbour, average linkage - you still can use them.
Also, you might choose to rectify your dissimilarities into metric/euclidean by adding constant to all the elements. Iteratively add small value and check when the "double centrat" of the matrix looses negative eigenvalues. When it's lost, your dissimilarities got euclidean. Look here how to do double centering.


Proving spheres are orthogonal

Question:
Given two spheres in $\mathbb{R}^3$:
$x^2+y^2+z^2=2ax; \ \  \ x^2+y^2+z^2 = 2by$
and $a,b>0$, and $\gamma$ the intersection of the spheres, show that for any $p_0 \in \gamma$, the spheres are orthogonal at $p_0$.

I am not sure I fully understand the problem but here is what I tried:
First of all assuming $p_0$ is some point s.t each sphere can be represented as a function $z_1, z_2 : \mathbb{R}^2 \to \mathbb{R}$ in a neighborhood of $p_0$ (if it isn't we can use another variable), what I think we want to show is that the tangent spaces to $z_1, z_2$ are orthogonal at this point, i.e $\langle\nabla z_1(p_0), \nabla z_2(p_0)\rangle=0.$ But when I calculate this I get that it does not equal 0:
$z_1 = \sqrt{2ax-x^2-y^2}, z_2 = \sqrt{2by-x^2-y^2}$
$\nabla z_1 = (\frac{2a-2x}{2 \sqrt{2ax-x^2-y^2}}, \frac{-2y}{2 \sqrt{2ax-x^2-y^2}})$
$\nabla z_2 = (\frac{-2x}{2 \sqrt{2by-x^2-y^2}}, \frac{2b-2y}{2 \sqrt{2by-x^2-y^2}})$
$\langle\nabla z_1(p_0), \nabla z_2(p_0)\rangle \neq 0.$
Can someone explain where is my mistake?
Answer: Let$$f(x,y,z)=(x-a)^2+y^2+z^2\quad\text{and}\quad g(x,y,z)=x^2+(y-b)^2+z^2.$$Then your spheres are the surfaces$$\{(x,y,z)\in\Bbb R^3\mid f(x,y,z)=a^2\}\quad\text{and}\quad\{(x,y,z)\in\Bbb R^3\mid g(x,y,z)=b^2\}.$$If $p=(x_0,y_0,z_0)\in\gamma$ then the tangent plane to the first sphere at $p$ is orthogonal to$$\nabla f(x_0,y_0,z_0)=\bigl(2(x_0-a),2y_0,2z_0\bigr)$$and the tangent plane to the second sphere at $p$ is orthogonal to$$\nabla g(x_0,y_0,z_0)=\bigl(2x_0,2(y_0-b),2z_0\bigr).$$And we have\begin{align}\bigl\langle\nabla f(x_0,y_0,z_0),\nabla g(x_0,y_0,z_0)\bigr\rangle&=\bigl\langle\bigl(2(x_0-a),2y_0,2z_0\bigr),\bigl(2x_0,2(y_0-b),2z_0\bigr)\bigr\rangle\\&=4x_0^{\,2}+4y_0^{\,2}+4z_0^{\,2}-2ax_0-2by_0\\&=2(x_0^{\,2}+y_0^{\,2}+z_0^{\,2}-ax_0)+2(x_0^{\,2}+y_0^{\,2}+z_0^{\,2}-by_0)\\&=0+0\text{ (since $p\in\gamma$)}\\&=0.\end{align}And, since the vectors $\nabla f(x_0,y_0,z_0)$ and $\nabla g(x_0,y_0,z_0)$ are orthogonal, then so are tangent planes at $p$, since one of them is orthogonal to the first vector, whereas the other one is orthogonal to the second vector.
Comment: The spheres defined by your $f$ and $g$ are not the same as in the question (doesn't affect the gradients, though).
Comment: @lisyarus The first sphere is$$\{(x,y,z)\in\Bbb R^3\mid f(x,y,z)=a^2\},$$whereas the second one is$$\{(x,y,z)\in\Bbb R^3\mid g(x,y,z)=b^2\},$$right?!
Comment: Ugh, sorry, messed that up, you're right!
Answer: The gradients are not applied properly.
Let $f(x,y,z)=x^2+y^2+z^2-2ax$ and $g(x,y,z)=x^2+y^2+z^2-2by$.
Then the spheres are given by $f(x,y,z)=0$ respectively $g(x,y,z)=0$.
The gradients of $f$ and $g$ are orthogonal to their tangent spaces. So to verify if the tangent spaces are orthogonal, we need that for every $(x,y,z)$ on both spheres that $\langle \nabla f(x,y,z),\nabla g(x,y,z)\rangle=0$.
Answer: First solution:
Here is a quick analytic solution first.
Let $p_0=(x_0,y_0,z_0)$ be a point on both spheres.
Then the tangent plane in $p_0$ to the one or the other sphere has the equation:
$$
\begin{aligned}
2x_0(x-x_0) + 2y_0(y-y_0) + 2z_0(z-z_0) - 2a(x-x_0) &=0\ ,\\
2x_0(x-x_0) + 2y_0(y-y_0) + 2z_0(z-z_0) - 2b(y-y_0) &=0\ ,
\end{aligned}
$$
so that two (unnormalized) normal vectors to the two planes are $(x_0-a,y_0,z_0)$ and $(x_0, y_0-b,z_0)$. Their scalar product is:
$$
x_0(x_0-a)+y_0(y_0-b)+z_0^2=\frac 12\Big( \ (x_0^2+y_0^2+z_0^2-2ax_0)+(x_0^2+y_0^2+z_0^2-2by_0)\ \Big)=0\ .
$$

Second solution:
Trying to go as the OP goes is also possible, even if complicated. The locally defined function $z_1$ is only a part of the parametrization
$$
(x,y)\to(x,y,z_1(x,y))\ .
$$
Letting $x$ variate around $x_0$, and keeping $y=y_0$ we obtain a tangent vector $v_x$ to the sphere, similarly keeping $x=x_0$ and letting $y$ variate around $y_0$ we get an other tangent vector $v_y$. These two vectors, and the normal vector $n_1=v_x\times v_y$,  are:
$$
\begin{aligned}
v_x &= (1,0,\nabla_x z_1(x_0,y_0)) =\left(1, 0, \frac{a-x_0}{\sqrt{2ax_0-x_0^2-y_0^2}}\right)\ ,\\
v_y &= (0,1,\nabla_y z_1(x_0,y_0)) =\left(0, 1, \frac{0-x_0}{\sqrt{2ax_0-x_0^2-y_0^2}}\right)\ ,\\
n_1 &= v_x\times v_y
=
\left(
\ -\frac{a-x_0}{\sqrt{2ax_0-x_0^2-y_0^2}}\ ,
\ -\frac{0-y_0}{\sqrt{2ax_0-x_0^2-y_0^2}}\ ,
\ 1\
\right)
\\
&\sim \left(\ x_0-a\ ,\ y_0\ ,\ \sqrt{2ax_0-x_0^2-y_0^2}\ \right)
\\
&=(\ x_0-a\ ,\ y_0\ ,\ z_0\ )\ .
\end{aligned}
$$
The computation of the corresponding normal vector using the second parametrization delivers analogously the value
$$
(\ x_0\ ,\ y_0-b\ ,\ z_0\ )\ .
$$
As in the first solution, these vectors are orthogonal.

Third solution:
A geometrical solution is as follows.
The first sphere is a sphere $(S_a)$ centered in $(a,0,0)$ with radius $a$.
The second sphere is a sphere $S_b$ centered in $(0,b,0)$ with radius $b$.
The inversion with center $O=(0,0,0)$ and power $2ab$ transforms $S_a$ in the plane with equation $x=b$, and $S_b$ in the plane with equation $y=a$. Obviously, these planes intersect orthogonally, the inversion is an orthogonal transformation, we apply it again, so $S_a$ and $S_b$ intersect orthogonally.

Proving spheres are orthogonal


Why is cudaLaunchCooperativeKernel() returning not permitted?

Question: So I am using GTX 1050 with a compute capability of 6.1 with CUDA 11.0. I need to use grid synchronization in my program so cudaLaunchCooperativeKernel() is needed. I have checked my device query so the GPU does have support for cooperative groups. I am unable to execute the following function
 extern "C" __global__ void test(int x) {
    if (x) {
       printf("%d", x);
       if (threadIdx.x == 0)
          test<<<1, 1>>>(--x);
    }
}

After calling,
cudaLaunchCooperativeKernel((void *)test, 1, 1, (void **) (&x));

getting an error 'operation not permitted' (code is 800). Now, this is returned when the device has no support of cooperative groups (Not in this case). So, what could cause this problem?
Answer: Your kernel makes use of dynamic parallelism.
However, dynamic parallelism is not allowed in kernels which are launched via cudaLaunchCooperativeKernel
This is mentioned in the documentation of the runtime API. https://docs.nvidia.com/cuda/cuda-runtime-api/group__CUDART__EXECUTION.html
Comment: I see! So is there any workaround for grid synchronization in my case?
Comment: I think the only workaround for grid synchronization is having two kernels, one for the part before synchronization, one for the part after synchronization.


How can I show that for all $v\in V$ there's $F\in V^{**} $ such that $F(f)=f(v)$ for all $f\in V^*$?

Question: I'm trying to show that the map $\Phi :V\to V^{**}$ given by $\Phi (v)(f):=f(v)$ is well-defined. To show that I need to prove that for all $v\in V$ there's $F\in V^{**}
$ such that $F(f)=f(v)$ for all $f\in V^*$. However I don't know how to prove that in the infinite dimensional case!
My question: Suppose that $V$ is an infinite dimensional vector space. How can I show that for all $v\in V$ there's $F\in V^{**}
$ such that $F(f)=f(v)$ for all $f\in V^*$?
Below there's a lemma that I'm trying to use to prove the question above.
Lemma: Let $V$ be a vector space. Suppose that $\{v_i\}_{i\in I}$ is a base of $V$. Then there's a unique linearly independent subset $\{v^i\}_{i\in I}$ of $V^*$ such that $v^i(v_j)=\delta _{ij}$ for all $i,j\in I$ in which $\delta $ is the Kronecker delta.

EDIT:
I'll clarify my question:
Given two sets $A$ and $B$, we say that $f\subseteq A\times B$ is a map from $A$ to $B$ (which we denote by $f:A\to B$) if $(\forall x\in A)(\exists !y\in B)\left((x,y)\in f\right)$ is a true proposition.
So, my question is to prove that $\Phi :=\big\{(v,F)\in V\times V^{**}:(\forall  f\in V^*)\left(F(f)=f(v)\right)\big\}$ is a map from $V$ to $V^{**}$. That is, I want to prove that $(\forall v\in V)(\exists! F\in V^{**})\left((v,F)\in \Phi \right)$ is a true proposition.
Comment: Simply verify that if you define a map $F: V^*\rightarrow \mathbb{C}$ in this way, it is bounded and linear.
Comment: The proof is just as straightforward in the infinite dimensional case.
Comment: As Jonathan says, what you have is a _definition_ of $F$ (I would consider indexing it as $F_v$ to make it clear that there's one for each $v\in V$); you just have to show that that definition meets the conditions for $F_v$ to be an element of $V^{**}$.
Comment: @JonathanHole In my question $V^{**}$ is the algebraic double dual of $V$. That is, the elements of $V^*$ are just linear functionals (not necessarily continuous)!
Comment: @StevenStadnicki My problem is finding a linear map $F\in V^{**}$ such that $F(f)=f(v)$ **for all**  $v\in V$ and **for all** $f\in V^*$. I don't how to solve the problem using your suggestion!
Comment: Then it becomes even easier -- you don't have to show it is bounded!
Comment: @rfloc I think you have your quantifiers wrong. There isn't a _single_ linear map that works for every $v$; rather, for _each_ $v$ there's a $F_v$ that is a map from $V^*\mapsto \mathbb{R}$ (or whatever your underlying field/ring/what-have-you is). And _defining_ $F_v$ by saying $F_v(f)=f(v)$ is a map from $V^*\mapsto\mathbb{R}$; you just need to show linearity.
Comment: The map $\Phi$ that you're trying to show exists is then the map that takes each $v$ to its corresponding $F_v$.
Comment: Please see my edit in my question because I believe nobody understood my question!
Answer: Suppose that $V$ is a vector space over a field $k$. Take $v \in V$. Then, if you define a map $\Phi(v) : V^* \to k$ by $$(\forall f \in V^*) \quad \Phi(v)(f) = f(v)$$ note that $\Phi(v)$ is well-defined ($f \in V^* \implies \Phi(v)(f) \in k$) and is linear since if $f_1,f_2 \in V^*$ and $\lambda \in k$, $$\Phi(v)(\lambda f_1+f_2) = (\lambda f_1+f_2)(v) = \lambda f_1(v)+f_2(v) = \lambda \Phi(v)(f_1)+\Phi(v)(f_2).$$ Thus, $\Phi(v) \in (V^*)^* =: V^{**}$, and then $\Phi : V \to V^{**}$ is well-defined!
Comment: @rfloc *Generally* here is key. However, **if** one defines a map for all values within the domain **and then** shows that this definition is consistent with the definition of linearity, then one has indeed shown that there exists a linear map that is described by the definition.
Comment: I showed that for any $v \in V$ there is a unique $F \in V^{**}$ (namely, $F = \Phi(v)$) such that $F(f) = f(v)$ for all $f \in V^*$. Uniqueness of $\Phi(v)$ follows from the fact that if $F$ is some other element of $V^{**}$ such that $F(f) = f(v)$ for all $f \in V^*$, then $F$ and $\Phi(v)$ are two functions from $V^*$ to $k$ that coincide in every $f \in V^*$, so $F = \Phi(v)$. Also, I didn't showed that $\Phi$ is linear, I showed that $\Phi(v)$ is an element of $V^{**}$ for any $v \in V$, which is different.
Comment: @rfloc Is there a reason that you believe that we should use this fact to prove the existence of such a map?
Comment: Please see my edit in my question because you didn't understand my question!
Comment: Let $V,W$ be two vector spaces. I know that if $\{v_i\}_{i \in I}$ is a base of $V$ and $\{w_i\}_{ i\in I}$ is a collection of elements of $W$, then there's a unique linear map $T:V\to W$ such that $T(v_i)=w_i$ for all $i\in I$. However I don't know to use this fact to prove that existence of a linear map $F:V^*\to k$ such that **for all** $f\in V^*$ we have $F(f)=f(v)$.
Comment: @BenGrossmann This fact show that (generally) we can't define a linear map with specific values for all elements of its domain!
Comment: @rfloc That's right. But, isn't $\Phi(v) : V^* \to k$ a linear map such that $\Phi(v)(f) = f(v)$ **for all** $f \in V^*$?
Comment: @BenGrossmann Now I understood! Thank you for your clarification!


Finding all solutions for congruences

Question: Decide which of the following congruences are solvable, and if so, find all solutions:
a) $x^2 \equiv c  \bmod 363$, where $c= 1,5,31$
b) $x^2 \equiv 54 \bmod 125$
Now, I know how to find which of those are solveable, but I have no idea how to find the solutions.
(For example b) is solvable).
Any ideas?
Comment: At $x=1$, $c=1$ is trivial.
Comment: this is the modular log and not trivial, but it can be done depending on how many calculations you can afford.
Comment: @SimpleArt Yes, but for the nontrivial congruences?Is there any method generally to find it? Or a method for specific cases?
Comment: Note that $x^2\equiv0,1\pmod3$.  Thus, we can already see $c=5$.
Comment: for $c=1$ i have found $$x=1,122,241,362$$
Comment: Yes, use the symmetry of $(+x)^2=(-x)^2$ to find solutions faster.
Comment: @Dr.SonnhardGraubner How?
Comment: @ChakaChaka From my last hint, one only needs to check the first half of the values from $1$ to $363$.
Comment: @SimpleArt you can get something cheaper by using CRT, and when attacking mod $11^2$ first solving $\bmod 11$ to avoid a ton of cases.
Comment: @SimpleArt But it's still 181 numbers to check...
Comment: @JorgeFernándezHidalgo Why $mod \ 11$?
Comment: well, $363=11^2 \times 3$, you only have to check $22$ cases.
Comment: $11^2\times3=363$.  Same idea as I used to show $c=5$ is not possible.
Answer: Perhaps these general ideas can help you:
Suppose that we want to solve $x^k \equiv c \bmod p_1^{\alpha_1}p_2^{\alpha_2}\dots p_n^{\alpha_n}$
It suffices to find the solutions $\bmod p^a$ for each prime power and then combine them using the chinese remainder theorem.
So how can we solve $x^k\equiv c \bmod p^a$?
One way is to do it inductively over $a$.
First find all the solutions to $x^k \equiv p^{a-1}$, so when we check for the solutions to $x^k\equiv p^{a-1}$ we only have to check congruences which also solved the previous equation.

Finding all solutions for congruences


Limits of Incommensurable quantities

Question:
By taking the unit of measure sufficiently small, however, the ratio of two incommensurable quantities can be expressed as nearly to the true value as may be desired. Thus an approximate value of the ratio can be found which shall differ from the true value by an amount less than any specified amount, however small.

I don't understand this. Can somebody explain it to me simply and probably give some examples as well? This is an excerpt from the book Geometry for the practical man by J.E. Thompson to those of you curious which book it came from.
Answer: This is an ancient conundrum going back to the era of classical Greece.
The Greeks first believed that for any two geometric magnitudes there would exist a common unit which would divide evenly into both magnitudes.
So given, for example, the diagonal of a square and its side they thought there would be a tiny unit which would divide a whole number of times (let is say $m$ times) into the diagonal and a whole number of times (let us say $n$ times) into the side. Then if $d$ is the magnitude of the diagonal and $s$ the magnitude of the side, then
$$ d=\frac{m}{n}\times s $$
However it was learned that in the case of the diagonal and side of a square, there was no such common unit. The actual formula is
$$ d=\sqrt{2}\times s $$
and $\sqrt{2}$ is an irrational number, meaning it is not equal to the ratio of any two whole numbers $m$ and $n$.
However, they realized that if one made the units sufficiently small one could approximate, in this case, $\sqrt{2}$ or any such irrational magnitude, to approximate the magnitude with a rational number to any degree of precision required.
For example, $\dfrac{239}{169}\approx1.414201183$ whereas $\sqrt{2}\approx1.4142135562$. So the rational number $\dfrac{239}{169}$ is approximately equal to $\sqrt{2}$ to four decimal place precision. So if we divide the side of a square into $169$ equal units, that unit will go approximately, but not exactly, $239$ times into the diagonal of the square giving an approximation of the ratio of the diagonal to the side of the square.

Limits of Incommensurable quantities


asynchronous iteration, how to move to next step of iteration while waiting for a task to complete?

Question: I am trying to write an iterator which moves on to the next step in the iteration while awaiting an IO bound task. To roughly demonstrate what I'm trying to do in code
for i in iterable:
    await io_bound_task()   # move on to next step in iteration
    # do more stuff when task is complete

I initially tried running with a simple for loop, with a sleep simulating an IO bound task
import asyncio
import random

async def main() -> None:
    for i in range(3):
        print(f"starting task {i}")
        result = await io_bound_task(i)
        print(f"finished task {result}")

async def io_bound_task(i: int) -> int:
    await asyncio.sleep(random.random())
    return i

asyncio.run(main())

here the code runs synchronously and outputs
starting task 0
finished task 0
starting task 1
finished task 1
starting task 2
finished task 2

which I assume is because the for loop is blocking. So I think an asynchronous for loop is the way to proceed? so I try using an asynchronous iterator
from __future__ import annotations

import asyncio
import random

class AsyncIterator:
    def __init__(self, max_value: int) -> None:
        self.max_value = max_value
        self.count = 0

    def __aiter__(self) -> AsyncIterator:
        return self

    async def __anext__(self) -> int:
        if self.count == self.max_value:
            raise StopAsyncIteration
        self.count += 1
        return self.count

async def main() -> None:
    async for i in AsyncIterator(3):
        print(f"starting task {i}")
        result = await io_bound_task(i)
        print(f"finished task {result}")

async def io_bound_task(i: int) -> int:
    await asyncio.sleep(random.random())
    return i

asyncio.run(main())

but this also seems to run synchronously and results in the output
starting task 1
finished task 1
starting task 2
finished task 2
starting task 3
finished task 3

every time. So I think the asynchronous iterator is not doing what I assumed it would do? At this point I'm stuck. Is it an issue with my understanding of the asynchronous iterator? Can someone give me some pointers as to how to achieve what I'm trying to do?
I'm new to working with async, so apologies if I'm doing something stupid. Any help is appreciated. Thanks.
I'm on python 3.8.10 if that is a relevant detail.
Comment: Have you looked at https://docs.python.org/3/library/asyncio-task.html#asyncio.create_task?
Comment: Ah thank you, tasks indeed seems to be what I need. So I'm creating tasks inside a loop, adding them to a list and then awaiting inside another loop, which works as required. Perhaps you could write a simple answer which I can accept? otherwise I'll answer the question myself.
Answer: The thing that you are looking for is called a task, and can be created using the asyncio.create_task function. All the approaches you tried involved awaiting the coroutine io_bound_task(i), and await means something like "wait for this to complete before continuing". If you wrap your coroutine in a task, then it will run in the background rather than you having to wait for it to complete before continuing.
Here is a version of your code using tasks:
import asyncio
import random

async def main() -> None:
    tasks = []
    for i in range(3):
        print(f"starting task {i}")
        tasks.append(asyncio.create_task(io_bound_task(i)))

    for task in tasks:
        result = await task
        print(f"finished task {result}")

async def io_bound_task(i: int) -> int:
    await asyncio.sleep(random.random())
    return i

asyncio.run(main())

Output:
starting task 0
starting task 1
starting task 2
finished task 0
finished task 1
finished task 2

You can also use asyncio.gather (if you need all results before continuing) or asyncio.wait for awaiting multiple tasks, rather than a loop. For example if task 2 completes before task 0 and you don't want to wait for task 0, you could do:
async def main() -> None:
    pending = []
    for i in range(3):
        print(f"starting task {i}")
        pending.append(asyncio.create_task(io_bound_task(i)))

    while pending:
        done, pending = await asyncio.wait(pending, return_when=asyncio.FIRST_COMPLETED)
        for task in done:
            result = await task
            print(f"finished task {result}")


asia-southeast1-b computer engine down

Question: 2019-02-07 19:52:12.748 JST asia-southeast1-b computer engine down.
event_subtype:  "compute.instances.hostError"
event_type:  "GCE_OPERATION_DONE"
What caused the server down?
How does google solve it?
thank you
Answer: https://cloud.google.com/compute/docs/faq#hosterror

There was a host error with my virtual machine and it was restarted. What happened?
A host error means that there was a hardware or software issue on the physical machine hosting your virtual machine that caused your virtual machine to crash. When Compute Engine detects such an event, we add a compute.instances.hostError entry to your operations log. If your virtual machine is set to automatically restart, which is the default, Google will also restart your virtual machine on a different physical machine.
In general, physical hardware failures and software failures can happen from time-to-time, but are rare occurrences. To protect your applications and services from potentially disruptive system events like these, make sure you design robust systems and build scalable and resilient web applications. Use managed instance groups to perform health checking and scaling across groups of Compute Engine instances.

asia-southeast1-b computer engine down


What is a robust statistical test? What is a powerful statistical test?

Question: Some statistical tests are robust and some are not. What exactly does robustness mean? Surprisingly, I couldn't find such a question on this site.
Moreover, sometimes, robustness and powerfulness of a test are discussed together. And intuitively, I couldn't differentiate between the two concepts. What is a powerful test? How is it different from a robust statistical test?
Comment: Power and robustness are orthogonal concepts, even if they are two important properties of a test. It seems to me it would be better to ask two separate questions.
Comment: We could word _robustness_ as the property of an adapted procedure that's insensitive to violations of some assumptions of its core theory.
Answer: Robustness has various meanings in statistics, but all imply some resilience to changes in the type of data used. This may sound a bit ambiguous, but that is because robustness can refer to different kinds of insensitivities to changes. For example:

Robustness to outliers
Robustness to non-normality
Robustness to non-constant variance (or heteroscedasticity)

In the case of tests, robustness usually refers to the test still being valid given such a change. In other words, whether the outcome is significant or not is only meaningful if the assumptions of the test are met. When such assumptions are relaxed (i.e. not as important), the test is said to be robust.
The power of a test is its ability to detect a significant difference if there is a true difference. The reason specific tests and models are used with various assumptions is that these assumptions simplify the problem (e.g. require less parameters to be estimated). The more assumptions a test makes, the less robust it is, because all these assumptions must be met for the test to be valid.
On the other hand, a test with fewer assumptions is more robust. However, robustness generally comes at the cost of power, because either less information from the input is used, or more parameters need to be estimated.
Robust
A $t$-test could be said to be robust, because while it assumes normally distributed groups, it is still a valid test for comparing approximately normally distributed groups.
A Wilcoxon test is less powerful when the assumptions of the $t$-test are met, but it is more robust, because it does not assume an underlying distribution and is thus valid for non-normal data. Its power is generally lower because it uses the ranks of the data, rather than the original numbers and thus essentially discards some information.
Not Robust
An $F$-test is a comparison of variances, but it is very sensitive to non-normality and therefore invalid for approximate normality. In other words, the $F$-test is not robust.
Comment: Your answer is very clear and easy to understand. I edited by question to ask more about whether a test is `powerful` as I see you discussed that in your answer. Would you mind explaining what does a powerful test means?
Comment: This is a great answer, just want to add that there are ways to formalize the definition. Some consider a test to be robust if it has both the **robustness of validity**, i.e. significance level of the test is stable given small departures from the null, and the **robustness of efficiency**, i.e. power is still good given small departures from the specified alternative; and these qualities can be quantified through the use of [influence functions](http://web.as.uky.edu/statistics/users/pbreheny/621/f10/notes/8-31.pdf).
Comment: @Eric, isn't the equivalence only true for two groups?
Comment: @eric_kernfeld I think Frans is referring to the use of $F$ to compare variances not its use in ANOVA.
Comment: I included a short description of how this relates to the power of a test.
Comment: This is a nice answer, but why do you ascribe different properties to t-tests and F-tests? They are mathematically equivalent.
Comment: So can we say most statistical procedures are asymptotically robust?
Comment: I see. Points taken.
Answer: There is no formal definition of "robust statistical test", but there is a sort of general agreement as to what this means. The Wikipedia website has a good definition of this (in terms of the statistic rather than the test itself):

Robust statistics are statistics with good performance for data drawn from a wide range of probability distributions, especially for distributions that are not normal.

https://en.wikipedia.org/wiki/Robust_statistics


Dúvida ao pegar grupo de checkbox repetido

Question: Estou fazendo um formulário de cadastro onde eu tenho todos os dias da semana para selecionar
<input type="checkbox" name="dias[]" value="Segunda"> Seg
<input type="checkbox" name="dias[]" value="Terça"> Ter
<input type="checkbox" name="dias[]" value="Quarta"> Qua
<input type="checkbox" name="dias[]" value="Quinta"> Qui
<input type="checkbox" name="dias[]" value="Sexta"> Sex
<input type="checkbox" name="dias[]" value="Sábado"> Sáb
<input type="checkbox" name="dias[]" value="Domingo"> Dom

O Problema é que no formulário tem um botão Adicionar +1 onde duplica esse grupo de checkbox. Como são checkbox eu coloquei o name dele como array e caso tenha mais de um grupo de checkbox eu não sei como fazer para pegar, pois preciso pegar grupo por grupo, ou seja, se eu tenho um grupo só irei fazer um foreach() com PHP e resolvo o caso, pois os indices seram de 0 a 6 (pois são 7 dias). Agora se tem 2 grupos, os indices seram de 0 a 13 e a cada 7 é um grupo e eu preciso dividir esses grupos.
Answer: Tem que fazer o input como array multidimensional: name="dias[0][]":
<form action="test.php" method="post">
    <input type="checkbox" name="dias[0][]" value="Segunda"> Seg
    <input type="checkbox" name="dias[0][]" value="Terça"> Ter
    <input type="checkbox" name="dias[0][]" value="Quarta"> Qua
    <input type="checkbox" name="dias[0][]" value="Quinta"> Qui
    <input type="checkbox" name="dias[0][]" value="Sexta"> Sex
    <input type="checkbox" name="dias[0][]" value="Sábado"> Sáb
    <input type="checkbox" name="dias[0][]" value="Domingo"> Dom
    <input type="checkbox" name="dias[1][]" value="Segunda"> Seg
    <input type="checkbox" name="dias[1][]" value="Terça"> Ter
    <input type="checkbox" name="dias[1][]" value="Quarta"> Qua
    <input type="checkbox" name="dias[1][]" value="Quinta"> Qui
    <input type="checkbox" name="dias[1][]" value="Sexta"> Sex
    <input type="checkbox" name="dias[1][]" value="Sábado"> Sáb
    <input type="checkbox" name="dias[1][]" value="Domingo"> Dom
    <input type="submit" />
</form>
<?php
if( !empty( $_POST['dias'] ) ) {
    foreach( $_POST['dias'] as $key => $value ) {
        echo "
Semana $key
";
        foreach( $value as $dias ) {
            echo "$dias
";
        }
    }
}
?>


roots of hyperbolic functions

Question: I am having difficulty with understanding one part of the answer to the following:
Find conditions on a, b, and c which are necessary and sufficient to ensure that the equations
$$
a\cosh x + b\sinh x = c
$$
has exactly one root.
I have rearranged the equation to form a quadratic equation and used the discriminate and got:
$$
a^2 = c^2 + b^2
$$
However, the answer is that the above statement is only true if the signs of a+b and a-b are the same. When the signs of a+b and a-b are different then
$$
b^2+c^2>a^2
$$
This is the part that I don't understand how to prove. I have used graphing software to see that it is true but I can't seem to prove it. Could you help with this please?
Answer: If you let $e^x=y$, you end with the equation
$$ (a+b)y^2-2 c y+(a-b)=0$$
So, first we need two roots
$$\Delta=b^2+c^2-a^2  \geq 0$$ and one of them must be negative since $y >0$ so $\frac{a-b}{a+b} <0$ that is to say $a^2-b^2 <0$

roots of hyperbolic functions


How to determine if a user is logged in with hello.js?

Question: How can I determine if a user is logged in with hello.js?
With the Google Sign-In SDK, I can register a callback with gapi.auth2.init() that will be called when the SDK is set up and ready to answer questions like "are you logged in?"
hello.js doesn't appear to have any such hook. At page load, the auth.login event will fire when the user is found to be logged in, but auth.logout is not fired when the user is found to be not logged in.
Answer: You can use this:
hello.getAuthResponse('facebook'); // null if not logged in with FB,

Comment: +1 Yes.... that should be marked as answer. You should develop a injected method on your state/route provider to verify AuthResponses of your providers. Or something more elegant, you store on $rootscope var the selected provider(google, windows, fb etc..) and ask only if this provider still authenticated.
Answer: Probably already solved but still.
I'm currently using event 'auth.login' which is run every time user successfully logs in. So basically you can define this event once, when initializing hello js.
hello.on('auth.login', function (response) {
        console.log('on auth login');
        console.log(response);
        const cookies = new Cookies();
        let auth = response.authResponse;
        cookies.set('auth', auth.access_token, {path: '/', maxAge: auth.expires_in});
        callback(param);
    });

What happens here is that when user is logged in cookie is set. You can do some other stuff here like invoke callback method. Note that my example here is based on React.


Detect NavigationDrawer state on Fragment

Question: I have a navigation drawer in my BaseActivity. Now I want to detect the NavigationDrawer state(Opened or Closed) in a separate fragment. I tried in Fragment life cycle methods, but no method is triggered when NavaigationDrawer is opened or closed. Any one Please help me. Thanks in advance.
Answer: You can use this line of code in your fragment that you want to check if the drawer is closed or not:
DrawerLayout mDrawerLayout = (DrawerLayout)getActivity().findViewById(R.id.drawer_layout);
ListView mDrawerList = (ListView) getActivity().findViewById(R.id.list_slidermenu);

        if (!mDrawerLayout.isDrawerOpen(mDrawerList)){

            System.out.println("The Drawer is closed!");

        }

Basically you are calling the layout from the activity that is hosting that fragment.
Answer: You have to implement DrawerListener in baseactivity,
BaseActivity implements DrawerListener

Now you have to assign
yourNavigationDrawerObject.setDrawerListener(this);//please put your object behalf of yourNavigationDrawerObject

call when navigation drawer close.
@Override
public void onDrawerClosed(View arg0) {
    // TODO Auto-generated method stub

}

call when navigation drawer open
@Override
public void onDrawerOpened(View arg0) {
    // TODO Auto-generated method stub

}

Answer: in your navigationdraweractivity make drawer layout as public
public DrawerLayout drawerLayout;

In your Fragment
NavigationsDrawerActivity _activity =(NavigationsDrawerActivity)this.Activity;

then add your events
this._activity.drawerLayout.DrawerOpened += drawerLayout_DrawerOpened;
this._activity.drawerLayout.DrawerClosed += drawerLayout_DrawerClosed;


Android RTL form API 10 to API 21

Question: I have to build an app with both support for english and arabic layouts, the working range is from api 10 (2.3.3) to api 21 (5.0).
Following this document I configured the app, but I cannot use "start" and "end" because the range of support is too wide.
I thought I can create a layout folder like "layout-16" where to put all layouts with "start" and "end" for versions from 4.2, and another like "layout-ar" where to put all the mirrored layouts for versions before api16.
It could work like that? Or the "layouts-ar" will override the "layout-16"?
Thank you
Answer: Since the language is has a bigger priority than the app version, I should advice to have several folder like:

layout-v16 for all your layout that support start/end
layout-ar-v16 empty folder to force the system to use layouts-16.
layout-ar for arabic and android under the version 16.
layout for standard layouts.

Good luck !

Android RTL form API 10 to API 21


Problema na execução do depurador Visual studio

Question: Estou com um problema no meu projeto, utilizo o ASP.NET MVC 5 e de um tempo para cá eu recebo essa mensagem sempre que executo meu projeto, o problema não é o visual studio instalado na maquina(como nessa solução) pois meus colegas de trabalho tem o mesmo problema quando utilizam na maquina deles.
Eu consigo rodar meu aplicativo tranquilo, o problema é que se está aparecendo essa mensagem há algo de errado e eu ja fiz 300 milhões de pesquisas e não resolvo.
A mensagem é:

O depurador não foi instalado corretamento. Não é possível depurar o
  tipo de código solicitado. Execute o programa de instalação para
  reparar o depurador.

Eu tenho certeza de que não é o meu visual studio e sim o projeto. Alguém ja passou por algo parecido? Está dificil encontrar uma solução, segue o print do erro:
Comment: esse erro é quando vc tenta rodar testes automatizados? Pode ser o webdriver que não está instalado...
Comment: Não, esse erro ocorre quando eu vou executar a aplicação web
Comment: Instalei o SQL Server Data Tools (SSDT) for Visual Studio 2017 e estou com o mesmo problema. Parece que tem um número considerável de gente com este problema. Veja esta [questão no Fórum do SQL Server](https://social.msdn.microsoft.com/Forums/sqlserver/en-US/ea1aadfd-7ae9-48aa-be01-d5bf518800b9/error-in-visual-studio-2017-integration-services-project-unable-to-start-debugging-the-debugger-is?forum=sqlintegrationservices).
Comment: @LeonardoBonetti Neste mesmo forum no post acima, postei uma solução que rosolveu o meu caso (procura na página por gwarah). Espero que ajude no teu caso.
Answer: 1 - Limpe as pastas: C:\Program Files (x86)\Common Files\Microsoft Shared\VS7Debug C:\Program Files\Common Files\microsoft shared\VS7Debug
2 - Fazer um recover do Visual Studio
OBS.: Isso pode ser causado por DLL's corrompidas. https://blogs.msdn.microsoft.com/yash/2007/09/20/debugger-not-working/
Answer: Segundo este artigo da microsoft, vc deve seguir o seguinte passo:

Se várias versões do Visual Studio tiverem sido instaladas e
  desinstaladas no computador, a depuração do WF3 poderá falhar com uma
  das duas possibilidades a seguir: Os pontos de interrupção não foram
  atingidos. A seguinte mensagem é exibida: Não é possível iniciar a
  depuração no servidor web. O depurador não está instalado
  corretamente. Não é possível depurar o tipo de código solicitado.
  Execute a instalação para instalar ou reparar o depurador. Se qualquer
  um desses cenários ocorrer durante a depuração de fluxos de trabalho
  do .NET Framework 3.0 ou 3.5, execute um reparo da instalação do
  Visual Studio.
Comment: Então, mas a questão é que todos os lugares levam a mostrar que é problema do visual studio. Por exemplo, você afirmou que não é, mas como não comprovou, eu tentei seguir a linha de que poderia ser este problema. Qual VS você usa? já tentou outra versão? o erro persistiu? tente atualizar seu .net framework...
Comment: Eu disse que o problema é no **projeto** e não no Visual Studio, ja tentei esse processo :/
Answer: O problema se resolveu ao mudar a porta do projeto de http://localhost:54345/ para alguma outra aleatória, exemplo http://localhost:54348/.


Count numbers of checkboxes and update MySQL

Question: I'm updating some MySQL data for specific entries selected through checkboxes, my code for that looks like this:
<?php
    if($_POST['code_approve']){
        for($i=0;$i<count($_POST['checkbox']);$i++){
            $approval_id = $checkbox[$i];
            $sql = "UPDATE table SET status='approved', used='processed' WHERE id='$approval_id'";
            $result = mysql_query($sql);
        }
        if($result){
            echo "<meta http-equiv=\"refresh\" content=\"0;URL=table.php\">";
        }
    }
?>

Now I want to know how many checkboxes have been selected, and for every checkbox selected add 25 to table "members" row "balance".
I tried like this:
<?php
    if($_POST['code_approve']){
        for($i=0;$i<count($_POST['checkbox']);$i++){
            $approval_id = $checkbox[$i];
            $approvedamount = count($_POST['checkbox'])
            $approvedx25 = $approvedamount * 25;
            $sql = "UPDATE table SET status='approved', used='processed' WHERE id='$approval_id'";
            $sql2 = "UPDATE members SET balance = + '$approvedx25'";
            $result = mysql_query($sql);
        }
        if($result){
            echo "<meta http-equiv=\"refresh\" content=\"0;URL=table.php\">";
        }
    }
?>

But that didn't work at all, what's the proper way to do this ?
//EDIT
Please ignore this question, it worked, i just forgot to add the mysql_query.
Comment: I think that you should remove the quotes in teh where clause and make it like that, for start: WHERE id=$approval_id.. also where is that checkbox array come from?!?$checkbox[$i].. I think too much of your code is missing
Comment: You should not run SQL queries in a loop, it is not very efficient. Collect the IDs in the loop, then write one UPDATE query using IN.
Comment: Look at 'Check box group' section here: http://www.html-form-guide.com/php-form/php-form-checkbox.html
Answer: Your update query should be something like this:
$sql2 = "UPDATE members SET balance = balance + ".$approvedx25;

The way you wrote it, the update in withing the for clause, thus executed once for every checkbox. I'm not sure you want that, since you already multiply by the number of checkboxes.
Also, mind, your second query ($sql2) is not executed in your code.


print not working in Ruby

Question: I created a very simple run calculator for a class assignment, but I can't get it to display on one line.  I want the output to be "Your workout time is X minutes". I can get the first two parts on one line, but when I replace "puts workout_time" with "print workout_time", it doesn't work. I get something that looks like a progress bar, and the message "contacting server". I am using repl.it if that matters. This is my code:
#warm up and cool down times are fixed
#user enters remaining values in minutes

warm_up = 4
cool_down = 4
workout_time = []

puts "How many minutes per set do you want to run?"
run = gets.chomp.to_i

puts "How many minutes do you want to rest each set?"
rest = gets.chomp.to_i

puts "How many times do you want to repeat the run/walk?"
sets = gets.chomp.to_i

workout_time << (run+rest)*sets + warm_up + cool_down

print "Your workout time will be "
puts workout_time
puts " minutes"

Thanks!
Comment: `puts "Your workout time will be #{workout_time.first} minutes"`. This will do. I don't see why you're using an array anyway, just use an integer.
Comment: Oh wow - thanks! I actually tried that, or I thought I did - I used square brackets instead of curly brackets.
Comment: I agree with @sagarpandya82: There's no need to use an array to hold one value. You can remove the initialization of the `workout_time` variable (or if you keep it use `0` instead of `[]`), and later just assign it: `workout_time = (run+rest)*sets...`
Answer: Try to:
print "Your workout time will be %d minutes" % [workout_time]

Answer: See here: Concatenating string with number in ruby
You will want to use a puts statement with "Your workout time is X minutes" but replace the X with #{workout_time} like this:
puts "Your workout time will be #{workout_time} minutes"

print not working in Ruby


Forms - unitary group?

Question: If $Id$ is the $n$ by $n$ identity matrix and $J$ is the $2n$ by $2n$ matrix with $Id$ in the upper right corner and $-Id$ in the lower left corner, then $Sp_{2n} = \{G\in Gl_{2n} : G^{tr}JG = J\}$ is the symplectic group.
The unitary group is the set of matrices $G$ that satisfy that $G^*G = GG^* = Id$. Is there a way to describe the unitary group like how the symplectic is described?
Answer: Yes, if you like it: $U(n)=\{G\in Gl_n\colon G^*\, Id\, G=Id\}$.
Comment: Duh, now I feel stupid.

Forms - unitary group?


Parse a config file in PHP (key value)

Question: I have a config file which structure looks like this:
#comment1
key1 value1

#comment2
key-key2 value2

#comment3
key3 value3 value4

I have been trying to parse this in PHP with the following code:
$lines = explode(PHP_EOL, $string);
$config = [];

foreach ($lines as $l) {
    preg_match("/^(?P<key>\w+)\s+(?P<value>.*)/", $l, $matches);

    if (isset($matches['key'])) {
        $config[$matches['key']] = $matches['value'];
    }
}

However I am not able to get the regex right, the above regex is only functioning for the line with #comment1, it does not parse key-key2 properly and #comment3 key-value has 2 values which should just be 1 string inside the array.
Output I wish to have:
[
   'key1' => 'value1',
   'key-key2' => 'value2',
   'key3' => 'value3 value4'
]

Anyone able to help me with the regex?
Comment: How do you read the file? Big blob or line by line
Comment: Line by line (I am exploding on PHP_EOL (newline) in the string content)
Comment: So `$lines` is in fact just a single line ?
Comment: $lines is the array, and I foreach through it, $l is the line itself inside the foreach.
Comment: You might want to just explode the line on space and check that count = 2.
Comment: If it were me I'd change the config file to JSON.
Comment: @JayBlanchard This is not possible, the file I demonstrated (with #comment1 etc) is how I receive it, and I have to parse that. I would love to get it in JSON but simply not possible.
Answer: It should be simple enough not to have to use regex as you can check for # at the start of the line easily enough and then use explode() with a space and limit of 2 parts to extract the key and data...
$lines = explode(PHP_EOL, $string);
$config = [];

foreach ($lines as $l) {
    if ( !empty($l) && $l[0] != '#' ) {
        list($key, $value) = explode(" ", $l, 2);
        $config[$key] = $value;
    }
}
print_r($config);

Comment: Great solution actually, never thought of this. Thank you!
Answer: Using your existing code; just explode each line on space limiting to 2 elements and check that you get 2 elements:
$lines = explode(PHP_EOL, $string);

foreach ($lines as $l) {
    if(count($parts = explode(' ' , $l, 2)) == 2) {
        $config[$parts[0]] = $parts[1];
    }
}

Comment: This has problems when the comment has a space in it.

Parse a config file in PHP (key value)


Question on Block Maxima Method for Extreme Value Theory

Question: I am reading about extreme value theory. Let $X_1, X_2, ...$ be i.i.d. random variables and $M_n = \text{max}\{X_1,...,X_n\}$ as usual.
I understand that, by the Fisher-Tippett-Gnedenko theorem:
If there exist sequences $b_n \in \mathbb{R}$ and $a_n > 0$ s.t.
$$\frac{M_n - b_n}{a_n} \xrightarrow{d} G,$$
for some distribution function, then $G$ is a Generalised Extreme Value (GEV) distribution, i.e. belongs to the Gumbel, Frechet or Weibull family.
In a later chapter about the block maxima, there is the following statement in these notes extreme value theory (german, sorry!): "We model the distribution of the maxima through a GEV distribution. Of course, for the convergence normalising constants are needed, but in our case, we can assume that these are already part of the parameters $\mu, \sigma, \gamma$ (which are the location / scale / shape parameters of the GEV distribution."
This last sentence confused me. Does that hold in general? If yes, why? If not, which assumptions are neccessary?
Any hints appreciated. Thank you very much!
P.S. Like I said, I am referring to these notes on extreme value theory. It's German, sorry! (Remark 6.1.2) But the same statement can also be found here on these slides, for example (page 4).
Answer: This would be better as a comment but I don't have enough reputation: $a_n$ functions as a shift parameter and $b_n$ as a scale parameter, which is analogous to $\mu$ and $\sigma$. If you have a variable $X_n$ which is centred at $5$, you can shift it to be located at zero using $b_n=5$, alternatively you can set $\mu=5$, likewise for the scale.


Prevent delete content before it is removed in external index

Question: This is my use case.
We have a Drupal 8 installation that we used as decoupled, so one external API retrieve all content and them indexed. So, this external API update indexed content when Changed date is updated. But, if the content is missing it doesnt do nothing. The content is removed from index only when content is unpublished.
I was thinking in deny users to delete content, and add an state or a field value to notify that the node need to be deleted in external index. Then a while delete content with a cron.
Comment: I don't really understand.. but it sounds like you need a reconciler task running independent of the indexer (perhaps after that task) that checks if the local IDs in your index still exist in Drupal, else, wipe it from the index.
Comment: What about implementing hook_entity_delete() to store deleted ids in a variable that will be read by the external API to delete indexed content (and for each deleted indexed content , delete the id in the variable)

or

if the external API can be triggered to delete a content by its id, directly trigger it from the hook_entity_delete()
Answer: The plan was prevent users to delete content, then unpublished content, save.. then index will remove content after a while. Time later we can remove unpublished content.
What I did

Remove permission to delete for all roles(without admin). So no body can delete content directly.
I enabled Content Moderation (core) module. Here I added a State "To Delete"(unpublished) to all CTs. So we add the option to erase a content later.
When external index check content unpublished and erase it.
I added a cron that check content with State "To Delete" that have more than 1 week without been updated. Then we delete those nodes.
<code>function MODULE_cron() {

  $nids_to_delete = getIdsByModerationState('to_delete');

  // @todo verify if empty array
  // @todo verify default language
  $query = \Drupal::entityQuery('node')
    ->condition('nid', $nids_to_delete, 'IN')
    ->condition('changed', strtotime('-1 week'), '<=')
    ->condition('status', NOT_PUBLISHED);
  $nids = $query->execute();
  // @todo test entity_delete_multiple('node', $array);
  foreach ($nids as $nid) {
    $node = Node::load($nid);
    $node->delete();
  }

}

function getIdsByModerationState($moderation_state) {
  $query = \Drupal::database()->select('content_moderation_state_field_data', 'ms');
  $query->join('node_field_revision', 'nf', 'nf.nid=ms.content_entity_id AND nf.vid=ms.content_entity_revision_id AND nf.langcode=ms.langcode');
  $query->fields('ms');
  $query->condition('ms.moderation_state',$moderation_state);
  $results = $query->execute()->fetchAllAssoc('content_entity_id');
  $array_result = array_keys($results);
  return $array_result;
}
</code>
Comment: I don't get what this has to do with an external index.
Comment: Hi @kevin continually the external index check Drupal API checking content. If content is published it add it to this own. If it is unpublished it is erased. Thanks for your comments!


Incorporating autocorrelation into forecasts

Question: I have a time series $x_{t}$ which is an AR(1) process with a constant
term, e.g.
$
x_{t} = c + \phi x_{t-1} + \epsilon_{t}
$
How can I incorporate information about the autocorrelation of
$x_{t}$ in order to maximize $\frac{\mu_x^*}{\sigma_x^*}$ where
$x_{t}^* = a_{t}x_{t}$?
where $\mu_x^*$ and $\sigma_x^*$ are the sample mean and standard deviation of $x_{t}^*$ respectively and $a_t$ is some function of the past history of $x_{t}$, e.g. $a_t = f(x_{t-1}, x_{t-2},...)$
As a concrete example, here is some R code to generate an AR(1) process
> phi <- 0.3
> var_x <- 0.001^2
> mean_x <- 0.0015 / sqrt(252)
> var_eps <- var_x * (1 - phi^2)
>
> set.seed(1)
> eps <- rnorm(252*15, sd = sqrt(var_eps))
> c <- mean_x * (1 - phi)
> x <- filter(c + eps, 0.3, method = "recursive")
>
> mean(x) / sd(x)
[1] 0.09388863

If I were just to observe $x_t$ generated above, I could diagnose that this is
in fact an AR(1) process using acf and pacf

and then fit an AR(1) model to estimate $\mu$ and $\phi$
> ar1 <- arima(x, order = c(1, 0, 0))

Call:
arima(x = x, order = c(1, 0, 0))

Coefficients:
         ar1  intercept
      0.3047      1e-04
s.e.  0.0155      0e+00

sigma^2 estimated as 9.847e-07:  log likelihood = 20776.83,  aic = -41547.65

Using this estimate I can forecast $x_t$
c_est <- ar1$coef[2] * (1 - ar1$coef[1])
x_fcst <- ar1$coef[1] * x[-c(1)] + c_est

But here I am at a bit lost regarding how to incorporate this forecast in an
optimal way into $a_t$, where as above optimal is defined as maximizing $\frac{\mu_x^*}{\sigma_x^*}$.
Note
In the above $\frac{\mu_x^*}{\sigma_x^*}$ represents the Information Ratio with a benchmark of 0, and $x_t$ can be thought of as a time series of returns.
Comment: What are $a_t$, $\mu_x^*$, $\sigma_x^*$? What is the point of maximizing $\frac{\mu_x^*}{\sigma_x^*}$?
Comment: @RichardHardy responded inline
Comment: @RichardHardy I'm wondering if there is anything still unclear in your mind? This question unfortunately doesn't seem to be getting much traction
Comment: Sorry. The activity at Cross Validated has been relatively high the last few days, so there is a lot to do :) Unfortunately, I do not think I will be able to help you in the nearest future. Still, I hope you don't mind my earlier comment asking for clarification; it should have helped any other users seeing the question and could potentially have attracted an answer.
Comment: No absolutely, all feedback welcome. Just wanted to check that as it's currently formulated the question is reasonably clear. Thanks.
Answer: I've added my own attempt at an empirical solution/observation, partly because I believe
it helps clarify my question. This does not really address the core issue of the question which is related to the theoretical underpinnings of determining $a_{t}$.
Define $a_t$ as follows
$a_t = 1 + \frac{x_{t|t-1} - \mu_{x}}{\sqrt{Var(x_{t|t-1})}}n$
where $n$ is some scalar, $\mu_{x}$ is estimated using the full sample mean
of $x_t$ and similarly $Var(x_{t|t-1})$ uses the full sample variance of
$x_{t|t-1}$. Admittedly this is not a function of the form
$a_t=f(x_{t-1},x_{t-2},...)$ since it uses full sample estimates but ignoring
this for the time being, we can implement the above as follows
level <- x_fcst - ar1$coef[2]
calc_at <- function(level, n) {
  conv <- 1 + (level / sd(level))*n
  conv <- c(1, conv)
  conv
}

ats <- list()
scale <- c(0, 0.2, 0.4, 0.6, 0.8, 1:5)
for (i in 1:length(scale)){
  ats[[i]] <- calc_at(level, scale[i])
}

calc_ir <- function(at, x) {mean(x*at) / sd(x*at) * sqrt(252)}
irs <- lapply(ats, calc_ir, x=x)

which shows an asymptotic increase in $\frac{\mu_{x^*}}{\sigma_{x^*}}$
plot(scale, unlist(irs), ylab = "mu / sigma")

accompanied by decreases in the scaled returns autocorrelation
acf(x*ats[[4]])

acf(x*ats[[8]])


Prove that $f( \limsup \limits_{x \to +\infty} x_n)$ = $ \limsup \limits_{x \to +\infty} f(x_n)$

Question: The problem is divided into two questions:
$x_n$ is a real valued sequence.

Prove that $f( \limsup \limits_{n \to +\infty} x_n)$ = $ \limsup \limits_{n \to +\infty} f(x_n)$ given that $f$ is continuous and increasing.
What can we say when $f$ is decreasing.

If it were a regular limit I can just pass the $\lim$ inside the function and we're done. But this is $\limsup$ .
Thanks for your help.
Answer: For any sequence $(y_{n})$ let $y_{n}^{+} = \sup_{k\geq n}y_{k}$. Let $L = \limsup x_{n}$ be a real number. Since $L = \lim x_{n}^{+}$ and $f$ is continuous, we have $$f(L) = \lim f(x_{n}^{+}).$$ Now we show that $f(x_{n}^{+}) = f(x_{n})^{+}$ for each $n$. Since $x_{n}^{+}\geq x_{k}$ for each $k\geq n$ and  $f$ is increasing, we have $f(x_{n}^{+})\geq f(x_{n})^{+}$. For any $\varepsilon > 0$ there exists $k\geq n$ such that $x_{n}^{+}-\varepsilon < x_{k}$. Again using the fact that $f$ is increasing we get $f(x_{n}^{+}-\varepsilon)\leq f(x_{k})\leq f(x_{n})^{+}$. Letting $\varepsilon\rightarrow 0$ and using the continuity of $f$ we get $f(x_{n}^{+})\leq f(x_{n})^{+}$.
If $f$ is decreasing then $(-f)$ is increasing and thus $(-f)(\limsup x_{n}) = \limsup\:(-f)(x_{n})$. This reduces to $f(\limsup x_{n}) = \liminf f(x_{n})$ after simplification.


Displaying data on a website based on selection in a dropdown box

Question: I have the following problem:
In my data model I have a class called Type. Type consists of a title and a description.
Now I have a dropdown box in which the user may select an instance of Type:
<h:selectOneMenu id="typeDropdown" onchange="displayDescription();">
      <f:selectItems value="#{operationCreator.types.title}" />
</h:selectOneMenu>

Below the dropdown box is a div area in which I want the description of the selected Type displayed.
My question is the following:
How can I store the description of the Type instances in javascript? A simple JSF tag which iterates over the list would do the job, but unfortunately I know of none. They all print additional HTML tags (like datatable), or work only with surrounding JSF tags (like selectItems).
I do know I could fix my problem using AJAX push, but I don't want to. I want to access my data on page load in javascript.
I hope you can help me!
Thanks, Michael
Comment: The nature of this question (a relatively clumsy attempt to solve a problem which is in JSF 2.x to be solved by only one additional tag) indicates that you're still on the old JSF 1.x. Is this true?
Comment: No, I am using the latest JSF version. However I am new to JSF, so any hints and tipps on how to do it in a complete different way are appreciated! My only restriction is to avoid ajax.
Comment: Why do you want to avoid ajax? That's exactly the solution to your problem.
Comment: The site will be displayed on mobile clients. Because of latency issues AJAX is out of scope.
Answer: Prepare the data in JSON format and let JSF just print it as a JS variable. You could do that either directly in backing bean
public String getTypesAsJson() {
    return typesAsJson;
}

with

or in the view by iterating over a Java collection like List<Type> and printing the JavaScript code accordingly if the values are guaranteed to not contain any special characters in JS such as quotes and newlines:

The first way is preferable as it eliminates the risk for syntax errors in the produced JS code when the type title or description contains a JS special character. You can use among others Google Gson to convert a Java collection of beans to a string in valid JSON format.
typesAsJson = new Gson().toJson(types);

Now, if you make sure that the item value of the dropdownlist is the type title, then you can get the associated description as follows
<h:selectOneMenu ... onchange="displayDescription(this)">

with
function displayDescription(dropdown) {
    var title = dropdown.options[dropdown.selectedIndex].value;
    var description = types[title];
    // ...
}


What is the closure of $\ell_1$ in $\ell_2$?

Question: It is not difficult to show that the sequence space $\ell_1$ is a subspace of $\ell_2$ that is not closed in the $\ell_2$ topology (see Problem 2 in this pdf file for instance)
What is the closure of $\ell_1$ in $\ell_2$?
Comment: See here: https://math.stackexchange.com/questions/1710874/proving-that-l-r-is-dense-everywhere-in-l-p-1-leq-r-leq-p
Answer: $\ell^1 $ is dense in $\ell^2$ (w.r.t. the $\ell^2$ norm topology). The argument is simple: given $\textbf{x} = (x_1, \ldots x_n, \ldots) \in\ell^2$ fix $\epsilon >0$ and take $\textbf{x}_N = (x_1, \ldots x_N, 0, 0, 0 \ldots)$ where $N$ is such that $\displaystyle \left(\sum_{k=N+1}^\infty x_k^2\right)^{1/2} < \epsilon.$
Then $\textbf{x}_N$ is obviously in $\ell^1$ and $\|\textbf{x} - \textbf{x}_N\|_2 < \epsilon$.
Hence the closure of $\ell^1$ in the $\ell^2$ topology is $\ell^2$.
Answer: All $e_n$ are in $\ell_1$. What is the  closure of their span in $\ell_2$?
Answer: Closure of $l_p$ in $l_q$ is $l_q$ for any $p,q$ with $p<q$. Or, $l_p$ is dense in $l_q$ for any $p,q$ with $p<q$. You can prove it either by using the concept/arguement given by Henno Brandsma (above) or by using the technic given by David Bowman (above).


How do i check the reaction content in discord.py?

Question: I am creating a ticket system. And i want a confirmation with the /close command. But how do i do that? I tried it wit an if statement but it didnt work.
This is what i have:
@bot.command(name='Close', aliases=['close'])
async def close(ctx):
    if ctx.message.channel.name.startswith('ticket'):
        msg = 'The ticket is closed. If you aren\'t done yet react to this message with , if you are react with '
        embed = discord.Embed(title='Closed ticket', description=msg)
        message = await ctx.send(content=None, embed=embed)
        await message.add_reaction('')
        await message.add_reaction('')
        await ctx.message.channel.set_permissions(ctx.author, send_messages=False)
        reaction = await bot.wait_for('reaction')
        if reaction.content == '':
            countdown = await ctx.send('**Ticket will be closed in 10 seconds**')
            await asyncio.sleep(1)
            await countdown.edit(content='**Ticket will be closed in 9 seconds**')
            await asyncio.sleep(1)
            await countdown.edit(content='**Ticket will be closed in 8 seconds**')
            await asyncio.sleep(1)
            await countdown.edit(content='**Ticket will be closed in 7 seconds**')
            await asyncio.sleep(1)
            await countdown.edit(content='**Ticket will be closed in 6 seconds**')
            await asyncio.sleep(1)
            await countdown.edit(content='**Ticket will be closed in 5 seconds**')
            await asyncio.sleep(1)
            await countdown.edit(content='**Ticket will be closed in 4 seconds**')
            await asyncio.sleep(1)
            await countdown.edit(content='**Ticket will be closed in 3 seconds**')
            await asyncio.sleep(1)
            await countdown.edit(content='**Ticket will be closed in 2 seconds**')
            await asyncio.sleep(1)
            await countdown.edit(content='**Ticket will be closed in 1 second**')
            await asyncio.sleep(1)
            await ctx.message.channel.delete()
        if reaction.content == '':
            await ctx.send('**Ticket reopened**')
            await ctx.message.channel.set_permissions(ctx.autor, send_messages=True)
    else:
        await ctx.send('This isnt a ticket')

And i didn't even get any errors?
Answer: When waiting for a reaction to be added, you should use "reaction_add" instead of just "reaction":
@bot.command(...)
async def close(ctx):
    # Code

    # A check is usually encouraged when in a public channel,
    # but for a private channel with just one or two members, it should be fine
    reaction, user = await bot.wait_for("reaction_add")
    # Do some stuff

Two values are actually being returned from this wait_for, as seen in the documentation's example - reaction, and user.
Additionally, the discord.Reaction object has no content attribute.
You'll actually be looking for str(reaction) instead:

References:

Client.wait_for()
discord.Reaction
discord.User
Comment: Thanks!! You helped me again (-:. It finally worked thank you so much!


How famous piano player differs from an average piano player?

Question: Let's assume the following situation:

The two piano players compete performing the same piece of moderate  difficulty in front of public, who can do better.
One of the them is really good, maybe famous.
However also weaker player knows the piece well enough not to make very obvious mistakes like hitting a wrong key.

It seems to me that the public would be more impressed by the music from the really good, famous pianist, but why? If both play the right notes for the right duration (and also my laptop can do through MIDI interface), how is the music from the more gifted player objectively better?
Comment: Not sure this is completely in the site scope, but an interesting question!
Comment: @JacobSwanson it's absolutely in the site scope.
Comment: @Codeswitcher, there seems to also be a psychological side to this question, too.
Comment: @JacobSwanson  I think that if you think this is a psychological question, you don't understand what more advanced musicians study.
Comment: @Codeswitcher, I didn't mean to imply that this is ONLY a psychological question, but it could be answered that way.
Comment: I guess the psycologic answer wouldn't give an objective reason though.
Answer: Music is more than playing the right pitches at the right time.  Playing the right pitches at the right time is the absolute minimum standard to producing a musical work.
Here's a bunch of the other mechanical phenomena you must then also get "right":

Tempo (including variations in tempo, such as rubato)
Dynamics (both volume and attack)
Phrasing.

Once you can do all that, then you get to the artistry part.
What is on the page is only part of the music.  Quite a bit of expressiveness is left up to the performer to pick for themselves.  At that level of play, you are not merely judged for producing the music "correctly" as per what is written in the score, but for your artistic choices about how to handle what is not written down.
Here, watch this video to have your mind slightly blown.  It's a cello master class with famed conductor Benjamin Zander of the Boston Philharmonic:
http://poptech.org/popcasts/benjamin_zander__poptech_2008
As a general word of advice: seek out master classes.  Master classes are private lessons conducted in public to edify the audience as much as the student.  Usually they're extremely expert instructors teaching very advanced performers.  I have no idea where one can find master classes in piano; I sometimes take in master classes in early music at festivals.  They have been fabulously informative about what comes next after getting the notes right.
Comment: I agree that the interpretation (the artistry) of the piece is exactly what most people would say makes a better performance. However, it still seems to me that such a valuation is extremely subjective.
Comment: I would also say that the extra criteria does not apply to some styles of music. For example, I think Bach would say that it is exactly hitting the right note at the right time that makes good music (actually, he did say that).
Comment: @DanielGrady I've been known to joke that the best interpretations of Bach were by Wendy Carlos, of "Switched on Bach" fame, because "she had them played by computer, the way Bach intended."  (Full disclosure: I'm not a Bach fan.)  If Bach intended his music to have its full interpretive flourishing by being rendered as mechanically purely as possible, well, that _too_ is an artistic interpretive choice. The choice not-to-do is as much as a choice to-do.  There may be as much intentionality in the rest as the pitch.
Comment: @DanielGrady You seem to be having trouble with the concepts of objective and subjective.  That which is subjectively experienced (i.e. everything) has an objective reality, roughly speaking. If one person prefers the original and another a cover, if one prefers the modern orchestral interpretation and the other the historically informed instruments, if one prefers the more loose, rubato approach, and the other prefers a brisk dancing tempo: the preference of one over the other is subjective, but that which is preferred is an objective phenomenon which can be decisively pointed out.
Comment: @DanielGrady One of the remarkable things about music, especially in the Western traditions, but also in other traditions around the world, is that it has an astonishingly rich technical language for discussion of sensory experiences which are subjectively apprehended, viscerally comprehended, notoriously subtle, and highly fugitive.  We musicians have a thoroughly worked and nuanced language for discussing with precision that which is heard and felt.  Subjectivity is what we discuss, and we do it objectively.
Answer:
How is the music from the more gifted player objectively better?

Strictly speaking, one could only say that one performance is subjectively better than the other.  (Although it might sometimes happen that a preference for one of the players is unanimous.)
Another "strictly speaking" remark: the famous performer might not always come out ahead!  I once heard a quite famous cellist, János Starker, play so clinically and lifelessly that I left the hall furious, in a terrible mood.
A fun thing to do is to go to a Suzuki recital, where you can hear two or three different versions of the same piece on a given afternoon, all played quite well, but somewhat differently.  Go, listen, and find out for yourself what appeals to you the most, and what makes you enjoy and remember one version more than another.  You might not be able to put it into words -- but that's okay.
Answer: First off, "famous" as a criteria for assessing virtuosity is problematic at best.
Additionally, the ability of a particular audience to discern quality is also problematic.
What it comes down to is that music is not just a sequence of notes arranged in a particular juxtaposition to each other.  Music is communication, it's a form of core emotional communication.
Take a piece of music and play it at 130bpm, then play it at 127bpm, and it might turn into a very different piece, far more expressive more moving, more connecting.
The art of phrasing a melodic line is extremely subtle, but easily discernible.  A midi file might play all the notes "exactly as written" and it sounds very good, but then a true player plays the same phrase and it sounds "like music."  The difference is milliseconds of timing, micro-decibels of difference in emphasis, maybe 0.001 percent difference, but the difference in what we perceive is stark, obvious.
The experienced player doesn't "fight" the music.  Imagine an analogy, of two skiers going down an intermediate slope.  they ski together, and to outward appearances the novice is skiing just as ably as the expert, but when they get to the bottom of the hill, the expert is calm, unruffled, and the novice is breathing hard, exhausted.  They both ran the same hill, followed the same line, on the same snow surface, with the same skis.  The expert let the mountain and the skis do the work, the novice fought it and muscled it the whole way down.  (I'm the novice skiier, btw)
This is the same idea between the two pianists.  The novice is functioning on the "remain on skis for duration of run" level, the virtuoso is functioning on an entirely different level of subtlety.
Answer: There is no "objective" standard of goodness here. The better player will convince the listener that what they are hearing is worth listening to. There's nothing much more to be said than that.
Of course some of "listeners" may be in the hall for reasons other than actually listening, if the player is "famous" - and some people seem judge piano playing by the same standards as an athletics competition or a circus act, where "what it sounds like" is fairly irrelevant to "how impressive it looks" or "how fast you can play the notes".
Answer: That's like asking how an audience chooses a speaker to prefer in a recital when both speakers produce the right sequence of syllables.
Or how they prefer a theatric performance when all the right words are given in correct order.
The reason people go to concerts rarely is that their eyesight would be too bad to enjoy reading the scores themselves.  They come for a rendition of the score, not a copy.
They want to hear a musician's take on a composer's work.  If the view of the musician is that he counted off all beats at the right pitch successfully, that tends to be rather boring.  It's a common fallacy to counter the boredom by adding speed rather than detail to the rendition.


how to get the installation path in C#?

Question: I am modifying a .NET v4.5.2 code, and I want to be able to get a script path from the installation folder (so when a user install the app, the app is able to access and run the script)
I tried Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) method but it returned the wrong value (it returned the path: "C:\Users\HP\AppData\Roaming" , whereas my program location (after installation) is "C:\Program Files (x86)". I also tried Environment.GetCommandLineArgs()[0] and Path.GetDirectoryName(appFileName) but they returned the location of the file where the code was written. could you please help me?
Comment: It is worth noting that .net 4.5.2 is End Of Life, as of April 2022. You should strongly consider upgrading.
Comment: This may help https://stackoverflow.com/questions/837488/how-can-i-get-the-applications-path-in-a-net-console-application
Answer: try AppDomain.BaseDirectory()
String _path = System.AppDomain.CurrentDomain.BaseDirectory;

Comment: Thank you ..I have just tried it, it also returns the code file location
Comment: I have my doubts that this would result in something much different from `Environment.GetCommandLineArgs()[0]`.

how to get the installation path in C#?


Connect a specific port in webview

Question: How can I load an UIwebView with a specific port, when I try on xcode6, nothing is displayed in the simulator ...
I have use this code :
NSString *urlString = @"http://www.myurl.com:9090";
NSURL *url = [NSURL URLWithString:urlString];
NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url];
[_webView loadRequest:urlRequest];

With this code, webview is not load ...
Answer: Hello Everything is OK no issue in url  plz try correct url
NSString *urlString = @"https://support.microsoft.com/en-us/kb/307882";
NSURL *url = [NSURL URLWithString:urlString];
NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url];
[_webView loadRequest:urlRequest];

Comment: With https , and this URL it's ok but with my specific port ( 9092 ) , it's not ok , so why and how can I resolv the problem ?
Comment: may be url is not correct some issue in Your Url that why Cant open iniWebView
Comment: My url is correct , in safari on my iPhone and the simularor it's loaded

Connect a specific port in webview


Illegal argument error: logits and labels must be same size

Question: I am getting an error when calculating the cost function using softmax. It says that the shape of my logits and labels are not match
InvalidArgumentError (see above for traceback): logits and labels must be same size: logits_size=[1000,2] labels_size=[1,1000]
 [[Node: SoftmaxCrossEntropyWithLogits = SoftmaxCrossEntropyWithLogits[T=DT_FLOAT, _device="/job:localhost/replica:0/task:0/cpu:0"](Reshape, Reshape_1)]]

Even if I do reshape or transpose the shape cannot match as logits is [1000,2] size and labels is [1000,1]. How do I tackle this issue?
n_nodes_hl1 = 250
n_nodes_hl2 = 250
n_classes = 2
batch_size = 1000

with open("xdf.pickle", 'rb') as f:
  features = pickle.load(f)
with open("ydf.pickle", 'rb') as f:
  labels = pickle.load(f)

def neural_network_model(data, feature_count):
  hidden_layer_1 = {'weights': tf.Variable(tf.random_normal([feature_count, n_nodes_hl1])),
                  'biases': tf.Variable(tf.random_normal([n_nodes_hl1]))}
  hidden_layer_2 = {'weights': tf.Variable(tf.random_normal([n_nodes_hl1, n_nodes_hl2])),
              'biases': tf.Variable(tf.random_normal([n_nodes_hl2]))}
  output_layer = {'weights': tf.Variable(tf.random_normal([n_nodes_hl2, n_classes])),
                'biases': tf.Variable(tf.random_normal([n_classes])), }

  l1 = tf.add(tf.matmul(data, hidden_layer_1['weights']), hidden_layer_1['biases'])
  l1 = tf.nn.relu(l1)
  l2 = tf.add(tf.matmul(l1, hidden_layer_2['weights']), hidden_layer_2['biases'])
  l2 = tf.nn.relu(l2)

  output = tf.matmul(l2, output_layer['weights']) +  output_layer['biases']
  return output

def train_neural_network(x, y, features, labels):
  X_train, X_test, y_train, y_test = train_test_split(features, labels, test_size=0.2)

  prediction = neural_network_model(x, len(features.columns))
  cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=prediction, labels=y))
  optimizer = tf.train.AdamOptimizer().minimize(cost)
  hm_epochs = 1

  with tf.Session() as sess:
    sess.run(tf.initialize_all_variables())
    for epoch in range(hm_epochs):
        epoch_loss = 0

        for i in range(int(len(X_train) / batch_size)):
            epoch_x = X_train[i*batch_size: min((i + 1)*batch_size, len(X_train))]
            epoch_y = y_train[i*batch_size: min((i + 1)*batch_size, len(y_train))]
            i, c = sess.run([optimizer, cost], feed_dict = {x:epoch_x, y:epoch_y})
            epoch_loss += c

        print('Epoch', epoch, ' completed out of ', hm_epochs, ' loss: ', epoch_loss)

    correct = tf.equal(tf.argmax(prediction, 1), tf.argmax(y, 1))
    accuracy = tf.reduce_mean(tf.cast(correct, 'float'))

    print('Accuracy: ', accuracy.eval({x: X_test, y: y_test}))

 x = tf.placeholder('float', [None, len(features.columns)])
 y = tf.placeholder('float')
 train_neural_network(x, y, features, labels)

Answer: Since I do not know what data you have, I can only guess. Your network has n_classes output neurons (2 in your case), but I assume that your labels are binary (0 or 1). You will either have to reduce the number of output neurons to 1 (this should work since you only have two classes), or convert your labels into one-hot labels ([1,0] for a label 0 and [0,1] for a label 1).
You could also try using tf.nn.sparse_softmax_cross_entropy_with_logits(), maybe it will work, so that you don't have to change the rest of the network...


How to do query with timestamp?

Question: I have this table:
id (int)
name (varchar)
insert (timestamp)

An example row is this:
14, John, 2010-02-25 01:48:36

In this table I have 1 million of rows and I want to know how many rows have been inserted in each day. So I want something like this:
2010-02-25 153
2010-02-24 98
2010-02-23 219
2010-02-22 127
...

What query do I have to do ?
Answer: Try this:
SELECT DATE(`insert`) AS day, COUNT(*) AS cnt
FROM your_table
GROUP BY day

Note that days that have no rows will not be represented in the result set.

How to do query with timestamp?


Return matching nodes in a nested tree: Javascript

Question: I have an array of objects that is implemented as a tree with the follwing structure. I am trying to implement a  search functionality that basically searches the key inside these objects and return them by maintaining the relationship.
const arr = [
  {
    name: "internalcorp.com",
    config: {
      val1: false,
      val2: false
    },
    children: [
      {
        name: "internalcorp.com.child1",
        config: {
          val1: true,
          val2: true
        },
        children: [
          {
            name: "internalcorp.com.grandchild1",
            config: {
              val1: true,
              val2: true
            },
            children: []
          },
          {
            name: "internalcorp.com.grandchild2",
            config: {
              val1: false,
              val2: true
            },
            children: []
          }
        ]
      },
      {
        name: "internalcorp.com.child2",
        config: {
          val1: true,
          val2: false
        },
        children: []
      }
    ]
  },
  {
    name: "internalcorpwebsite.com",
    children: [
      {
        name: "internalcorpwebsite.com.child1",
        className: "level-1 leaf",
        children: [],
        val1: false,
        val2: false
      }
    ],
    config: {
      val1: false,
      val2: false
    }
  }
];

Here I need to search the array based on key "name" recursively , and return that object maintaining the parent-child relationship. THe search should be a contains search
Code that  I tried:
function result(input) {
  let res = arr.map((item) => {
    if (item.name === input) return item;
  });
  return res;
}
console.log(result("website"));

Comment: I still don't know what you mean by that. The child elements don't point back to their parents, so if you isolate them from their parents, by nature you're going to lose that relationship. Could you show us the resulting structure you expect when you search for (say) `"internalcorp.com.grand"`?
Comment: What do you mean by *"...and return them by maintaining the relationship..."*?
Comment: Some notes on the bit of code you've posted: `map` isn't a filtering operation, there's no attempt at handling nesting shown, and you've said the search should be a "contains" search, but you've used equality  (`===`) in your code.
Comment: Welcome to SO! Please take the [tour] (you get a badge!) and read through the [help], in particular [*How do I ask a good question?*](/help/how-to-ask) Your best bet here is to do your research, [search](/help/searching) for related topics on SO and elsewhere, and give it a go. ***If*** you get stuck and can't get unstuck after doing more research and searching, post a [mcve] showing your attempt and say specifically where you're stuck. People will be glad to help.
Comment: @T.J.Crowder Ideally the hierarchy of parent-child should be intact.
Answer: Something like this, you can play with it here: Codepen Playground
I've made the search to case insensitive and you can also search for multiple words, it should give you full tree and maintain parent-child relationship, try it out

const arr = [
  {
    name: "internalcorp.com",
    config: { val1: false, val2: false },
    children: [
      {
        name: "internalcorp.com.child1",
        config: { val1: true, val2: true },
        children: [
          {
            name: "internalcorp.com.grandchild1",
            config: { val1: true, val2: true },
            children: []
          },
          {
            name: "internalcorp.com.grandchild2",
            config: { val1: false, val2: true },
            children: []
          }
        ]
      },
      {
        name: "internalcorp.com.child2",
        config: { val1: true, val2: false },
        children: []
      }
    ]
  },
  {
    name: "internalcorpwebsite.com",
    children: [
      {
        name: "internalcorpwebsite.com.child1",
        className: "level-1 leaf",
        children: [],
        val1: false,
        val2: false
      }
    ],
    config: {
      val1: false,
      val2: false
    }
  }
];
function result(input) {
  const v = input.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
  const regex = new RegExp(v.trim().replace(" ", "|"), "i");
  return arr.filter(function f(o) {
    let found = false;
    if (regex.test(o.name)) found = true;
    if (o.children) {
      const x = o.children.filter(f);
      if (x.length) {
        o.children = x;
        return true;
      }
      return found;
    }
  });
}
console.log(result("website.com"));


How to add file extensions to list of acceptable in IMCE

Question: I am using Ckeditor editor/IMCE file upload.
How do I get to the config settings where I can add more extensions which are accepted?
Answer: Go to admin/config/content/wysiwyg. Under the textformat table if CKEditor is choosen on full html for example under the operations column, select edit. And you should see buttons and plugins, and you should find the Imce checkbox listed as one of the last checkboxes
Answer: For adding additional buttons and plug-ins to add more extra functionalities,just follow these steps:-

Go to the CONFIGURATION (admin/config) option which is displayed on the menu bar.
Then select WYSIWYG PROFILES which is part of Content Authoring section.
For the three text formats available (i.e FULL HTML, FILTERED HTML, PLAIN TEXT), configure the CK EDITOR for the format you wish to configure for.
Then select EDIT which is displayed in the operations's section.
Go to BUTTONS AND PLUG-INS link.
Check the checkboxes for the functionality you want to enable in your ck editor.
Save the settings.
Answer: I found this question in trying to add to the list of permitted file extensions for uploaded files using IMCE. Following the accepted answer didn't get me where I needed to go. Instead I had to go to Admin > Configuration > Media > IMCE, then click to edit the profile I needed to adjust (Admin, in my case).
From there (example.com/admin/config/media/imce/profile/edit/3), I was able to add to the list under "Permitted file extensions". I hope this helps for other folks who land on this thread.
FYI, I'm using Wysiwyg version 7.x-2.2+63-dev, IMCE Wysiwyg API bridge version 7.x-1.0, and IMCE version 7.x-1.9.


Understanding the whiskers of a boxplot

Question: I have a question regarding the interpretation of the whiskers of a boxplot. I have read the following: "On the top and bottom of
the rectangle, the "whiskers" show the range of 1.5 times the distance between the
0.25- and 0.75-quantiles", but do not entirely understand what is meant by "distance".
It can't be that the probability mass is meant, since between the 0.25 and 0.75 quantile we obviously always have the same percentage of data.
What then is the idea?
Answer: The value of X that corresponds to the 75 quantile minus the value of X that corresponds to the 25th is the distance. For example, for SAT Math Test, 620 is the 75th and 520 is the 25th quantile. So if you score above 620, you're done better than 75% of the test takers. The whiskers would extend up to 1.5*(620-520) points long.
Comment: +1, a (slightly more) complete answer is that the whiskers are *up to* 1.5*IQR, if you don't have any more data within that interval, the whisker stops short. In addition, any additional data beyond that point are plotted individually as potential outliers.
Comment: @gung and an even more complete answer is that the whiskers always lie on an existing point in the data
Comment: Well, but then the whiskers would be of the same length on both sides of the box (which is not necessarily the case).
Comment: With this little additional explanation it's clear now, thanks a lot!
Comment: I edited the answer with @gung's excellent point.
Comment: That's a good point, @hadley, I should have been clearer about that.
Comment: EDA has more rules than one of those beard competitions!
Answer: A boxplot is intended to summarize a relatively small set of data in a way that clearly shows

A central value.

The spread of "typical" values.

Individual values which depart so much from the central value, relative to the spread, that they are singled out for special attention and separately identified (by name, for instance).  These are called "identified values."

This is to be done in a robust way: that means the boxplot should not look appreciably different when one, or a relatively small portion, of the data values is arbitrarily changed.
The solution adopted by its inventor John Tukey is to use the order statistics--the data as sorted from lowest to highest--in a systematic way.  For simplicity (he did calculations mentally or with pencil and paper) Tukey focused on medians: the middle values of batches of numbers.  (For batches with even counts, Tukey used the midpoint of the two middle values.)  A median is resistant to changes in up to half the data on which it is based, making it excellent as a robust statistic.  Thus:

The central value is estimated with the median of all the data.

The spread is estimated with the difference between the medians of the "upper half"--all data equal to or above the median--and the "lower half"--all data equal to or less than the median.  These two medians are called the upper and lower "hinges" or "fourths".  They tend nowadays to be replaced by things called the quartiles (which have no universal definition, alas).

Invisible fences for screening outliers are erected 1.5 and 3 times the spread beyond the hinges (away from the central value).

"The value at each end closest to, but still inside, the inner fence is 'adjacent'."
Values beyond the first fence are called "outliers."
Values beyond the second fence are "far out."

(Those old enough to remember the hippie argot of the '60s will understand the joke.)
Since the spread is a difference of data values, these fences have the same units of measure as the original data: this is the sense of "distance" in the question.
Concerning the data values to identify, Tukey wrote

We can at least identify the extreme values, and might do well to identify a few more.

Any graphical method to display the median, hinges, and the identified values arguably deserves to be called a "boxplot" (originally, "box-and-whisker plot").  The fences usually are not depicted.  Tukey's design consists of a rectangle describing the hinges with a "waist" at the median.  Unobtrusive line-like "whiskers" extend outward from the hinges to the innermost identified values (both above and below the box).  Usually these innermost identified values are the adjacent values defined above.
Consequently, the default appearance of a boxplot is to extend the whiskers to the most extreme non-outlying data values and to identify (through text labels) the data comprising the ends of the whiskers and all outliers.  For example, Tupungatito volcano is the high adjacent value for the volcano heights data depicted at the right of the figure: the whisker stops there.  Tupungatito and all taller volcanos are separately identified.
So that this will display the data faithfully, distance in the graphic is proportional to differences in data values.  (Any departure from direct proportionality would introduce a "Lie Factor" in Tufte's (1983) terminology.)

These two boxplots from Tukey's book EDA (p. 41) illustrate the components.  It is noteworthy that he has identified non-outlying values at the high and low ends of the States dataset at the left and one low non-outlying value of the Volcano heights at the right. This exemplifies the interplay of rules and judgment that pervades the book.
(You can tell these identified data are non-outlying, because you can estimate the locations of the fences.  For instance, the hinges of the state heights are near 11,000 and 1,000, giving a spread around 10,000.  Multiplying by 1.5 and 3 gives distances of 15,000 and 30,000.  Thus, the invisible upper fence must be near 11,000 + 15,000 = 26,000 and the lower fence, at 1,000 - 15,000, would be below zero.  The far fences would be near 11,000 + 30,000 = 41,000 and 1,000 - 30,000=-29,000.)

References
Tufte, Edward.  The Visual Display of Quantitative Information.  Cheshire Press, 1983.
Tukey, John.  Chapter 2, EDA.  Addison-Wesley, 1977.

Understanding the whiskers of a boxplot


Why do we get the same AIC for different models in a GLMM?

Question: Our problem here described is to interprete the AIC from a GLMM negbin. Our data compose by 2 Categorical variables (Yes/Not), 2 Numerical variables and our random factor, all without any NA. We calculate AIC from all models possiblities, with synergy between variables, and we got this results:
Predictors in model_____loglik_____AIC
Categorical1*Categorical2+Numerical1*Numerical2_____-271,03_____560,07
Categorical1+Categorical2*Numerical1*Numerical2_____-271,03_____560,07
Categorical1*Categorical2*Numerical1+Numerical2_____-271,03_____560,07
Categorical2*Numerical1*Numerical2_____-271,03_____560,07
ETC.........................................................
We obtain the same AIC for different combinations. What does it means? I just found that models could be equivalents, but any more information would be better to understand it.
Answer: Assuming that I understand your question correctly, you should first know how the AIC is computed:
$AIC = 2k - 2 \ln\left(\hat{L}\right)$.
Here, $k$ is the number of coefficients estimated, and $L$ is the likelihood. Your first 3 models have exactly 2 coefficients, hence the value of $k$ is the same across all 3 models. The log-likelihood is also the same for all 3 models, so necessarily the AIC has to be the same for all 3 models. As to why the log-likelihood is the same for all 3 models, that is a matter you should have a good look at I guess
Comment: Thank you very much for answering, We have one model with the best AIC but the others have the same AIC, it could indicate that models are wrong?
Concretely these are our results

Predictors in model________________________________loglik__AIC__Delta AIC
None____________________________________________-281,79_569,58_-10,81
Development_stage*N_applications+Altitude_____________-272,39_558,77__0
Type_treatment*Development_stage+Altitude*N_applications_-271,03_560,07_1,29
Type_treatment+Development_stage*Altitude*N_applications_271,03_560,07_1,29

ETC...

Thanks in advance
Comment: I must say that the formatting of your output here makes it somewhat hard to read. However, If I understand the output correctly, we are still dealing with 2 coefficients in both of the bottom 2 models. These get the same loglikelihood. This can be because either both models perform equally bad, or because your estimation method somehow doesn't work as it should. What are the data types of Type_Treatment, Development_stage, Altitude and N_applications? The answer might be hidden in there, or otherwise you could revise your estimation methods
Comment: Sorry for the format. Comments don't allow to add a table like i want.
Data is compound by 2 categorical variables, 2 numerical variables and our random factor: Type_Treatment (Yes/No), Development_stage (Yes/No), Altitude (number), N_applications (1,2 or 3) and Random Factor.
Maybe we could disscus it by email.
Thank you very much.
Comment: I think that either there is an error in your estimation method, or these models happen to be equally good. If it is neither, then I think the problem is beyond my knowledge/skill