What do the covariance function really tell us?

Question: Let the covariance function be defined as $C(s,t)=\mathbb{E}(X_{s}X_{t})-\mathbb{E}(X_{s})\mathbb{E}(X_{t})$. I seen atleast two places where authors claim that this function together with the mean "characterises" a square integrable process up to a isometry of $L^{2}(\Omega,\mathcal{A},P)$ for fixed $P$.
I cant really see why this is the case since even if we know $C(s,t)$ we still now nothing about the finite dimensonal distributions. This could be the covariance between any kind of variables.
These are the places
https://www.amazon.com/Course-Theory-Stochastic-Processes-Wentzell/dp/0070693056 ,
page 17
https://www.amazon.com/Introduction-Stochastic-Control-Electrical-Engineering/dp/0486445313/ref=sr_1_1?s=books&ie=UTF8&qid=1521619878&sr=1-1&keywords=stochastic+control
page 26
Update
In Astrom he adds weak stationarity, but I cant find anything like this in Wentzell tho, here is that text,
Comment: Could you please name these two places where you found this claim?
Comment: @Cm7F7Bb done :)
Comment: One important example where $C(s,t)$ does determine the finite dimensional distributions is when the process is Gaussian. In general it is absolutely wrong to make such a claim.
Comment: @KaviRamaMurthy even if $P$ is given?
Comment: Suppose $\{X_t\}$ and  $\{Y_t\}$ have mean $0$ and the same covariance function $C(s,t)$. We can define $T(\sum c_j Xt_j)= T(\sum c_j Yt_j)$ to get a linear map which preserves norm. This gives an $L^{2}$ isometry from the closed subspace of $L^{2}$ spanned by $\{X_t\}$ onto the one spanned by $\{Y_t\}$. However, these two subspaces are not related and I don't see how you can get an isometry on the whole of $L^{2}$.
Comment: The question takes about isometry of $L^{2}$. This means we are talking about isometry with respect to the $L^{2}$ norm.
Comment: The statement on page 17 of Aströms Book refers to "Normal" or "Gaussian" Processes. These are indeed characterised by their mean and covariance function. Are you sure there is a more general statement? If so where?
Comment: @gg WOW, it is actually somting written about this in Astrom on page 17 aswell. However this is the page in Wentzell. The statement that I am talking about in Astrom is on page 26, he only assumes weak stationarity, this should be added above however.
Answer: First, we also require that the mean of the two processes are the same, otherwise if we set $\Omega=\{a,b\}, \mathbb{P}(\{a\})=\frac{1}{2}, \mathbb{P}(\{b\})=\frac{1}{2}$ and set
$$\forall n\in \mathbb{N}, X_n(\omega)=1$$
and
$$\forall n\in \mathbb{N}, Y_n(\omega)=0,$$
we have that
$$\forall m,n \in \mathbb{N}, \operatorname{cov}(X_m,X_n)=0=\operatorname{cov}(Y_m,Y_n),$$
but
$$\forall n \in \mathbb{N}, \|X_n\|_2=1\neq0=\|Y_n\|_2,$$
so it can't exist $\Phi : L^2(\mathbb{P})\rightarrow L^2(\mathbb{P})$ such that $\forall f \in L^2(\mathbb{P}), \|\Phi(f)\|_2=\|f\|_2$ and $\forall n \in \mathbb{N}, \Phi(X_n) = Y_n$, otherwise:
$$1=\|X_1\|_2=\|\Phi(X_1)\|_2=\|Y_1\|_2=0,$$
absurd.
Second, notice that if we interpret the term isometry as a linear map from $L^2$ onto itself such that $\forall f\in L^2, \|\Phi(f)\|_2=\|f\|_2$, than the following provides a counterexample. Define the processes $X$ and $Y$, indexed by $\mathbb{Z}$, on the set $\Omega:=[-\pi,\pi]$, equipped with the normalized Lebesgue measure $\operatorname{d}\mathbb{P}=\frac{\operatorname dm}{2\pi}$, as $\forall n\in \mathbb{Z}, \forall \omega \in [-\pi,\pi], X_n(\omega)=e^{in\omega}$ and $\forall n >0, \forall \omega \in [-\pi,\pi], Y_n(\omega)=e^{i(n+1)\omega}$ and $\forall n\le0, \forall \omega \in [-\pi,\pi], Y_n(\omega)=e^{int}$.
Notice that both processes have the same mean and the same covariance, because $$ \forall n \in \mathbb{Z} \backslash \{0\}, \mathbb{E}(X_n)=0=\mathbb{E}(Y_n)$$ and $$\mathbb{E}(X_0)=1=\mathbb{E}(Y_0)$$ and $$\forall m,n\in\mathbb{Z}, \operatorname{Cov}(X_m,X_n)=\delta_{m,n}=\operatorname{Cov}(Y_m,Y_n).$$ Then if there exists a linear map $\Phi$ of $L^2$ onto itself such that $\forall f\in L^2, \|\Phi(f)\|_2=\|f\|_2$ and $\forall n\in \mathbb{Z}, \Phi(X_n)=Y_n$, get $f\in L^2(\mathbb{P})$ such that $\Phi(f)=X_1$. Then being $(X_n)_{n\in\mathbb{Z}}$ an orthonormal base of $L^2(\mathbb{P})$, we have:
$$X_1=\Phi(f)=\Phi(\sum_{n\in\mathbb{Z}}\langle f,X_n\rangle X_n)=\sum_{n\in\mathbb{Z}}\langle f,X_n\rangle\Phi(X_n)=\sum_{n\in\mathbb{Z}}\langle f,X_n\rangle Y_n,$$
and so:
$$1=\langle X_1,X_1\rangle=\langle\sum_{n\in\mathbb{Z}}\langle f,X_n\rangle Y_n,X_1\rangle=\sum_{n\in\mathbb{Z}}\langle f,X_n\rangle\langle Y_n,X_1\rangle=\sum_{n\in\mathbb{Z}}\langle f,X_n\rangle 0=0,$$
absurd.
Then we can't interpret the term isometry in this manner.
However, also if we interpret the term isometry dropping the surjectivity condition, i.e. as a linear map from $L^2$ into itself such that $\forall f\in L^2, \|\Phi(f)\|_2=\|f\|_2$, we can't require that $\forall t, \Phi(X_t) = Y_t$.  In fact, there are examples where such a map doesn't exist. For, get $S=Y$ and $T=X$, where $X$ and $Y$ are as in the previous example. Then if $\Phi$ satisfies these requiments so that $\forall n \in \mathbb{Z}, \Phi(S_n)=T_n$, then $$\overline{\operatorname{span}(\{\Phi(S_n)\}_{n\in\mathbb{Z}})}=\overline {\operatorname{span}(\{T_n\}_{n\in\mathbb{Z}})}=L^2(\mathbb{P})$$
and so
$$\Phi(T_1)\in \overline{\operatorname{span}(\{\Phi(S_n)\}_{n\in\mathbb{Z}})},$$
so
$$\Phi(T_1)=\sum_{n\in\mathbb{Z}} \langle \Phi(T_1),\Phi(S_n)\rangle\Phi(S_n)=\Phi\left(\sum_{n\in\mathbb{Z}} \langle \Phi(T_1),\Phi(S_n)\rangle S_n\right),$$
so
$$\Phi\left(T_1-\sum_{n\in\mathbb{Z}} \langle \Phi(T_1),\Phi(S_n)\rangle S_n\right)= \Phi(T_1)-\Phi\left(\sum_{n\in\mathbb{Z}} \langle \Phi(T_1),\Phi(S_n)\rangle S_n\right)=0,$$
but
$$T_1-\sum_{n\in\mathbb{Z}} \langle \Phi(T_1),\Phi(S_n)\rangle S_n = T_1-\sum_{n\le 0} \langle \Phi(T_1),\Phi(S_n)\rangle S_n + \sum_{n\ge 1} \langle \Phi(T_1),\Phi(S_n)\rangle S_n  =  T_1-\sum_{n\le 0} \langle \Phi(T_1),\Phi(S_n)\rangle T_n + \sum_{n\ge 1} \langle \Phi(T_1),\Phi(S_n)\rangle T_{n+1} \neq 0.$$
Then $\Phi$ isn't injective, while every isometry is injective, absurd.
So we have to interpret the result in another manner again. The working way is: there exists a linear map of $L^2$ into itself such that $\forall f\in L^2, \|\Phi(f)\|_2=\|f\|_2$ and either:

$\forall t, \Phi(X_t) = Y_t$ or
$\forall t, \Phi(Y_t) = X_t.$

Now, let's prove the result when $L^2(\Omega,\mathcal{A},\mathbb{P})$ is separable and, say, the index set is $[0,+\infty)$. We can assume that $\exists t\in[0,+\infty), X_t\not\equiv 0$, otherwise the conclusion immediatly follows, being the two processes identically zero.
Also the finite dimensional case is pretty straightforward, so we assume that we are in the infinite dimensional case.
Claim 1: there exists $\{t_n\}_{n\in\mathbb{N}}\subset[0,+\infty)$ such that:

$\{X_{t_n}\}_{n\in\mathbb{N}}$ is linear independent;
$\overline{\operatorname{span}(\{X_{t_n}\}_{n\in\mathbb{N}})}=\overline{\operatorname{span}(\{X_t\}_{t\in{[0,+\infty)}})}=:V.$

Proof: since $L^2(\Omega,\mathcal{A},\mathbb{P})$ is separable, so is $V$ too. Then choose a sequence $\{h_n\}_{n\in\mathbb{N}}$ dense in $V$. Then, for each $n\in\mathbb{N}$ there exists a sequence $\{g_{n,k}\}_{k\in\mathbb{N}}\subset {\operatorname{span}(\{X_t\}_{t\in{[0,+\infty)}})}$ such that: $$\forall n\in\mathbb{N}, \|g_{n,k}-h_n\|\rightarrow 0, k\rightarrow \infty.$$
Then, for each $n,k\in\mathbb{N}$ there exist $t_{n,k,1},...,t_{n,k,m_{n,k}}\in[0,+\infty)$ such that
$$ g_{n,k} \in \operatorname{span}(X_{t_{n,k,1}},...,X_{t_{n,k,m_{n,k}}}).$$
Then, since denumerable union of denumerable set is denumerable, we have that: $$\cup _{n\in\mathbb{N}} \cup_{k\in\mathbb{N}} \cup _{j=1}^{m_{n,k}} \{X_{t_{n,k,j}}\}$$
is denumerable and so we can extract a maximal (denumerable) subset of linear independent vectors from this set, say $$\{X_{t_n}\}_{n\in\mathbb{N}},$$  obtaining
$$\overline {\operatorname{span}(\{X_{t_n}\}_{n\in\mathbb{N}}} =   \overline {\operatorname{span}(\cup _{n\in\mathbb{N}} \cup_{k\in\mathbb{N}} \cup _{j=1}^{m_{n,k}} \{X_{t_{n,k,j}}\})}\\ = \overline {\operatorname{span}(\cup _{n\in\mathbb{N}} \cup_{k\in\mathbb{N}} \{g_{n,k}\})} = \overline {\cup _{n\in\mathbb{N}} \{h_{n}\}}=V,$$
and so the claim is proved.
Claim 2: $\{Y_{t_n}\}_{n\in\mathbb{N}}$ is linear independent;
Proof: first, notice that because $X$ and $Y$ have the same mean and the same covariance matrix, then:
$$\forall s,t\in[0,+\infty), \langle X_s,X_t\rangle=\operatorname{cov}(X_s,X_t)+\mathbb{E}(X_s)\mathbb{E}(X_t) \\ =\operatorname{cov}(Y_s,Y_t)+\mathbb{E}(Y_s)\mathbb{E}(Y_s)=\langle Y_s,Y_t\rangle.$$ Then, if $n\in\mathbb{N}$, we have that the Gram-matrix of $X_{t_1},...,X_{t_n}$ and of $Y_{t_1},...,Y_{t_n}$ coincide, i.e. $$(\langle X_{t_h}, X_{t_k}\rangle)_{h,k\in\{1,...,n\}} = (\langle Y_{t_h}, Y_{t_k}\rangle)_{h,k\in\{1,...,n\}}.$$
Then, being $X_{t_1},...,X_{t_n}$ linear independent, their Gram-matrix is invertible, then so is the Gram-matrix of $Y_{t_1},...,Y_{t_n}$, and then $Y_{t_1},...,Y_{t_n}$ are linear independent, and so the claim is proved.
Now, use Gram-Schmidt orthonormalization process, to build an orthonormal base $\{e_n\}_{n\in\mathbb{N}}$ of $V$ such that $$X_{t_1}\in \operatorname{span}(e_1), X_{t_2}\in \operatorname{span}(e_1,e_2), X_{t_3}\in \operatorname{span}(e_1,e_2,e_3),..., X_{t_n}\in \operatorname{span}(e_1,...,e_n),...$$
Do the same thing in $\overline{\operatorname{span}(\{Y_{t_n}\}_{n\in\mathbb{N}})}$, i.e. build an orthonormal base $\{f_n\}_{n\in\mathbb{N}}$ of $\overline{\operatorname{span}(\{Y_{t_n}\}_{n\in\mathbb{N}})}$ such that $$Y_{t_1}\in \operatorname{span}(f_1), Y_{t_2}\in \operatorname{span}(f_1,f_2), Y_{t_3}\in \operatorname{span}(f_1,f_2,f_3),..., Y_{t_n}\in \operatorname{span}(f_1,...,f_n),...$$
Then there exists an isometry $\Phi$ from $V$ onto $\overline{\operatorname{span}(\{Y_{t_n}\}_{n\in\mathbb{N}})}$ such that:
$$\forall n \in \mathbb{N}, \Phi(e_n)=f_n.$$
Claim 3:

$\forall t\in[0,+\infty), \forall n\in \mathbb{N}, \langle X_t, e_n \rangle = \langle Y_t, f_n \rangle.$
$\overline{\operatorname{span}(\{Y_{t_n}\}_{n\in\mathbb{N}})}=\overline{\operatorname{span}(\{Y_t\}_{t\in[0,+\infty)})}=:W$

Proof: first, remember that because $X$ and $Y$ have the same mean and the same covariance matrix, then:
$$\forall s,t\in[0,+\infty), \langle X_s,X_t\rangle=\langle Y_s,Y_t\rangle$$
Now, notice that if $j\in\mathbb{N}$ and $e_j= \sum_{k=1}^j a_{j,k} X_{t_k}$, then $f_j=\sum_{k=1}^j a_{j,k} Y_{t_k}$, as you can see by determinant formula for $e_j$ and $f_j$, so
$$\forall j,n\in\mathbb{N}, \langle X_{t_n},e_j\rangle = \langle X_{t_n},\sum_{k=1}^j a_{j,k} X_{t_k}\rangle = \sum_{k=1}^j \overline{a_{j,k}} \langle  X_{t_n}, X_{t_k}\rangle \\ = \sum_{k=1}^j \overline{a_{j,k}} \langle Y_{t_n}, Y_{t_k}\rangle = \langle Y_{t_n}, \sum_{k=1}^j a_{j,k} Y_{t_k}\rangle = \langle Y_{t_n}, f_j\rangle.$$
Then, if $t\in[0,+\infty)$:
 $$X_t = \sum_{j=1}^{+\infty} \langle X_t , e_j \rangle e_j  = \sum_{j=1}^{+\infty} \langle X_t , \sum_{k=1}^j a_{j,k} X_{t_k} \rangle e_j = \sum_{j=1}^{+\infty} \sum_{k=1}^j \overline{a_{j,k}} \langle X_t ,  X_{t_k} \rangle e_j,$$
and there exists $Z\in \overline{\operatorname{span}(\{Y_{t_n}\}_{n\in\mathbb{N}})}^{\perp}$ such that:
$$Y_t = Z + \sum_{j=1}^{+\infty} \langle Y_t , f_j \rangle f_j  =
Z + \sum_{j=1}^{+\infty} \langle Y_t , \sum_{k=1}^j a_{j,k} Y_{t_k} \rangle f_j,  = Z + \sum_{j=1}^{+\infty} \sum_{k=1}^j \overline{a_{j,k}} \langle Y_t ,  Y_{t_k} \rangle f_j$$
so, if $n\in\mathbb{N}$, then:
$$\langle X_t, e_n \rangle = \langle \sum_{j=1}^{+\infty} \langle X_t , \sum_{k=1}^j a_{j,k} X_{t_k} \rangle e_j , e_n \rangle = {\sum_{j=1}^{+\infty} \sum_{k=1}^j \overline{a_{j,k}} \langle X_t ,  X_{t_k} \rangle \langle e_j , e_n \rangle = \sum_{j=1}^{+\infty} \sum_{k=1}^j \overline{a_{j,k}} \langle Y_t ,  Y_{t_k} \rangle \langle f_j , f_n \rangle} \\ = \langle \sum_{j=1}^{+\infty} \langle Y_t , \sum_{k=1}^j a_{j,k} Y_{t_k} \rangle f_j , f_n \rangle = \langle Z+ \sum_{j=1}^{+\infty} \langle Y_t , \sum_{k=1}^j a_{j,k} Y_{t_k} \rangle f_j , f_n \rangle = \langle Y_t, f_n \rangle$$
and so the first part of the claim is proved.
For the second, just note that $$\|Y_t\|_2^2=\|X_t\|_2^2=\|\sum_{j=1}^{+\infty} \sum_{k=1}^j \overline{a_{j,k}} \langle X_t ,  X_{t_k} \rangle e_j\|_2^2 = \sum_{j=1}^{+\infty} | \sum_{k=1}^j \overline{a_{j,k}} \langle X_t ,  X_{t_k} \rangle|^2 \\ = \sum_{j=1}^{+\infty} | \sum_{k=1}^j \overline{a_{j,k}} \langle Y_t ,  Y_{t_k} \rangle|^2 = \|\sum_{j=1}^{+\infty} \sum_{k=1}^j \overline{a_{j,k}} \langle Y_t ,  Y_{t_k} \rangle f_j\|_2^2 = \|\sum_{j=1}^{+\infty} \langle Y_t , f_j \rangle f_j\|_2^2  \\ \le \|\sum_{j=1}^{+\infty} \langle Y_t , f_j \rangle f_j\|_2^2 + \|Z\|_2^2 = \|Z+\sum_{j=1}^{+\infty} \langle Y_t , f_j \rangle f_j\|_2^2 = \|Y_t\|_2^2,$$
and so $Z=0$, i.e. $$Y_t \in \overline{\operatorname{span}(\{Y_{t_n}\}_{n\in\mathbb{N}})}.$$
Being $t$ arbitrary, we obtain
$$\overline{\operatorname{span}(\{Y_{t_n}\}_{n\in\mathbb{N}})}=\overline{\operatorname{span}(\{Y_t\}_{t\in[0,+\infty)})},$$
i.e. the last part of the claim is proved.
Notice that:
$$\forall t\in[0,+\infty), \Phi(X_t)=\Phi(\sum_{n\in\mathbb{N}} \langle X_t, e_n\rangle e_n)=\sum_{n\in\mathbb{N}} \langle X_t, e_n\rangle \Phi(e_n)\\=\sum_{n\in\mathbb{N}} \langle X_t, e_n\rangle f_n=\sum_{n\in\mathbb{N}} \langle Y_t, f_n\rangle f_n=Y_t.$$
Now either $\dim (V^\perp)\le\dim (W^\perp)$ or $\dim (W^\perp)<\dim (V^\perp)$. Assume that $\dim (V^\perp)\le\dim (W^\perp)$ (if the other case holds, just switch the role of $X$ with the role of $Y$, the role of $V$ with the role of $W$, the role of $V^\perp$ with the role of $W^\perp$ and the role of $\Phi$ with the role of $\Phi^{-1}$ in what follows).
Then there exists an isometry $\Psi$ from $L^2(\Omega,\mathcal{A},\mathbb{P})$ into $L^2(\Omega,\mathcal{A},\mathbb{P})$ such that:

$\forall v \in V, \Psi(v)=\Phi(v);$
$\Psi(V^{\perp})\subset W^{\perp}$.

Now, noticing that
$$\forall t\in[0,+\infty), \Psi(X_t) = \Phi(X_t) = Y_t,$$
we have finally got the conclusion.
Some final remarks: about your doubt on how such an isometry could be possible knowing nothing about the distributions of the involved random variables, notice that being isometric has nothing to do with having the same distribution. For example in $\Omega=\{0,1\}$ with $\mathbb{P}(\{0\})=1/2=\mathbb{P}(\{1\})$, then $X(0)=1, X(1)=1$ has the same $L^2(\mathbb{P})$ norm of $Y(0)=-1, Y(1)=1$, but the range of the first is $\{1\}$ while the range of the second is $\{-1,1\}$, so they have not the same distribution. Actually, covariance is a scalar product on $L^2(\mathbb{P})/\mathbb{R}$, so it is a way of talking about length and angles in the space of square integrable random variables, once we have identified two random variables that differ by a constant.
Comment: For example in claim 2, having the same covariance function and the same mean implies that the matrix of $L^2(\mathbb{P})$ products  $(\langle X_{t_i},X_{t_j}\rangle)_{i,j\in\{1,...,n\}}$ is the same matrix of $(\langle Y_{t_i},Y_{t_j}\rangle)_{i,j\in\{1,...,n\}}$ and being this matrix not-degenerate by claim 1 ($X_{t_1},...,X_{t_n}$ are linear independent) it follows that $Y_{t_1},...,Y_{t_n}$ are linear independent
Comment: and for claim 4, the claim is obviously true for $t=t_k$ for any $k\in\mathbb{N}$, again using the fact that the mean and the covariance matrix are the same, then you should extend by density the result for all $t$.
Comment: I've edited again, because i've just realized that in your question you didn't mention that the involved processes have the same mean, a thing that i've assumed in my answer... This is obviously crucial, in fact, for example, the zero random variable and the identically one random variable have the same variance but there isn't any isometry that sends a random variable of $L^2(\mathbb{P})$ of norm 0 in a random variable of $L^2(\mathbb{P})$ of norm 1
Comment: well, actually I think that we have misunderstood what the authors mean with the term "isometry of $L^2$", because I interpreted it as a isometry of $L^2$ onto $L^2$ and the following is a counterexample. Take $\Omega:=[0,2\pi]$  with the normalized Lebesgue measure (i.e. the Lebesgue measure divided by $2\pi$) as $\mathbb{P}$. Then take $\mathbb{Z}$ as the index set. Define the process $X$ by  $X_n:=e^{int}$ and the process $Y$ by $Y_n:=e^{i(n+1)t}$ if $n\ge0$ and $Y_n:=e^{int}$ if $n<0$. Then $X$ and $Y$ have both the same mean and covariance.
Comment: However the map $\Phi$ defined by $\Phi(X_n)=Y_n$ isn't a surjective isometry of $L^2(\mathbb{P})$ (there isn't any random variable $f$ such that $\Phi(f)=1$), so the result, as I interpreted, is plainly false. However, if we get rid of the surjective requirement, i.e. we don't need to prove the false claim 3, than the result clearly holds. I'll edit what I've written to give you a complete answer.
Comment: Done, if there is something that it's still not clear, just tell me
Comment: @user1 It is not the notion of isometry that changes, and isometry is still a linear map $\Phi :L^2\rightarrow L^2$ such that $\forall f \in L^2, \|\Phi(f)\|_2 = \|f\|_2$. The point is that, for some choice of $X$ and $Y$, you can't guarantee the existence of a linear map $\Phi :L^2\rightarrow L^2$ such that $\forall f \in L^2, \|\Phi(f)\|_2 = \|f\|_2$ and $\forall t, \Phi(X_t)\ = Y_t$ (see the second part of the example 2).
Comment: However, if for that specific choice of $X$ and $Y$ you are unfortunate, i.e. it happens that such an isometry doesn't exist, then you turn again to be lucky if you switch the role of $X$ with the role of $Y$, i.e. if you look for an isometry $\Phi$ such that $\forall t, \Phi (Y_t) = X_t$. Then, as proved in the answer, you can guarantee the existence of such an isometry.
Comment: As you can see in the second part of the second example, with that choice of $S$ and $T$, it doesn't exist an isometry $\Phi$ such that $\forall t, \Phi(S_t)=T_t$, but it exists an isometry $\Phi$ such that $\forall t, \Phi(T_t)=S_t$ (the first part of the second example).
Comment: Where did you use that $X$ and $Y$ have the same mean and covariance function? And why is Claim 4 true?
Comment: Anyway I think that you are worried about the simplest things to check (just work out the calculations), the real problem here is claim 3.
Comment: @Bob let us assume that we have a mean function condition aswell, just as Wentzell writes when he concludes that the isomerty fixes the identity element. Ill read the answer carefully in a while.
Comment: @gg i've worked out the proof of the claim that puzzled you
Comment: All claims are now proved
Comment: So I started to read the answer, I dont think isometries on infinite dimensional spaces have to be surjective. Consider the shift on the space of seqeunces for instance, this is called an isometry. However it dosnt hurt to mention this for other readers tho.
Comment: I've found a typo in the second example, I'm on the way of editing
Comment: @user1 edited, if you find other typos somewhere (there's a lot of indexes so this could be the case), feel free of editing or tell me
Comment: I dont understand the last notion of isometry, the previous definition i.e that $\Phi(X_{t})=Y_{t}$ for all $t$ seams contained in it as one of the conditions in an "or statement" is enough to make it true. Or do you mean something else by the second defnition of isometry?
Comment: @Bob got it, thanks.
Comment: Thanks for the outline, very nice. I did however, by accident award the bounty to the wrong answer while scrolling up as his was so short. I think I can get you 100 points in some other way if you want to. Let me know!
Comment: @user1 I think that it is the best that you ask advice to some moderator, I don't want to have anything to do with non-trasparent procedures of points exchange. If there's nothing to do, at the end they are just points... I had fun in thinking about this answer
Comment: @user1: no worry, have a good day
Answer: If two processes $\{X_t\}$ and $\{Y_t\}$  in $L^{2}$ have the same mean and covariance then there exists an isometric isomorphism of $L^{2}(P)$ onto itself which maps $X_t$ to $Y_t$. As mentioned in my earlier comment we can construct an isometry between the closed subspaces spanned by the two processes. These subspaces have the same orthogonal dimension so it is possible to extend the isometry to the whole of $L^{2}$. It is not enough to have the same covariance; the means also have to be equal.


Words to describe this Dance Music texture/effect

Question: So we always have like in dance music 4/4 and like 4 kicks in one bar with two claps or snares on every second beat going and let's say I add some bassline that plays totally different rhythm/pulse (not sure for correct term) and now they are playing against each other, making music sound more interesting but still flow together. What is it called in music? I know that this is not polymeter or polyrhythm. Then I keep adding more instruments like strings and drones playing some even more different rhythms that plays like one note a bar let's say and some arps that plays 1/16 a bar. I'm just looking for definition of this and where I could learn more how to layer these different voices playing against each other in different rhythms/pulses for interesting variation.
I have an example of this first track in the beginning:

There is drums, man's voice saying "mhmm" every 4 beats, some different rhythm bells in the background and some other stuff going on.
Answer: Counterpoint or counter-rhythm.
Some feel 'counterpoint' should only be used with the mean 'point against point' meaning pitch against pitch and use the term 'counter-rhythm' to mean the combination of more than one rhythm.
Comment: NB: *punctum contra punctum*, from which we get the word "counterpoint," literally means "note against note" in Latin. (The relation is especially clear in the German *Kontrapunkt*.)
Comment: When I read Piston's _Counterpoint_ the big take away for me was independence of lines will be more pronounced from rhythmic difference than pitch difference. I suppose that was just my personal impression, and I shouldn't use 'counterpoint' instead of 'counter-rhythm.'
Answer: In a classical sense, it would make sense to use the term "counterpoint" for the distinct melody lines all sounding independent. In a more general and often rhythmic sense, it could also be called polyphony. Also, "layered texture" might be a more contemporary description of the effect.
I advise everyone that it's not extremely important to have classical music terminology in this kind of music; no one's going to know what you're talking about.
Comment: These aren't 'classical' terms. Maybe 'technical' or 'scholarly' terms are better words. But the term describe much more than classical style. I figured that when the OP mentioned 'polyrhythm' they were looking for technical terminology. But, I do agree with you that such technical terms might not be the best way to talk about this style of music.
Comment: @MichaelCurtis So if we have counterpoint as in classical music having two independent melodies playing simultaneously, that means we have a polyrhythm happening too, right?
Comment: @Limpuls, not necessarily. The two lines could have different pitch contours, but use the same rhythm. Those two lines would be considered less independent than if they had different rhythms. Also, take care the the term 'polyrhythm' versus 'counterrhythm.' Polyrhythm is a kind of metrical grouping contrast. In Bach's counterpoint polyrhythm would be unusual. In modern dance music polyrhythm would be common.
Comment: @MichaelCurtis Yes, I just find out that polyrhythm is two or more same bar/metre length loops playing at the same time but having different amount of notes that are not divisions of the time measure. Like 4/4 kick drum playing against 3/4 hi hats triplets or 6/8, etc. Thanks for clearing things out for me.
Answer: If you have two "layers" or tracks with the same loop lengths but a pattern of accenting that is fully or partially offset, perhaps you could say that is an example of syncopation. If you have two layers with similar but offset metres that sustain for a long period of time, I'm not entirely sure why that couldn't be called a polyrhythm.
If the pattern lengths of two repeating layers are different, again, I think you might describe that as a polyrhythm - possibly more specifically as a cross-rhythm. Sustained hemiola is an example of cross-rhythm often found in dance music.
Comment: Yeah,  I read that syncopation is unexpected rhythm changes, like upbeat or downbeat.
Regarding polyrhythm, I'm still not sure what it means. What do you mean by offset metres? Like if one layer is playing 4 bars long melody and some other layer is playing some other instrument for 2 bars?


Pytest for my function that validates json file contents

Question: I have a Python function that creates & appends content to a json file on the disk. Wanted to develop test cases using pytest.
Json snippet:
{
    "pictures": [
        "/home/mywork/pictures/pictures.zip",
        "/home/mywork/pictures/record.json"
    ],
    "lab_results": [
        "/home/mywork/lab_results/lab_results.zip",
        "/home/mywork/lab_results/private/results.json"
    ]
    ....
  }

How should I assert availability of files on the disk? I mean, json values are the physical files on the disk & would like to throw an error if the file is missing or of different pattern/format.
Is there a recommended way of doing that or any pre available module from pytest?
Comment: Checking availability of files on disk should be part of your exception handling in your actual application, rather than a function of pytest.  Your pytest should be checking that your program  properly handles the files missing condition, by supplying mock file systems to your code.
Answer: Best practice would be to mock the filesystem calls and run your tests without touching the filesystem.
If you absolutely need to run tests against the filesystem pytest provides the tmp_path fixture to provide a unique temporary directory for you to use during testing.
You would then follow basic test practices of setting up your test environment, (in this case adding the relevant files to the directory), triggering a behavior (reading from or writing to files in the directory), then asserting that things happened as expected.


Pegar conteúdo de campos de texto através do ID usando JavaScript

Question: Tenho um checkbox que na hora que seleciono e busco o valor no campo type="text", um dos campos está funcionando perfeitamente mais o segundo campo não funciona.

function pega(){
 var opcao = document.getElementById("opcao");
 var numero1 = document.getElementById("number1").value;
 var numero2 = document.getElementById("number2").value;

 if (opcao.checked == true){
  document.getElementById("total").innerHTML = numero1;
 }
  /*

 if (opcao.checked == true){
  document.getElementById("total").innerHTML = numero2;
 }*/

}
<input type="checkbox" id="opcao" name="Pacote" value="primeira opcao" onclick ="pega()">
<input type="text" id="number1" />

<input type="checkbox" id="opcao" name="Pacote" value="primeira opcao" onclick ="pega()">
<input type="text" id="number2" />

Minha ideia depois é calcular os dois campos, mas preciso saber se dessa forma que estou fazendo irei conseguir?
Comment: Você está usando o mesmo id para dois elementos diferentes, não faça isso. Nomeie cada um como opcao1 e opcao2, depois cheque se eles estao checked, como ja esta fazendo.
Comment: Primeiro, acho que você tinha que aceitar a resposta do @Sergio. Depois, por que você não usa jQuery? Por que você não coloca ***labels*** nos ***checkbox*** e pega o valor com `$("input[type='checkbox']").val();`ou outra variante jQuery, como `$(#idCheckbox).val();`? Se ao selecionar um ***checkbox*** o outro deve ser desmarcado, por que não usar `input[type="radio"]`?
Answer: Em HTML os IDs têm de ser únicos. Para agrupar elementos usa-se classes (class)  e para identificar de maneira unica usa-se id.
Assim o problema no teu código é que .getElementById("opcao") só vai retornar um elemento, o primeiro que encontrar.
Podes corrigir isso dando IDs diferentes, ou podes usar o facto de que quando a função pega pode receber o argumento event que é o evento que dispara esse onclick. E aí, a propriedade .target que te diz qual o elemento clicado. Assim opção = e.target;
Outra opção é fazer assim, que lê os valores de todos os checkbox independentemente de quantos forem:
var opcoes = document.querySelectorAll('input[type="checkbox"]');
var inputs = document.querySelectorAll('input[type="text"]');

function lerValores(els) {
  return [].map.call(els, function (el) {
    return el.checked;
  });

}

function pega(e) {
  var total = 0;
  lerValores(opcoes).forEach(function (checked, i) {
    if (checked) total += parseInt(inputs[i].value, 10);;
  });
  document.getElementById("total").innerHTML = total;
}

Exemplo: http://jsfiddle.net/pfb7sw78/
Comment: Sergio resolveu meu problema, mais não entendi o que esse cara faz ?

  function levarValores(els){
    return [].map.call(els, function(el) {
      return el.checked;
    });
  }
Comment: @DiBoa Essa função pega os valores das checkbox marcadas. Esses valores serão usados na outra função `pega ()`
Answer: Acredito que o que você deseja seja isso:

function pega(){
    if (document.getElementById("opcao1").checked == true) {
        document.getElementById("total").innerHTML = document.getElementById('number1').value;
      }
    if (document.getElementById("opcao2").checked == true) {
        document.getElementById("total").innerHTML = document.getElementById('number2').value;;
      }

}
<input type="checkbox" id="opcao1" name="pacote1" value="number1" onclick ="pega()">
<input type="text" id="number1" />

<input type="checkbox" id="opcao2" name="pacote2" value="number2" onclick ="pega()">
<input type="text" id="number2" />


How does the theorem 2 of algebra of limits contradict in this Q?

Question: Q: $\lim _{x \rightarrow 1} \frac{x^{15}-1}{x^{10}-1}$
Solution in my textbook using theorem 2 of algebra of limits I.e $\lim _{x \rightarrow a} \frac{x^{n}-a^{n}}{x-a}=n a^{n-1}$ .
$\begin{aligned} \lim _{x \rightarrow 1} \frac{x^{15}-1}{x^{10}-1} &=\lim _{x \rightarrow 1}\left[\frac{x^{15}-1}{x-1} \div \frac{x^{10}-1}{x-1}\right] \\ &=\lim _{x \rightarrow 1}\left[\frac{x^{15}-1}{x-1}\right] \div \lim _{x \rightarrow 1}\left[\frac{x^{10}-1}{x-1}\right] \\ &=15(1)^{14} \div 10(1)^{9} \text {} \\ &=15 \div 10=\frac{3}{2} \end{aligned}$
I agree with it using the formula but I also thought of thinking how would it be solved from the long way [Inserting x = 1]
We get :
$\frac{(1)^{15}-1}{1-1} \div\left[\frac{(1)^{10}-1}{1-1}\right]$
$\rightarrow \frac{0}{0} \div \frac{0}{0}=0$
My answer is completely different from the solution of my textbook. How is that possible ?
If anyone wants to argue that we cannot put value of x = 1 just like that. There is another example in my textbook according to which , we can.
In all of them , the Q simply says: Find the limit.
1)$\begin{aligned} \lim _{x \rightarrow 2} \frac{x^{2}-4}{x^{3}-4 x^{2}+4 x} &=\lim _{x \rightarrow 2} \frac{(x+2)(x-2)}{x(x-2)^{2}} \\ &=\lim _{x \rightarrow 2} \frac{(x+2)}{x(x-2)}=\frac{2+2}{2(2-2)}=\frac{4}{0} \end{aligned}$
Here , x is tending to 2. This is a rational function.
EDIT: I will share a few more examples.

We have $\lim _{x \rightarrow 1} \frac{x^{2}+1}{x+100}=\frac{1^{2}+1}{1+100}=\frac{2}{101}$

(iii) $\lim _{x \rightarrow-1}\left[1+x+x^{2}+\ldots+x^{10}\right]=1+(-1)+(-1)^{2}+\ldots+(-1)^{10}$
Comment: Your hint is correct: "we cannot put value of $x=1$ just like that".  The limit theorems in textbooks have *hypotheses* that must be satisfied.  Here, if we want to "put value $x=1$", they are not satisfied, so we cannot.
Comment: @GEdgar How can we prove putting x = 1 is wrong ?
Comment: I would suggest watching this complete video but this can also help you understand what is [infinitesimally small](https://www.youtube.com/watch?v=RZ1Extuvcsw&t=90s)
Comment: @S.M.T it's not wrong it's just not the definition of limit $f(x=1)=\frac 00$ is right but the limit of $f(x\to1)=\frac 32$ Did limit ask you to find the $x=1?$ NO! it's $x\to1$ so why don't you try $x=0.9999999999999$ it tends to be $1$ is NOT $1$ I hope this will help you understand the very first step towards the amazing world of Calculus.
Comment: @DarshanP. K. Thanks , I will check it.
Comment: There is no such thing as 4/0.
Comment: @DanielWainfleet Yes , correct but they did put x = 2. It matters in the end if the answer comes to be defined or not defined but the process , they used , says out x = 2.
Comment: @S.M.T Can you try to include an image? Or better, can you try to type the solution provided?
Comment: @soupless I have already typed the solution.
Comment: That's it? Ok, that's totally wrong. The one-sided limits are unbounded (informally, left-hand limit $=-\infty$, and right-hand limit $=+\infty$) which means the limit does not exist.
Comment: @S.M.T No, I'm only referring to the solution to the $x=2$ limit.
Comment: @soupless 2 more examples from my book.
Comment: @S.M.T You may want to accept an answer so that your question will be removed from the Unanswered tab.
Answer: The solution you used, that is,

\begin{aligned} \lim _{x \rightarrow 1} \frac{x^{15}-1}{x^{10}-1} &=\lim _{x \rightarrow 1}\left[\frac{x^{15}-1}{x-1} \div \frac{x^{10}-1}{x-1}\right] \\ &=\lim _{x \rightarrow 1}\left[\frac{x^{15}-1}{x-1}\right] \div \lim _{x \rightarrow 1}\left[\frac{x^{10}-1}{x-1}\right] \\ &=15(1)^{14} \div 10(1)^{9} \text {} \\ &=15 \div 10 \\ &=\frac{3}{2} \end{aligned}

is correct. But the part where you replaced $x$ with $1$ is wrong.

Why is it that some limits can be solved by replacing $x$ with $a$, but some cannot? This is because of continuity. That is, some functions are "good" that solving for the limit as $x$ approaches $a$ is the same as evaluating the function at $x = a$. These functions are:

Polynomial functions, for all real $x$

Rational functions, for all $x$ in the domain

Radical functions, for all $x$ in the domain

For $\sqrt[n]{x}$ and odd $n$, $x$ can be any real number
For $\sqrt[n]{x}$ and even $n$, $x$ can be any nonnegative real number

Trigonometric functions, for all $x$ in the domain

For $\sin x$ and $\cos x$, $x$ is a real number
For $\tan x$ and $\sec x$, $x$ is a real number and $\cos x \neq 0$.
For $\cot x$ and $\csc x$, $x$ is a real number and $\sin x \neq 0$.

Exponential functions, for all real $x$

Logarithmic functions, for all $x$ in the domain

Any combination (addition, multiplication) of these functions

In summary, as long as the value of $a$ is in the domain of the function which is a combination of these through addition (including) and multiplication (including division, removing the zeroes of the denominator from the domain), we can substitute it.

Why is the limit not the same when I substituted $x = 1$ to $\frac{x^{15} - 1}{x^{10} - 1}$ and when $x$ approached $1$?
This is because $x = 1$ is not in the domain. You'll soon know what functions are "good" once continuity shows up.

See this page for more information.
Comment: Why didn't my textbook teach me that continuity earlier. I mean , it's trouble like this.
Comment: Because continuity requires limits, hence limits are first taught. However, when teaching limits, to avoid confusion, "good" functions are used but will come to the point where methods to the "good" functions will be shown to not work in general.
Comment: A function is continuous if: (1) $\lim\limits_{x \to a}f(x)$ exists; (2) $f(a)$ exists; and (3) $\lim\limits_{x \to a}f(x) = f(a)$. This is why limits are first introduced. @S.M.T
Comment: So , in all the 3 examples I provided. We can use x = a ?
Comment: @S.M.T In the second and third example, yes. We can use $x = a$ as the values are in the domain. However, in the first example, we can't do that because $x = 1$ is removed from the domain. But because we can simplify things and still not affect the limit, DanielWainfleet's method can be used although we can drop the condition "If $x \neq 1$, then -".
Answer: Let,
$$f(x) = \frac {x^{15}-1}{x^{10}-1}$$
Well, I agree with you! that the value of function $f(x = 1)$ is $ \frac {1^{15}-1}{1^{10}-1}$
But,
The value of limit of function $f(x)$ as $x \to 1$ is $\frac 32$

Limit of function: This means you take the value of the function as $x\to a$ doesn't mean $x = a $ it means it's very very very close to $a$ it's never $a$

Try this: $f(x = 0.99999) = \frac {(0.99999)^{15} - 1}{(0.99999)^{10} - 1} \approx \frac 32$
Comment: @S.M.T Thanks a lot!
Comment: This can [help you for sure](https://www.youtube.com/watch?v=RZ1Extuvcsw&t=90s)
What is infinitesimally small?
Comment: I'll be glad to help you improve my answer if you still find difficulty understanding the limit.
Comment: I gave an example below of my Q. The textbook uses limit of function & puts x = 2. How is that correct to use then ?
Comment: @S.M.T About $x = 2$?
Here they mean that there is no other way to eliminate those ruining points because of which we won't be able to remove the ruining point from the numerator and denominator

*Or else try* $x = 2 \pm \delta$ where $\delta \to 0$ like $0.000000000001$
Comment: @S.M.T see when you put $x = 1$ the answer comes to be $\frac 00$ but when you put $x = 2$ the answer came to be $\frac 40$ here they mean the answer format is not **zero over zero** $\frac 00$ that is what they tried to check if the answer is of format **zero over zero** also known as the indeterminant format $\frac 00$
Does this clear your doubt?
Comment: Thank u for being here but I'm still not getting it. Mostly because u see , I provided an example at last. There are similar examples like that too , not all of them with solution as 4/0. But all of them used the value in x that was given in the Q as tending to. & suddenly , in this Q , it says u can't do that. So , I am having difficulty in understanding why is the previous one even true.
Comment: @S.M.T I'm disappointed that I couldn't help you. Enjoy:-)
Comment: Why do u say enjoy ? I have given 2 more examples. Maybe , they can help.
Comment: @S.M.T It just I'm sick today with a killing cold and my eyes are asking me to take a rest it just I was trying to visit and answer a few simple + short questions on MSE.
I need a damn rest!!!!
Comment: Oh sure , take care. Try putting something cold on eye for some time. It really helps
Answer: $x^{15}-1=(x-1)(1+x+x^2+...+x^{13}+x^{14}).$
$x^{10}-1=(x-1)(1+x+x^2+...+x^{8}+x^{9}).$
So if $x\ne 1$ then $$\frac {x^{15}-1}{x^{10}-1}=\frac {1+x+x^2+...+x^{13}+x^{14}}{1+x+x^2+...+x^{8}+x^{9}}$$ which obviously converges to $\frac {15}{10}$ as $x\to 1.$
Comment: Why did u write , "So if x is not equal to 1"
Comment: I wrote "If $x\ne 1$" because if $x=1$ then the RHS is a number and the LHS is $0/0$, which does not exist.


How should I think about this subset of a product of projective lines?

Question: Consider the group $G = \mathrm{GL}_2(\mathbb{C})$, and it maximal torus $T$ of invertible diagonal matrices. The coset space $G/T$ should have the structure of a (smooth?) variety/scheme/manifold. Direct computation shows that $G/T$ can be described as the space
$$ G/T = \{([a:b], [c:d]) \in \mathbb{P}^1 \times \mathbb{P}^1 \mid ad - bc \neq 0\}$$
How should I think about this space? For example, there seem to be many line bundles over this space that have an infinite-dimensional space of sections, as I found by attempting to induce characters from $T$ up to $G$, but I'm not sure of the reason for this geometrically. I'm also having trouble with some basic questions: is it connected? And importantly, where can I learn the theory required to understand this? (At least at an "intuitive" level).
Comment: There are the elements of the form $\scriptstyle\begin{pmatrix}1& b \\ c & bc+1\end{pmatrix}=\begin{pmatrix}1& 0 \\ c & 1\end{pmatrix}\begin{pmatrix}1& b \\ 0 & 1\end{pmatrix}$ and some other like $\scriptstyle\begin{pmatrix}0& 1 \\ -1 & d\end{pmatrix}$
Answer: Here is a more detailed answer : there is a natural projection map $p : G/T \to \Bbb P^1$, projecting onto the first component. The fiber over $(a:b)$ is $\Bbb P^1 \backslash \{(a:b)\}$.
Such map has a nice interpretation : if $B$ is the group of upper-triangular matrices, $G/B$ can be interpreted as the complete flag variety in $\Bbb C^2$ i.e $\Bbb P^1$. The canonical map $G/T \to G/B \cong \Bbb P^1$ exhibits $G/T$ as a $B/T \cong \Bbb C$-bundle over $G/B \cong \Bbb P^1$.
This automatically shows you that $G/T$ is connected. Alternatively one could also embbed $Q = \Bbb P^1 \times \Bbb P^1$ in $\Bbb P^3$ as a quadric surface via the Segre embedding, and $G/T$ should correspond to the complement of an hyperplane section of $Q$ which is connected.
Now the tricky part comes, computing which bundle is $G/T \to G/B$. My guess is a correct approch would use something like Borel-Weil theorem (in fact the chapter about homogenous spaces in "Representation theory, a first course" by Fulton and Harris looks very nice, maybe it's a good place to looks even if they essentially look at $G/B$ for $B$ a Borel subgroup) and identify it nicely.
Since any bundle over $\Bbb P^1$ is $\mathcal O(k)$ we just need to check how many zeroes/poles has a generic section. I pick $\sigma : G/B \to G/T, (a,b) \mapsto ((a,b);(-b,a))$. This map is a rational section, with only two poles at $(1, \pm i)$. This means that $G/T \to G/B$ is the cotangent bundle of $\Bbb P^1$, namely $\mathcal O(-2)$.
Comment: Thank you for the excellent answer! I went and computed which $B$-representation the bundle $G/T \to G/B$ comes from (in the Borel-Weil sense), got a consistent answer: the character is $(-1, 1)$, the dual of $(1, -1)$ which I know to give the bundle $\mathcal{O}(2)$.
Comment: @Joppy : Thanks, this is very nice that you could deduce the results using representation theory. In fact your comment motivated me to learn more about this theorem, do you have a good reference for learn more about this ?
Comment: There are some lovely lectures by Joel Kamnitzer which contain examples of this construction: https://arxiv.org/abs/0912.0569. Fulton's "Young Tableaux" contains a construction of the irreps of $\mathrm{GL}_n$ as line bundles on the flag variety. Jantzen's "Representations of Algebraic Groups" has a discussion valid for any algebraic group, but assumes a lot more of the reader, and has almost no examples.
Comment: @Joppy : this looks perfect, thanks a lot !


Why are functors exact if they preserve all short exact sequences?

Question: If a functor $F\colon \mathcal C → \mathcal D$ of abelian categories preserves short exact sequences, why is it exact?
I know the argument is supposed to be that you can split up long exact sequences into short sequences, like it is done here.  But what then?  Say we have an exact sequence
$$M' \overset α \longrightarrow M \overset β \longrightarrow M'',$$
which we split up to receive a diagram like shown in the link above.  Next we apply $F$ to end up with a diagram of the same shape with exact diagonals – how does it follow that the vertical arrows yield an exact sequence?
Or can we prove that functors preserving short exact sequences already preserve kernels and cokernels (without the use of additivity)?  Or is this result only true for additive functors?
Comment: At the end of [this answer](http://math.stackexchange.com/a/207665/2614) to a related question, I post a link to something I wrote up (in Spanish) which contains exactly what you want. If you understand it and write it up in English and post it as an answer, I'd upvote it :)
Comment: @lenticcatachresis I neither speak nor read Spanish but I might just be able to guess my way through this with a dictionary.  With David's answer, though, this will be unnecessary.  Many thanks eitherway!
Answer: Proceeding as you say, you have a diagram
$$\begin{matrix}
\ddots &   & \vdots &  &  &  & &  &   \\
 &  \searrow & \downarrow&  &  &  & &  &  \\
 &  & A_{i-1}&  &  &  & 0&  &   \\
 &  & \pi \downarrow & \searrow^d &  &  & \downarrow &  &  \\
0 & \rightarrow & K_i & \overset{\iota}{\longrightarrow} & A_i &  \overset{\pi}{\longrightarrow} & K_{i+1} & \rightarrow & 0 \\
 &  & \downarrow &  &  & \searrow^d & \iota \downarrow & &  \\
 &  & 0 &  &  & & A_{i+1} & &  \\
 &  &  &  &  & & \downarrow & \searrow & \  \\
 &  &  &  &  & & \cdots & & \ddots   \\
\end{matrix}$$
where you know rows and columns are exact and you want to deduce the diagonal is exact. (Sorry for rotating $45^{\circ}$ from your image, but I had to do it to get the diagram with the tools available here.)
Since $\pi$ is epic (think surjective), we know that $$\mathrm{Image}(A_{i-1} \overset{d}{\longrightarrow} A_{i}) = \mathrm{Image}(A_{i-1} \overset{\pi}{\longrightarrow} K_i \overset{\iota}{\longrightarrow} A_i) =\mathrm{Image}(K_i \overset{\iota}{\longrightarrow} A_i) $$
Since $\iota$ is monic (think injective), we know that
$$\mathrm{Ker}(A_{i} \overset{d}{\longrightarrow} A_{i+1}) = \mathrm{Ker}(A_{i} \overset{\pi}{\longrightarrow} K_{i+1} \overset{\iota}{\longrightarrow} A_{i+1}) =\mathrm{Ker}(A_{i} \overset{\pi}{\longrightarrow} K_{i+1}).$$
Since the horizontal row is exact, we know $\mathrm{Image}(K_i \overset{\iota}{\longrightarrow} A_i)=\mathrm{Ker}(A_{i} \overset{\pi}{\longrightarrow} K_{i+1})$. We deduce that $\mathrm{Image}(A_{i-1} \overset{d}{\longrightarrow} A_{i}) = \mathrm{Ker}(A_{i} \overset{d}{\longrightarrow} A_{i+1})$, as desired.
Comment: Since you work in *abelian* categories, instead of 'injective / surjective' you can equally well use 'monomorphism / epimorphism' and the used properties hold.
Comment: @Jim I know that, but that is hardly enlightening and not very satisfying unless you prove/understand Mitchell's embedding theorem first which I haven't and which seems to me too much of an effort for this problem.
Comment: Thanks! This seems to work for the category of modules, say, where there is a notion of injectivity and kernels/cokernels can be defined as submodules rather than some limits/colimits.  Does this approach generalise to arbitrary abelian categories?  (Sorry for being so lazy not to think about it in detail.)
Comment: Modulo some size concerns which aren't relevant here, abelian categories are module categories so if you can prove the statement for module categories then you've proven it for abelian categories.  See [here](http://en.wikipedia.org/wiki/Mitchell%27s_embedding_theorem) or [here](http://ncatlab.org/nlab/show/Freyd-Mitchell+embedding+theorem).
Comment: @Berci Thanks, so generally $\operatorname{ker}~if = \operatorname{ker}~f$ whenever $i$ is a monomorphism and $\operatorname{img}~fp = \operatorname{img}~f$ whenever $p$ is an epimorphism – which can be proven by checking the universal properties, right?
Comment: Yes. Perhaps you have to use that $i$ is a kernel of some arrow and $p$ is a cokernel, or something else from Abelian categories..
Comment: Edited to use the words epic and monic as appropriate. Of course, there are various theorems you have to prove to know that epic and monic works like injective and surjective, but I'm leaving those for you to either think about or trust.


Rails Ajax - load partial view via javascript

Question: I am building a small twitter-like feed. A user has an input, and you have a feed of inputs.
The feed is effectively a list of posts. Each post's view is defined by a _post.html.haml partial view.
I have an AJAX post method that creates a new post in the backend. The problem is that you have to refresh the page to actually view the post appear on the feed.
I would like to append the html to the feed column. However, I create a post on the feed column using a partial view that takes in a local variable of the post details.
Partial views are on the server side. How can I still use the same partial view to obtain the html code for the new post I have created so that I can append it to feed column without having to refresh the page.
Thanks!
Answer: Try render(:update) in the action you post to:
render(:update) do |page|
  page.replace_html 'divID', :partial => 'your-partial'
end

Comment: This couples the frontend to the backend because the frontend depends on the backend knowing about the frontend's structure.
Comment: Can this be one in jQuery as well? As from the documentation it was written as prototype helper.
Answer: Post code snippets so it can easy to answer. Anyway you can do like this. When you are creating a new post using get ajax request it will go into your controller action. In controller action you can do:
   def get_new_post   #This is the controller action called by your ajax
     post = Post.create!(ajax_params)
     render :partial => "post", :locals => {:post => post}
   end

In view you append the new post to post list as below:
$.get("ajax_request", function(data, status){
 if(status=="success"){  //if your ajax is success
   $("#post-list").append(data)  //Assuming post-list is the div id of list of posts
 }
});

Comment: how would the render know where exactly to render the partial?
Comment: you will get rendered data in data of your ajax request so you can append it to post list
Comment: this probably could work (will try it out now). I was wondering if you can you replace the html via the controller as shown by adamdunson? It would mean that I would not have to write up the javascript code as shown. I could not get adamdunson's code to work ...
Comment: In adamdunson case might work when you have the partial for list of posts. But when you have partial for displaying single post my solution will work. I think there may be other solutions. But I normally use this one.
Comment: anyway you are creating the post using ajax so it will be the get request so response data will contain the your new post when you do render partial


SSL Certificate installation issue on ubuntu server

Question: I have been given the task of updating the certificate for one of our clients on their server. Problem is, not only have I never done this before, but the process involved on all the sites I have read seems to not work for me.
Firstly, I never supplied my client with a key file before they got the new certificate, I was under the impression they needed that to generate it.
Secondly, the only other certificate file on the server is a generic looking one from Verisign, not domain specific like the new one I have been sent.
Lastly, the one I have been sent is a .cer file which is apparently as good as a .crt file but its making me more suspicious that its the wrong certificate.
My ssl.conf that refers to the certificates is like so;
SSLCertificateFile /etc/httpd/ssl/ssl.cert.pem
SSLCertificateKeyFile /etc/httpd/ssl/ssl.key
SSLCACertificateFile /etc/httpd/ssl/ca.crt <<< This is the verisign one

So, basically, I have a .cer file, a conf and a server and none of it seems right to me. I'd really love any help.
Thanks,
Christian
Answer: You've got a lot of learning ahead of you.  SSL is a tricky pest.  The first question is: is the currently-installed certificate a valid one (issued by a "real" CA, etc) for the domain they're hosting (modulo expiry dates)?  If it is, things are a bit easier.
Oh, BTW, whoever set this up previously was obviously a bit of a RHEL freak, because /etc/httpd isn't where Ubuntu keeps it's stuff.  That might bite you down the line.
For a start, the "Verisign" cert in /etc/httpd/ssl/ca.crt isn't the end-user certificate, it's the certificate of the CA that issued the previous certificate.  That might need to change if you're getting a new certificate from a different CA.
It sounds like, if it's a renewal (and the previous cert on there is valid), the new cert may have been generated from the existing key.  That's fine -- the key is private, after all, and doesn't need to change each year.  To check if they line up, run:
openssl rsa -noout -in /etc/httpd/ssl/ssl.key -text
openssl x509 -noout -in /new_cert_file.cer -text

And check the modulus data output by each of those commands.  If they're the same, then the new cert was generated from the old key, and all will probably be OK.  If they're different, then you'll need to get the key that the cert was generated from, and use that.  If openssl complains about the cert file being in an invalid format, then your guess was right that the file is no good, and it'll need to be converted or reissued.  (In that case, paste the cert file and someone might recognise the format and be able to tell you how to convert it).
To install the new cert (and possibly the key) rename the existing files out of the way and then copy the new files into place.  Restart Apache (a full restart is safest, but if you only changed the cert a reload should do the trick).  Check that Apache came back up, and accessing the site with HTTPS should report the new expiry date on the cert.  If there are problems, it's best to move the old files back into place (that's why we moved them out of the way in the first place) and then examine the errors in the logs to see what went wrong and how to fix it.
Comment: Fantastic explanation - thanks.
modulus data was the same. In the end, I just needed to reference the new certificate file and restart apache, worked beautifully. Checked the cert when browsing to the page and it was all good. I was trying to create keys and all sorts of stuff before, thank god I backed up the conf files as the process was far simpler than I was doing.

Thanks again!


Solving $\int_{-\infty}^{+\infty}e^{-2\alpha|x|}\cos^2(x)\,dx$

Question: I'd like some help solving the integral
$$
\int_{-\infty}^{\infty} e^{-2 \, \alpha \, |x|} \cdot \cos^2(x) \; \, dx
$$
with $\alpha > 0$
I just assumed 'integration-by-parts' was the way to go, but the first part
of the product alone ($e^{-2\alpha|x|}$) gets quite confusing. Is there any trick to making it stay manageable?
The absolute-value in the exponent is confusing me, too - do I have to differentiate between cases every time?
Comment: Use the symmetry to get rid of the absolute value.
Comment: what is $\alpha$?
Comment: Sorry, α > 0. It's just a parameter -> I want the solution in terms of α.
Answer: We have:
$$ I = \int_{-\infty}^{+\infty}e^{-2\alpha|x|}\cos^2(x)\,dx = 2\int_{0}^{+\infty}e^{-2\alpha x}\cos^2 x\,dx =\int_{0}^{+\infty}e^{-2\alpha x}(1+\cos(2x))\,dx$$
hence:
$$ I = \frac{1}{2\alpha}+\frac{\alpha}{2(\alpha^2+1)}$$
since:
$$\int_{0}^{+\infty}e^{-\beta x}\,dx = \frac{1}{\beta},\qquad \int_{0}^{+\infty}e^{-\beta x}\cos x\,dx = \frac{\beta}{1+\beta^2}.$$
Answer: Since it is an even function, you can only do it for x > 0. Cos^2 ( x ) = ( 1 - cos2x )/ 2, and exp( -2ax )* cos (2x) is the real part of exp( -2ax + 2ix ). Remain is easy.


How do I calculate the average of 2 exchange rates?

Question: An exchange rate of 2, when reversed is 0.5. Calculated using 1/x.
I believe this is correct because: v / 2 = v * 0.5
The next day the exchange rate is 2.5, when reversed is 0.4. Calculated using 1/y.
The average exchange rate (AER) over the two days is 2.25. Calculated using (x + y) / 2.
I believe this is correct because:
(((v * x) + (v * y)) / 2) / AER = v
However I cannot reverse this in the same way because this equation doesn't balance:
(((v * (1/x)) + (v * (1/y)) / 2) / (1/AER) != v
What am I doing wrong?
Comment: Please format using [MathJax](https://math.meta.stackexchange.com/questions/5020/mathjax-basic-tutorial-and-quick-reference)
Comment: Why to "reverse" ? if you have $a$ and $b$ you have $\text {AV}= \dfrac {a+b}{2}$.
Comment: If you "reverse" you will have $\text {AV'}= \dfrac { (\frac 1 a + \frac 1 b)}{2}= \dfrac {a +b }{2ab}$.
Comment: Thanks Mauro. What is the relationship between AV' and AV? Is there anyway to get AV' from AV without using a and b? This is ultimately what I am trying to do. I don't understand why the relationship between AV' and AV is different to a' and b.
Answer: This is an oddity of the arithmetic mean (the typical one of adding and dividing by $2$).  The average of the reciprocals is not usually the reciprocal of the average.  In some cases, maybe this one, the geometric mean may be more appropriate.  The is the square root of the product.
Comment: Thanks. This was exactly the explanation I needed.


What is the meaning of the derivative of the real and complex part ($\text{Re}'$, $\text{Im}'$)?

Question: Given a complex valued function $z(t) = a\exp((b+i \omega)t)$, with $a \in \mathbb{C}$ and $b, \omega, t \in \mathbb{R}$, what is the meaning of $\text{Re}'(z(t))$ and $\text{Im}'(z(t))$ in the partial derivatives
$$\frac{d}{da}\text{Re}(z(t)) = \text{Re}'(z(t))\frac{d}{da}z(t)$$
$$\frac{d}{da}\text{Im}(z(t)) = \text{Im}'(z(t))\frac{d}{da}z(t)$$
after applying the chain rule?
I have difficulties to understand what $\text{Re}'$ and $\text{Im}'$ means conceptually, since I understand $\text{Re}$ and $\text{Im}$ as helper functions to extract the real and imaginary part respectively and thus I don't understand how I can analytically calculate their derivatives?
Comment: Firstly, be aware of what $\text{Re} \circ z$ is a function $\mathbb{R} \rightarrow \mathbb{R}^2 \rightarrow \mathbb{R}$ given by $t \mapsto z(t) \mapsto \text{Re}(z(t))$.
Answer: Treat $a,\,a^\ast$ as independent variables so$$\operatorname{Re}a=\frac{a+a^\ast}{2},\,\operatorname{Im}a=\frac{a-a^\ast}{2i}\implies\partial_a=\frac12\partial_{\operatorname{Re}a}+\frac{1}{2i}\partial_{\operatorname{Im}a}.$$Since $\operatorname{Re}z=e^{bt}(\operatorname{Re}a\cdot\cos\omega t-\operatorname{Im}a\cdot\sin\omega t)$, $$\partial_a\operatorname{Re}z=\frac12 e^{bt}\cos\omega t-\frac{1}{2i}e^{bt}\sin\omega t=\frac12 e^{(b+i\omega)t}.$$Dividing out $dz/da=e^{(b+i\omega)t}$, the first equation requires $$\operatorname{Re}^\prime(z)=\frac12,$$which makes sense because $\operatorname{Re}z=\frac{z+z^\ast}{2}$. Similarly, you can show $\partial_a\operatorname{Im}z=\frac{1}{2i}e^{(b+i\omega)t}$, whence$$\operatorname{Im}^\prime z=\frac{1}{2i},$$which makes sense because $\operatorname{Im}z=\frac{z-z^\ast}{2i}$.
Comment: Thank you! The trick of writing $\text{Re}$ and $\text{Im}$ explicitly is great. However, I think there is a few mistakes: $\frac{d}{da} \text{Re}(z(t)) = \frac{z(t)+z^*(t)}{2} = \frac{1}{2}(\frac{d}{da} z(t) + \frac{d}{da} z^*(t)) = \frac{1}{2}(\exp(bt)(\cos(t\omega)+i\sin(t\omega))+\exp(bt)(\cos(t\omega)-i\sin(t\omega))) = \exp(bt)cos(t\omega) = \text{Re}(\frac{d}{da} z(t))$ and accordingly $\frac{d}{da} \text{Im}(z(t)) = -i\text{Im}(\frac{d}{da} z(t))$
Comment: @Genius $\frac{d}{da}\left(z^\ast\right)\ne\left(\frac{dz}{da}\right)^\ast$ in general because $a$ is complex viz. $\frac{da^\ast}{da}=0$. For example, with $z=a$ this inequality becomes $\frac{d0}{da}\ne1^\ast$.
Comment: According to what I have found out by now, $a$ and $a*$ can not be treated as independent variables, one has to follow the Cauchy-Riemann equations instead to find the solution
Comment: @Genius [You read wrong, then](https://math.stackexchange.com/questions/85648/why-can-the-complex-conjugate-of-a-variable-be-treated-as-a-constant-when-differ). See also [here](https://en.wikipedia.org/wiki/Wirtinger_derivatives).
Comment: Posted my solution. Let me know what you think. For the gradient approach I am implementing, my solution actually works.
Answer: The solution can be found by using the Cauchy-Riemann equations:
\begin{align*}
Re'(z(t)) &= \frac{\partial\text{Re}(\text{Re}(z(t)))}{\partial\text{Re}(a)} + i\frac{\partial\text{Im}(\text{Re}(z(t)))}{\partial\text{Re}(a)}\\
&= \frac{\partial\text{Im}(\text{Re}(z(t)))}{\partial\text{Im}(a)} + i\frac{\partial\text{Re}(\text{Re}(z(t)))}{\partial\text{Im}(a)}\\
\end{align*}
\begin{align*}
Im'(z(t)) &= \frac{\partial\text{Re}(\text{Im}(z(t)))}{\partial\text{Re}(a)} + i\frac{\partial\text{Im}(\text{Im}(z(t)))}{\partial\text{Re}(a)}\\
&= \frac{\partial\text{Im}(\text{Im}(z(t)))}{\partial\text{Im}(a)} + i\frac{\partial\text{Re}(\text{Im}(z(t)))}{\partial\text{Im}(a)}\\
\end{align*}
Where the real part of $z(t)$ is $$\text{Re}(z(t)) = \text{Re}(a)\exp(bt)\cos(\omega t) - \text{Im}(a)\exp(bt)\sin(\omega t)$$ and the imaginary part of $z(t)$ is $$\text{Im}(z(t)) = \text{Re}(a)\exp(bt)\sin(\omega t) + \text{Im}(a)\exp(bt)\cos(\omega t)$$
and therefore $$Re'(z(t)) = \exp(bt)\cos(\omega t)$$ and $$Im'(z(t)) = \exp(bt)\sin(\omega t)\text{.}$$
For the whole solution, we have to apply the chain rule, which then finally yields
\begin{align*}
\frac{\partial}{\partial a}Re(z(t)) &= \exp(bt)\cos(\omega t)\exp((b+i\omega)t)\\
&= \exp((2b+i\omega)t)\cos(\omega t)
\end{align*} and
\begin{align*}
\frac{\partial}{\partial a}Im(z(t)) &= \exp(bt)\sin(\omega t)\exp((b+i\omega)t)\\
&= \exp((2b+i\omega)t)\sin(\omega t)\text{.}
\end{align*}
Comment: You seem to be differentiating with respect to $a$ rather than $z$. The equations you asked about in the original question were clearly doing the latter.
Comment: You might want to double-check how often $b$ appears in your final results. Your Cauchy-Riemann equations can be simplified with results such as $$\operatorname{Re}\operatorname{Re}w=\operatorname{Re}w,\,\operatorname{Re}\operatorname{Im}w=\operatorname{Im}w,\,\operatorname{Im}\operatorname{Im}w=\operatorname{Im}\operatorname{Re}w=0.$$
Comment: @J.G. Why are our solutions different? What is the correct solution and why?


Matching and returning rows in php and MySQL

Question: I would love to get some help with this. I'm using php and MySQL to build a website. I currently have 3 tables, I'll include less in the examples. Basically I have a users table, a groups table and a grouplink table. What I have is the uid from the users table.
How should I go about it in php so I could, let's say: match users-uid to grouplink-uid, get the grouplink-gid it matches with, match grouplink-gid to groups-gid and return groups-grpname? And goes on a while loop so all group names the user is associated with are displayed.
Thanks in advance to those who will be willing to extend a hand.
users
-------
| uid |
-------
|  1  |
-------

groups
---------------
| gid |grpname|
---------------
|  1  | grp1  |
---------------
|  2  | grp2  |
---------------

grouplink
-------------------
| glid| uid | gid |
-------------------
|  1  |  1  |  1  |
-------------------
|  2  |  1  |  2  |
-------------------

uid is fk to uid in users while gid is fk to gid in groups
Answer: That's just a simple 2-way join query:
SELECT users.uid, groups.gid, groups.grpname
FROM users
INNER JOIN grouplink ON users.uid = grouplink.uid
INNER JOIN groups ON grouplink.gid = groups.gid

the actual retrieval of a joined query result is no different than a single table query - you've just got more fields to deal with.
Comment: Ahh, INNER JOINS. One topic I skipped whilst learning MySQL. Oh well, look at the price I had to pay. Good thing there's this place. Thanks, bud.
Answer: The SQL query that will get you what you're looking for goes something like this (assuming no null values in the grouplink table):
SELECT u.uid, g.gid, g.grpname
FROM users u
JOIN grouplink gl ON u.uid = gl.uid
JOIN groups g ON gl.gid = g.gid

Answer: Here is one way:
SELECT users.uid, groups.gid, groups.grpname
FROM users u, groups g, grouplink gl
WHERE g.id = gl.gid
AND gl.uid = u.uid

Answer: When the user-id is in the variable $iUserId you could query following sql string:
$sSql = "SELECT groups.`grpname` FROM groups
    INNER JOIN grouplink ON groups.`gid` = grouplink.`gid`
    WHERE grouplink.`uid` = '" . intval($iUserId) . "'";
$rRes = mysql_query($sSql);
$aGroups = array();
while (($aRow = mysql_fetch_array($rRes)) !== false) {
   $aGroups[] = $aRow['grpname'];
}

Now all groups associated with the user are in the array $aGroups.


Getting text from a file in a batch script

Question: I have made a script that makes a file with custom text in, but soon i need to be able to take text FROM THE TEXT FILE I MADE TO THE BATCH SCRIPT. Like being able to ECHO the text in the file in the batch script. If you don't understand what i mean, just ask me in the answer/comment stuff and i'll answer you with more info.
(I'm a beginner so that's why i can't do it myself.)
Comment: can we see your code plz
Comment: start with `set /p line=<file.txt`. (see also `set /?`) Come back, if you have a specific problem with it.
Answer: Have you tried using " type FILENAME"?
(I don't got enough reputation to comment, so it goes here:)
Text file 'test.txt' contains:

foobarbaz

Opening a CMD in the same folder as this text file and doing:

type test.txt

will output

foobarbaz

into the CMD window on it's own line, might depend on the OS you're on, but you should be able to google search for type(.exe)
(I tested on Win 8.1)
You should also be able to stream this output where you want, based on your needs.


MySQL: Combine multiple disparate tables into one

Question: I have multiple tables, say A, B, and C where B and C have a foreign key to A.
I want to write a query that will return a result set where the columns of the result set are the columns of A and B and C combined, i.e.
A.id A.name B.id B.name C.id C.name
-----------------------------------
1    Thing  2    Bee    NULL NULL
1    Thing  NULL NULL   1    Cow

That is, essentially a combination of the results of an individual LEFT OUTER JOIN on B and C, but combined into a single result set. I am ok with there being multiple NULL columns.
EDIT: The result set will always have the entries of A, but only ONE of either B or C.
Is this possible? Or is there a better way of joining this information?
Comment: Also do you want to show the matching rows of B and C in the same row or in different rows as shown in in you OP.
Comment: So you don't want `B` and `C` to be in the same row with their related `A`, but different rows for `A`?
Comment: I've tried chaining LEFT OUTER JOINs on multiple tables but, understandably, it doesn't give me the correct result set as it only returns matches.
Comment: Here, there could be no relation between B and C. Really, the ultimate result should always have the columns of A and one of either the columns of B or C, but never both B and C.
Comment: Ok that's more descriptive _A and one of either the columns of B or C, but never both_
Comment: You can use `UNION ALL` along with JOINs to get to your result
Comment: Unfortunately, I can't use UNION ALL because there's no guarantee that B and C have the same number of columns.
Comment: Wait, so the columns are variable too? You don't know all the columns of B and C ahead of time?
Comment: Sorry. I definitely know the columns of B and C, but B and C have different number of columns.
Comment: That should not matter as long as you are selecting only the ones you need and you know what cols you need in the output.
Answer: Since you never want a single row to contain both B and C, you might UNION together two separate join queries, substituting NULL literals for the opposite table to get the columns to align.  Each part of the UNION supplies the relationship between A->B or A->C, but must return NULL for all the columns of the opposite table.  Supply a NULL literal to leave empty every column from the other table.
In the end to sort them, you can conditionally check that the B columns are NOT NULL to force the B row to sort ahead of the C row, after first ordering by A.id.
(
  SELECT
    A.id AS a_id,
    A.name AS a_name,
    B.id AS b_id,
    B.name AS b_name,
    /* Substitute NULLs... for the other table C, for *all columns* */
    NULL AS c_id,
    NULL AS c_name,
    NULL AS other_c
    /* etc, other cols from C */
  FROM A
    LEFT JOIN B ON A.id = B.a_id
/* UNION, rather than UNION ALL  in case both tables have NULLs */
) UNION (
  SELECT
    A.id AS a_id,
    A.name AS a_name,
    /* This time substitute NULLs for B, again *all columns* */
    NULL AS b_id,
    NULL AS b_name,
    C.id AS c_id,
    C.name AS c_name
    C.other_c
  FROM A
    LEFT JOIN C ON A.id = C.a_id
)
ORDER BY
  a_id,
  /* sort the non-null B ahead... */
  CASE WHEN b_id IS NOT NULL THEN 0 ELSE 1 END


How do I remove the recursion from the drawSquare method and get the exact same result?

Question: I need to remove the recursion from the drawSquare method. There is a lot more I have to do after removing the recursion from that method however the rest I can figure out on my own.  I just really need a working solution that does the exact same thing without recursion and I will figure out the rest.
Here is how I made the Square class:
import java.awt.Color;

public class Square {
    final int BLACK = Color.BLACK.getRGB();
    final int WHITE = Color.WHITE.getRGB();
    protected int center_x;
    protected int center_y;
    protected int side;
    protected int color;
    protected Square parentSquare;

    public Square(){
        this.center_x = 0;
        this.center_y = 0;
        this.side = 0;
        this.color = WHITE;
        this.parentSquare = null;
    }
    public Square(int center_x,int center_y,int side,int color){
        this.center_x = center_x;
        this.center_y = center_y;
        this.side = side;
        this.color = color;
        this.parentSquare = null;
    }
    public Square(int center_x,int center_y,int side,int color,Square parentSquare){
        this.center_x = center_x;
        this.center_y = center_y;
        this.side = side;
        this.color = color;
        this.parentSquare = parentSquare;
    }
    public void setX(int center_x){
        this.center_x = center_x;
    }
    public int getX(){
        return center_x;
    }
    public void setY(int center_y){
        this.center_x = center_y;
    }
    public int getY(){
        return center_y;
    }
    public void setSide(int side){
        this.side = side;
    }
    public int getSide(){
        return side;
    }
    public void setColor(int color){
        this.color = color;
    }
    public int getColor(){
        return color;
    }
    public void setParent(Square parentSquare){
        this.parentSquare = parentSquare;
    }
    public Square getParent(){
        return parentSquare;
    }
}

This is the original Tsquare.java that produces a fractal of squares branching from each squares 4 corners until the side = 0: (full TSquare.java class modified to use Square objects)
import java.awt.image.*;
import java.awt.Color;
import java.io.*;
import javax.imageio.*;
import java.util.*;
public class TSquare {
    static final int SIDE = 1000; // image is SIDE X SIDE
    static BufferedImage image = new BufferedImage(SIDE, SIDE, BufferedImage.TYPE_INT_RGB);
    static final int WHITE = Color.WHITE.getRGB();
    static final int BLACK = Color.BLACK.getRGB();
    static Scanner kbd = new Scanner(System.in);

    public static void main(String[] args) throws IOException{
        String fileOut = "helloSquares.png";
        System.out.print("Enter (x,y) coordinates with a space between: ");
        int x = kbd.nextInt();
        int y = kbd.nextInt();
        System.out.println(x+","+y);//TESTLINE TESTLINE TESTLINE TESTLINE
        // make image black
        for (int i = 0; i < SIDE; i++) {
            for (int j = 0; j < SIDE; j++) {
                image.setRGB(i, j, BLACK);
            }
        }
        Square square = new Square(SIDE/2,SIDE/2,SIDE/2,WHITE);
        drawSquare(square);

        // save image
        File outputfile = new File(fileOut);
        ImageIO.write(image, "jpg", outputfile);
    }

    private static void drawSquare(Square square){ // center of square is x,y length of side is s
        if (square.side <= 0){ // base case
            return;
        }else{
            // determine corners
            int left = square.center_x - (square.side/2);
            int top = square.center_y - (square.side/2);
            int right = square.center_x + (square.side/2);
            int bottom = square.center_y + (square.side/2);
            int newColor =square.color-100000;
            Square newSquareA = new Square(left,top,square.side/2,newColor);
            Square newSquareB = new Square(left,bottom,square.side/2,newColor);
            Square newSquareC = new Square(right,top,square.side/2,newColor);
            Square newSquareD = new Square(right,bottom,square.side/2,newColor);
            for (int i = left; i < right; i++){
                for (int j = top; j < bottom; j++){
                    image.setRGB(i, j, square.color);
                }
            }
            // recursively paint squares at the corners
            drawSquare(newSquareA);
            drawSquare(newSquareB);
            drawSquare(newSquareC);
            drawSquare(newSquareD);
        }

    }

}

I'm looking to reproduce the exact actions of this code just minus the recursion and everything I try doesn't seem to work. I cant even get a single white square to display on top of the original black canvas.
Comment: You can simulate recursion using a stack or a queue. I would think it makes your code less readable though.
Comment: Actually DSOI the next part of the program I have to deal with is implementing the same thing in a LInked Stack. If  that's how to simplify doing it I would extremely appreciate some input on that subject. If you could show me how to implement it without recursion using a simple stack I can modify it to work with the Linked Stack
Comment: Sorry for late comment, but you can use java.util.Vector. I don't have specific implementation, I can get one if you want though.
Answer: If we want readability without compromising speed I suggest first making some additions to Square:
public int half() {
    return side/2;
}
public int left() {
    return center_x - half();
}
public int top() {
    return center_y - half();
}
public int right() {
    return center_x + half();
}
public int bottom() {
    return center_y + half();
}

public void draw(BufferedImage image) {

    int left = left();
    int top = top();
    int right = right();
    int bottom = bottom();

    for (int i = left; i < right; i++){
        for (int j = top; j < bottom; j++){
            image.setRGB(i, j, color);
        }
    }
} //End Square

Also moving I/O out to enable unit testing.
package com.stackoverflow.candied_orange;
import java.awt.image.*;
import java.awt.Color;
import java.io.*;
import javax.imageio.*;
import java.util.*;
public class FractalSquareIterative {

    public static void main(String[] args) throws IOException{

        final int SIDE = 1000; // image is SIDE X SIDE
        BufferedImage image = new BufferedImage(SIDE,SIDE,BufferedImage.TYPE_INT_RGB);

        drawImage(SIDE, image);
        saveImage(image);
    }

    //Removed IO to enable unit testing
    protected static void drawImage(final int SIDE, BufferedImage image) {
        final int BLACK = Color.BLACK.getRGB();
        final int WHITE = Color.WHITE.getRGB();
        final int HALF = SIDE / 2;

        //Draw background on whole image
        new Square(HALF, HALF, SIDE, BLACK).draw(image);

        //Draw foreground starting with centered half sized square
        Square square = new Square(HALF, HALF, HALF, WHITE);
        drawFractal(square, image);
    }

Now that Square is dealing with all the square things the fractal code is a little easier on the eyes.
    private static void drawFractal(Square square, BufferedImage image){

        Queue<Square> squares = new LinkedList<>();
        squares.add(square);

        while (squares.size() > 0) {

            //Consume
            square = squares.remove();

            //Produce
            int half = square.half();
            if (half > 2) {

                int left = square.left();
                int top = square.top();
                int right = square.right();
                int bottom = square.bottom();
                int newColor = square.color - 100000;

                squares.add(new Square(left, top, half, newColor));
                squares.add(new Square(left, bottom, half, newColor));
                squares.add(new Square(right, top, half, newColor));
                squares.add(new Square(right, bottom, half, newColor));
            }
            square.draw(image);
        }
    }

    protected static void saveImage(BufferedImage image) throws IOException {
        String fileOut = "helloSquares.png";
        File outputfile = new File(fileOut);
        ImageIO.write(image, "jpg", outputfile);
    }
} //End FractalSquareIterative

Reliably faster than the recursive version but not significantly so at this size.
If you want a peek at my unit tests you'll find them here.
Comment: candied_orange you're the man. Your input above really helped TONS. I was able to convert my drawSquare method to use a LinkedStack without issue. I've been toying with modifying things to get it to display the new squares behind the existing ones rather than on top of them, I figured similarly to my recursive version it would depend on where I put the draw method within the while loop but it seems to do the same thing no matter where I put it.  Any chance you'd have a quick fix for getting the squares to generate behind existing squares?
Comment: @SpilledMilkFactory short of creating layers of transparent images no. That problem is typically solved by controlling the order of rendering (depth first vs breadth first traversal) I was very careful to produce the same image as your code here. If you can post code that does what your asking for using recursion I can convert it. Probably best to ask a new question. If that's not what you mean clue me in.
Comment: This is what I mean using recursive means, Basically the only difference between my original posted drawSquare method and this one is the placement of the for loop that draws it. If you move the for loop that actually draws each square from above the recursive calls to directly after the recursive calls it paints them behind eachother.  I tried to paste the different code but it was too long for the comment box.  the placement of the nested for loop is the only difference when using recursion. I suppose all things considered it is still technically painting them on top but starting at the end
Comment: Show me the code in a different question. Should give you plenty of room. I need to see the results you're expecting.
Comment: https://stackoverflow.com/questions/57946906/how-do-i-make-my-squares-generate-behind-each-other-rather-than-on-top-of-eachot
Answer: Here's one implementation using an ArrrayDeque ( https://docs.oracle.com/javase/7/docs/api/java/util/ArrayDeque.html ).
It's worth comparing ArrayDeque against some other Java types :
a) Stack is an interface, and the api page (https://docs.oracle.com/javase/8/docs/api/java/util/Stack.html) says

A more complete and consistent set of LIFO stack operations is provided by the Deque interface and its implementations, which should be used in preference to this class.

b) I originally wrote this using good old familiar ArrayList, with Square square = squares.remove(0); instead of pop.   I am quite surprised at how much faster this ArrayDeque implementation appears to be than that ArrayList (not that I have run any formal benchmarks)
private static void drawSquare(Square startSquare){

    Deque<Square> squares = new ArrayDeque<Square>(400000);
    squares.push(startSquare);

    while (!squares.isEmpty()) {
        Square square = squares.pop();

        System.out.println(square);
        // center of square is x,y length of side is s
        if (square.side > 0){ // base case
            // determine corners
            int left = square.center_x - (square.side/2);
            int top = square.center_y - (square.side/2);
            int right = square.center_x + (square.side/2);
            int bottom = square.center_y + (square.side/2);
            int newColor =square.color-100000;
            addSquare(squares, left,top,square.side/2,newColor);
            addSquare(squares, left,bottom,square.side/2,newColor);
            addSquare(squares, right,top,square.side/2,newColor);
            addSquare(squares, right,bottom,square.side/2,newColor);

        }
    }
}
private static void addSquare(Deque<Square> squares, int x, int y, int side, int color) {
    // STRONGLY recommend having this "if" statement !
    // if (side > 0) {
           squares.push(new Square(x, y, side, color));
    // }
}

As noted in my comment, it is WELL worthwhile to not create squares of size 0 rather than creating them and simply ignoring them when their turn comes around.   This would be true for the recursion-based operations as well - but especially so for these non-recursion based ones, since the multitude of squares would be really eating up memory and processing time.
Comment: Thank you so much for your response, your above code helps a lot.  I'm required to use a LinkedStack interface but seeing this done with a Deque certainly helps to wrap my mind around the removal of the recursion nonetheless


Saving arabic tweets from tweepy in CVS

Question: I am trying to retrieve a user's timeline tweets using tweepy (Python 3.6). Now, I found a code with which I can do that and save them in CVS form. It works without problems when retrieving English tweets, yet tweets written in arabic are displayed this way: "b'\xd9\x82\xd8\xaa\xd8\xa7\xd9\x84\x...". I've gone through multiple forums and saw this issue being raised several times but I haven't been able to find a solution. I figured it must have something to do with the encoding utf-8, but I do not know how to manipulate the code. Anyone has a suggestion? THANKS!
this is my code:
>>> import tweepy
>>> import csv
>>> consumer_key = "..."
>>> consumer_secret = "..."
>>> access_key = "..."
>>> access_secret = "..."
>>> def get_all_tweets(screen_name):

#authorize twitter, initialize tweepy
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_key, access_secret)
api = tweepy.API(auth)

#initialize a list to hold all the tweepy Tweets
alltweets = []

#make initial request for most recent tweets (200 is the maximum allowed count)
new_tweets = api.user_timeline(screen_name = screen_name,count=200)

#save most recent tweets
alltweets.extend(new_tweets)

#save the id of the oldest tweet less one
oldest = alltweets[-1].id - 1

#keep grabbing tweets until there are no tweets left to grab
while len(new_tweets) > 0:
    print("getting tweets before %s" % (oldest))

    #all subsiquent requests use the max_id param to prevent duplicates
    new_tweets = api.user_timeline(screen_name = screen_name,count=200,max_id=oldest)

    #save most recent tweets
    alltweets.extend(new_tweets)

    #update the id of the oldest tweet less one
    oldest = alltweets[-1].id - 1

    print("...%s tweets downloaded so far" % (len(alltweets)))

#transform the tweepy tweets into a 2D array that will populate the csv
outtweets = [[tweet.id_str, tweet.created_at, tweet.text.encode("utf-8")] for tweet in alltweets]

#write the csv
with open('%s_tweets.csv' % screen_name, 'w') as f:
    writer = csv.writer(f)
    writer.writerow(["id","created_at","text"])
    writer.writerows(outtweets)

pass

>>> if __name__ == '__main__':
#pass in the username of the account you want to download
get_all_tweets("#username")

Answer: In Python 3.x, there's no need to call encode() when writing writing to files as the system open() command now defaults to text mode (In Python 2.x, you can use io.open())
Change tweet.text.encode("utf-8") to tweet.text.
As Python 3 uses your locale to work out what file encoding to use when you open a file in text mode, it's safer to change your open() code to:
with open('%s_tweets.csv' % screen_name, 'w', encoding='utf-8') as f:

Now, Python will automatically encode any strings to UTF-8 as it writes the file.
Comment: Hi! thanks a lot for this clarification. Unfortunately, now when I open the CSV file the arabic characters appear as: بس بعدني بتمنى شوÙ.
Comment: What are you using to open the CSV?
Comment: Oh wait. Good question! I was using Excel, but just realised it works well with TextEdit! Amazing, thank you! Do you by any chance know why this happens with Excel and how it can be overcome?
Comment: Yes, Excel assumes CSVs are encoded in an 8-bit codepage. To force it to read the CSV as UTF-8, change `encoding='utf-8'` to `encoding='utf-8-sig'` and rewrite the CSV file. This will write a UTF-8 BOM at the start of the file.

Saving arabic tweets from tweepy in CVS


Why $ \dfrac{d}{dx} f(kx) = kf'(kx) $?

Question: In MIT OCW 18.01 Single variable calculus lecture 6, minute 18:00-18:20, the professor used an example to explain why $e$ exists.
Context:
$f(x) = 2^x$
$b=2^k$
$ f(kx)=2^{kx} = (2^k)^x $
Then the professor wrote this, that by chain rule: $$ \dfrac{d}{dx} f(kx) = kf'(kx) $$
Why does it work? Why need to add additional $k$ there?
If I expand derivative of $f(x)$ as: $$ \dfrac{d}{dx}f(x) = 2^x\dfrac{(2^{\Delta x} - 1)}{\Delta x} $$ then derivative of $f(kx)$ should be:
$$ \dfrac{d}{dx}f(kx) = f'(kx) = 2^{kx}\dfrac{(2^{\Delta x} - 1)}{\Delta x} $$
Even if it's typo where Professor intended to write: $\dfrac{d}{dx}f(kx) = kf'(x) $ I don't think that it will work either.
Because
$$ k 2^{x}\dfrac{(2^{\Delta x} - 1)}{\Delta x} \ne  2^{kx}\dfrac{(2^{\Delta x} - 1)}{\Delta x} $$
right?
Comment: Slight mistake: $$\dfrac{d}{dx}f(kx) = f'(kx) = 2^{kx}\dfrac{(2^{k\Delta x} - 1)}{\Delta x}$$
Answer: Since $f(kx)=2^{kx}$, then derivative for $x$ is
$$\frac{df}{dx}(kx)=f'(kx)\cdot k$$
Because if you let $g(x)=kx$, then
$$\frac{df}{dx}(g(x))=f'(g(x))g'(x)$$
which is the chain rule.
Comment: Now that I see $k$ is just function to multiply $x$ instead of $x^k$, it's much more understandable. Thanks!
Answer: A general differentiable $f$ satisfies $$\dfrac{d}{dx}f(kx)=\underbrace{\dfrac{d(kx)}{dx}}_k\underbrace{\dfrac{d}{d(kx)}f(kx)}_{f^\prime(kx)}.$$

Why $ \dfrac{d}{dx} f(kx) = kf'(kx) $?


For Loop no R - Regressão Linear

Question: Olá, como estão?
Sou iniciante, e gostaria de tirar algumas dúvidas quanto a possibilidade de ser realizado, de maneira automática, regressões lineares.
Possuo uma base de dados com 520 observações (linhas) e 67 variáveis (colunas).
Gostaria de realizar regressões, como por exemplo, coluna 1 com coluna 2, coluna 1 com coluna 3 e assim sucessivamente. Também salvar, em uma nova base de dados, os resíduos de cada regressão.
Atualmente, faço de maneira manual no R, o que tende a causar uma demora no processo todo.
Ainda não possuo conhecimentos em for loop ou funções do tipo.
Se alguém puder dar uma luz, ajudaria muito.

reg <- lm(ativos$BBAS3~ativos$ITSA4)
residuos <- reg$residuals
summary(reg)

#Aqui é análise de estacionáriedade dos resíduos
estacionariedade_u <- ur.df(residuos, type = "none", selectlags = "AIC")
summary(estacionariedade_u)

Answer: Correr várias regressões não é assim tão difícil quanto isso. O maior problema para quem está a começar a aprender R é nas funções *apply que são ciclos for disfarçados. Simplificam imenso as coisas quando se está à vontade com elas.
Primeiro vou criar um conjunto de dados, com 520 observações (linhas) e 7 variáveis (colunas). A resposta é a primeira coluna e as variáveis regressoras são as colunas seguintes.
set.seed(1234)    # Torna os resultados reprodutíveis

m <- 520
n <- 6
BBAS3 <- 1:m + rnorm(m, 0, 0.1)
ativos <- data.frame(BBAS3)
regr <- matrix(BBAS3 + rnorm(m*n), nrow = m)
colnames(regr) <- paste0("ITSA", 1:n)
ativos <- cbind(ativos, regr)

Agora o código do problema.
A função lapply aplica a todos os elementos do primeiro argumento a mesma função. Neste caso vou aplicar uma função sem nome, definida ad-hoc, por isso uma função dita anónima.
library(urca)

model_list <- lapply(ativos[-1], function(x)
  lm(BBAS3 ~ x, data = ativos))

E pronto. Todas as regressões já correram, com as 6 colunas em questão a serem uma de cada vez passadas no argumento x. É por isso que retirei a primeira coluna, ativos[-1], para ficar só com os regressores.
Veja o resultado da primeira regressão.
model_list[[1]]    # Uma maneira
model_list$ITSA1   # Equivalente
#
#Call:
#lm(formula = BBAS3 ~ x, data = ativos)
#
#Coefficients:
#(Intercept)            x
#    0.09342      0.99991

Agora podemos usar esta lista de modelos para extrair o que quisermos, sempre com lapply.
resid_list <- lapply(model_list, residuals)
lapply(resid_list, summary)

estacionariedade_list <- lapply(resid_list, ur.df, type = "none", selectlags = "AIC")
estac_smry <- lapply(estacionariedade_list, summary)

Esta última lista, estac_smry, tem em cada elemento valores de interesse.
estac_pval <- lapply(estac_smry, function(x)
  x@testreg$coefficients[, 4])

estac_r.squared <- sapply(estac_smry, function(x)
  x@testreg$r.squared)

estac_adj.r.squared <- sapply(estac_smry, function(x)
  x@testreg$adj.r.squared)

As duas últimas instruções usam sapply para obter vetores como saída, o lapply dá sempre listas.
Comment: Rui Barradas, muito obrigado pela ajuda, sou extremamente grato. Realmente, simplificou muito. Vou focar mais na família apply.

For Loop no R - Regressão Linear


Calculus - Maximum volume equation

Question: I tried my best to come up with an answer but I failed. I would really appreciate if someone can help me with this:

Question: To carry a suitcase on an airplace, the length + width + height must be less than or equal to $ 62$ in. Assuming that height is fixed, show that the maximum volume is $ V = h(31-\frac{1}{2}h)^2 .$

Based on that, I did the following:
$$l+w+h = 62$$
$$l+w = 62 - h$$
$$V = lwh$$
$$dV = dl(lwh) + dw(lwh) +dh(lwh)$$
$$dV = wh + lh + 0$$
$$dV = h(l+w)$$
$$dV = h(62-h)$$
I dont know what else to do after this...Any suggestions recommendation is greatly appreciated!
Comment: Please see https://math.meta.stackexchange.com/questions/5020/
Answer: $$l+w+h=62$$
Therefore, $L+w=62-h$.  In order to maximise the volume, the area enclosed by the rectangle, $l\times w$ should be maximum and thus, $l=w$.  Therefore we may write: $2w=62-h$, or, $w=31-\frac1 2 h$.  Now substitute this in the equation for total volume, $V=lwh=(31-\frac 1 2 h)^2h$.
QED.
Answer: Using Cauchy-Schwarz inequality
$ l+w+h = 62$
$l+w = 62-h$
$(l^2+w^2)(1^2+1^2) \geq (l+w)^2$
$2(l^2+w^2) \geq (l+w)^2$
$2((l+w)^2-2lw) \geq (l+w)^2$
$2(l+w)^2-4lw \geq (l+w)^2$
$(l+w)^2 \geq 4lw$
since $ lw = \frac{V}{h} $
$(62-h)^2 \geq \frac{4V}{h}$
$h(62-h)^2 \geq 4V$
$ V \leq h(31-\frac{1}{2}h)^2$
Answer: We want to express the volume as a function of a single variable.  Since $h$ is a constant, that variable can be either $l$ or $w$.  Let's use $w$.
We are given that $l + w + h = 62~\text{in}$.  Hence, $l = 62~\text{in} - h - w$.  Substituting $62~\text{in} - h - w$ for $l$ in the equation $V = lwh$ yields
$$V(w) = (62~\text{in} - h - w)wh = (62~\text{in})wh - wh^2 - w^2h$$
Differentiating with respect to $w$, while remembering that $h$ is a constant, yields
$$V'(w) = (62~\text{in})h - h^2 - 2wh$$
Setting the derivative equal to $0$ and solving for $w$ yields
$$w = 31~\text{in} - \frac{h}{2}$$
Since $h > 0$,
$$V''(w) = -2h < 0$$
Thus, the function has a relative maximum at $w = 31~\text{in} - \dfrac{h}{2}$ by the Second Derivative Test.
When $w = 31~\text{in} - \dfrac{h}{2}$, then
$$l = 62~\text{in} - h - w = 62~\text{in} - h - \left(31~\text{in} - \frac{h}{2}\right) = 31~\text{in} - \frac{h}{2}$$
Thus, the maximum volume of the suitcase is
$$V = lwh = \left(31~\text{in} - \frac{h}{2}\right)\left(31~\text{in} - \frac{h}{2}\right)h = \left(31~\text{in} - \frac{h}{2}\right)^2h$$
Answer: Hint

To maximise the volume at fixed height you have to maximise the section of the suitcase. In this case it has to be either rectangular of square: in any case you can construct a square with the same area as a rectangle. Square section is very much easier to work with.

Solution

 To maximise the volume with a fixed height you have to maximise the section of the suitcase. In the simplest case, because it doesn't really matters, you can choose a square section so that $w=l$. In this case you have $$2w = 62-h\\w = 31-{1\over 2}h$$ the area of a square is $$S = w^2 = (31-{1\over 2}h)^2$$ In the end, the maximum volume is $$V=hS = h(31-{1\over 2}h)^2$$

Calculus - Maximum volume equation


How to create textarea and edittext with border and fixed label?

Question: I am new to Android. I am wondering how can we get a bordered Edittext and Textarea like we have in HTML something like this:

I am finding it hard to get such output in Lollipop devices as it shows as a line and a floating label.
Comment: Make custom shape in _drawable_ folder
Answer: In situation like this according to Google docs you would prefer TextInputLayout
For example:
<code><android.support.design.widget.TextInputLayout
                android:id="@+id/password_layout"
                android:layout_width="match_parent"
                android:layout_height="wrap_content>

                <EditText
                    android:id="@+id/input_password"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:hint="@string/password_hint"
                    android:textColor="#777777"
                    android:textColorHint="#777777"
                    android:textSize="@dimen/text_20"
                    android:imeActionId="@+id/input_password"
                    android:imeOptions="actionNext"
                    android:inputType="textPassword"
                    android:singleLine="true" />
            </android.support.design.widget.TextInputLayout>
</code>