Calendar REST API in Office 365 APIs Preview - not all events

Question: I am building a JS Webapp with the new Office 365 REST Api. My problem is, that I am no getting all occurence events from a Roomcalendar.
Has anybody an Idea?
I am trying to receive all Events with this URL:
https://outlook.office365.com/EWS/OData/Users(firstname.lastname@example.com)/Events?$top=100&$filter=End%20ge%202014-08-20T22:30:00Z%20and%20Start%20le%202020-12-14T22:30:00Z
Thanks in advance
Answer: The server will page the results back to you in lots of 100 (AFIAK), your date range is quite large 2014-2020 if you have Recurring appointments with no End date your more then likely going to get pages of results. Check the Results you getting back for @odata.nextLink eg
"@odata.nextLink": "https://outlook.office365.com/EWS/OData/Users('email@example.com')/Events/?%24top=100&%24filter=End+ge+2014-08-20T22%3a30%3a00Z+and+Start+le+2020-12-14T22%3a30%3a00Z&%24skip=100"
This is what you should use to the get the next page of results
Cheers
Glen
Comment: Hmm thats not exactly what i am searching for. I just need the next 100 meetings with all occurences. How could i solve this?
Comment: If your missing something in the results what is it specifically your missing that you are expecting to be returned ?
Comment: Was my bad. Everything is there, but could it be possible that $orderby=Start is not working?
Comment: Yeah I can't get $orderby to work either it just ignores whatever I enter.
Comment: Thanks that was everything I wanted to know.
I solved it by selecting a minor range and getting more results to avoid the paging.


Como transformar o JSON_ENCODE do PHP para JSON em javascript

Question: Olá,
Meu javascript puxa o resultado de um select feito no PHP, o que chega no Javascript é o seguinte:

Não entendo por que esta vindo com esse "string()" na frente,
já tentei usar JSON.parse, mas não funciona, como na imagem abaixo,

A pergunta é: Como eu transformo essa string em JSON?
Comment: Bem-vindo Sydrack Santos, para obter boas respostas esse post vai lhe ajudar: https://pt.meta.stackoverflow.com/questions/5483/manual-de-como-n%C3%83o-fazer-perguntas/5485#5485
Comment: Podes mostrar o código no PHP que gera essa string e como estás a receber no JavaScript? sem ver o código é dificil ajudar...
Answer: Você provavelmente esta fazendo isso no seu código de PHP:
var_dump($variavel);

O que você precisa fazer é:
echo $variavel;

Answer: No contexto do seu php
$suaVariavel = json_encode($seu_Obj_ou_Arr);
print($suaVariavel);

No contexto do Javascript
$.getJSON(url.php, parans, function(respJson){
   // Aqui você acessa seu json já no formato de objeto.
   // Coloca isso --- respJson.nome --- em qualquer lugar que desejar.
   // E assim por diante.
});

PS: Não esquece de char o jQuery.js na sua página para funcionar o getJSON


How to calculate the integral on surface which cannot be expressed in functions easily?

Question: Surface $S$ is part of $x^2+y^2=1$ between planes $z=0$ and $x+y+z=2$, a vector field $\vec{F}=x\vec{i}+y\vec{j}+z\vec{k}$, what is the value of integration $$ \iint_{S} \vec{F}\cdot\vec{n} dS$$
My solution is:
$$ \iint_{S} \vec{F}\cdot\vec{n} dS = \iint_{S} \vec{F}\cdot d\vec{S} = \iint_{S} xdydz + ydzdx + zdxdy$$
then I met a problem that I cannot express the surface $S$. I know it is a part of cylindrical surface between the plane $z=0$ and the intersection line of cylinder and the plane.
Could anyone please help me to work it out?
Update:
Thanks to James S. Cook, I get to know how to transform the surface integral into a double integral. So is the solution below right? If it is wrong, could anyone please point the mistakes out?
let $x=\cos{\theta}, y=\sin{\theta}$, so by changing the variable, we have the new integration area $X=\{(z,\theta): 0\leq z \leq 2-\cos{\theta} - \sin{\theta}, 0\leq\theta\leq2\pi\}$, and the integral becomes:
$$\iint_{S} xdydz + ydzdx + zdxdy = \iint_{S} \left[\cos{\theta}(-\cos{\theta})+\sin{\theta}(-\sin{\theta})\right]dzd\theta
=\int^{2\pi}_0 d\theta\int^{2-\cos{\theta}-\sin{\theta}}_0dz
=4\pi$$
Comment: I think the calculation's ok now, however, this only accounts for the flux of the vector field through the cut-cylinder. If they intended the closed surface we still need to add the flux of the base ($z=0$) and cap ($z=2-x-y$). I think the flux through the base is zero since the normal component of the vector field is zero for the base. I'm not sure about the cap without calculation. Is $4\pi$ not the expected answer?
Comment: @JamesS.Cook, according to the problem, it seems that we just need to calculate the flux through $S$. Nevertheless, there is one thing puzzles me that why the normal vector is $(\sin\theta, \cos\theta, 0)$. In fact, I do not have an expected answer for this problem.
Comment: Once you have a parametrization of a surface, say $X(u,v) = (x(u,v),y(u,v),z(u,v))$ then we calculate partial velocities $\frac{\partial X}{\partial u} = X_u$ and $\frac{\partial X}{\partial v} = X_v$. Of course, these are tangent to the coordinate curves $X(u,v_o)$ and $X(u_o,v)$ through $p = X(u_o,v_o)$. We have $N=X_u \times X_v$ is perpendicular to both $X_u$ and $X_v$ hence it must point in the normal direction to the surface. The $\langle \sin \theta, \cos \theta, 0 \rangle$ can be calculate as I indicate in the answer $N = X_{\theta} \times X_z$. It's a short calculation.
Answer: If $x+y+z=2$ then $z = 2-x-y$ you have $0 \leq z \leq 2 - x - y$ for the surface. I think it is natural to use $z$ and $\theta$ as parameters for the surface:
$$ X(\theta,z) = (\cos \theta, \sin \theta, z)$$
it is simple to calculate $X_{\theta} \times X_z = \langle \sin \theta, \cos \theta, 0 \rangle$. I usually denote this normal vector field as $\hat{r}$ as it is a unit-vector field which points in radial direction. So, you just need to calculate:
$$ \iint \vec{F} \cdot d\vec{S} = \iint_D \vec{F}(\cos \theta, \sin \theta, z) \cdot \langle \sin \theta, \cos \theta, 0 \rangle \, dz \, d\theta $$
But, the parameter space $D$ is a bit complicated, $0 \leq z \leq 2 - x - y$ translates into:
$$ 0 \leq z \leq 2 - \cos \theta - \sin \theta $$
and $0 \leq \theta \leq 2\pi$.
which suggests we should do the iterated integration with $dz$ as the first integral.
Comment: Thanks for your prompt reply. Now I understand the integral area, but I always have trouble finding the right normal vector for the surface. So I choose differential form method. However, it seems different from the answer derived from the normal vector method. Could you please help me figure the problem out? I have adding my calculation in the **update** in the problem description.


Hoffman and Kunze Chapter 2 Theorem 11 Clarification

Question: I'm a bit confused by the proof of Theorem 11 in chapter 2 of the Hoffman and Kunze Linear Algebra book:
Theorem 11. Let $m$ and $n$ be positive integers and let $\mathbb{F}$ be a field.
Suppose $W$ is a subspace of $\mathbb{F}^n$ and $\dim(W)\leq m$. Then there is precisely one
$m\times n$ row-reduced echelon matrix over $\mathbb{F}$ which has $W$ as its row space.
Proof. There is at least one $m\times n$ row-reduced echelon matrix
with row space $W$... (I understand this part)
Now let $R$ be any row-reduced echelon matrix which has $W$ as its row
space. Let $\rho_1,\dots,\rho_r$ be the non-zero row vectors of $R$ and suppose that
the leading non-zero entry of $\rho_i$ occurs in column $k_i$, $i=1,\dots,r$. The
vectors $\rho_1,\dots,\rho_r$ form a basis for $W$ (Theorem 10). In the proof of Theorem 10, we
observed that if $\beta=(b_1, \dots , b_n)$ is in $W$, then the unique expression of $\beta$ as a linear combination of $\rho_1,\dots,\rho_r$ is
$$\beta=\sum_{i=1}^{r}b_{k_i}\rho_i.$$
Thus any vector $\beta$ is determined if one knows the coordinates $b_{k_i}$, $i=1,\dots,r$.
Suppose $\beta\in W$ and $\beta\ne0$. We claim the first non-zero coordinate
of $\beta$ occurs in one of the columns $k_s$. Since
$$\beta=\sum_{i=1}^{r}b_{k_i}\rho_i$$
and $\beta\ne0$, we can write
$$\beta=\sum_{i=s}^{r}b_{k_i}\rho_i\;,\;b_{k_s}\ne0.$$
From the fact that $R$ is a row-reduced echelon matrix one has $R_{ij}=0$ if $i>s$ and $j\leq k_s$. Thus
$$\beta=(0,\dots,0,b_{k_s},\dots,b_n)\;,\;b_{k_s}\ne0$$
and the first non-zero coordinate
of $\beta$ occurs in one of the columns $k_s$.
It is now clear that $R$ is uniquely determined by $W$. The description
of $R$ in terms of $W$ is as follows. We consider all vectors $\beta = (b_1, \dots , b_n)$
in $W$. If $\beta\ne0$, then the first non-zero coordinate of $\beta$ must occur in some
column $t$:
$$\beta=(0,\dots,0,b_t,\dots,b_n)\;,\;b_t\ne0.$$
Let $k_1, \dots , k_r$ be those positive integers $t$ such that there is some $\beta\ne0$
in $W$, the first non-zero coordinate of which occurs in column $t$. Arrange
$k_1, \dots , k_r$ in the order $k_l < k_2 < \dots < k_r$. For each of the positive
integers $k_s$ there will be one and only one vector $\rho_s$ in $W$ such that the
$k_s$th coordinate of $\rho_s$ is 1 and the $k_i$th coordinate of $\rho_s$. is 0 for $i\ne s$. Then $R$ is the $m\times n$ matrix which has row vectors $\rho_1, \dots , \rho_r, 0, \dots , 0$.
I understand that there will be at most one such vector $\rho_s$ since "any vector $\beta$ is determined if one knows the coordinates $b_{k_i}$, $i=1,\dots,r$", but how do we know there's one in $W$ at all? Is it because "there's at least one $m\times n$ row-reduced echelon matrix
with row space $W$"? Also, why is it "now clear that $R$ is uniquely determined by $W$"? Thanks.
Answer:
how do we know there's one in W at all? Is it because "there's at least one m×n row-reduced echelon matrix with row space W"?

Yes, you're right. There's at least one $m \times n$ row-reduced echelon matrix $R$ and we defined each $\rho_s$ as a non-zero row in $R$. $W$ is the row space of $R$ so each $\rho_s$ has to be in $W$.

Also, why is it "now clear that R is uniquely determined by W"?

This part follows by uniqueness of each $\rho_s$. Like I said before, each $\rho_s$ corresponds to a non-zero row in $R$. Now that we know that each $\rho_s$ is uniquely determined by $W$, the non-zero rows of $R$ are also unique, hence $R$ is uniquely determined by $W$.


In this 1979 ACDC concert Angus' guitar seems unplugged

Question:

Is he miming, playing along to a backing track? Or ifhe is playing, how can that be?
Comment: I was in the middle of posting an answer when this was closed. I don't rembmer where I first heard this but, Angus Young was an early adopter of wireless and apparently liked the tone the early ones produced even using it during studio recording. http://www.voodooguitar.net/2016/10/angus-youngs-secret-wireless-weapon.html
Comment: Nabulio - please in future write questions. I have edited this one for you so it could be reopened. @MichaelCurtis - please feel free to leave an answer :-)
Answer: Wireless radio transmitter, attached to the strap or on his body somewhere. At the other end is a receiver plugged into his amp on stage.
Random Google of a range from a music store...   https://www.gear4music.com/Electric_Guitar/Wireless.html
Equally random image of both halves of an example...

The systems available in 1979 had a rather unfortunate issue of being very near the same frequencies used by taxi companies to call their drivers.
It was a fairly common interruption in those days, halfway through your best solo effort.. "Car 39, come in. Car 39, can you do a pick up at the airport?"
Comment: Back in those days, it wasn't even necessary to use a system like this. I was on first name terms with a taxi driver at one venue we did often...
Comment: MM desks were known for that... shielding was... ermm... approximate.
Answer: I don't remember where I first heard this but, Angus Young was an early adopter of wireless and apparently liked the tone the early ones produced even using it during studio recording.
This page has a overview:
http://www.voodooguitar.net/2016/10/angus-youngs-secret-wireless-weapon.html


Como fazer um cálculo de porcentagem no Oracle?

Question: Não consigo fazer um Select que possa fazer 1 cálculo de IPI no Oracle.
Tabela VS01
Campos:
PD = 001
TP = 100 reais
IPI = 15
Select PD,TP,IPI,

       TP * IPI% AS TOTAL <<< aqui que não consigo executar

From VS01

PD || TP || IPI || TOTAL
001   100    15     115
Comment: É isso: `select tp, ipi, sum( tp + ipi ) as total from tabela group by tp, ipi` ?
Answer: É pura matemática:
Select PD, TP, IPI, TP * (1.00 + IPI / 100) AS TOTAL

Coloquei no GitHub para referência futura.
Pode ser que queria fazer algum arredondamento.
Comment: Deu certo Obrigado.
Answer: Como nosso amigo Manieiro disse, é pura matemática.
Basta multiplicar a porcentagem pelo valor.
Exemplo: calcular 30% de 700.
Basta multiplicar a fração 30/100 por 700.

Agora no PL/SQL eu tenho a coluna porcentagem que é o valor referente a 50% da coluna ao lado direito titu_valo que é corresponde a mensalidade.
Faço exatamente como explicado acima, primeiro entre parêntesis eu faço o cálculo da fração de 50 que corresponde a 50% dividido por 100 que é o denominador da porcentagem e logo depois em seguida multiplico pelo valor da mensalidade, ficando assim:
((50/100) * titu_valo)

Resultado:


Is this counterexample for $T$ closed, symmetric $\iff T$ self-adjoint valid?

Question:
Lemma Let $T: \text{dom}(T) \to \mathscr{H}$, where $\mathscr{H}$ is a Hilbert space, be densely defined.
  Then $T$ is closed and symmetric if and only if $T = T^{**} \subset T^*$.

To better get a feeling for this statement I wanted to construct an operator $T$ which was closed and symmetric but not self-adjoint.
Is the following valid to see the necessity of "densely defined"
Let $T: D\to \mathscr{H}$, where $D$ is not closed (then by the closed graph theorem we get that $T$ is closed, right?) be the zero operator, i.e. $T x = 0$ for all $x \in D$.
Then
$$
\langle T x, y \rangle
= \langle 0, y \rangle
= 0
= \langle x, 0 \rangle
= \langle x, T y \rangle
$$
holds for all $x,y \in D$, hence $T$ is symmetric.
Furthermore, by definition,
$$
\text{dom}(T^*)
= \{ y \in \mathscr{H}: x \mapsto \langle T x, y \rangle \text{ is continuous on } D\}
$$
Let $\Phi: D \to \mathbb{C}$, $x \mapsto \langle T x, y \rangle$. Then $\Phi \equiv 0$, and is trivially continuous, hence dom$(T^*) = \mathscr{H} \supsetneq D$.
Therefore, we can not have $T = T^*$, i.e. $T$ is not self-adjoint.
Questions

Is this counterexample valid?
How could $D$ look like?
Comment: The zero operator is closed only if its domain is closed.
Comment: @s.harp So the counterexample is valid if I choose $D$ to be a closed strict subset of $\mathscr{H}$?
Comment: And ... because the operator has to be densely-defined, then ...
Answer: The original study of symmetric operators started with differential operators. The differentiation operator $\partial=\frac{1}{i}\frac{d}{dx}$ is a good example, with different properties on $L^2(-\infty,\infty),L^2[0,\infty), L^2[0,2\pi]$.
Because of needing complete spaces, differentiability is a little tricky to define. For example, how do you define a differentiable function when functions are the same if they are changed on a set of measure $0$, which could change where or if the function is differentiability. The problem is that a function $f\in L^2[0,\infty)$ is really an equivalence class $[f]$ of functions that are equal a.e. to the given function $f$. The standard way of handling this is to say that $[f]\in\mathcal{D}(D)$ on $[0,\infty)$ (or the other intervals,) if there is an element $g$ of the equivalence class $[f]$ such that $g$ is absolutely continuous on $[0,\infty)$ with $g'\in L^2[0,\infty)$. If there are two such elements in the equivalence class, they're actually the same function. So everything is well-defined. And so is the value of $g(0)$. Therefore it makes sense to talk about $f(0)$, provided this sort of meaning is understood.
Then it makes sense to define $\partial : \mathcal{D}(\partial)\subset L^2[0,\infty)\rightarrow L^2[0,\infty)$ by $\partial f=-if'$. If you impose the condition $f(0)$ on $\mathcal{D}(\partial)$, then you have an operator that is symmetric, but not selfadjoint. It is not selfadjoint because the adjoint $\partial^*$ is the same operator, but without the requirement that the functions in the domain vanish at $x=0$. It is easy to verify through integration by parts that
$$
                 \langle \partial f,g\rangle = \langle f,\partial^*g\rangle,\;\;\;f\in\mathcal{D}(\partial),g\in\mathcal{D}(\partial^*).
$$
The operator $\partial$ is closed, densely-defined and symmetric, but it is not selfadjoint because the adjoint $\partial^*$ has a strictly larger domain.


finding the argument of $1-\cos 2\theta -i\sin 2 \theta$

Question: "Let z = $1-\cos 2\theta -i\sin 2 \theta$, $0\leq \theta \leq \pi$. Find the modulus and argument of z in terms of $\theta$ in their simplest forms."
The modulus is pretty easy, I got $2\sin \theta$ which is correct.
The problem is, when finding the argument of z, I got $\tan \alpha = \frac{-1}{\tan \theta}$, where $\alpha$ is the argument.
the correct answer is $\alpha = \theta - \pi/2$, however I am curious why $\alpha = \theta + \pi/2$ doesn't work. This also fits the equation above, but is wrong. Can someone explain?
Comment: Consider separately the cases of acute and obtuse $\theta$, and bear in mind the argument has to be from $-\pi$ to $\pi$. Alternatively, work out $\cos\alpha,\,\sin\alpha$ for each option (note these change sign of you increase $\alpha$ by $\pi$).
Comment: Note that you introduced an erroneous solution by going to $\tan\alpha$ (minimal period $\pi$) instead of the full $(\cos\alpha,\sin\alpha)$ (minimal period $2\pi$).  You need to go back and check for the correct $\alpha$ modulo $2\pi$.
Answer: When you calculate $\tan \alpha$, you are specifying the slope of the line connecting the origin to your point $(1-\cos2\theta,-\sin2\theta)$. What's missing is the direction traveled along this line with the origin as the starting point.
Your two proposed arguments separated by a difference of $\pi$, represent the two opposite directions possible on your line, only one of which is correct for actually getting from the origin to your destination. To orient yourself, multiply the cosine of each possible argument by the modulus you found, $2\sin\theta$, and compare with the intended $x$-coordinate $1-\cos2\theta$. Only the candidate $\alpha=\theta-\pi/2$ points you the right way.
Comment: Shouldn't the point be $(1-\cos 2 \theta, -\sin 2 \theta)$? If so, this explains it.
Comment: Corrected. Mistyped. Thank you.
Answer: $$z = 1-\cos 2\theta -i\sin 2 \theta$$
Modulus
$$|z| = \sqrt{(1-\cos 2 \theta)^2 + (-\sin 2 \theta)^2}  = \\
= \sqrt{1 + \cos^2 2  \theta - 2 \cos 2 \theta + \sin^2 2 \theta} = \\
= \sqrt{2 - 2 \cos 2 \theta} = \\
= \sqrt{2 - 2 \cos^2 \theta + 2  \sin^2 \theta} = \\
= \sqrt{2 - 2 \cos^2 \theta + 2  (1-\cos^2 \theta)} = \\
= \sqrt{2 - 2 \cos^2 \theta + 2  -2\cos^2 \theta} = \\
= \sqrt{4 - 4 \cos^2 \theta} = \\
= 2 \sqrt{1 - \cos^2 \theta} = \\
2 |\sin\theta|.$$
Argument
First of all, notice that
$$\eta = \arctan\frac{- \sin 2\theta}{1 - \cos 2\theta}
=\arctan\frac{- 2 \sin \theta \cos \theta}{1 - \cos^2 \theta + \sin^2 \theta}
=\arctan\frac{- 2 \sin \theta \cos \theta}{2\sin^2 \theta} = \\
= -\arctan\text{cotan} \theta = \theta - \frac{\pi}{2}.
$$
since:
$$\arctan(\text{cotan} \beta) = \frac{\pi}{2} - \beta.$$
Additionally, notice that:
$$\mathcal{Re}[z] = 1-\cos 2 \theta \geq 0 ~\forall \theta \in [0, \pi]$$
Then, in this case, under the assumption that $\arg{z} \in (-\pi, \pi]$:
$$\arg{z} = \eta = \theta - \frac{\pi}{2}.$$
Why does $\alpha = \theta + \frac{\pi}{2}$ not work?
First of all, notice that:
$$\mathcal{Im}[z] = -\sin 2 \theta \geq 0 ~\forall \theta \in \left[\frac{\pi}{2}, \pi\right]$$
Hence, for $\theta \in \left[\frac{\pi}{2}, \pi\right]$, $z$ represents a vector in the first quadrant of the complex plane. This means that its argument must be positive and less that $\frac{\pi}{2}$. Indeed:
$$\eta = \theta - \frac{\pi}{2} \in \left[0, \frac{\pi}{2}\right] ~\forall \theta \in \left[\frac{\pi}{2}, \pi\right],$$
while
$$\alpha = \theta + \frac{\pi}{2} \in \left[\pi, 3\frac{\pi}{2}\right] ~\forall \theta \in \left[\frac{\pi}{2}, \pi\right].$$
The last shows that $\alpha = \theta + \frac{\pi}{2}$ does not work.
Answer: You would be correct in saying that  trigonometric identities lead to an ambiguity.   If we apply the "angle-addition" formula for cotangent (so that we don't have to deal with undefined values), we have
$$ \cot ( \ \theta \ \pm \ \phi \ ) \ \ = \ \ \frac{\cot \theta · \cot \phi \ \mp \ 1}{ \cot \phi \ \pm \ \cot \theta} \ \ ; $$
since your result for the argument of $ \ z \ $ is $ \ \cot \alpha \ = \ -\frac{1}{\cot \theta} \ \ , \ $ we find that $  \ \cot \frac{\pi}{2} \ = \ 0 \ \ $ produces
$$ \cot \left( \ \theta \ \pm \ \frac{\pi}{2} \ \right) \ \ = \ \ \frac{\cot \theta · 0 \ \mp \ 1}{ 0 \ \pm \ \cot \theta} \ \ = \ \ -\frac{ 1}{  \cot \theta} \ \ . $$
So on these grounds alone, it seems that we should have $ \ \alpha \ = \  \theta \ \pm \ \frac{\pi}{2} \ \ . $
However, the given expression $ \ z \ = \ ( \ 1 - \cos [2 \theta] \ )  - i·\sin [2 \theta] \ \ $ should be considered in terms of where the numbers described lie on the Argand plane.   (We will see below that this is a circle of radius $ \ 2 \ $ centered on $ \ (1 \ , \ 0) \ \ , \ $ which is "traced-out" counter-clockwise starting at the origin.)
The way we'll discuss this is to examine transformations of $ \ u \ = \ \cos \theta \ + \ i·\sin \theta \ \ , \ $ with $ \ |u| \ = \ 1 \ \ , \ $ over $ \ 0 \ \le \ \theta \ \le \ \pi \ \ . \ $  [This is marked on the graph at left below along the red semi-circular arc, with "landmark" values shown, including $ \ v \ = \ cis \ \frac{\pi}{4} \ = \ \frac{\sqrt2}{2} + i·\frac{\sqrt2}{2} \ $ and $ \ w \ = \ cis \ \frac{3 \pi}{4} \ = \ -\frac{\sqrt2}{2} + i·\frac{\sqrt2}{2} \ \ . \ ] \ $ DeMoivre tells us that $ \ u^2 \ = \ \cos (2 \theta) \ + \ i·\sin (2 \theta) \ \ , \ $ the transformed numbers still having unit modulus and are now arranged counter-clockwise over the full unit circle [in orange].  Multiplying these numbers by $ \ -1 \ $ to produce $ \ -u^2 \ $ "reverses" their directions relative to the origin, or can be interpreted as having $ \ \pi \ $ added to  their arguments, since $ \ -1·u^2 \ = \ e^{ \ i  \pi}·e^{ \ i \ · \ 2 \theta} \ \ ; \ $ this has no effect on the "orientation" of the numbers on the circle [green in the graph at right below].  (Again, the "labeled" numbers are the values of $ \ u \ $ marked at the "positions" to which they have been transformed.)

The remaining transformation to obtain $ \ z \ = \    1 - ( \ \cos [2 \theta] \   + i·\sin [2 \theta] \ ) \ = \ 1 - u^2 \ \ $ adds $ \ 1 \ $ to the real part of $ \ -u^2 \ \ , \ $ which has the effect of  horizontally translating the circle "to the right" by $ \ 1 \ $ unit [seen in the graph below].  This final transformed circle (in fact, a "one-petal rose") can be represented, using $ \ \alpha \ $ in the manner marked, as $ \ r \ = \ 2 \cos \alpha \ $ over $ \ -\frac{\pi}{2} \ \le \ \alpha \ \le \ +\frac{\pi}{2} \ \ , \ $ with $ \ \alpha \ $ behaving as a "standard" polar angle.  Using the argument of $ \ u \ $ instead, the circle is also represented by $ \ r \ = \ 2 \sin \theta \ = \ |z| \ \ $ over $ \ 0 \ \le \ \theta \ \le \ \pi \ \ ; \ $ so this circle can be interpreted as displaying the modulus of $ \ z \ \ , \ $ which you found correctly.  The angle variables increase in the counter-clockwise direction on both circles, making this consistent with $ \ \alpha \ = \ \theta \ - \ \frac{\pi}{2} \ \ . \ $

Having said all of this, we still have a source of ambiguity that would permit $ \ \alpha \ = \ \theta \ + \ \frac{\pi}{2} \ \  $ to be correct.  After all, we could also have read $ \ -u^2 \ $ as $ \ -1·u^2 \ = \ \large{e^{ \ -i  \pi} } \normalsize{·e^{ \ i \ · \ 2 \theta} \ \ .} \ $  This would place the unit-modulus numbers in the same positions on the transformed circle, but would reduce the value of $ \ \theta \ $ relative to $ \ \alpha \ $ by $ \ \pi \ $ radians. The "correctness" of the given answer is then owed to the "right-handed"/counter-clockwise convention of describing angles.


Are there examples of non exponential family distributions with sufficient statistics?

Question: In Casella Berger's Statistical Inference, they observe that it is rare to find 'a sufficient statistic with dimension smaller than the sample' (section 6.2.1). Although rare, are there examples of non-exponential distributions with dimension reducing sufficient statistics available? The passage in question effectively rules out the order statistics as being a sufficient statistic that reduces dimension in the manner discussed.
Comment: Uniform distribution on $(0,\theta)$ is an example.
Answer: Yes, uniform distribution on $(0,\theta)$ ($\theta>0$) is an example. In this case we can write the density function as
$$
  f(x; \theta) = \frac1{\theta}\cdot I(0 < x < \theta)
$$
where $I$ is the indicator function.  Then the likelihood function from an iid sample can be written
$$
L(\theta) = \prod_{i=1}^n f(x_i;\theta) = \prod_i \frac1{\theta}  I(0 < x_i < \theta) = \\
   \frac1{\theta^n} \prod_i I(0 < x_i < \theta) = \\
  \frac1{\theta^n} I(0 < \max_i x_i < \theta)
$$
and now you can invoke the factorization theorem and conclude that $ \max_i x_i $ is a sufficient statistic.


Monitor free space with monit ... but only if the folder is mounted

Question: For my backup, external disk space is mounted via cronjob as /mnt/backup on a Ubuntu machine every night. When the backup is complete, the disk is unmounted. No need to expose the backup drive to potential attackers on this webserver.
From time to time, this backup drive runs full, which is ... yep, Linux does not like full disks. So I told monit to alert on low disk space.
check filesystem backup with path /mnt/backup
        if space usage > 85% then alert

That works, but whenever the backup is complete and the disk is unmounted, monit goes into "Status: Does not exist" and raises a flag. Is there an option to tell monit not to send any alert, if the filesystem does not exist?
According to the monit manual, each possible action will do something "and send an alert".
Answer: According to https://www.mmonit.com/monit/documentation/monit.html#SERVICE-POLL-TIME,
you can limit the time Monit will monitor the filesystem. As long as the backup start at the same time, this will prevent some useless messages.
Comment: The service is listed as "initializing" while waiting for the time to come, i.e., it does not throw an error and won't show up as warning in M/Monit. I think, that is the solution, I have been hoping for - thanks a lot!
Comment: As long as the service is not monitored, the status is "initializing". A more useful status will shown after the first monitoring interval in the given time frame. Unfortunately, the status will reset to "initializing" with the next monitor reload. But this will prevent useless messages.


Changing Webform's submit button's text

Question: The famous Webform module gives a beautiful nicely designed "Submit" button.
How can I change its text from "Submit", to anything else? I want to change it to another language but I found no way to do it by the UI, or by the Translation mechanism.
Comment: Do you have your site with multi-language?
Answer: Well, normally the webform provides you the facility to edit the submit button form text at
Go to webform->form settings->Submit button text
Or either way you can use the string override module
Hope it may help you!
Answer: You can change the submit button text of a webform very easily. Follow these steps :

Edit specific webform of which you want to change the submit text.
Go to Webform -> Form Settings.
Go to Advanced Settings -> Submit Button Label field.
Here you can add the desired text you want to appear on the submit button.

Changing Webform's submit button's text


How override __init__ add instance forms.Form Django

Question: I want to add an instance parameter to my forms.Form, this way I can initialize it in views and get the expected result in my forms. I know i can use 'initial', but I wanted to try something different.
Views.py
city_form = CityForm(instance=user.profile.city)

Forms.py
class CityForm(forms.Form):
    post_nr = forms.CharField(max_length=5, widget=forms.TextInput(attrs={'placeholder': 'Post nr.'}))
    city = forms.CharField(required=False, max_length=30, widget=forms.TextInput(attrs={'placeholder': 'By', 'readonly': True}))

    class Meta:
        model = City

    def __init__(self, *args, **kwargs):
        self.instance = kwargs.pop('instance', None)

        if self.instance:
            self.fields['post_nr'] = self.instance.post_code
            self.fields['city'] = self.instance.name

        super(CityForm, self).__init__(*args, **kwargs)

The referenced instance will be a City object, from my City class which has the variables I specify above.
But I am getting:

'CityForm' object has no attribute 'field'
Answer: A form doesn't have a fields attribute until you call super().__init__(). You need to move that code down. What you're currently doing is overriding the field instance with its value. Instead you should set the initial value:
def __init__(self, *args, **kwargs):
    instance = kwargs.get('instance', None)

    super(CityForm, self).__init__(*args, **kwargs)

    if instance:
        self.initial['post_nr'] = instance.post_code
        self.initial['city'] = instance.name

You might also want to take a look at using a ModelForm.
Comment: You're overriding the field instance with the value of the field. It is actually quite complex to change the value of the field after instantiating the form, you should rather modify the `data` or `initial` dicts before instantiating.
Comment: Yes, I thought of it. However when I add the `super` method before my code, my fields simply vanish. My instance is empty, but shouldn't it create the fields anyway?
Comment: Did you move the `super()` up, or did you add a second call? The latter would explain your fields vanishing.
Comment: I did exactly as you showed and the fields vanished. It could have something with my code, because if I remove my condition down there, they come back. I guess it is replacing the field code instead of the value inside of it.
Comment: Also, I don't want to use ModelForm because I don't want to save information with this form. I just want to fetch data with a JavaScript function I have. This method is going to throw back the validated instance of the City the user typed in the field.
Comment: And how do I do that?
Comment: `data['field_name'] = value` and `initial['field_name'] = value` I believe.
Comment: Yep. `self.initial['field_name'] = value` worked, instead of `self.fields['field_name'] = value`. You can add this to your answer. I will mark as resolved.
Answer: the answer posted by @knbk solves the OP's problem perfectly. but in user scenario, here are some improvements I'd like to add.
def __init__(self, *args, **kwargs):
    instance = kwargs.pop('instance', None)
    super(CityForm, self).__init__(*args, **kwargs)
    if instance:
        self.instance = instance
        if self.data.get('title', None) is None:
            self.initial['title'] = instance.title

by inheriting forms.Form, use pop to get instance because the keyword is not expected by forms.Form constructor.

if instance is passed in, assign it to the form so that you can use it in save method etcetera.

always check whether request.POST is passed in, if the initial is not included in data, this means you are not submitting a update form within an instance, only then you should overwrite initial, otherwise the data will never be updated.


Exposed filter show results

Question: I have a content type say sample. I've created a view page to slideshow all sample content type. I have an exposed filter at the top of the page, people search using id there, on searching it is giving the correct result with the slider but the slider is'nt working at the result page. I want it show the result first and then the others.
Is it possible.
Comment: Just make this filter `Required`
Comment: @NikhilM I've made it required, It is'nt showing anything now under the preview.
Comment: Can you provide a screenshot of your Views settings? And maybe the current result also?
Comment: @ScottAnderson Done...
Comment: Any JS errors in console? Also do you have Theme Developer module installed?
Comment: @ScottAnderson How to check for JS errors in console. No I'm not using theme developer module.
Comment: You may need to install Firebug extension for Firefox, then right click on the page and select 'Inspect Element with Firebug', then click the Console tab http://i.imgur.com/eSG0zHE.png
Answer: Enable the Use Ajax option under the Other Tab..
Comment: I've anabled ajax, I'm getting the result but other slides are not showing up.

Exposed filter show results


Opening Phone Links in didSelectRowAtIndexPath iPhone SDK

Question: Is it possible to determine a row's detailTextLabel based on an indexPath in didSelectRowAtIndexPath?
I want to be able to open a phone link using
[[UIApplication sharedApplication] openURL:xyz]

if the cell has the detail text label "phone".
Is this possible?
Thanks
Answer: [[myTableView cellForRowAtIndexPath:path].detailTextLabel.text isEqualToString:@"phone"];

Answer: Assuming that you provide the data source for the table view, you could check your data directly instead of the table view cell.
If this is somehow not possible, you could always call yourself:
[[tableView dataSource] tableView:tableView cellForRowAtIndexPath:indexPath]; and inspect the resulting cell.


Do uilleann pipes have a "louder" lower D?

Question: I've always loved the skirl of the uilleann pipes ever since I first heard it used in the James Horner's Titanic OST as a kid. I don't know much of anything about the instrument (or bagpipes generally) yet, but I have one particular question:
Something I've noticed in uilleann pipes music is the lowest note of the chanter, a D, usually sounds distinctly louder than the higher notes. A good example of this is in this track from the aforementioned Titanic OST (note the harsh D at the 8-second mark).
I'm an amateur composer and I use lots of sampled sound libraries, and of the uilleann pipes patches I have, one (from ProjectSAM's Symphobia 2) has that distinct louder lower D tone, whilst the others (EastWest's Ra, Cinesamples's CineWinds, and Native Instruments's Kontakt 5 Factory Library) have a lower D that isn't notably different in loudness or tone than the other notes.
So this is my question: Is the uilleann pipes' lower D meant to sound distinctly louder than the other notes when played by a human, or does that depend on technique or something? I'd really appreciate it if someone could explain it.
Comment: It's a guess but I wonder if the player is using the chanter for most of the melody but a drone to reach the low D. One of the reasons I have for believing this is that the D doesn't stop immediately but continues to play underneath the following notes. Have a look at this link for an explanation of drones and chanters https://en.wikipedia.org/wiki/Uilleann_pipes
Answer: The volume and tone of uilleann bottom D is certainly a function of being played "off the knee," but perhaps more significantly, it is a function of which bottom D technique the piper chooses to play:

Soft bottom D
Hard bottom D

Both are played with the chanter lifted, as the sound passes through the bottom hole.
However, it is arguably more than a stylistic difference, insofar as the fundamental pitch of these two notes can differ by as much as a quarter-tone or more.
At a normal bag pressure simply lifting the chanter would produce soft bottom D.  This is typically somewhat flat of concert D, usually by some fraction of a semitone.  If your drones, regulators, tone holes, etc. are tuned to a concert pitch, then depending on the set, a soft bottom D in the context of a tune can sound jarring and outright wrong.
Hard bottom D is played by increasing the pressure used to play the note a little bit.  When the chanter is lifted, you then quickly play an A grace note and then seal it.  (This is called a "cut.")  If the pressure is sufficient and the cut fast enough the chanter will actually begin to sound a noticeably different sound, which has some almost foghorn-like overtones.  This is what you noticed in the Titanic OST.  Hard bottom D is an iconic uilleann sound and it is typically more in tune with concert D.
For this reason many pipers will choose to play hard bottom D exclusively, to sound the most in tune, most of the time.  As the lowest and in some ways loudest note on the pipes, hard low D is often used as a percussive tool.  It can really break up phrases in jigs and reels, and can be cut or otherwise modified with almost any gracenote to great rhythmic effect.
I should add that hard bottom D is also in some sense harder to play.  Without focusing on maintaining correct hard D bag pressure, it is easy for a hard D to fall back into a soft bottom D, which can sound very jarring as the flattening of the note will be marked.  There's a wide range of pressures that will produce a soft bottom D, but only a narrow band of pressure space that will create a correct hard bottom D without any squeals.  Staying in this pocket takes practice.
There are more advanced techniques with uilleann pipes where "bursts" of volume of this sort can be managed, together with lifting or lowering the chanter, to create various effects.  For a list of such techniques, check out https://www.uilleannobsession.com/faq.html#cut
For more on the harmonics of hard vs soft bottom D, check out this excellent summary: http://blog.robertrueger.de/?p=157
Comment: I should also add, there's a "hard E" too!  It's fingered slightly differently from a regular E, and has the same pressure jump, and it produces a louder, more "aggressive" E!
Answer: It's a stylistic thing, because many players favour having a really strong solid low D note for emphasising rhythm, and making their ornamentation really 'pop' with that strong low note.
In a classic 'chicken and egg' situation some instrument builders are biasing their chanters to make the hard low D easier to play, which will then increase the prevalance of that as a stylistic device.
Classic players like Willy Clancy and Liam O'Flynn used the hard low D in their ornamentation; it's also a desirable quality for many Irish music players in a flute as well, possibly because that emulates the pipes.
If the sample patch set you're using don't have the lower D louder you'll need to be careful not to overdo it, so again it's a question of listening to good players. Or, if you've got 21 years to spare, why not just learn to play the pipes for real instead? 'Seven years learning, seven years practicing, and seven years playing' is the old saying ...
Comment: Thanks for the answer! So to be crystal, the lower D being played more loudly is just a player's preference thing? Are players actually taught to play that note more sharply? Also, if written out, does the composer just add an accent (>) to that note, or otherwise indicate to play it with emphasis?
Comment: Yes, it is a preference, but players are taught that a striong low note is part of the style. In the uilleann pipes' natural environment of Irish traditional music the music isn't written out in that level of performance detail (if at all, it being very much an aural tradition). For film scores etc. I cannot comment on whether that would be specified by the composer, or how it would be indicated in a score.
Answer: The bottom D is different from every other note, because the hole at the end of the pipe must be open (and it is the only open hole).
That means that the bottom D has a different tone colour from the rest of the notes, as well as being louder.
For all the other notes, the end hole is covered by pressing the pipe against the player's leg, so that covering all the finger holes produces silence.
This is different from the highland pipes, where the end hole is always open and the large difference in tone colour doesn't occur.
See this tutorial at about 4 minutes from the start:
Comment: Huh. That's a completely different answer than the above, yet the video is pretty persuasive. Thanks for posting this!

Do uilleann pipes have a “louder” lower D?


How do you call: Ln(Xt/Xt-1)?

Question: What is the best word/ phrase of describing the following:
 Ln(Xt/Xt-1)?
Is that:
A: natural log of differences?
B: natural log of growth rates?
C: Something else??
The reason I need to know the precise answer is because of my thesis. I transformed variables to ln(Xt/Xt-1), but don't what it is called. I've to describe something like: variables have been transformed to their logarithmic [insert correct answer]. I'm confused by other papers....
Comment: "Log difference"?
Comment: The notation is ambiguous: obviously you don't mean $X_t/X_t-1\cong 0$ (which is a literal reading of what you have posted), but do you mean $$\frac{X_t}{X_t-1}$$ or $$\frac{X_t}{X_{t-1}}?$$ Please edit the question to clarify this crucial point.
Comment: The latter. Thus, the log of the return.
Answer: While this depends on what $X_t$ signifies, what you're probably looking for is called the logarithmic return transformation, a.k.a force of interest. If your thesis is in Econometrics or Finance, just call them "log-returns" and most of your audience will know what you mean.

How do you call: Ln(Xt/Xt-1)?


How do I use transform-result in rest API using MarkLogic search?

Question: How do I transform the results in search using the rest API; specifically the snippet part?
I'm currently looking at this
document but I can't understand where to put it since there are so many ways to add such a thing.
I'm trying to get the whole document put into the snippet part.
<transform-results apply="snippet">
    <per-match-tokens>30</per-match-tokens>
    <max-matches>4</max-matches>
    <max-snippet-chars>200</max-snippet-chars>
    <preferred-matches/>
</transform-results>

It would be helpful if there were some kind of examples.
Comment: One footnote to Geert's good answer -- as an alternative, you can get a set of documents of any format with a bulk search.  See:  http://docs.marklogic.com/guide/rest-dev/bulk#id_65903
Answer: Here a pretty common example of default snippeting, as well as a few results states for different snippeting:
<options xmlns="http://marklogic.com/appservices/search">

  <transform-results apply="snippet">
    <preferred-elements>
      <element ns="" name="body"/>
    </preferred-elements>
    <max-matches>2</max-matches>
    <max-snippet-chars>200</max-snippet-chars>
    <per-match-tokens>20</per-match-tokens>
  </transform-results>

  <operator name="results">

    <state name="compact">
      <transform-results apply="snippet">
        <preferred-elements>
          <element ns="" name="body"/>
        </preferred-elements>
        <max-matches>1</max-matches>
        <max-snippet-chars>100</max-snippet-chars>
        <per-match-tokens>10</per-match-tokens>
      </transform-results>
    </state>

    <state name="detailed">
      <transform-results apply="snippet">
        <preferred-elements>
          <element ns="" name="body"/>
        </preferred-elements>
        <max-matches>3</max-matches>
        <max-snippet-chars>300</max-snippet-chars>
        <per-match-tokens>30</per-match-tokens>
      </transform-results>
    </state>

    <state name="raw">
      <transform-results apply="raw"/>
    </state>
  </operator>

</options>

You can easily blend in operator state selection in your search string, just add something like results:detailed. You can also use operator-state in structured queries.
HTH!
Comment: for me using `` with `` worked to get the entire content of the body but other result types didn't work.
Comment: Please open a new SO question if you'd like to raise attention to a new issue.
Comment: Its the same issue i am talking about.


I want to get text from an excel file with its font style and weight using C# .net?

Question: While getting text from an excel its resetting the font style and its structure. I want to get that exact text as it shows in excel sheet. Like if I have a sentence in which some words are bold, I want to get that text as bold also.
Answer: You should try EPPlus (http://epplus.codeplex.com/)
This is for creating excel workbooks, but I'm sure it has features for processing excel files as well.
Answer: I guess an alternative is to use the OpenXML SDK; however, it will only work with .xlsx files. I'm learning to use this SDK myself to generate .docx and .xlsx files, mainly because it's free and developed by Microsoft!
Answer: If you know the exact index that needs to be bold you can do something like below:
<code>Using Excel = Microsoft.Office.Intertop.Excel

Excel.Application xlApp;
Excel.Workbooks xlBooks;
Excel.Workbook xlBook;
Excel.Worksheet xlSheet;

xlApp = new Excel.Application();
xlBooks = xlApp.Workbooks;
xlBook = xlBooks.Add("");
xlSheet = xlBook.ActiveSheet;

xlSheet.Cells[row,col].Font.Bold = true
</code>


Pausing Javascript Timer

Question: How to pause this timer? And if it's paused how to unpause and continue counting? It should be a function

function timer($time) {
    let $lorem = $("#lorem");
    function countdown() {
      let $minutes = Math.floor($time / 60);
      let $seconds = $time % 60;
      let $result = $minutes + ":" + ($seconds < 10 ? "0" + $seconds : $seconds);
      --$time;
      $lorem.text($result);
    }
    countdown();
    setInterval(countdown, 1000);
  }
  timer(200);

Comment: does my answer solved your problem? If any answer helps you [vote it up](http://meta.stackexchange.com/questions/173399/how-to-upvote-on-stack-overflow), If the answer is what you looking for mark it as [Correct answer](http://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work) for the future readers. Thank you!
Answer: You can do this by storing the result of setInterval in a variable:
var timeKeeper = setInterval(countdown, 1000);

Then when you want to pause, use clearInterval:
clearInterval(timeKeeper);

This will stop the interval from executing. To start again, reset the timer variable:
timeKeeper= setInterval(countdown, 1000);

Answer: Use a flag pause with a click event, on click toogle pause:
  let pause = false;
  $lorem.on('click', function() {
    pause = !pause;
  });

Then check if !pause and time > 0 then reduce the time by 0.1s
If the time <= 0 to remove the interval just call clearInterval(setInt) (note you need to define it first like let setInt = setInterval(countdown, 100);)
Using 100ms because better precision when you pause, otherwise after a click, your clock still gonna run into next sec then stop.
If !pause then $time = $time - 0.1; continue. Otherwise keep the same time and pass to next call.

function timer($time) {
  let $lorem = $("#lorem");
  let pause = false;
  let setInt = setInterval(countdown, 100);
  $('#pause').on('click', function() {
    pause = !pause;
  });

  function countdown() {
    if (!pause && $time > 0) {
      $time = ($time - 0.1).toFixed(1);
    }
    if($time <= 0){
      clearInterval(setInt);
    }

    let $minutes = Math.floor($time / 60);
    let $seconds = Math.ceil($time % 60);
    let $result = $minutes + ":" + ($seconds < 10 ? "0" + $seconds : $seconds);

    $lorem.text($result);
    console.log($time);
  }

}
timer(3);

<button id="pause">Pause</button>
Comment: Here's a fiddle that demonstrates it.  `setInterval()` does not drift but `setTimeout` does.  The `setInterval` will sometimes be off for one cycle if the function execution scheduling doesn't happen immediately, but the interval continues to fire right on schedule after that, whereas with `setTimeout()` any timing error continues to accumulate over time.   https://jsfiddle.net/h4h9sfep/
Comment: `setInterval()` is better than using `setTimeout()`.  With `setTimeout` the time to schedule and execute the callback function will not be accounted for in the time before the next timeout. So you will get a slight drift over time for each update.  With `setInterval()` there should be no drift.
Comment: @RJM do you have a reference, I did not know that, hmm, I will try a setInterval version
Comment: @RJM updated, using `setInterval()` I think you are right because the drift is not counted so yeah, thank!
Comment: @RJM I see, the process time between the timeout are not counted, good to know!

Pausing Javascript Timer


$\det (e^A) = e^{\text{Tr}(A)}$ without Jordan canonical form, Schur decomposition?

Question: Let $V$ be a finite-dimensional vector space over $\mathbb{C}$. How do I show that $$\det\,e^A = e^{\text{Tr}\,A}$$for any $A \in \text{End}\,V$ without invoking Jordan canonical form or Schur decomposition?
Comment: You could use that the diagonalizable matrices form a dense set w.r.t. the matrix norm.
Comment: @CountIblis Naive question: isn't density independent of the norm, in finite dimension?
Comment: @ClementC. All the possible norms are going to be equivalent, but the argument does depend on the fact that you can write any non diagonalizable matrix as the limit of a sequence of diagonalizable ones.
Comment: @CountIblis So the proof (of the density) uses this norm -- then the result applies to all.
Comment: @ClementC.  The topology is clearly independant of the norm, but without specification it is not always clear what topology you are refering to. For example, the set $M_n(\mathbb{C})$ also inherits a Zariski topology and the discrete topology, which are important in the study of algebraic geometry and the study of flat metrics respectivly.
Comment: There is only one reasonable topology on $M_n(\mathbb{C})$ when we are talking about the exponential map.
Comment: See §6 in Doron Zeilberger, *A combinatorial approach to matrix algebra*, http://www.math.rutgers.edu/~zeilberg/mamarimY/DM85.pdf . (This proves the version where the entries of $A$ are indeterminates and you are working in a power series ring. For the case of complex entries, you need to evaluate the power series.)
Answer: Let $f : \mathbb{R} \rightarrow \mathbb{C}$ be defined by $f(t) = \det e^{tA}$.  This satisfies the ODE $\dot{f} = f \ \mathrm{Tr} A$, with the initial value $1$.  Solving this and setting $t=1$ gives the RHS.
Added in response to comment:  The map $\det : \mathrm{End}(V) \rightarrow \mathbb{C}$ is differentiable at the identity with derivative $\mathrm{Tr}$; this is a straightforward computation.  We then have
$$\dot{f}(t_0) = \frac{\mathrm{d}}{\mathrm{d}t}\bigg|_{t_0} \det e^{(t-t_0)A} \det e^{t_0A}=\mathrm{Tr}\bigg(\frac{\mathrm{d}}{\mathrm{d}t}\bigg|_{t_0}(t-t_0)A\bigg) \det e^{t_0A}=f(t_0) \mathrm{Tr} A$$
for all $t_0$, using the chain rule.
If one were being super rigorous about the ODE step, one could define $g:\mathbb{R} \rightarrow \mathbb{C}$ by $g(t)=e^{t\mathrm{Tr}A}$ and consider $(f/g)^\dot{}$.
Comment: @SimonS: Added explanation.
Comment: I like the idea of this answer. But how do you show that ODE is satisfied without using the JCF?
Comment: Nice answer.  Emilio's link provides a possible derivation of that derivative.
Comment: @Omnomnomnom: Yes, I just looked at Emilio's link and it proves a more general result which is nice.  In the situation where the thing you're taking $\det$ of is invertible though you just need the derivative at the identity, which I think is something one can convince oneself of just by staring at it.  The Jacobi formula is harder to 'feel'.
Answer: We know that

$Tr(A) = \sum_{\forall k} \lambda_k(A)$
$\lambda_k(e^A) = e^{\lambda_k(A)}, \forall k$
$\det(A) = \prod_{\forall k} \lambda_k(A)$

These together with "logarithm laws": $e^{\sum a} = \prod e^{a}$ can show what we want.
Comment: This answer is pretty intuitive. I'm wondering what a quick proof of (2) is that doesn't use spectral mapping theorem or Jordan normal form.
Answer: It is a consequence of Jacobi formula. You can see the proof at: https://en.wikipedia.org/wiki/Jacobi%27s_formula.
Answer: You can derive this from the Lie product formula.  Write $A = B + C + D$ where
$B$ and $C$ are is the strictly upper triangular and  strictly lower triangular parts respectively of $A$, and $D$ is the diagonal.  Thus $\text{Tr}(A) = \text{Tr}(D)$.  For scalars $t$, $e^{tB}$ and $e^{tC}$ are upper and lower triangular with
$1$'s on the diagonal, so $\det e^{tB} = \det e^{tC} = 1$, while $$\det e^{tD} = \prod_i e^{tD_{ii}} = \exp\left(\sum_i tD_{ii}\right) = e^{\text{Tr}(tD) }$$
Now using the Lie product formula
$$\eqalign{\det \exp(B+D) &= \lim_{N \to \infty} \left((\det \exp(B/N)) (\det \exp(D/N))\right)^N \cr &= \lim_{N \to \infty} (1 \cdot e^{\text{Tr}(D)/N})^N = e^{\text{Tr}(D)} }$$
and similarly
$$ \det \exp(A) = \det \exp(B+D+C) = \lim_{N \to \infty} \left((\det \exp(B+D/N)) (\det \exp(C/N))\right)^N = e^{\text{Tr}(D)} $$
Answer: We can show that the function $f(A)=det(e^A)-e^{tr(A)}$ doesn't depend on any of the variables of $A$. We can do this as follows. We first show that for each matrix $A$, $f(A+\lambda E_{ij})=f(A)$ for $i\neq j$. Then $f(A+\lambda E_{ij})=det(e^{A+\lambda E_{ij}})-e^{tr(A+\lambda E_{ij})}=det(e^{A+\lambda E_{ij}})-e^{tr(A)}$. We compute $det(e^{A+\lambda E_{ij}})=det(e^Ae^{\lambda E_{ij}})=det(e^A)det(1+\lambda E_{ij})=det(e^A)$, where the first equality metrits explanation. We have $e^{A+\lambda E_{ij}}=e^{A}e^{\lambda E_{ij}}\prod_i e^{p_i([A, E_{ij}])}$ where $p_i$ involves taking taking commutators with $\lambda E_{ij}$ and $A$. We only need to show thus that $det(e^{\prod_i p_i([A, E_{ij}]})=1$. But $tr([A, E_{ij}])=0$, which is the condition for its exponential to be in $SL(n)$, by basic lie-theory, and $e^{p_i([A, E_{ij}])}$ consists of only sums of commutators, we have the desired result. Thus $f(A)$ only depends on the diagonal elements. Thus we only need to show that $det(e^A)=e^{tr(A)}$ for diagonal $A$. This trival though, since $e^A$ just the exponential of the diagonal entries, and so we are reduced to the sum formula.
Answer: Since so many proofs have been supplied that do not invoke the Schur decomposition nor Jordan canonical form, I see no harm in including two proofs that invoke them.
Proof 1: Schur decomposition.
The Schur decomposition states that if $A$ is a square matrix over an algebraically complete field (or if the characteristic polynomial for $A$ splits over the field we are in), then $A$ is similar to an upper triangular matrix. That is, there exists invertible $P$ such that $P^{-1}AP = T$, and $T$ is upper triangular.
Specifically for the complex numbers, we can say even more, in that we can choose $P$ to be unitary, i.e. $P^* P = I$. But we do not need that part here.
So we assume we have $P^{-1}AP = T$, which we can also write as $A = PTP^{-1}$. Two things to note:

$\text{Tr}(A) = \text{Tr}(T)$. Hence $e^{\text{Tr}(A)} = e^{\text{Tr}(T)}$.
For every nonnegative integer $k$, we have $A^n = PT^kP^{-1}$. Put all of these powers into the direction of the exponential, then factor $P$ out of one side and $P^{-1}$ out of the other, and we  obtain $e^A = Pe^T P^{-1}$. It then follows that$$\det(e^A) = \det(P)\det(E^T)\det(P^{-1}) = \det(E^T).$$

So now, all we need to do is to prove the theorem for matrices that are already upper triangular.
Let$$T = \begin{pmatrix}\lambda_1&&&\\ &\lambda_2&*&\\ &0&\ddots&\\  &&&\lambda_n\end{pmatrix}.$$Then$$\text{Tr}(T)=\lambda_1+\dots+\lambda_n,\text{ }\det(T)=\lambda_1\lambda_2\dots\lambda_n.$$As always, the asterisk means "there are entries here that could be anything, which we are not tracking carefully because it does not really matter." By direct computation,$$T^k=\begin{pmatrix}\lambda_1^k&&&\\ &\lambda_2^k&*&\\ &0&\ddots&\\  &&&\lambda_n^k\end{pmatrix}.$$We compute that$$e^T=\begin{pmatrix}e^{\lambda_1}&&&\\ &e^{\lambda_2}&*&\\ &0&\ddots&\\  &&&e^{\lambda_n}\end{pmatrix}.$$From that,$$\det(e^T)=e^{\lambda_1}e^{\lambda_2}\dots e^{\lambda_n}=e^{\lambda_1+\cdots+\lambda_n}=e^{\mathrm{Tr}(T)},$$as desired.
Proof 2: Jordan canonical form.
The Jordan canonical form of $A$ is$$A = \begin{pmatrix} J_1 &&& \\ &J_2&& \\ &&\ddots& \\ &&&J_k\end{pmatrix},$$where we have Jordan blocks$$J_i = \begin{pmatrix} \lambda_i & 1 & & 0 \\ &\ddots & \ddots &  \\ &&\ddots&1 \\ 0 &&& \lambda_i\end{pmatrix}.$$We have$$J_i = \lambda_i I_{n_i \times n} + \begin{pmatrix} 0 & 1 && 0 \\ &\ddots&\ddots& \\ &&\ddots&1 \\ 0 & & & 0 \end{pmatrix} = A_i + B_i \implies A_iB_i = B_iA_i.$$Set$$D = \begin{pmatrix} A_1 &&& \\ & \ddots && \\ &&\ddots& \\ &&&A_k\end{pmatrix}, \text{ }\, B = \begin{pmatrix} B_1 &&& \\ & \ddots && \\ &&\ddots& \\ &&&B_k\end{pmatrix}.$$Then $$A = D + B,\text{ }DB = BD \implies e^A = e^{D+B} = e^De^B \implies \det(E^A) = \det(E^D)\det(E^B).$$We have$$e^D = \begin{pmatrix} e^{A_1} &&& \\ & \ddots && \\ &&\ddots& \\ &&&e^{A_k}\end{pmatrix}, \text{ }\,\det(e^B) = 1.$$So$$\det(e^D) = e^{n_1\lambda_1 + \dots + n_k\lambda_k} \implies \det(e^A) = \det(e^D) = e^{n_1\lambda_1 + \dots + n_k\lambda_k} = e^{\text{Tr}(A)},$$as desired.
Answer: The claim is trivial for diagonal matrices. Suppose that $A$ is diagonalisable, that is, $A = VDV^{-1}$ for some diagonal matrix $D$ and $V$ invertible. We have $e^{{\rm Tr}\, A} = e^{{\rm Tr}\, VDV^{-1}} = e^{{\rm Tr}\, VV^{-1}D} = e^{{\rm Tr}\, D}$. On the other hand, $\det e^A = \det e^{VDV^{-1}} = \det V e^D V^{-1} = \det e^D = e^{{\rm Tr}\, D}.$
Observe that the functions $A\mapsto \det e^A$ and $A\mapsto e^{{\rm Tr} A}$ are continuous and agree on the dense set of diagonalisable matrices. So they must be equal.
Answer: We may assume that $A\in M_n(\mathbb C)$. Recall that if $\lambda_1,\lambda_2,\ldots,\lambda_n$ are the eigenvalues of $A$ and $p$ is a polynomial, then $\det(p(A))=\prod_ip(\lambda_i)$. (This is a direct consequence of the fact that determinant is multiplicative. No diagonalisation or triangulation is involved. See theorem 1 in this answer for instance.)
By Cayley-Hamilton theorem, for each $m$ the partial sum $\sum_{k=0}^m\frac{1}{k!}A^k$ lies inside the matrix subspace $W=\operatorname{span}\{I,A,A^2,\ldots,A^n\}$. Hence $e^A$ also lies inside $W$ because $W$ is closed. That is, $e^A=p(A)$ for some polynomial $p$. However, for each (possibly non-semisimple) eigenvalue $\lambda$ of $A$, if $v$ is a corresponding eigenvector, then $p(\lambda)v=p(A)v=e^Av=e^\lambda v$. Therefore $p(\lambda)$ is necessarily equal to $e^\lambda$. Hence
$$
\det(e^A)=\det(p(A))=\prod_ip(\lambda_i)=\prod_ie^{\lambda_i}=e^{\sum_i\lambda_i}=e^{\operatorname{tr}(A)}.
$$
Answer: So many good answers, I'll take my shot as well.
You can use the already mentioned fact the the gradient of the determinant at the identity matrix is the trace, together with $ e^{A}=\lim_{n\to \infty}(I+\frac{1}{n}A)^n $.
Then, from standard calculus,
$$ \det e^A = \lim \det (I+\frac{1}{n}A)^n = \lim (1 +\frac{1}{n}Tr\; A + o(\frac{1}{n}))^n = e^{Tr\; A}. $$


Two concerns: Available for security updates / Image captions

Question: I am looking at revamping a set of sites from ASP to Drupal. I like a lot of what I see in Drupal, but have two concerns:

In reading about Drupalgeddon, it seems that the problem was that many people didn't even see the security notice before hackers started exploiting the vulnerability. I have no staff, so this means I need to be available immediately to install security updates when they are announced. I don't know that I want to be chained to my websites that way, or leave them potentially vulnerable if I decide to go on vacation for a month.
I've been amazed to find that Drupal has no innate ability to put captions on images. Doing that appears to require choosing between three modules (Image Caption, Image Field Caption, or Image Caption Formatter) with no documentation that compares and contrasts the modules to help with the choice. Putting captions on images is a pretty basic requirement, so it makes me wonder what else I'm going to find out I can't do easily once I start porting content.

Comments?
Answer:
No matter which CMS you use this will always be an issue. If you do not have time to be proactive about maintaining your software, you should look into paying someone to do it for you.
This is the result of Drupal's modular design. It's done this way so it can accommodate the wide-spectrum of use cases. It's a simplicity/flexible tradeoff that can be good and bad depending on the circumstances.
Comment: For what it's worth re: #1, I've found Drupal less often hit by exploits than Wordpress sites I also manage. Part of that I'm sure is the result of smaller market share of Drupal.
Comment: re: #2, Drupal's modular design can be very obtuse to newbies. If you're not looking for flexibility it could be overkill for your use case.

If you don't have the time to manage your software or customize your platform, you might want to consider managed WordPress hosting. You won't have to manage it or customize it for image captioning.


How to end loop when user inputs "exit" when asked for name?

Question: When the program prints "Please enter your name: ", if the user enters exit, the program should end.
BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);

String input = "";

while(true) {
    System.out.println("Please enter your name: ");
    input = User_Input.next();
    bufferedWriter.write("Name: " + input);
    System.out.println("Please enter your address: ");
    input = User_Input.next();
    bufferedWriter.write(", Address: " + input);
    System.out.println("Please enter your phone no: ");
    input = User_Input.next();
    bufferedWriter.write(", Phone: " + input);
    bufferedWriter.newLine();
}
bufferedWriter.close();

Comment: In the future, please improve your questions so they are easier to answer. Please go through the [ask]
Answer: In any kind of loop

break can be used to exit the loop
continue causes the loop to continue with the next iteration
return breaks the loop and causes the container method to exit by giving the control back to the caller

In your case you can test if the condition is met like this:
input = User_Input.next();
if ("exit".equals(input))
    break;


Save image once Glide has loaded it

Question: I load images using Glide like such:
Glide.with(getContext()).load(apdInfo.url)
         .thumbnail(0.5f)
         .crossFade()
         .diskCacheStrategy(DiskCacheStrategy.ALL)
         .into(apd_image);

And wish to save the Bitmap loaded like such:
private void saveImage() {
    final ImageView apd_image = (ImageView) view.findViewById(R.id.apd_image);
    final InternalFileHandler IFH = new InternalFileHandler(getContext());

    apd_image.setDrawingCacheEnabled(true);
    apd_image.buildDrawingCache(true);
    Bitmap bitmap = apd_image.getDrawingCache();

    // Simply saves the bitmap in the filesystem
    IFH.savePicture("APD", bitmap, getContext());
    apd_image.destroyDrawingCache();
}

The issue is that if I call saveImage before Glide has loaded my picture, it won't work.
How may I wait or Glide to load it? Please note that using Glide's listeners did not work.
EDIT:
I now use the following listeners:
 .listener(new RequestListener<String, GlideDrawable>() {
                @Override
                public boolean onException(Exception e, String model, Target<GlideDrawable> target, boolean isFirstResource) {
                    //handle the exception.
                    return true;
                }

                @Override
                public boolean onResourceReady(GlideDrawable resource, String model, Target<GlideDrawable> target, boolean isFromMemoryCache, boolean isFirstResource) {
                    // onResourceReady is called twice for some reason, this is my work around for now
                    if (first) {
                        GlideBitmapDrawable glideBitmapDrawable = (GlideBitmapDrawable) resource;
                        // Convert to Bitmap
                        Bitmap bm = glideBitmapDrawable.getBitmap();
                        saveImage(bm);
                        first = false;
                    } else {
                        first = true;
                    }
                    return true;
                }
            })

Comment: what exactly did not work and how?
Answer: Use the listener so that when the image is fetched and ready to be used, you can save it using the saveImage method of yours.
Do this:
Glide.with(getContext()).load(apdInfo.url)
     .thumbnail(0.5f)
     .crossFade()
     .diskCacheStrategy(DiskCacheStrategy.ALL)
     .into(new SimpleTarget<GlideDrawable>() {
                @Override
                public void onResourceReady(GlideDrawable glideDrawable, GlideAnimation<? super GlideDrawable> glideAnimation) {
                    apd_image.setImageDrawable(glideDrawable);
                    apd_image.setDrawingCacheEnabled(true);
                    saveImage();
      }});

Call the saveImage method inside onResourceReady() callback and use the GlideDrawable resource. I would suggest using the GlideDrawable rather than getting the image using Drawing Cache.
Comment: It does not seem to save my image, perhaps because I am using Drawing Cache as you have said, how may I use GlideDrawable in this case?
Comment: You just need to change GlideDrawable to Bitmap and then call your IHF.savePicture(...) method.
Comment: And how may I convert a GlideDrawable to a Bitmap?
Comment: I have found how to convert it, but it now seems that my picture is not displayed in my ImageView.
Comment: What did you try?
Comment: I have added a code snippet.
Please note that my files are saved properly, but that my ImageView is empty.

Save image once Glide has loaded it


Purchasing hard drives with non-sequential serial numbers

Question: I've always heard that you should not purchase hard disks with sequential serial numbers for any storage system.  Now I find myself, for the first time, in a position where I need to purchase around sixteen drives and there seems to be no way to buy this many hard disks and guarantee they weren't all from the same day of manufacturing.
How do I do this?  Explain why I'm being overly paranoid.
Comment: Great question.
Answer: I'm going to disagree with joeqwerty here, because I had a similar issue. Check out my experience here, and see the accepted answer. 3/5 of my disks, all purchased in the same transaction, all failed within 24 hours of eachother.
Although I think my experiences were fairly extreme, the real problem happens later on in the life of the device, when all the drives the same age will start to fail in a similar timeframe, so your line of thinking is spot on, but might prove to be more difficult than you think to get around, unless you wait 6 months before buying a 2nd batch of drives.
I guess one solution is to buy disks from different manufacturers and mix them up, however I've had poor experience with this too, because my Western Digitals were 2Mb smaller than my Seagates. Not really an issue when you're building a new array (there will just be 2Mb of unused space on the larger disks), but is a HUGE problem when you've got a failed array and you're trying to rebuild it and you can't becuase all your spare disks are 2Mb too small.
The only thing I can suggest you do is perhaps buy 8 disks from one retailer and then buy another 8 from somewhere else. I doubt you'll be losing out on any volume discounts, and if it helps put your mind at ease then it's worth the extra effort.
Comment: This is the paper: http://labs.google.com/papers/disk_failures.pdf
Comment: Didn't Google do a report stating that failure rates did not correlate to manufacturers or models, but did strongly correlate to production batches?
Comment: You can't really argue with experience like that.
Comment: I had a similar experience. I populated a server with 16 drives. Within one year, five drives had failed. It has been two years since those five drives were replaced and not a single additional drive has failed.
Answer: You are not paranoid, it's indeed very bad to use drives from the same batches, for a simple reason :

Same drives, built the same way, from the same components, used the same way, are likely to fail at a same time.

I've been working for years at a data recovery company, and i've seen amounts of RAID array with several drives failing at the same time (within array rebuild time), usually all those with consecutive or very close serial numbers (I recall a sad customer who had a RAID of 5 drives, 3 of them having the magnetic substrate wiped out from the platter...)
I'm not sure if you are talking about a RAID system here, but if so, I advice against mixing drives from different makers, as you'll lose performance due to different seek times and data transfer rate, and as Farseeker stated, you're likely to have size issues with raid.
To splay the failure date of these drives, you should turn to different resellers, since it's unlikely they'll have the same batch of drive.
You can also "burn" those coming from the same batch : use heavily one drive alone one week, add another drive and use them both heavily another week, add a third drive and use them three heavily  ... For 16 drives it is a bit inconvenient, so you should evaluate the risks of the drives failing in the same period to set the burning time.
Answer: Presumably the thinking would be that if there was a glitch in the manufacturing process that affected one drive in a sequentially numbered series (drives from the same manufacturing batch) that all of the drives in that series\batch would be affected. IMHO, there are three reasons to discount this line of thinking:

Modern manufacturing processes are in fact, a science. While manufacturing errors do occur, it seems that the incidence of failure for any x number of units produced is a very small number and that post-manufacturing QA testing would render this number even smaller. The chances of getting some multiple number of units with the same defect seems unlikely to me.
If an anomoly existed in a single unit from a specific batch, that anomoly might slip through testing but I find it hard to believe that a larger number of units with the same inherent anomoly would slip through testing and make it into your hands.
If the issue was an engineering issue and not a manufacturing issue, chances are that all units in the same product family, from any and all manufacturing series\batches would be affected so it wouldn't really matter if they came from the same batch or not, they would all be faulty until the engineering problem was discovered, resolved, and the manufacturing process adjusted accordingly.

Of course, I'm neither a manufacturing nor an engineering expert, so these are just my thoughts on the matter.
Comment: Yet, despite all that, manufacturers do indeed produce bad batches of drives.
Answer: joeqwerty's answer is great on the 'why', which I think you already understand.  As for the 'how', you ask your retailer or reseller, and if they can't help you, you spend a little bit more and go to someone who can.
Alternatively, you can buy different brands, which is a good way to assure that you won't at least have all your disks fail at once.


How to display wishlist in JTable?

Question: I've just been learning Java recently and have a math problem. The requirement is to enter the displayed data into the table. Then filter out the list of mssv with DiemTb>7. But i don't know how to do.

This is my code:
private  ArrayList<Student> list;
 DefaultTableModel model, hocbong;
public NewJFrame() {
    initComponents();
    this.setLocationRelativeTo(null);
    list=new ArrayList<>()  ;
    model = (DefaultTableModel) jTable1.getModel();

}

and
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
    Student s=new Student();
    s.setMssv(txtmssv.getText());
    s.setDiem1(Float.parseFloat(txtdiem1.getText()));
    s.setDiem2(Float.parseFloat(txtdiem2.getText()));
    s.setDiem3(Float.parseFloat(txtdiem3.getText()));

    list.add(s); // them vao danh sach SV
    showResult();

}

private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {

}

private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {

}

public void showResult(){
    Student s = list.get(list.size()-1);
    model.addRow(new Object[]{
         s.getMssv(), s.getDiem1(),s.getDiem2(), s.getDiem3(), s.getDiemTB()
    });}

Thanks
Answer:
Then filter out the list of mssv with DiemTb>7.

Read the section from the Swing tutorial on Sorting and Filtering for a complete working example.
The example shows how to use a regex filter on String.
However, read the RowFilter API as it also includes a number filter.
I guess you would use something like:
RowFilter.numberFilter(ComparisonType.AFTER, 7);

How to display wishlist in JTable?


Jqplot graph appears only on first submit

Question: I have the following jQuery code to execute when I click a button
<code>$('#substat').click(function() {
    $.post('ext/engine.php', post, function(data){
        $('#statout').empty().append(data).dialog(
         {height:350, width:700, dialogClass: 'shadowme', position: 'center'})
        });
});
</code>
UPDATE - I have checked code by code to see where the problem is. As it looks, it is the PHP part which looks like this:
<code>$html = '<script>';
for($s = 0; $s < $m; $s++) {
    if ($m-$s != 1) { $var1 .= $out[total][$s].', '; $var2 .= $out[age][$s].'", "'; }
    else { $var1 .= $out[total][$s]; $var2 .= $out[age][$s].'"';}
    if ($out[total][$s] > $max) { $max = $out[total][$s]; }
}
if ($max > 10) { $max = round($max/10); }
$html .= 'VarH = ['.$var1.'];
    plot1 = $.jqplot("statout", [VarH], {
                legend:{show:true, location:"ne"},
                title:"Gente",
                series:[ { label:"VarH", renderer:$.jqplot.BarRenderer } ],
                axes:{
                    xaxis:{ renderer:$.jqplot.CategoryAxisRenderer, ticks:['.$var2.'] },
                    yaxis:{ min:0, tickInterval:'.$max.', autoscale: true }
                },
                seriesDefaults:{ lineWidth:5, rendererOptions: { barWidth:5, barMargin:5, barPadding:0 } }
            });
    </script>';
echo $html;
</code>
If i change the last line from echo $html; to echo "Hello"; it will always work.
But if i leave it with the $html variable created with jqplot it will only work one time when rendered inside the jquery dialog. After that I have to refresg the webpage to make it work again instead of just clicking again on the submit button to create the dialog with the graph in it.
Comment: Updated to include the PHP code.
Comment: Update2 - I can change the graph anytime if i leave it opened. It will change everytime i click on the submit button so it can change the graph inside the dialog BUT if i close the dialog the graph does not show until I refresh the webpage.
Answer: I had the same problem. The solution is to display the dialog first and afterwards (!) load the chart into.
Comment: Do you have an idea how to load it into the dialog afterwards taking into consideration that the dialog must be hidden at all times before popping the graph out.
Comment: Thank you wmask for this answer. I spent a good deal of time trying to understand why my chart was not visible within the dialog before I read your answer !


.NET Core MVC com jQuery Vertical Accordion Menu

Question: Estou usando o menu accordion vertical do jQuery do seguinte template: https://templatemag.com/demo/Dashio/ No entanto, a operação não funciona como nele.
Clicando em um menu

  List

Ele não permanece aberto e não altera a classe do link para indicar que ele foi clicado. Alguém pode me dizer o porquê?
Comment: informe o trecho de código `jQuery` que vc está utilizando
Answer: Segue o trecho:
$(function() {
  $('#nav-accordion').dcAccordion({
    eventType: 'click',
    autoClose: true,
    saveState: true,
    disableLink: true,
    speed: 'slow',
    showCount: false,
    autoExpand: true,
    //        cookie: 'dcjq-accordion-1',
    classExpand: 'dcjq-current-parent'
  });
});


Prove/Show that Limit is equal to 0.

Question: I'm really struggling on this question.  I've been thinking about it for awhile now but this is one of those where I don't really have much intuition on what to do.

Problem 3. Prove that if the limit $\lim_{x\to +\infty}f(x) =: L$ exists (finite or infinity) and the improper integral. $$\int_a^{+\infty}f(x) dx$$
is convergent, then $L = 0$.

Here is some facts that I know that I think I should perhaps use.
Facts/Knowledge I know:
The above integral can be rewritten as:

$$\int_a^{\infty}f(x)dx = \lim_{A\to \infty}\int_a^{A}f(x)dx$$

We know that limit as x goest to infinity of $f(x)=L$.  I need to somehow show that limit L is equal to 0.
If I take the integral I get $\lim_{A \to \infty} F(A)-f(a)$ and I know this does not equal infinity as the integral converges.  I'm not sure if this is on the right track or what to do next.
I was thinking maybe perhaps instead I could use the Cauchy Criterion to come up with a proof.  Note: I'm not used to doing proofs with Improper integrals.

Theorem 1 (Cauchy Criterion). The improper integral (1) converges if and only if for every $\epsilon > 0$ there is an $M\geqslant a$ so that for all $A, B \geqslant M$ we have
$$\Bigg|\int_A^B f(x) dx\Bigg| < \epsilon$$
Answer: Assume that $L\in(0,\infty)$, then for some $M$, we have $f(x)>\dfrac{L}{2}$ for all $x\geq M$, then $\displaystyle\int_{M}^{\infty}f(x)dx\geq\int_{M}^{\infty}\dfrac{L}{2}dx=\infty$.
If $L\in(-\infty,0)$, then for some $N$, we have $f(x)<\dfrac{L}{2}$ for all $x\geq N$, then $\displaystyle\int_{N}^{\infty}f(x)dx\leq\int_{N}^{\infty}\dfrac{L}{2}dx=-\infty$.
Similar reasoning applies for the case that $L=\infty$ or $L=-\infty$. For example, $L=\infty$: Simply choose $M'$ such that $f(x)>1$ for all $x\geq M'$, the integrating both sides on $[M',\infty)$ to get the contradiction.
Comment: I'm sorry but I don't understand how does this show that L=0.
Comment: Essentially by considering the cases that $L$ being real number differs from zero, and that plus or minus infinity, we get contradiction in each case, so $L$ must be zero.
Comment: I'm sorry, I don't really understand several things.
Comment: 1. Why does f(x)>L/2 whenever x>M and f(x)N?                                2. How do we get a contradiction in each case and how does similar reasoning apply for the case L=infinity or L=-infinity?
Comment: Just the application of the definition of limit: Take $\epsilon_{0}=L/2$ (assume that $L>0$), then there exists some $M$ such that for all $x\geq M$, we have $|f(x)-L|<\epsilon_{0}=L/2$, breaking the absolute value, then $f(x)>L-L/2=L/2$.
Comment: Thanks I got that. But I don't really understand how the cases that L=infinity or L=-infinity works?
Comment: I have added the details.
Comment: Thanks, I just don't understand how integrating both sides on [M', infinity) to get the contradiction.  Sorry just trying to understand, having difficulty understanding this topic.
Comment: Then the right side is just $\infty$, the same contradiction that we got for $L>0$ case. As you know if we say that $\displaystyle\int_{a}^{\infty}f(x)dx$ exists, then so must be $\displaystyle\int_{M}^{\infty}f(x)dx$ for any $M$, so $\displaystyle\int_{M}^{\infty}f(x)dx$ must be a real number, hence it cannot greater or equal with $\infty$.
Comment: So the contradiction for all the cases is that the integral must be a real number as it is convergent but we are getting that it is greater than or equal to infinity or less than or equal to -infinity.  Is that correct?
Comment: Yes, exactly what I want to say.
Comment: can you explain why theintegral of L/2 equal to inifiny ?

Prove/Show that Limit is equal to 0.


Clarification on the rule of 10 for logistic regression

Question: Been brushing up on my logistic regression and I've seen a couple of things about the one in ten rule.
To illustrate my current understanding (or lack thereof) lets consider a case with only two independent binary variables.  Does this mean I need a minimum of 20 total samples to justify having the two independent variables?
Perhaps my intuition is wrong but that seems low.  Especially if the two variables were highly correlated.  Consider the extreme case where I have twenty samples and for all samples, both x_1 and x_2 are 1.  In this case I would think one would want more data where the explanatory variables are distinguishable.  I'm sure the confidence intervals on the betas here would be significantly large and that is to be taken into consideration, but I'm just trying to rectify this rule (and yes I know it's a rule of thumb) with extreme cases like this
Comment: Related: http://stats.stackexchange.com/questions/26016/sample-size-for-logistic-regression/161802#161802
Answer: For logistic regression the rule of thumb isn't 10 total samples per independent variable, it's 10 cases having the lower-frequency outcome. So if you're analyzing a 20%/80% outcome ratio, that rule of thumb suggests 50 total samples per independent variable.
And this is only a rule of thumb. Some thumbs are bigger than others.
Your intuition about correlated predictors adds a further important consideration. It depends somewhat on what you're trying to accomplish with your regression analysis, for example whether you really want (or even should seek) separate estimates for each predictor, or you are willing to combine information from correlated predictors in some way. Follow the regularization and multicollinearity tags on this site to see ways to deal with correlated predictors.
What would be best, of course, would be a pilot study to get preliminary data. Those initial estimates of the relations of the predictors to each other and to outcome would then inform a power analysis for definitive experimental design.
Comment: You need 10 cases with the _least-frequent_ outcome. If there is a 20/80 ratio of your 2 outcomes, 50 samples will give you a 10/40 ratio of cases with those outcomes.
Comment: I'm sorry I don't quite follow your 20/80 example.  For arguments sake lets say I have a poll and I'm getting 20% yes responses and 80% no responses.  How do I go from that to determining that I need 50 samples per independent variable?


prove by induction: $x_n=a^nx_0+b(1+a+\cdots+a^{n-1})$ given $f(x)=ax+b$ with initial value $x_0$

Question: prove by induction: $x_n=a^nx_0+b(1+a+\cdots+a^{n-1})$ given $f(x)=ax+b$ with initial value $x_0$
I'm fine with base case and hypothesis, but having some problems showing that it is true for $P(n+1)$ by using $P(n)$, can someone show me how to use $P(n)$?
Comment: I surmise that you meant $x_{n+1} = f(x_n) = ax_n + b$.  But that should be explicit. $\qquad$
Answer: The formula in question holds for $n=1$. Assume that it holds for some $n\geq1$. Then
$$\eqalign{x_{n+1}&:=f(x_n)=ax_n+b\cr &\>=a\bigl(a^nx_0+b(1+\ldots+a^{n-1})\bigr)+b\cr
&\>=a^{n+1}x_0+b(1+a+a^2+\ldots+a^n)\ ,\cr}$$
as it should be.


How do I fo back and deduct the role hiearchy of my trial account?

Question: Apologies for the new question, but I am having trouble understanding the best practices for understanding the recommended role set up for my account. I am auditing what I have created to backwards engineer and correct it on a new warehouse.
So here is the situation:

I granted all permissions on all warehouses modify AND usage to the sysadmin.
When running worksheets and ./snowsql in parallel, I used the ACCOUNTADMIN for all of the sessions in snowsql.

When I use the Sysadmin to modify the tables that copied the data staged in the warehouse sometimes I have permissions and other times I don't.
I have been sifting through account history with the ACCOUNTADMIN role to view all the grants with the recommended query from the documentation below:
select *
from table(information_schema.query_history())
order by start_time;

I filtered then by the database and query_id to include grant
select *
from table(information_schema.query_history())
where database_name = 'temp_db'
and query_id like '%grant%'
order by start_time;

I did this to see if there were any differences in the grants I did between databases in the warehouse. I only set up two warehouses so it was easy to see.
Going forward, Accountadmin is used to create roles, warehouses, and databases.
To prevent the need to do an audit when switching between roles, I want to set future grants on Sysadmin to specific databases in a warehouse for modification and usage, how do I do that?
Answer: Permissions to warehouses, database, and all other objects are separate things.  Granting permissions to a warehouse let's that role use or modify a warehouse, but that has nothing at all to do with creating, updating, etc. other objects like databases, schemas, tables, and views.  Also, only the role that OWNS a table can drop or alter a table.  So, you might want to check on the ownership of the tables between SYSADMIN and ACCOUNTADMIN.  As a best practice, ACCOUNTADMIN shouldn't own anything.
It would take quite a bit more information to give you a full rundown of RBAC in Snowflake.  If you are struggling with it, you might want to contact Professional Services at Snowflake and get them to come in and do an overview (QuickStart or Security package) to get you straightened out.


How long was Adrian Boult's baton? Why did he use such a long one?

Question: This question is fairly self-explanatory -- watching Boult conduct is almost magical. There are some excerpts from a BBC documentary floating around that explain in part the development of is singular technique:

But did he write any other documentation on his baton technique and why he selected such a lengthy baton? Which, uh, how long was that thing? It looks like he's majestically swinging a fishing pole at the orchestra. And yet he's probably one of the best conductors I've ever seen.
Comment: Interesting that the clips of Nikisch contradict Boult's description of finger rather than elbow movement.
Comment: @LaurencePayne I actually thought so too, but it isn't like Boult only ever used his fingers -- he gets pretty amped by his usual standards in this recording: https://www.gramophone.co.uk/classical-music-news/rare-colour-footage-of-sir-adrian-boult-conducting-elgar-revealed
Comment: They're pretty well 'on the click'.  Not doing that 'philharmonic delay' thing. :-)
Comment: @LaurencePayne Yeah, you're right! Interesting observation, since he's such an iconic British conductor. You might expect more delay.
Answer: Since there's currently no answer here, I thought I'd do some digging. I haven't been able to get an exact number, but we can at least have a little fun getting an approximation.
In Boult's obituary in the New York Times, Edward Rothstein highlights Boult's

six-foot frame

and

a baton that was nearly the length of his arm.

And in an activity created by the Forensics Department at Rice University, we see that

a person's height can be estimated using the lengths of the long bones of the body—the femur, tibia, and fibula in the leg, and the ulna, radius, and humerus of the arm.

So, let's try it! The height of a Caucasian male is estimated to be the length of the ulna times 3.76 and with a further 75.55 cm added. Regarding the radius, it's 3.79 times the length, plus an additional 79.42 cm. And as for the humerus, it's 2.89 times the length, plus 78.10 cm.
Solving these equations, we see that 6 feet (182.88 cm) suggests an ulna length of 28.54 cm (11.24 in), a radius length of 27.29 cm (10.74 in), and a humerus length of 36.26 cm (14.28 in). Averaging the ulna and radius lengths and combining them to the humerus, that's an arm length of 64.18 cm (25.27 in).
So our current best guess is that his wand length approached 25 inches, about the length of Harry Potter and Lord Voldemort's wands combined.
Comment: Holy cow! This is probably my favorite answer ever. I love the Harry Potter comparison--some how it seems like the best way of representing this data. It kind of was a magic wand, wasn't it? In addition, I now know more about the exact proportions of Sir Boult's body than I ever dreamed... ROFL


Alternate to iPhone URL schemes?

Question: I'm making a website. On it, I want to have a link to my twitter account, http://twitter.com/[username].
On iOS devices, I've coded it so that it goes to twitter://[username], the iOS URL scheme for the official Twitter app. However, if the user does not have this app installed, safari just errors, saying that the 'URL is invalid'.
Does anyone know a way around this, so that it'll load the app if they have it, and the normal web URL if they don't?
Answer: You can not access anything external to your application, so you will not be able to see if another application has been installed.
One option would be to load your profile in a web view and then at least they can get to your profile.
Comment: Ah Ok, you still cannot see what applications are loaded. Why not just load the twitter website in Safari?
Comment: To clarify, I'm not making an application. This is a website that would be visited in mobilesafari.
Comment: Someone downvote? Hmm, OK it's not quite an answer because the question wasn't clarified in the original - but the information given in my answer is correct. Prove me wrong or give me a comment at a minimum...
Answer: For anyone who stumbles upon this page and still wants further clarification, you can use an if/else statement.
<code>if ([[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:@"twitter:@user"]])
{
     [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"twitter:@user"]];
}

else
{
     webView.urlString = @"http://www.twitter.com/user";
     [[self navigationController] pushViewController:webView animated:YES];
     [netView release];
     netView = nil;
 }
</code>
Comment: You can in an iOS app, not in a web app though.

Alternate to iPhone URL schemes?


How to keep matplotlib (python) window in background?

Question: I have a python / matplotlib application that frequently updates a plot with new data coming in from a measurement instrument. The plot window should not change from background to foreground (or vice versa) with respect to other windows on my desktop when the plot is updated with new data.
This worked as desired with Python 3 on a machine running Ubuntu 16.10 with matplotlib 1.5.2rc. However, on a different machine with Ubuntu 17.04 and matplotlib 2.0.0, the figure window pops to the front every time the plot is updated with new data.
How can I control the window foreground/background behavior and keep the window focus when updating the plot with new data?
Here's a code example illustrating my plotting routine:
import matplotlib
import matplotlib.pyplot as plt
from time import time
from random import random

print ( matplotlib.__version__ )

# set up the figure
fig = plt.figure()
plt.xlabel('Time')
plt.ylabel('Value')
plt.ion()

# plot things while new data is generated:
t0 = time()
t = []
y = []
while True:
    t.append( time()-t0 )
    y.append( random() )
    fig.clear()
    plt.plot( t , y )
    plt.pause(1)

Comment: As I cannot test this in any way, just a suggestion what to try: instead of `plt.ion()`, what happens if you use `plt.show(block=False)` and then in your `while` loop add `plt.draw()` right after the `plt.plot()` call?
Comment: @Thomas Kühn: Thanks for your suggestion. However, that did not change anything on the Ubuntu 17.04 / matplotlib 2.0.0 environment.
Comment: What [backend](http://matplotlib.org/faq/usage_faq.html#what-is-a-backend) are you using? It may be worth changing this to see if this solves the problem.
Comment: @Ed Smith: I don't know which backend is used by default with my example code shown above. But just to be sure I tried it with explicitly selecting the TkAgg backend. This did not change anything.
Comment: Here's a workaround https://stackoverflow.com/a/45734500/277267
Answer: matplotlib was changed somewhere from version 1.5.2rc to 2.0.0 such that pyplot.show() brings the window to the foreground (see here). The key is therefore to avoid calling pyplot.show() in the loop. The same goes for pyplot.pause().
Below is a working example. This will still bring the window to the foreground at the beginning. But the user may move the window to the background, and the window will stay there when the figure is updated with new data.
Note that the matplotlib animation module might be a good choice to produce the plot shown in this example. However, I couldn't make the animation work with interactive plot, so it blocks further execution of other code. That's why I could not use the animation module in my real-life application.
import matplotlib
matplotlib.use('TkAgg')
import matplotlib.pyplot as plt
import time
from random import random

print ( matplotlib.__version__ )

# set up the figure
plt.ion()
fig = plt.figure()
ax = plt.subplot(1,1,1)
ax.set_xlabel('Time')
ax.set_ylabel('Value')
t = []
y = []
ax.plot( t , y , 'ko-' , markersize = 10 ) # add an empty line to the plot
fig.show() # show the window (figure will be in foreground, but the user may move it to background)

# plot things while new data is generated:
# (avoid calling plt.show() and plt.pause() to prevent window popping to foreground)
t0 = time.time()
while True:
    t.append( time.time()-t0 )  # add new x data value
    y.append( random() )        # add new y data value
    ax.lines[0].set_data( t,y ) # set plot data
    ax.relim()                  # recompute the data limits
    ax.autoscale_view()         # automatic axis scaling
    fig.canvas.flush_events()   # update the plot and take care of window events (like resizing etc.)
    time.sleep(1)               # wait for next loop iteration

Comment: if you're just updating lines and don't need other rescaling, etc., you can just replace `plt.pause()` with `fig.canvas.flush_events()`. this is the key call difference
Comment: If you have UI problems due to using `time.sleep`, like being unable to move/resize the window, take a look at this answer https://stackoverflow.com/a/45734500/277267 which is somewhat of a re-implementation of the `plt.pause` method.
Comment: If I could mark this answer as useful a hundred time, I'd certainly do it. Thanks a lot for your code snippet, it works wonderfuly :)
Comment: matplotlib is giving me such headaches... when using Qt as a backend (`matplotlib.use('Qt5Agg')`), you need to insert a `fig.canvas.draw_idle()` before the `flush_events` call...
Answer: For the tkinter backend (matplotlib.use("TkAgg")), using flush_events is not sufficient: you also need to call fig.canvas.draw_idle() before each fig.canvas.flush_events(). As @samlaf wrote, the same holds for the Qt5Agg backend.


Como parar a execução de um código no nodemon?

Question: Qd eu quero executar algo usando o nodemon eu digito no terminal nodemon nomeDoArquivo.js, blz, mas e qd eu quero parar a execução?
Pq qd é um codigo tp timer por exemplo, a execução não para, então eu preciso fechar o terminal e abrir de nv para encerrar... Existe algum comando para parar a execução atual sem tem q fechar o terminal?
Comment: ueh só `ctrl + c` já para!
Answer: Nesse caso é melhor não usar o nodemon usa apenas node script.js, o nodemon ele fica monitorando seus arquivos, quando você altera algum arquivo ele da reload na aplicação isso é útil quando você esta desenvolvendo a aplicação. Mas no seu caso onde você quer executar apenas um arquivo não tem necessidade de usar.
Answer: Se quiser apenas que ele execute uma vez e não fique executando continuamente/observando alterações nos ficheiros e actualizando automaticamente on save, você deve rodar apenas o comando node nomeDoArquivo.js. Se ainda assim você preferir usar o nodemon basta utilizar o comando que você usou anteriormente nodemon nomeDoArquivo.js e quando quiser parar a execução basta combinar as teclas Ctrl + C
Answer: Quando você quiser parar qualquer programa em execução no terminal, você ultiliza Ctrl + C


FluentPDO é seguro?

Question: Alguém que já chegou a usar o FluentPDO, sabe me informar se ele é seguro em relação a SQL Injects? Tudo bem que ele usa PDO, mas de repente ele não trata os dados antes de ser enviado para a base de dados.
E caso ela for segura, pretendo estudá-la para desenvolver minha própria model utilizando PDO.
Answer: Depende da forma como ele é usado. Observando os exemplos na página linkada, temos:
syntax                           description
$table->where("field", "x")      Translated to field = 'x'
$table->where("field > ?", "x")  bound by PDO

Como você pode ver, o primeiro caso simplesmente coloca o valor utilizado na query, sem nenhum tratamento adicional. Se você usar um valor tipo:
$table->where("field", "Robert'); DROP TABLE Students;--")

Então ele será colocado na query, e você sofrerá uma Injeção de SQL. Entretanto, se você usar a segunda forma:
$table->where("field = ?", "Robert'); DROP TABLE Students;--")

Então a ' no valor será "escapada", e seu sistema estará seguro.
Em resumo, usar FluentPDO não vai automaticamente tornar seu sistema seguro ou inseguro, é necessário levar cada chamada da API em consideração, caso a caso, ao determinar a segurança da aplicação.
Comment: Grato pela resposta! :)

FluentPDO é seguro?


Fundamental group of $\mathbb{C}^2\setminus \Delta?$

Question: Let $\Delta=\{(z,z): z\in \mathbb{C}\}$. What will be the fundamental group of $\mathbb{C}^2\setminus \Delta?$
I am unable to proceed at all. Please give me a hint.
Comment: Have you considered thinking of $\mathbb C^2$ as $\mathbb R^4$?
Comment: Yeah, if I will take $\mathbb{C}^2$ as $\mathbb{R}^4$ then the space is same as $\mathbb{R}\times (\mathbb{R}^3\setminus \mathbb{R})$. But then I don't know what to do.
Comment: $\Delta$ is the two-plane, with basis $(1,0,1,0), (0,1,0,1)$. Now do a basis change...
Answer: By using a linear transformation, we see that
$\Bbb C^2\setminus\Delta$ is homeomorphic to $\Bbb C^2\setminus(\Bbb C
\times\{0\})$. This is homotopy equivalent to $\Bbb C\setminus\{0\}$
which in turn is homotopy equivalent to the circle $S^1$.
Comment: I am unable to get the Homotopy between $\mathbb{C}^2\setminus (\mathbb{C}\times \{0\})$ to $\mathbb{C}\setminus \{0\}$.