Serret-Frenet for Non-unit "speed" space curves

Question: The Serret-Frenet equations form a system of linear, often non-autonomous, ordinary differential equations that recover the local tangent, normal and binormal vectors of a unit "speed" space curve from the curve's curvature and torsion.
The equations are scaled for space curves of non unit "speed." (see sec. 5 of the previous Wikipedia article) This means that in order to find the local frame  one must also supply data about the curve parameterization. Often, one wants to find the curve parameterization for known curvature/torsion variables.
Question 1: So, if one were to solve the SF equations
$
\begin{align}
\dfrac{d\mathbf{T}}{ds} &= & \kappa \mathbf{N}, \\
\dfrac{d\mathbf{N}}{ds} &= - \kappa \mathbf{T} & & + \tau \mathbf{B},\\
\dfrac{d\mathbf{B}}{ds} &= & -\tau \mathbf{N},
\end{align}
$
for a given curvature and torsion, then would the associated space curve be identical, up to its "speed," to the one found by solving
$
\frac{d}{ds} \begin{bmatrix}
\mathbf{T}\\
\mathbf{N}\\
\mathbf{B}
\end{bmatrix}
= \|\mathbf{r}'(s)\|
\begin{bmatrix}
0&\kappa&0\\
-\kappa&0&\tau\\
0&-\tau&0
\end{bmatrix}
\begin{bmatrix}
\mathbf{T}\\
\mathbf{N}\\
\mathbf{B}
\end{bmatrix}?$
It seems that this should not be the case since the $||\textbf{r}'(s)||$ prefactor could greatly complicate the system of equations.
Question 2: Assuming that the answer to question 1 is no, then what is the utility of the SF equations? Knowledge of $||\textbf{r}'(s)||$ likely comes from knowledge of $\textbf{r}'(s)$, which should allow one to find the tangent, normal and binormal vectors bypassing SF.
Answer: The Serret-Frenet formula in the case where the curve is not parametrised by arc-length are
$$\frac{1}{V_r(t)}\frac{d}{dt}\begin{pmatrix} T\\ N\\ B \end{pmatrix} = \begin{pmatrix} 0 & \kappa & 0\\-\kappa & 0 & \tau \\ 0 &-\tau & 0\end{pmatrix} \begin{pmatrix} T\\N \\B \end{pmatrix}$$
where $V_r(t)=\Vert \dot{r}(t) \Vert$ is the speed of your curve. This is true because in the case of non-arc-legnth parametrisation, the definition of torsion and curvature changes, in order to take into account the speed. Namely, we have that for a $C^3$ biregular curve, the torsion is defined by
$$\tau = \frac{1}{V_r} \langle B, \dot{N} \rangle$$
and the curvature $\kappa$ is defined as the norm of the curvature vector
$$K = \frac{1}{V_r} \dot{T}$$
Assuming that all these quantities are well defined (which requires, as I mentionned earlier, that the curve be at least $C^3$ and biregular), then it holds that the "trace", or the image of the curve, is invariant under reparametrisation (actually we even need a lot less: assuming merely that the curve is $C^1$ and regular is enough, for instance).
Serret-Frenet formulas provide a cinematic interpretation of the curvature and the torsion. Locally, these quantities tell you how the curve is going to evolve. More generally, it is possible to show that (under the usual hypothesis $C^3$ and biregular) if two curves parametrised by arc-length possess same curvature and same torsion, then they are "equal" in the sense that there exists a deplacement of $\mathbb{R}^3$ from one onto the other. Therefore curvature and torsion control all the geometry of the curve, and thus solving Serret-Frenet completely determines the curve.
A further refinement of this theorem would be that if you arbitrarily give two (continuous) functions, one for curvature, and one for torsion, then there exists a unique curve parametrised by arc-length whose curvature and torsion are the one prescribed (up to a deplacement of the space).
Comment: welcome to the MSE. Nice answer.
Answer: Observe,
$$ \frac{dT}{dt} = \frac{ds}{dt}\frac{dT}{ds} \ \& \ \frac{dN}{dt} = \frac{ds}{dt}\frac{dN}{ds} \ \& \ \frac{dB}{dt} = \frac{ds}{dt}\frac{dB}{ds}$$
but, the Serret-Frenet equations allow us to write the change in $T,N,B$ in terms of $\kappa, \tau$-weighted sum of $T,N,B$. That is, the equations you quote from Wikipedia. Except, note the distinction between $s$ (arclength) and $t$ (an arbitrary parameter). We define the curvature and torsion with respect to the change of $T,N,B$ in terms of arclength. That choice is important as without it the curvature and torsion would not be well-defined. As the equations above reveal, the magnitude of the rates of change in $T,N,B$ are different for different speed parametrizations of a given curve. That said, it is important to allow for non-unit-speed parametrizations in the theory because often the arclength parametrization is uglier than the $t$-parametrization. In fact, it may not even be possible to calculate the arclength explicitly ! So, we need the $s$-equations for logic, and we need the $t$-equations for computational flexibility. Why do we need the Frenet-Serret equations at all? I suppose it's nice to be able to show congruence of curves which defy highschool geometry contructive geometry. We just have to show the curvature and torsion match then we know the curves are the same curve up to some Euclidean motion. Moreover, this is merely the first chapter in a deeply interesting chapter of math known as Cartan's method of moving frames... much more to see here.


Inequality for a parabolic pde

Question: I am trying to solve the following exercise.
Consider the linear parabolic equation
\begin{equation}
\partial _t u -\nabla (A(x,t)\nabla u)=f(x,t), x \in \Omega,t>0,
\end{equation}
subject to the initial data $u(x,0)=u_0(x)$ for $x\in\Omega$, where the diffusion matrix A satisfies
\begin{equation}
\xi ^{-1}|y|^2\leq \sum _{i,j =1} ^n A _{i,j}(x,t)y_i y_j\leq\xi|y|^2, x\in\Omega,t>0,\forall y \in R^n
\end{equation}
for some $\epsilon>0$.
Let $f\equiv 0$ and consider the Neumann boundary condition $(A(x,t)\nabla u(x,t))\nu=0$for $x\in\partial\Omega$. Show that
\begin{equation}
\lVert u(t)-\frac{1}{|\Omega|}\int _{\Omega} u_0(x) dx\rVert _{L^2(\Omega)}\leq Ce^{- \mu t}
\end{equation}
for some $C,\mu >0$.
I tried the following.
First I subtracted the mean value of u over $\Omega$ from both sides of the equation and defined
\begin{equation}
v=u-\frac{1}{|\Omega|}\int _{\Omega} u_0(x) dx.
\end{equation}
Then $v$ satisfies
\begin{equation}
\partial _t v-\nabla (A(x,t)\nabla v)=-\frac{1}{|\Omega|}\int _{\Omega} \partial _t u_0(x) dx\ in\ \Omega \times (0,\infty)
\end{equation}
\begin{equation}
v(x,0)=0\ in\ \Omega
\end{equation}
\begin{equation}
(A(x,t)\nabla v)n=0,\ on\ \partial\Omega
\end{equation}
I know from the first part of the exercise that
\begin{equation}
\lVert u(t) \rVert _{L^2(\Omega)}\leq Ce^{- \lambda t}
\end{equation}
for some $C,\lambda >0$.
Therefore, it holds that
\begin{equation}
\lVert v(t) \rVert _{L^2(\Omega)}\leq Ce^{- \lambda t}
\end{equation}
for some $C,\lambda >0$.
My next step was to combine the two results
\begin{equation}
C_p \lVert \nabla v(t)\rVert \geq \lVert v(t)\rVert \geq 0.
\end{equation}
This implies that $\nabla v=0$. Thus, $v$ is a constant function.
As the mean value of $v$ is zero, I know that $v\equiv 0$.
Therefore,
\begin{equation}
\lVert \lVert u(t)-\frac{1}{|\Omega|}\int _{\Omega} u_0(x) dx\rVert\rVert _{L^2(\Omega)}=\lVert v(t)\rVert _{L^2(\Omega)}=0.
\end{equation}
This shows that
\begin{equation}
\lVert \lVert u(t)-\frac{1}{|\Omega|}\int _{\Omega} u_0(x) dx\rVert\rVert _{L^2(\Omega)}\leq Ce^{\mu t}.
\end{equation}
Is my solution correct or are there any mistakes?
Comment: As the function $u_0$ does not depend on time, clearly $\partial_t u_0 = 0$, so why include it in your PDE for $v$. Secondly, the bound $\Vert u(t) \Vert_{L^2(\Omega)} \leq Ce^{-\lambda t}$ uses the Dirichlet boundary conditions, which we now do not have. Finally, where does $C_p \Vert \nabla v(t)\Vert \geq \Vert v(t) \Vert \geq 0$ come from? $v$ has neither zero mean value nor zero boundary conditions, and this inequality certainly doesn't imply that $\nabla v = 0$.
Comment: Additionally, $v(x,0) = 0$ is wrong, we have $v(x,0) = u_0(x) - \frac{1}{\vert\Omega\vert} \int_\Omega u_0(x)\,dx$.
Comment: Thank you! Could you show me how to do it correctly?
Answer: Let $v = u - \frac{1}{\vert\Omega\vert} \int_\Omega u_0(x) \,dx$. Then $v$ is a solution to
\begin{align*}
\partial_t v - \nabla\cdot(A\nabla v) &= 0 \quad \text{in} \ \Omega\times (0,\infty), \\
v(x,0) &= u_0(x) - \frac{1}{\vert\Omega\vert} \int_\Omega u_0(x) \,dx \quad \text{in} \ \Omega, \\
(A\nabla v )\cdot\nu &= 0 \quad\text{on}\ \partial\Omega\times (0,\infty).
\end{align*}
As $u$ is mass preserving, i.e.
$$ \frac{d}{dt} \int_\Omega u(t,x) \,dx = 0$$
for all $t > 0$ (Prove it!), we have in particular
$$ \int_\Omega u(t,x) \, dx = \int_\Omega u_0(x) \, dx$$
for all $t > 0$. This implies that
$$ \int_\Omega v(x,t) \,dx = \int_\Omega u(x,t) \,dx - \int_\Omega u_0(x) \, dx = 0$$
for all $t>0$. If we then define the energy $E:[0,\infty)\rightarrow\mathbb{R}$, $E(t) = \frac{1}{2} \int_\Omega v(t,x)^2 \,dx$, we obtain
\begin{align}
\frac{d}{dt} E(t) &= \int_\Omega v\partial_t v \,dx = - \int_\Omega A\nabla v \cdot\nabla v \, dx \\
&\leq - \frac{1}{\xi} \int_\Omega \vert\nabla v \vert^2 \, dx \\
&\leq -\frac{c}{\xi} \int_\Omega v^2 \, dx \\
&= -\frac{2c}{\xi} E(t).
\end{align}
Here we used the Poincare inequality, which is applicable since $\int_\Omega v \, dx = 0$. We conclude using Gronwall's inequality.

Inequality for a parabolic pde


Projective bundle of a sum of ample line bundles

Question: Let $X$ be a quasi-projective variety, and let $L_1,...,L_n$ be ample line bundles on $X$. Is that true that if $E= \oplus L_i$, then
$$\mathbb{P}(E) \cong Proj(\bigoplus_{i_j \in \mathbb{N}^n} H^0(L_1^{\otimes i_1} \otimes...\otimes L_n^{\otimes i_n}))?$$
It is not true if $L_i$ are not ample, because then a priori $H^0(L_1^{\otimes i_1} \otimes...\otimes L_n^{\otimes i_n})$ may be 0 for any choice of $i_j$ (take for example on $\mathbb{P}^1$, $L_i=O(-i)$). I think that if $X$ is projective then it is true, maybe we could use that $H^0(O_X(1)) \otimes H^0(O_X(n)) \to H^0(O_X(n+1))$ is surjective for $n$ big enough, but I haven't been able to do it though.
Comment: Have you tried seeing if this works in the simplest example? :-|
Comment: What do you mean? It seems to be working if you take $X$ projective and $L$ very ample, or $X=\mathbb{A}^n=D_{\mathbb{P}^n}(X_0) \subseteq \mathbb{P}^n$ and $L$ the restriction of $O(1)$, these are the simplest examples that are coming to my mind
Answer: I feel like I'm basically reiterating what Dtseng said, but maybe this will clear some things up.
Fix $X$ a scheme, and a set of line bundles $L_1,\ldots,L_n$. Denote $E = \bigoplus_{i=1}^n L_i$. We start by giving your graded ring a name.
Definition. The section ring or ring of sections of $L_1,\ldots,L_n$ is defined to be
$$R(X;L_1,\ldots,L_n) := \bigoplus_{i_j \in \mathbf{N}^n} H^0\!\left(X,L_1^{\otimes i_1} \otimes L_2^{\otimes i_2} \otimes \cdots \otimes L_n^{\otimes i_n}\right).$$
The original reference for section rings is [EGAII, 4.5], but I also recommend [PAGI, §2.1] and [dFEM, §1.8].
We will need the following Lemma in both sections below:
Lemma. There is a decomposition
$$\operatorname{S}(E) \cong \bigoplus_{i_j \in \mathbf{N}^n} L_1^{\otimes i_1} \otimes L_2^{\otimes i_2} \otimes \cdots \otimes L_n^{\otimes i_n},$$
where $\operatorname{S}(E) = \bigoplus_{d \ge 0} \operatorname{S}^d(E)$ denotes the symmetric algebra of $E$. In particular, we have
$$H^0\!\left(X,\operatorname{S}(E)\right) \cong R(X;L_1,\ldots,L_n).$$
Proof. We have the following chain of isomorphisms:
$$
\operatorname{S}(E) \cong \bigotimes_{i=1}^n \operatorname{S}(L_i)
= \bigoplus_{i_j \in \mathbf{N}^n} \operatorname{S}^{i_1}L_1 \otimes \operatorname{S}^{i_2}L_2 \otimes \cdots \otimes \operatorname{S}^{i_n}L_n \cong \bigoplus_{i_j \in \mathbf{N}^n} L_1^{\otimes i_1} \otimes L_2^{\otimes i_2} \otimes \cdots \otimes L_n^{\otimes i_n}
$$
The first isomorphism follows by using the universal property for symmetric algebras: see [EGAII, 1.7.1], or just note that this is the vector bundle version of [Lang, XVI, Prop. 8.2]. The second equality is just by definition. The last isomorphism is a consequence of the fact that for a line bundle $L$, we have $L^{\otimes n} \overset{\sim}{\to} \operatorname{S}^n L$ (one way to see this is that the canonical map from left to right is surjective, and both bundles have the same rank, so the map must be an isomorphism).
The last claim follows by taking global sections on both sides. $\blacksquare$
Now we can answer your question in the affirmative in some cases encompassing your examples. Recall that if $E = \bigoplus_{i=1}^n L_i$, by definition [Hartshorne, II, §7], we have
$$\mathbf{P}(E) = \operatorname{\mathbf{Proj}}\!\left( \operatorname{S}(E) \right)$$
where $\mathbf{Proj}$ is the relative Proj construction over $X$.
$X$ an affine scheme, $L_i$ arbitrary
Suppose $X$ is an affine scheme. Then, the proof of your statement is fairly short:
Proposition. We have an isomorphism
$$\mathbf{P}(E) \cong \operatorname{Proj}\!\left(R(X;L_1,\ldots,L_n)\right).$$
Proof. In the affine case, for any graded quasi-coherent $\mathcal{O}_X$-algebra $\mathscr{S}$, we have
$$\operatorname{\mathbf{Proj}}(\mathscr{S}) \cong \operatorname{Proj}\!\left(H^0(X,\mathscr{S})\right)$$
by the construction for relative $\operatorname{\mathbf{Proj}}$. In our case, letting $\mathscr{S} = \operatorname{S}(E)$, we have $H^0\!\left(X,\operatorname{S}(E)\right) = R(X;L_1,\ldots,L_n)$ by the Lemma, and so the isomorphism follows by the definition of $\mathbf{P}(E)$. $\blacksquare$
$X$ a normal complete variety over a field $k$, $L_i$ ample
Suppose $X$ is a normal complete variety over a field $k$. We first use the Lemma above to reduce to the case when $n = 1$, i.e., there is only one line bundle.
Lemma. Consider the projective space bundle $\mathbf{P}(E)$. Then, we have an isomorphism of $k$-algebras
$$R(X;L_1,\ldots,L_n) \cong R\!\left(\mathbf{P}(E);\mathcal{O}_{\mathbf{P}(E)}(1)\right).$$
Proof. Let $\pi\colon \mathbf{P}(E) \to X$ denote the projection morphism. By [EGAIII, Prop. 2.1.15] or [AVB, Lem. 3.1], there is a graded isomorphism of algebras
$$\operatorname{S}(E) \cong \bigoplus_{d \ge 0} \pi_*(\mathcal{O}_{\mathbf{P}(E)}(1))$$
and taking global sections yields $R(\mathbf{P}(E);\mathcal{O}_{\mathbf{P}(E)}(1))$ on the left-hand side. The previous Lemma gives the right-hand side. $\blacksquare$
We can then conclude:
Proposition. If $L_1,\ldots,L_n$ are ample, then
$$\mathbf{P}(E) \cong \operatorname{Proj}\!\left(R(X;L_1,\ldots,L_n)\right).$$
Proof. By the Lemma above, it suffices to show
$$\mathbf{P}(E) \cong \operatorname{Proj}\!\left(R\!\left(\mathbf{P}(E);\mathcal{O}_{\mathbf{P}(E)}(1)\right)\right).$$
By [AVB, Lem. 2.2] or [PAGII, Prop. 6.1.13(i)], we have that $E$ is an ample vector bundle, and so $\mathcal{O}_{\mathbf{P}(E)}(1)$ is ample. Thus, the Proposition reduces to showing the following
Claim. If $Y$ is a complete normal variety over a field $k$, and $L$ is an ample line bundle on $Y$, then
$$Y \cong \operatorname{Proj}\!\left(R(Y;L)\right).$$
and applying it to $Y = \mathbf{P}(E)$, $L = \mathcal{O}_{\mathbf{P}(E)}(1)$, since $\mathbf{P}(E)$ is normal if $X$ is. I can flesh out the details of the Claim if you'd like, but there is already a proof on Math.SE using Serre vanishing, and you can also prove this by using [Hartshorne, II, Exc. 5.13–14]. You can also look at this other Math.SE answer. $\blacksquare$
I'll end by remarking that even if $n = 1$, if we weaken the condition to $L$ semi-ample, that is, $L^{\otimes m}$ is globally generated for all $m \gg 0$, the isomorphism does not hold. The situation instead is that there is a canonical morphism $f\colon X \to \operatorname{Proj}\!\left(R(X;L)\right) =: Y$ such that $f_*\mathcal{O}_X = \mathcal{O}_Y$, but the morphism is only birational: a curve $C \subset X$ is contracted if and only if $(L \cdot C) = 0$. See [dFEM, Rem. 1.8.5] for this claim. We illustrate this with a concrete
Example. Let $X = \operatorname{Bl}_0\mathbf{P}^2$ be the blow-up of $\mathbf{P}^2$ at the origin, and consider $L = \mathcal{O}_X(\ell)$ the line bundle corresponding to the strict transform of a line $\ell$ in $\mathbf{P}^2$, not passing through $0$. Then, $L$ is semi-ample (since $\lvert \ell \rvert$ is already base-point free) but not ample since $(L \cdot E) = 0$, where $E$ is the exceptional divisor. Moreover,
$$R(X;L) = \bigoplus_{d \ge 0} H^0(X,L^{\otimes d}) = \bigoplus_{d \ge 0} H^0\!\left(X,\mathcal{O}_X(d\ell)\right) = \bigoplus_{d \ge 0} H^0\!\left(\mathbf{P}^2,\mathcal{O}_{\mathbf{P}^2}(d\ell)\right) \cong k[x_0,x_1,x_2],$$
but certainly $\operatorname{Bl}_0\mathbf{P}^2 \not\cong \operatorname{Proj}(k[x_0,x_1,x_2]) = \mathbf{P}^2$ (since, e.g., $\operatorname{Bl}_0\mathbf{P}^2$ has a $(-1)$-curve while $\mathbf{P}^2$ does not).
Answer: I was so sure that this result was going to be false, and wrote something below saying to look at using relative proj instead. If that's what you were looking for, the original answer is at the bottom.
However, I think the claim is true if $X$ is projective, so, if you're interested, please check my work on this. If $X$ is quasi-projective, you have way too many sections, so there's no chance it'd work. For example, we could let $X=\mathbb{A}^1$ and $\mathscr{E}=\mathscr{O}$, in which case you're taking Proj of a ring that is not even finitely generated in degree 1.
First, we use the concept of an ample vector bundle, which was given in the answer here: How do we define ample vector bundles. One of the equivalent definitions of an ample vector bundle $\mathscr{E}$ over $X$ was that the tautological line bundle $\mathscr{O}_{\mathbb{P}\mathscr{E}}(1)$ is ample on $\mathbb{P}\mathscr{E}$.
So now there are two things to see:
1) The direct sum of ample vector bundles is ample.
2) $H^{0}(Sym^r\mathscr{E})=H^0(\mathscr{O}_{\mathbb{P}\mathscr{E}}(r))$.
It's probably possible to see this directly, but it's late, so I'm just going to dig through the article (http://archive.numdam.org/ARCHIVE/PMIHES/PMIHES_1966__29_/PMIHES_1966__29__63_0/PMIHES_1966__29__63_0.pdf ) given in the linked answer above to see that it's true. Claim 1) is given in Proposition 2.2, and this I think can be done directly from the definition.
Claim 2) is a special case of Lemma 3.1, where we let $F=\mathscr{O}_X$ to get $Sym^r\mathscr{E}=\pi_{*}\mathscr{O}_{\mathbb{P}\mathscr{E}}(r)$ where $\pi: \mathbb{P}\mathscr{E}\rightarrow X$ is the projection.
Finally, putting the two together, we get that $\mathscr{O}_{\mathbb{P}\mathscr{E}}(1)$ is ample, so $\mathbb{P}\mathscr{E}=Proj(\oplus_{r\geq 0}{H^0(\mathscr{O}_{\mathbb{P}\mathscr{E}}}(r)))=Proj(\oplus_{r\geq 0}{H^{0}(Sym^r\mathscr{E})})$, which is equal to the formula you gave above in the case where $\mathscr{E}$ is a direct sum of ample line bundles.

Original answer:
It seems to me that what you're looking for is the relative proj construction. In the relative proj construction, instead of having a graded ring over some base ring $A$, we have a sheaf of graded algebras over a scheme $X$. Over each open affine ${\rm Spec}(A)$ in $X$, the relative proj agrees with the usual version, and it glues together to a projective scheme over $X$.
Given that, if we have a locally free sheaf $\mathscr{F}$, we have $\mathbb{P}\mathscr{F}=\mathcal{Proj}({\rm Sym}^{\cdot}\mathscr{F})$ (whether we take the dual $\mathscr{F}^{\vee}$ inside of the symmetric power depends on your convention for what $\mathbb{P}\mathscr{F}$ means). If you assume $\mathscr{F}$ splits as a direct sum of line bundles and expand, you get something similar to your formula, but as a sheaf of graded rings over $X$ instead of just one graded ring. For a reference, this is definition 17.2.3 in Vakil's notes (http://math.stanford.edu/~vakil/216blog/FOAGdec2915public.pdf).
Comment: I am sorry to bother you again but I don't understand a few things.. I don't understand why is it not true for $\mathbb{A}^1$. I was thinking that with $\mathbb{A}^1$ you should get $Proj(k[x,t])$ where $x$ has degree 1 and $t$ has degree 0, so it is $\mathbb{P}^0_{\mathbb{A}^1}=\mathbb{A}^1$, where am I wrong? Moreover in your answer, how do you get $\mathbb{P}(E)=Proj(\bigoplus H^0(Sym^r(E)))$? (claim 2 is Hartshorne III.8.4 a)
Comment: Okay, you have to make a consistent choice of what you're taking Proj over. In the first answer, I'm assuming we're working with schemes over $k$ (I think we can generalize, but it's better to start with this), and all our Proj constructions are over $k$. With $\mathbb{A}^1$, if we take Proj over $k$, the degree 1 part is already $k[x]$, which is an infinite $k$-vector space, and we're already doomed.
Comment: Now, you might say that taking proj over $k$ was stupid, we should really take proj over $k[x]$, so we get the right answer. Then in the case where $X$ is not affine, say $\mathbb{P}^1$, we need to use relative proj, which is what I suggested in the original answer.
Comment: As for your second question, in general, if you have $X$ a projective variety over $k$ and $L$ a very ample line bundle, then $X=Proj(\oplus_{r\geq 0}{H^r(L^{\otimes r})})$.
Comment: Okay but in this case you don't know that $O_{\mathbb{P}(E)}(1)$ is very ample over $k$, it is just ample over $X$
Comment: I still don't understand why the formula gives us the answer. $O_{\mathbb{P}(E)}(1)$ a priori is not ample over $k$, how do we apply it?
Comment: Let us [continue this discussion in chat](http://chat.stackexchange.com/rooms/39149/discussion-between-user2-and-dtseng).


How can I move email messages from Exchange Online to Gmail?

Question: We have an Exchange Online mailbox that received hundreds of emails that were supposed to be forwarded via an inbox rule to an @gmail.com address.  I've setup an inbox rule to handle any new messages but I need to "easily" get the old messages into the Gmail mailbox.
If I export the old messages to a PST the user has the hassle of trying to import this into Gmail using an Outlook client.  Is there a way to "redirect" not forward all the old messages to the @gmail.com address?  The goal being the preserve the original email headers when the message is forwarded to the @gmail.com.  I don't want the message to appear as forwarded.
I've not been able to find a way to do this after a message has been received.  I've been looking at ways with PowerShell, EWS, etc.  Any solution is acceptable.
Comment: "Any solution is acceptable." seems to contradict, "If I export the old messages to a PST the user has the hassle of trying to import this into Gmail using an Outlook client." You already wrote a very good solution into the question and even wrote that you'll accept any solution... but I guess not the solution you already know about? As far as I know, that's the only solution. You can alway have the user authenticate a separate Outlook client to their gmail and then you can do the import instead of them.
Answer: Gmail has the ability to pull messages from an external account over POP3.
In Gmail:

Click the Gear icon
Go to Settings
Click Accounts and Import
Click Add a POP3 mail account you own
Use the following server information
POP Server: outlook.office365.com
Port: 995
Check the box for Always use a secure connection (SSL)


Java List with two Objects inside: List

Question: Is it possible to do the following?
List<Object o, Object p> listWithTwoObjects;

I want to retrieve data from a database and save it into this list, concretely in this way
Query query = "retrieve all posts and username, which this user posted";
List<Object o, Object p> userAndPost = query.getResultList();

o is the username, and p is the post. I can then render this to my template and show each post with its user.
My question is about the List with two Objects inside. Is it possible and if yes, how and where is the documentation for this?
Answer: You can define a Pair class as follows:
public class Pair
{
    String username;
    int post;

    public Pair(String username, int post)
    {
        this.username = username;
        this.post = post;
    }
}

and then simply use List<Pair>, for example:
List<Pair> pairs = new ArrayList<Pair>();
pairs.add(new Pair("doniyor", 12345));

// ...

Pair p = pairs.get(0);
System.out.pritnln(p.username); // doniyor
System.out.pritnln(p.post); // 12345

Comment: Or even better, name them ´userName´ and ´post´
Comment: I suggest avoiding the fully generic `Pair` class, since `key` and `value` are really not very useful names for variables and don't tell you what the data is actually supposed to mean.
Comment: if i render this to my template as a json, then it will look like this:

``["username1":"post1","username2":"post2","username3":"post3"]``, right?
Comment: You can make the Pair class even more generic by

Pair {
  K key;
  V value;

  public K getKey() {
    return key;
  }

  public V getValue() {
    return value;
  }
}

That way, you can reuse your class to a greater extent.
Comment: @Wasserman thanks Louis, i think ftom2 has given a good option, but i take a look and give a shot. lets c which is the best one..
Comment: @Wasserman see your point with names not making sense, but if we're going down that road I'd call the class UsernamePostPair :-D
Answer: If i understand correctly you want to have all posts of a user, so instead of using List you should use Map:
Map<String,List<Post>> map = new HashMap<String,List<Post>>();

Then, the key(String) would be the userName and the value would be a list of Post objects.
Comment: More likeley it would look like: [{"username1":{"post1","post2"},"username2":{"post1","post2"}]
Comment: if i render this to my template as a json, then it will look like this:
``["username1":"post1","username2":"post2","username3":"post3"]`` , right?
Comment: You can use a Multimap instead. It is effectively a Map with Collection-based values. It is part of the Guava library.
Comment: You can use a Multimap instead. It is effectively a Map with Collection-based values. It is part of the Guava library.
Answer: You can't define a list like that, but you can use a Map, with username as key and post as value. Or is there a particular reason to use a list?

Java List with two Objects inside: List


Are the categories ${\bf{Sets}}/2$ and ${\bf{Sets}} \times {\bf{Sets}}$ isomorphic? Awodey's exercise

Question:
Let $2=\{a,b\}$ be any set with exactly $2$ elements $a$ and $b$. Define a functor $F:
{\bf{Sets}}/2\rightarrow{\bf{Sets}}\times{\bf{Sets}}$ with $F(f:X\rightarrow 2)=(f^{-1}(a),f^{-1}(b))$. Is this an isomorphism of categories?

This is something that I've done: In ${\bf{Sets}}/2$, let $h:X\rightarrow\{a,b\}$ such that $h^{-1}(a)\not=\emptyset$ and $h^{-1}(b)\not=\emptyset$ and let $f:X\rightarrow\{a,b\}$ such that $f^{-1}(a)=X$ and $f^{-1}(b)=\emptyset$. Then there is no arrow between $f$ and $h$ in ${\bf{Sets}}/2$, but there is one arrow between $F(f)=(X,\emptyset)$ and $F(h)=(h^{-1}(a),h^{-1}(b))$ in ${\bf{Sets}}\times{\bf{Sets}}$, so these two categories are not isomorphic.
Is this reasoning ok?
I am a complete novice in the category theory!
Answer: Your argument is not correct. In fact, $F$ is fully faithful.
Define a functor $G : \mathsf{Set} \times \mathsf{Set} \to \mathsf{Set} / \{a,b\}$ by mapping two sets $A,B$ to the function $G(A,B) : A \coprod B \to \{a,b\}$ which maps the elmenets of $A$ to $a$ and the elements of $B$ to $b$. Here, $A \coprod B= A \times \{1\} \cup B \times \{2\}$ is the standard construction of the disjoint union. Then we have $FG \cong \mathrm{id}$ and $GF \cong \mathrm{id}$. Hence, $F$ is an equivalence of categories.
But $F$ is not an isomorphism. In fact, $F$ is not surjective on objects. If $A,B$ are two sets which are not disjoint, then $(A,B)$ doesn't lie in the image of $F$. (Notice, however, that $F$ lies in the essential image of $F$.)
Here is how I think about this: The notion of "isomorphism of categories" belongs to $0$-category theory $\approx$ set theory. It is much too strong to explain various "structural equalities of categories". A far better behaved notion is that of an "equivalence of categories". Only this belongs to $1$-category theory. If $A,B$ are two sets, then the property that $A,B$ are disjoint cannot be formulated in category theoretic terms, since this property is not invariant under self-equivalences of $\mathsf{Set} \times \mathsf{Set}$. In fact, we can make $A,B$ disjoint by replacing them by $A^* = A \times \{1\}$ and $B^* = B \times \{2\}$. Then $(A,B) \cong (A^*,B^*)$ in $\mathsf{Set} \times \mathsf{Set}$. In category theory, in order to state that two objects $A,B$ are disjoint, we need a larger object $S$ which contains both. Then their intersection is given by the pullback $A \times_S B$, and $A,B$ are called disjoint when this pullback is an initial object. In set theory, one often imagines the universe $V$ to be some kind of universal object which contains all other objects of consideration. Every set then has a unique embedding into $V$. In category theory, however, one really has to remember all the embeddings. In particular, there is a completely different point of view on subsets. For more on this, see SE/704593 and SE/295800. In my opinion category theory is the better language to explain structural mathematics.
Comment: Another approach that I have tried comes down to the fact that F is not surjective, but I was not sure whether I am allowed to use this principle (on an arbitrary large category) to prove that the mapping is not an isomorphism. So, whenever we talk about the "isomorphism of categories", we can reason like we do in set theory? I was wondering how should someone who has, let's say, read only the first chapter of Awodey's book and then tried to do corresponding exercises, think about this issue. Thank you so much for your answer!
Comment: Look up the definition of an isomorphism of categories - you will immediately realize that it induces a bijection on the object classes.
Answer: I'm afraid your argument is not correct: there are morphisms from $f$ to $h$.
Hint: Perhaps $F$ is not an $isomorphism$ of categories, but something slightly weaker?


Erro deploy Heroku app Django

Question: Após fazer o deploy no Heroku, fui abrir o link da minha aplicação (https://silima.herokuapp.com/), e a mesma apresentou o seguinte erro:
    ProgrammingError at /
relation "Produto" does not exist
LINE 1: ..., "Produto"."criado", "Produto"."modificado" FROM "Produto" ...
                                                             ^
Request Method: GET
Request URL:    https://silima.herokuapp.com/
Django Version: 2.0.3
Exception Type: ProgrammingError
Exception Value:
relation "Produto" does not exist
LINE 1: ..., "Produto"."criado", "Produto"."modificado" FROM "Produto" ...
                                                             ^
Exception Location: /app/.heroku/python/lib/python3.6/site-packages/django/db/backends/utils.py in _execute, line 85
Python Executable:  /app/.heroku/python/bin/python
Python Version: 3.6.3
Python Path:
['/app',
 '/app',
 '/app/.heroku/python/lib/python36.zip',
 '/app/.heroku/python/lib/python3.6',
 '/app/.heroku/python/lib/python3.6/lib-dynload',
 '/app/.heroku/python/lib/python3.6/site-packages']
Server time:    Qua, 23 Mai 2018 10:22:22 -0300

Comment: Após o deploy, você rodou as migrações de banco de dados do django?
Answer: Se você não teve problemas no deploy, imagino que tenha adicionado o add-on do Postgres. Então o heroku run python manage.py migrate deve resolver o problema. Lembrando que antes você tem que estar logado (heroku login).
Comment: Show de bola, era isso mesmo, esqueci de dar o migrate, deu certo, agora estou com mais uma duvida, algumas imagens o Django não renderizou na minha pagina, não são todas, apenas algumas. Estou esquecendo de algo ?
Comment: Depende. Seriam imagens que você fez upload?
Comment: Então, essas imagens estão em uma pasta dentro da pasta static, estranho que outras imagens deram certo.
Comment: @GabrielGeorge acho que o melhor seria criar uma nova pergunta e jogar lá os detalhes, como a arvore de diretorio do seu projeto, seu `settings.py` e etc
Comment: Sim, verdade ! Vou fazer isso, mesmo assim, muito obrigado pela força!

Erro deploy Heroku app Django


Como funciona o settimeout('__dopostback( 'dropdownlist 1 ' ' ')' 0)?

Question: eu gostaria de saber como que funciona, pois estou tentando aprender, e estou com algumas dúvidas, sou iniciante nesse assunto estou lendo sobre javascript há poucos dias.
Eu gostaria de saber como funciona também o tabindex.
Comment: Sua dúvida é sobre o `setTimeout`, ou sobre o `doPostBack` que tem dentro? Quanto ao tabindex, melhor postar uma pergunta separada sobre isso (aqui no site nós tentamos separar as perguntas assim por tema para que depois elas possam ajudar outras pessoas com a mesma dúvida).
Comment: java != javascript
Answer: Na prática eu utilizo para setar um evento server side via JavaScript.
Detalhes:

settimeout: Seta um tempo de espera para executar uma função ou ação.
dopostback: Chama a função de postback, passando com parâmetro o elemento do evento.


ASP.NET MVC Post Date Format

Question: Tenho um formulário que envia via post os parâmetros de pesquisa, porém o parametro do tipo data sempre que chega na action o mes e dia estão invertidos,  por exemplo, se coloco na página a data 04/03/2016 no controle chega 03/04/2016
@model CaixaIndexViewModel

        Pesquisa de caixas

        @using (Ajax.BeginForm(actionName: "Pesquisa", controllerName: "Caixa",
                                            routeValues: new { page = 1 },
                                            ajaxOptions: new AjaxOptions
                                            {
                                                HttpMethod = "GET",
                                                InsertionMode = InsertionMode.Replace,
                                                UpdateTargetId = "unobtrusive",
                                                OnComplete = "onComplete"
                                            }))
        {

                            Nome
                            <input type="text" class="form-control" id="nome" name="nome" value="@ViewBag.nome" />

                            Data
                            <input type="date" class="form-control" id="data" name="data" value="@ViewBag.data" />

                            Valor R$
                            <input type="text" class="form-control" id="valor" name="valor" value="@ViewBag.valor" />

                        <button type="submit" class="btn btn-primary" id="btnPesquisar">

                        </button>

        }

                    @if (Model.CaixaControle == null || Model.CaixaControle.DataHoraFechamento.HasValue)
                    {
                         Abrir caixa
                    }
                    else
                    {
                        if (Model.CaixaControle.DataHoraAbertura.Date == DateTime.Now.Date)
                        {
                             Novo
                        }
                         Fechar caixa
                    }

                    @if (Model.Pesquisa.Count() > 0)
                    {
                         Editar
                         Detalhes
                         Excluir
                    }

                    @Html.Partial("_Pesquisa", Model)

@section Scripts{

@Scripts.Render("~/bundles/jqueryval")

}

Controller
public ActionResult Index()
        {
            var nome = Request.Cookies["caixa.nome"]?.Value ?? "";

            var descricao = Request.Cookies["caixa.descricao"]?.Value ?? "";

            DateTime data = DateTime.Now.AddMonths(-1);
            DateTime.TryParse(Request.Cookies["caixa.data"]?.Value ?? "a", out data);
            if (data == DateTime.MinValue)
                data = DateTime.Now.AddMonths(-1);

            decimal valor = 0;
            decimal? valorPesquisa = null;
            if (decimal.TryParse(Request.Cookies["caixa.valor"]?.Value ?? "a", out valor))
            {
                valorPesquisa = valor;
            }

            int page = 1;
            int.TryParse(Request.Cookies["caixa.page"]?.Value ?? "1", out page);

            return Pesquisa(page, nome, data, valorPesquisa);
        }

        public ActionResult Pesquisa(int page, string nome, DateTime data, decimal? valorPesquisa = null)
        {
            data = data.Date;

            Response.Cookies["caixa.page"].Value = page.ToString();

            Response.Cookies["caixa.nome"].Value = nome;
            ViewBag.nome = nome;

            Response.Cookies["caixa.data"].Value = data.ToString();
            ViewBag.data = data;

            Response.Cookies["caixa.valor"].Value = valorPesquisa.ToString();
            ViewBag.valor = valorPesquisa;

            var caixas = from c in context.Caixa
                         where c.DataHoraCad >= data
                         orderby c.DataHoraCad descending
                         select new CaixaPesquisaModel()
                         {
                             CaixaId = c.CaixaId,
                             Descricao = c.Descricao,
                             Nome = c.Pessoa.Nome,
                             DataHora = c.DataHoraCad,
                             Observacao = c.Observacao,
                             Tipo = c.Tipo,
                             Valor = c.Valor
                         };

            int pageSize = 10;
            var itens = caixas.ToPagedList(page, pageSize);

            var caixaControle = context.CaixaControle
                .Where(a => a.UsuarioCaixa == this.Usuario)
                .OrderByDescending(a => a.DataHoraAbertura)
                .FirstOrDefault();

            var model = new CaixaIndexViewModel()
            {
                CaixaControle = caixaControle,
                Pesquisa = itens,
            };

            if (Request.IsAjaxRequest())
                return View("_Pesquisa", model);

            return View(model);
        }

Answer: Tenho os mesmos problemas em sistemas meus. Implementei um DateTimeBinder que resolve o problema:
public class DateTimeModelBinder : DefaultModelBinder
{
    public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
    {
        object result = null;

        string modelName = bindingContext.ModelName;
        string attemptedValue = bindingContext.ValueProvider.GetValue(modelName).AttemptedValue;

        if (String.IsNullOrEmpty(attemptedValue))
        {
            return result;
        }

        try
        {
            result = DateTime.Parse(attemptedValue);
        }
        catch (FormatException e)
        {
            bindingContext.ModelState.AddModelError(modelName, e);
        }

        return result;
    }
}

É preciso registrar este Model Binder no início da aplicação (Global.asax):
    protected void Application_Start()
    {
        AreaRegistration.RegisterAllAreas();
        GlobalConfiguration.Configure(WebApiConfig.Register);
        FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
        RouteConfig.RegisterRoutes(RouteTable.Routes);
        BundleConfig.RegisterBundles(BundleTable.Bundles);

        ModelBinders.Binders.Add(typeof(DateTime?), new DateTimeModelBinder());

        ...
    }

Confira também se seu Web.config contém o seguinte:
<system.web>
  <authentication mode="None" />
  <compilation debug="true" targetFramework="4.5.2" />
  <customErrors mode="Off" />
  <httpRuntime targetFramework="4.5" />
  <globalization uiCulture="pt-BR" culture="pt-BR" enableClientBasedCulture="true" />
</system.web>

Comment: Adicionei os códigos no meu projeto, mas mesmo assim continua trocando o mês pelo dia
Comment: optei por passar como string mesmo e converter na action

ASP.NET MVC Post Date Format


Trying to pull replies of comments from facebook with php and json

Question: I am trying to pull a public page from facebook using php and json to sort the data received. I have everything working perfectly apart from replies on comments on posts. I can get all the list of comments on a post but the replies to that comment do not appear on the json data that is returned to me. I believe when the user of the page comments on his own post the story tag is given to the comment and it is unrelated to the comments section of that post. But if anybody else replies to a comment i cannot see their message anywhere. Is there any way to try and get the replies of comments returned in json along with everything else?
Comment: having this same issue, please post back if you find a solution. page comment replies do not show in the facebook graph explorer either. stuck!
Answer: edit: found a better solution
see the answer here: How to get the image from a facebook photo comment?
the query you want to perform is
<code>/{page-post-id}/comments?fields=from,message,id,attachment,created_time,comments.fields(from,message,id,attachment,created_time)</code>
to query this via PHP you would do something like this:

$page_comment_id = 12345; // put your id here
$access_token = ''; // put your facebook access token here
$url = 'https://graph.facebook.com/' . $page_comment_id . '/comments?fields=from,message,id,attachment,created_time,comments.fields(from,message,id,attachment,created_time)&access_token=' . $access_token;
$data = json_decode(file_get_contents($url),true);
print_r($data);
Comment: and do you know what way you would put this request in php to pull down the replies?


File exist but laravel can't find it (FileNotFoundException)

Question: I'm trying to check if the file exists to delete it when the post is deleted but it's never finding it.
If I change the Storage::exists() for Storage::get() just to check, I get the File Not Found Exception with the path C:/xampp/htdocs/cms/blog/public/images/apple.jpg which I can see the picture if I put in the browser.
Store function on PostController
public function store(CreatePostRequest $request)
{
    $input = $request->all();

    if ($file = $request->file('file')) {
        //
        $name = $file->getClientOriginalName();
        $file->move(public_path('images/'), $name);
        $input['path'] = $name;
    }

    $new_post = Post::create($input);
    return redirect(route('post.show', $new_post->id));
}

Destroy function on PostController
public function destroy($id)
{
    $post = Post::findOrFail($id);

    if (Storage::exists(public_path('images/') . $post->path))
        Storage::delete(public_path('images/') . $post->path);

    $post->delete();

    return redirect(route('posts.index'));
}

I also have this on my filesystems.php
'links' => [
    public_path('storage') => storage_path('app/public'),
    public_path('images') => storage_path('app/images'),
],

I can easily show the image in blade with just src="{{'/images/' . $post->path}}"
Comment: try to set this path `public_path('images') => storage_path('app/public/images'),`
Answer: You could try using unlink.
$image_path = $post->path;
unlink($image_path);

The second option is to use the File Facade.
use Illuminate\Support\Facades\File;
$filename = $post->path;
File::delete($filename);

Make sure that the image path is correct.
Comment: Thanks the second option helped, because i need to check if exists before delete.
Answer: I Had to use the Illuminate\Support\Facades\File sugested by Aless
Fixed destroy funcion on PostController
public function destroy($id)
{
    $post = Post::findOrFail($id);

    $imagePath = public_path('images/') . $post->path;

    if (File::isFile($imagePath))
        File::delete($imagePath);

    $post->delete();

    return redirect(route('posts.index'));
}


unable to add configure field to drupal view

Question: I added a new field to an existing content type. But when I try to add same field or any other field to the view, I don't find it in the list except few.
Eg: I added image field to content type. Then I clicked on 'edit view' for which I want to add this image field. Then I click on add field under fields section. I don't find the fields of image body or anything, except title field others.
Can anybody help me sort out this issue?
Answer: Your view is not a Content view.  Create a "Content" relationship on the view, and all the content type fields configured on your site will become available to add to the view.


JBoss Developer Studio Third Party Plugins

Question: I am currently looking at development IDEs and one that I am considering is JBoss Developer Studio.  Since the system is based on Eclipse, I was wondering if it was possible to install third party plugins?
In particular, I am interested in being able to install plugins such as Aptana so that I can get Ruby on Rails support.
Does anyone know if third-party Eclipse plugins can be installed to JBoss Developer Studio and if there are any complications in doing so?
Answer: You installed JBoss Developer Studio and now you want to install more plugins then you can use Help > Install New Software.Its may be what you are looking for.


How to prevent node creation using hook_node_submit?

Question: Could you clarify me, how can I prevent node creation if I use hook_node_submit ?
What should I do in code of the hook for it ?
Do returning false ? Or throw an exception ?
That is, if some condition is true then the node simply does not create, without output of any error message.
Comment: It doesn't look like there is a way to prevent the node creation in this hook.
Answer: To stop a node being created, you need to implement hook_node_validate instead, and raise an error. The hook is specifically to:

Perform node validation before a node is created or updated.

Which is what you want.
The example in the docs page is probably quite close to what you'll need:
function hook_node_validate($node, $form, &$form_state) {
  if (isset($node->end) && isset($node->start)) {
    if ($node->start > $node->end) {
      form_set_error('time', t('An event may not end before it starts.'));
    }
  }
}

For the record, hook_node_submit is both conceptually the wrong place to try to stop a node being created, and too late in the process to do so anyway. The node hasn't been saved by that point, but you've lost any simple opportunity to stop the remaining submit handlers running and the default process completing. Even if you found a way to short out that functionality, there would be no sensible method to feed that back to the user.
You can throw an exception or kill the page request of course, yes, but Drupal obviously won't be able to recover from that and the request will terminate.
Comment: Can I do it without function form_set_error('') ?
Comment: No, that's what stops the form from submitting and subsequently the node being saved (you can use form_error instead but you have to use one of them). You might get better answers if you edit the question and explain what you're actually trying to achieve, and why invalidating the form, which would be the standard thing to do, isn't desirable
Comment: Hi @Clive your answer is always great but here I have one question is it possible to achieve this without showing the error message or is it useful if I do not show the error message. In question in the last line it is mentioned without output of any error message.
Answer: I don't 'think you can prevent node creation using hook_node_submit. Once this function execute it create node.
You can modify or something like that once node created depend on your conditions.


WPF, change separate color based on value

Question: I try change separate cell color based on value in wpf datagrid.I use datagrid 2d.
<code>      <DataGrid Name="c_dataGrid"
       RowHeaderWidth="0"
       ColumnHeaderHeight="0"
       AutoGenerateColumns="True"
       AutoGeneratingColumn="c_dataGrid_AutoGeneratingColumn"
       SelectionUnit ="CellOrRowHeader"
       IsReadOnly="True">
       </DataGrid>
</code>
I need change cell color when value is example 1.
Answer: Edited to more accurate:
<code><DataGridTextColumn>
    <DataGridTextColumn.ElementStyle>
        <Style TargetType="{x:Type TextBlock}">
            <Style.Triggers>
                <Trigger Property="Text" Value="1">
                    <Setter Property="Background" Value="Yellow"/>
                </Trigger>
            </Style.Triggers>
        </Style>
    </DataGridTextColumn.ElementStyle>
</DataGridTextColumn>
</code>
Comment: program writes error : Item collection must by empty before using ItemsSource.
Comment: Use search, there are much same topics about this error.


Oracle, inner join with group by clause

Question: I have two oracle tables :

USERS : ID, USERNAME, PASSWORD, ROLE
ARCHIVE_POSESSION : ID, USERID, ARCHIVEID

What I'm trying to do is obtain a query that returns me the following result set :

Username, Role, Number Of Archives

So far so good, but I can't wrap my head around the query, I'm still a beginner. So far this is where I got:
SELECT users.ID, USERNAME, ROLE, count(archive_posession.USERID)
from users inner join
archive_posession on
users.id = archive_posession.USERID
group by
archive_posession.USERID ;

But it gives me this error
ORA-00979: not a GROUP BY expression

Any tips? I'm sure group by is supposed to work for aggregate functions, but in this case I'm stoked.
Comment: possible duplicate of [ORA-00979 not a group by expression](http://stackoverflow.com/questions/1520608/ora-00979-not-a-group-by-expression)
Answer: The fields that you select are either be declared in group by or you should use an aggregate function.
For example
SELECT archive_posession, Max(USERID USERNAME), Max(ROLE), count(archive_posession.USERID)
FROM users INNER JOIN
archive_posession ON
users.id = archive_posession.USERID
GROUP BY
archive_posession.USERID ;

should do the trick.
The reason why that resolves this issue is because Group By returns a single row. So you should find a way to gather all selected fields that are not in group by in a single row only
Comment: Thanks for the effort but he got it first. Your post was informative so I'll give you an upvote.
Answer: It looks to me like you're trying to do something like
SELECT u.USERNAME, u.ROLE, COUNT(a.USERID)
  FROM USERS u
  INNER JOIN ARCHIVE_POSESSION a
    ON a.USERID = u.ID
  GROUP BY u.USERNAME, u.ROLE;

All columns in the SELECT list of a GROUP BY query must either be members of the GROUP BY list, or must be an aggregate function such as COUNT. In your query USERNAME and ROLE were not members of the GROUP BY list, and thus the query you saw was produced.
Comment: This did the trick, thanks! But there's a typo in your query, it's u.ID.
Comment: Ah, missed that. Corrected.
Comment: You got it wrong again. lol. ON a.USERID = u.ID . Anyway I'll vote your answer as correct.
Comment: To be fair, @istovatis posted his answer before mine.

Oracle, inner join with group by clause


Attaching the comment form programmatically

Question: How do I add the comments form (of the comments module) programmatically in a custom-made module?
In other words, what proper code should be added to your module code to add a complete "Post New Comment" form (of the Comments core module)?
That said, how do I force the installation of the Comment module with the installation of your own module?

I'm re-asking my question in an edited version with some new results i've reached :).
I've created a custom menu in a custom module of mine, with items of course.
I wanted to add the comment form (of the Comment module) to the page that my item takes me to.
The problem is that the page i'm redirected to is not a node, but it is a render-able page that displays the data according to it's 'page_arguments'.
It is as follows:

$items['car/%'] = array(
        'title' => 'Cars',
        'page callback' => 'car_page',
        'page arguments' => array(1),
        'access callback' => TRUE,
        'type' => MENU_CALLBACK,
);

I want to attach the comment form (of the Comment Module) to that page.
I used the following code:

module_load_include('module', 'contact');

$build = array(
    'header_text' => array(
        '#type' => 'markup',
        '#markup' => 'Building comments in page.',
    ),
    'the_form' => drupal_get_form('comment_form', ''),
);

return $build;

All is correct code.
But the problem is that the comment form and the posted comments are loaded depending on the node Id (nid), and in my case there is no node Id (nid)!
How could i assign a specific identifier of that custom page so that the comment form functions correctly and comments related to that page are correctly loaded?!
And in the code above, i managed to call the form using drupal_get_form(), and assigned an empty second argument! I don't think that's right, right?
Any ideas!?
Answer: comment_form() is expecting the parameter to be an object rather than an array so you should be doing something like this:
$comment = new stdClass;
$comment->nid = $row->nid;
$form = drupal_get_form('comment_form', $comment);

Note the lack of a 3rd parameter passed to drupal_get_form(), comment_form() only accepts the comment as a parameter, if you want to add a title you'll have to print that separately.
Finally drupal_get_form() returns a render array rather than a string so you need to pass it through the render() function:
print render($form);

The extra errors you're getting are just side-effects of passing an array rather than an object to the comment_form() function
Answer: Attach comments to what? Note that you can only attach comments to nodes.
The API function for saving comments is comment_save(). You will have to figure out what kind if properties you need to have on the $comment object that you want to pass in. Probably at least nid, subject and body['und'][0]['value'].

That said, how to force the installation of the comments module with the installation of your own module?

Thtat is a separate question, try to only ask a single question at once. You need to add dependencies[] = comment in your .info file.
Comment: Sorry for the 2 questions, but they seemed a bit related. Concerning the comments, i created a custom form which i want users to be able to commment on. So, i want to attach comments to the page that my custom form is in! Is that possible?
Comment: No. Not without some hacks, that is. (For example, you could create a fake node and then add comments to that node id and query them).


train and validation in a multi model pipeline

Question: I have a pipeline which contains two NN blocks one after the other (the second gets as input the first output). I was wondering how to train and validate the two blocks.

Split to train, val and test. run the training on the first block and get the results which will be the input to the second block. the validation phase will be the same.
I can run train and validation on the first block and the validation of the first will become train+ val for the second block.
Run k-fold cross-validation on the first block and save the val results for each fold. from this val data we can build a new dataset for the second block.

What is the best work paradigm for this problem?
Comment: This seems more like a question of machine learning architecture than a question of machine learning statistics. I think ai.stackexchange (or even datascience.stackexchange) would be more suitable.
Answer: The point of having separate validation and test sets is to make sure that you verify your results on "unseen" data. If you used the same data, or there were data leaks, you risk having overtly optimistic metrics that could lead to false conclusions about the model performance.
With splitting the data, there are three things to consider. First, how much data is "wasted" on validation vs training ($k$-fold does best in here). Second, how time-consuming or computationally demanding the training would be ($k$-fold is the slowest, as you repeat the process $k$ times, or need to run it in parallel). Third, how reliable the results are (if you verify results only using train set metrics, everything would be fast, no data "wasted", but the metrics would be unreliable). I'd say that an in-between strategy would be to have single training sets used by both models (why not?), separate validation set for each model, and a single test set (there would be only one future, unseen data, you don't need parallel universe for testing the outcomes).


Random variables for which Markov, Chebyshev inequalities are tight

Question: I am interested in constructing random variables for which Markov or Chebyshev inequalities are tight.
A trivial example is the following random variable.
$P(X=1)=P(X=-1) = 0.5$. Its mean is zero, variance is 1 and $P(|X| \ge 1) = 1$. For this random variable chebyshev is tight (holds with equality).
$$P(|X|\ge 1) \le \frac{\text{Var}(X)}{1^2} = 1$$
Are there more interesting(non-uniform) random variables for which Markov and Chebyshev are tight ? Some examples would be great.
Comment: What do we mean by tight  Chebyshev inequalities please?
Answer: The class of distributions for which the limiting case of the Chebyshev bound holds is well known (and not that hard to simply guess). Normalized to mean $0$ and variance $1$, it is
$$Z=\begin{cases}-k,&{\text{with probability }}{\:\frac {1}{2k^2}}\\\:0,&{\text{with probability }}1-\frac {1}{k^2}\\\:k,&{\text{with probability }}{\:\frac {1}{2k^2}}\end{cases}$$
This is (up to scale) the solution given at the Wikipedia page for the Chebyshev inequality.
[You can write a sequence of distributions (by placing $\epsilon>0$ more probability at the center with the same removed evenly from the endpoints) that strictly satisfy the inequality and approach that limiting case as closely as desired.]
Any other solution can be obtained by location and scale shifts of this: Let $X=\mu+\sigma Z$.
For the Markov inequality, let $Y=|Z|$ so you have probability $1-1/k^2$ at 0 and $1/k^2$ at $k$. (One can introduce a scale parameter here but not a location-shift parameter)

Moment inequalities - and indeed many other similar inequalities - tend to have discrete distributions as their limiting cases.
Comment: One where the bound is attained (or at least where you can approach it as the limit of a sequence)
Comment: What do we mean by tight  Chebyshev inequalities please? What are possible applications of this tightens please? Also I am not sure where is equality above please of Chebyshev's inequality?
Answer: I believe that getting a continuous distribution over the whole real axis that follows Chebyshev's bound exactly may be impossible.
Assume that a continuous distribution's mean and standard deviation are 0 and 1, or make it so via rescaling. Then require $P(\mid X\mid >x)=1/x^2$.
For simplicity consider $x>0$; the negative values will be defined symmetrically. Then the CDF of the distribution is $1-1/x^2$. And so the pdf, the derivative of the cdf, is $2/x^3$. Obviously this must be defined only for $x>0$ because of the discontinuity. In fact, this can't even be true everywhere, or the integral of the pdf is not finite. Instead, if discontinuities are to be avoided (e.g. the pdf cat just be 0 for $\mid x \mid <\alpha$) the pdf must be piecewise, equal to $\mid x \mid^3$ for $\mid x\mid \geq \alpha$.
However, this distribution fails the hypothesis - it does not have finite variance. To get a continuous distribution over the real axis with a finite variance, the expected values of $x$ and $x^2$ must be finite. Examining inverse polynomials, tails that go like $x^{-3}$ lead to a finite $E[x]$, but an undefined $E[x^2]$ because this involves an integral with asymptotically logarithm behavior.
So, Chebychev's bound can't be satisfied exactly. You can require $P(\mid X \mid > x ) = x^{-(2+\epsilon)}$ for arbitrarily small $\epsilon$, however. The tail of the pdf goes like $x^{-(3+\epsilon)}$ and has a defined variance on the order of $1/\epsilon$.
If you're willing to let the distribution live on only part of the real line, but still be continuous, then defining $pdf(x) = 2/\mid x \mid^3$ for $\epsilon < \mid x \mid < \Lambda$ works for
$$
\epsilon = \sqrt{2 \left( 1 - \frac{1}{\sqrt{e}} \right) }
$$
and
$$
\Lambda = \epsilon = \sqrt{2 \left( \sqrt{e} - 1 \right) }
$$
or any linear scaling thereof -- but this is basically $0.887 < |x| < 1.39$, which isn't much of a range. And its doubtful whether this restriction is still in line with the original motivation.
Comment: @MichaelChirico I don't think so either; I just didn't want to go through the effort.
Comment: I don't think it's hard to prove no infinite-support continuous variable can achieve the lower bound


invalid syntax when trying to use os.path.join in pygame in loading images and sounds

Question: I created a game using pygame and I loaded the images and the sound files using the full path name of the files, but I'd like to make the game executable to run in any location and any other computers.
To that  I replaced the full path name by os.path.join to load images and sound files from relative folder.
it was working fine for the first two lines by using it in more lines it gives me this error:
pygame.mixer.music.set_volume(0.5)
    ^
SyntaxError: invalid syntax
So if there a way to let the game load the data from the adjacent folder no matter where it's located, or to know

import pygame
import winsound
from pygame.locals import *
import auto_py_to_exe
from distutils.core import setup
import py2exe
import os
import sys
import time
import random

pygame.init()
screen_width = 800
screen_height = 500
win = pygame.display.set_mode((screen_width,screen_height))
pygame.display.set_caption('Game')

walkRight = [pygame.image.load(os.path.join('data','S1.png')), pygame.image.load(os.path.join('data','S2.png')), pygame.image.load(os.path.join('data','S3.png')), pygame.image.load(os.path.join('data','S4.png')), pygame.image.load(os.path.join('data','S5.png')), pygame.image.load(os.path.join('data','S6.png')), pygame.image.load(os.path.join('data','S7.png')), pygame.image.load(os.path.join('data','S8.png')), pygame.image.load(os.path.join('data','S9.png')), pygame.image.load(os.path.join('data','S10.png')), pygame.image.load(os.path.join('data','S11.png')), pygame.image.load(os.path.join('data','S12.png')), pygame.image.load(os.path.join('data','S13.png')), pygame.image.load(os.path.join('data','S14.png')), pygame.image.load(os.path.join('data','S15.png')), pygame.image.load(os.path.join('data','S16.png')), pygame.image.load(os.path.join('data','S17.png')), pygame.image.load(os.path.join('data','S18.png')), pygame.image.load(os.path.join('data','S19.png')), pygame.image.load(os.path.join('data','S20.png')), pygame.image.load(os.path.join('data','S21.png')), pygame.image.load(os.path.join('data','S22.png')), pygame.image.load(os.path.join('data','S23.png')), pygame.image.load(os.path.join('data','S24.png')), pygame.image.load(os.path.join('data','S25.png')), pygame.image.load(os.path.join('data','S26.png')), pygame.image.load(os.path.join('data','S27.png')), pygame.image.load(os.path.join('data','S28.png')), pygame.image.load(os.path.join('data','S29.png')), pygame.image.load(os.path.join('data','S30.png')), pygame.image.load(os.path.join('data','S31.png')), pygame.image.load(os.path.join('data','S32.png')), pygame.image.load(os.path.join('data','S33.png'))]
walkleft = [pygame.image.load(os.path.join('data','H1.png')), pygame.image.load(os.path.join('data','H2.png')), pygame.image.load(os.path.join('data','H3.png')), pygame.image.load(os.path.join('data','H4.png')), pygame.image.load(os.path.join('data','H5.png')), pygame.image.load(os.path.join('data','H6.png')), pygame.image.load(os.path.join('data','H7.png')), pygame.image.load(os.path.join('data','H8.png')), pygame.image.load(os.path.join('data','H9.png')), pygame.image.load(os.path.join('data','H10.png')), pygame.image.load(os.path.join('data','H11.png')), pygame.image.load(os.path.join('data','H12.png')), pygame.image.load(os.path.join('data','H13.png')), pygame.image.load(os.path.join('data','H14.png')), pygame.image.load(os.path.join('data','H15.png')), pygame.image.load(os.path.join('data','H16.png')), pygame.image.load(os.path.join('data','H17.png')), pygame.image.load(os.path.join('data','H18.png')), pygame.image.load(os.path.join('data','H19.png')), pygame.image.load(os.path.join('data','H20.png')), pygame.image.load(os.path.join('data','H21.png')), pygame.image.load(os.path.join('data','H22.png')), pygame.image.load(os.path.join('data','H23.png')), pygame.image.load(os.path.join('data','H24.png')), pygame.image.load(os.path.join('data','H25.png')), pygame.image.load(os.path.join('data','H26.png')), pygame.image.load(os.path.join('data','H27.png')), pygame.image.load(os.path.join('data','H28.png')), pygame.image.load(os.path.join('data','H29.png')), pygame.image.load(os.path.join('data','H30.png')), pygame.image.load(os.path.join('data','H31.png')), pygame.image.load(os.path.join('data','H32.png')), pygame.image.load(os.path.join('data','H33.png'))]

pygame.mixer.init()
pygame.mixer.Sound(os.path.join('sound','music.wav')
pygame.mixer.music.set_volume(0.5)
pygame.mixer.music.play(-1)

bg = pygame.image.load(os.path.join('data','FOREST.jpg').convert()

'''

Answer: You forgot one parenthesis here pygame.mixer.Sound(os.path.join('sound','music.wav')
It must be like this pygame.mixer.Sound(os.path.join('sound','music.wav'))


O Xamarin é uma opção viável para desenvolvimento mobile?

Question: Preciso desenvolver para mobile e estava pensando no Xamarin como opção, e só depois fui dar uma pesquisada e descobri que:

O Xamarin é pago, e o preço é meio salgado para uma reles licença individual.
Não há como desenvolver o app 100% em C#, a maioria diz que 75% do código vai ser escrito em C# e o restante na linguagem nativa do sistema.
Para compilar apps para iOS vou ter que comprar um Mac.

Com estes três pontos em mente gostaria de saber se o Xamarin é uma opção viável?
Comment: E tem como, no meu ponto de vista, desenvolver 95% em C#
Comment: `Xamarin` agora é gratuito no seu caso
Comment: @rubStackOverflow Se não estou errado, segue os mesmos termos de utilização do VisualStudio Community 2015.
Comment: Eu acho que se você sabe o que vai fazer o Xamarin é bom
Answer: Não vou responder a parte que pede opinião porque não é objetivo deste site e não deveria ser de nenhum, já que isto não resolve problema de ninguém.
É óbvio que é viável, afinal tem um monte de gente fazendo isto.
Cada um sabe onde seu calo dói e vai ver se a ferramenta atende em todos pontos. Não dá para pessoas aleatórias na internet dizer o que é bom para você.
Nunca ouvi falar que precisa usar outra linguagem para fazer outras partes. Até onde eu sei dá para fazer 100% em C#. Claro que pode existir alguma coisa muito específica e rara que não dê para fazer bem em C# porque o Xamarin ainda não está 100%. Não acho que isto torne ele muito menos interessante. Ainda há ganhos no seu uso.
O que pode acontecer é ter que fazer algumas partes em C# mesmo que só sejam úteis para uma das plataformas. Isto é comum, mas existem técnicas para reduzir esta necessidade.
E lembre-se que quase todo aplicativo tem uma parte no servidor também que pode servir todas plataformas.
Claro que ele não faz milagre. Fazer na linguagem nativa pode dar um resultado ligeiramente melhor. Aí depende do que acha que é mais importante. Aprender e usar 3 tecnologias diferentes e fazer o melhor possível ou usar uma só e fazer o necessário que ainda é muito bom.
Dá para compilar para iOS em uma máquina virtual ou usar um serviço externo. A própria Xamarin oferece um.
Se programar em outra linguagem também precisará de algo assim.
A Microsoft disponibiliza o produto principal gratuitamente.
Se o aplicativo é útil, serve para alguma coisa e pode comercializado, monetizado, etc., o custo da licença é irrelevante. O ganho por aproveitar o grosso do código pode ser tão vantajoso que o custo se torna irrisório.
O único problema é quando o aplicativo foi fruto de voluntarismo, e tem muito disto das lojas. Aí fica no prejuízo mesmo.
Coloquei no GitHub para referência futura.
Comment: Isso você só vai descobrir tentando. Ninguém vai conseguir te responder. Nem você sabe ainda o que será preciso.
Comment: Sua resposta me foi muito útil, mesmo assim quero ir um pouco mais fundo. A empresa desse cara faz web marketing e o principal dele é na criação de lojas virtuais, e alguns clientes dele pedem/precisam de apps, principalmente em Android. Pelo que ele me disse, as aplicações em geral devem mostrar um catálogo dos produtos da loja, e permitir a compra diretamente pelo app ou através de redirecionamento pelo browser. Isso não me parece tão complicado, exceto pela parte da integração com o banco da lojas. Me pergunto então se pelo menos no Android é possível fazer isso 100% em C#. Sabe me dizer?
Comment: Ezequiel, tudo que é possível ser feito para Android com Java é possível ser feito em C#. O Xamarin encapsula todas as chamadas de todas as APIs do Android, inclusive das APIs de suporte, que é a base de como devem ser feitos apps com Design Material. Não existe nenhum cenário que o C# não cubra, e falo isso por experiência. Só faz sentido usar algo em Java quando você já tem um jar/war implementado ou alguma dependência de algum terceiro que não faz sentido reimplementar, ai você consegue criar um projeto de Binding e puxar/usar esta dependência.


Preencher classe com resultado do banco

Question: Boa tarde a todos. Tenho uma necessidade gigante de conseguir montar uma situação.
Eu tenho um objeto DataTable com o resultado com a coluna "ID_CLIENTE".
Eu tenho um objeto Cliente com a propriedate ID_CLIENTE.
Existe alguma forma de preencher o objeto Cliente com os dados do DataTable automaticamente, apenas passando o tipo do objeto Cliente e ele saber que a coluna "ID_CLIENTE" do DataTable tem de ser bindado na propriedade "ID_CLIENTE" do objeto Cliente ?
Consegui ser claro?

Classe Cliente

public class Cliente
{
    public int ID_CLIENTE { get; set; }
    public string NOME_CLIENTE { get; set; }
    public DateTime DT_NASC_CLIENTE { get; set; }
}

Carregando DataTable

SqlConnection conexao = new SqlConnection("STRING_CONEXAO");
SqlCommand comando = new SqlCommand("SELECT * FROM TAB_CLIENTE", conexao);

DataTable dt = new DataTable();

try
{
    conexao.Open();
    dt.Load(comando.ExecuteReader());
    conexao.Close();
}
catch (Exception)
{
    if (conexao.State != ConnectionState.Closed)
        conexao.Close();
    throw;
}

Comment: Como você carrega o `Datatable`? e como está essa classe Cliente, pode fornecer todo o código dessa classe?
Comment: @VirgilioNovic Alterei a pergunta com os dados que pediu.
Comment: Cara, você precisa é de um ORM (like Entity Framework).
Comment: Você quer a conversão de um `DataTable` em uma `Class` ou pode propor uma solução ideal?
Comment: Gostaria da conversão do `DataTable` na `Class`, mas aceito propor a solução sim, com certeza.
Answer: Solução ideal, é fazer a lista do tipo que necessita com o código logo abaixo:
List<Cliente> clientes = new List<Cliente>();
SqlConnection conexao = new SqlConnection("STRING_CONEXAO");
SqlCommand comando = new SqlCommand("SELECT ID_CLIENTE,NOME_CLIENTE,DT_NASC_CLIENTE
                                     FROM TAB_CLIENTE", conexao);

using (SqlDataReader reader = comando.ExecuteReader())
{
    if (reader.HasRows)
    {
        while (reader.Read())
        {
            clientes.Add(new Cliente
            {
                ID_CLIENTE = reader.GetInt32(0),
                NOME_CLIENTE = reader.GetString(1),
                DT_NASC_CLIENTE = reader.GetDateTime(2)
            });
        }
    }
}
return clientes;

Observação: na sua SQL foi editada e colocado os 3 campos em ordem para ser utilizado no código

Por curiosidade se esse DataTable vier de algo que não é produzido por você pode utilizar esse código (que é um método de extensão utilizando reflection):
Observação: os campos da classe tem que ser igual ao mesmos nomes e tipos de campo para funcionar a reflection
Crie uma classe com o seguinte layout:
public static class MyExt
{
    public static List<T> ToListOf<T>(this DataTable dt)
    {
        const BindingFlags flags = BindingFlags.Public | BindingFlags.Instance;
        var columnNames = dt.Columns.Cast<DataColumn>()
            .Select(c => c.ColumnName)
            .ToList();
        var objectProperties = typeof(T).GetProperties(flags);
        var targetList = dt.AsEnumerable().Select(dataRow =>
        {
            var instanceOfT = Activator.CreateInstance<T>();

            foreach (var properties in objectProperties
                 .Where(properties => columnNames.Contains(properties.Name)
                   && dataRow[properties.Name] != DBNull.Value))
            {
                properties.SetValue(instanceOfT, dataRow[properties.Name], null);
            }
            return instanceOfT;
        }).ToList();

        return targetList;
    }
}

Código retirado SOen
Como utilizar?
DataTable dt = new DataTable();
List<Cliente> clientes = dt.ToListOf<Cliente>();

Outra forma poderia ser assim:
DataTable dt = new DataTable();
List<Cliente> result = dt.AsEnumerable()
            .Select(s => new  Cliente
            {
                ID_CLIENTE = s.Field<int>("ID_CLIENTE"),
                NOME_CLIENTE = s.Field<string>("NOME_CLIENTE"),
                DT_NASC_CLIENTE = s.Field<DateTime>("DT_NASC_CLIENTE")
            })
            .ToList();

Referencias:

Classe DataTable
Converting DataTable to List of class
Métodos de extensão (Guia de Programação em C#)
O que é Reflection, por que é útil? Como usar?
Reflexão (c#)
Comment: Virgilio, é exatamente isso que eu precisava. Maravilha. Com esse método de extensão, eu consigo fazer o bind de qualquer consulta do bando, desde que eu crie uma classe com as propriedades com o mesmo nome. EXATAMENTE isso que eu preciso! MUITO OBRIGADO.

Preencher classe com resultado do banco


Kubernetes: what proxy-mode does the NodePort type use?

Question: When I am using NodePort type to expose service in kubernetes, what proxy-mode does it use?
Comment: When a deployment is exposed with source IP for service type set to NodePort, ProxyMode can not be used due to how traffic is being handled see [doc](https://kubernetes.io/docs/tutorials/services/source-ip/#source-ip-for-services-with-type-nodeport) on source IP for services with Type=NodePort for more details. If you want to use Proxy-mode, check ClusterIP; because Kube-proxy  exposes its mode through a proxyMode endpoint because of the way it handles traffic see this [documentation](https://kubernetes.io/docs/tutorials/services/source-ip/#source-ip-for-services-with-type-clusterip)
Answer: When a deployment is exposed with source IP for service type set to NodePort, ProxyMode can not be used due to how traffic is being handled see doc on source IP for services with Type=NodePort for more details.
If you want to use Proxy-mode, check ClusterIP; because Kube-proxy exposes its mode through a proxyMode endpoint because of the way it handles traffic see this documentation


Subgroup of order $9$ of $S_6$

Question: Consider the permutation group $S_6$ and let $H\subseteq S_6$ be a subgroup of $9$ elements

It is abelian but not cyclic
It is cyclic
It is not abelian
If H is abelian then it is cyclic.

Wel I know a general result that group of order $p^2$ is abelian where $p$ is a prime number, hence $H$ is abelian.but I dont know whether $H$ is cyclic or not, is it?thank you for the help.
Comment: Time out, Patience. Digest a little.
Comment: Why are all your questions in 4 true or false?
Answer: Hint. If you write an element of $S_6$ as a product of disjoint cycles, the order of the element is the least common multiple of the length of the cycles. Is there a way to get an element of order $9$?
Comment: @Patience: Really? The least common multiple of $3$ and $3$ is $9$? Do please think about things more than 10 seconds before posting! The order is not the **product** of the lengths of the cycles, it is the **least common multiple**. Did you even bother to take that element and *check* if the order was $9$? What happens if you raise it to the 3rd power?
Comment: Dear sir, There is no way to get an 9 order element in $S_6$.so Only 1 is correct
Comment: Yah, there for example $(123)(456)$ is of order $9$ element. and yah, the general result I know that is abelian group.but how do I know that order $9$ element will be in $H$?
Comment: oops I am sorry, please pardon me dear sir.

Subgroup of order $9$ of $S_6$


Stat Testing multiple response question

Question: I have data from 500 respondents for a question, which of the following brands of phones have you seen/heard advertising in past 3 months?
a) Apple
b) Samsung
c) Nokia
d) Motorola
e) Lenovo
f) Others (Please Specify)
The responses I have are as below:
a) Apple: 90% (450/500)
b) Samsung: 88% (440/500)
c) Nokia: 85% (425/500)
d) Motorola: 20% (100/500)
e) Lenovo: 15% (75/500)
f) Others (Please Specify): 5% (25/500)
Which is the most appropriate stat test to test if there is any significance difference between Apple & Samsung. I thought of Z-Test, but since the populations of ad awareness is not independent, I don't think it can be used. Please advise.
Answer: How about turning it into a $2\times2$ contingency table and perfoming a $\chi^2$-squared test?
<code>contingency.table <- data.frame(Apple = c(450, 50), Samsung = c(440, 60))
rownames(contingency.table) <- c("yes", "no")
chisq.test(contingency.table)
</code>
No significant difference is detected between the proportion of people who have seen/heard from Apple or Samsung from advertising in past 3 months:
<code>    Pearson's Chi-squared test with Yates' continuity correction

data:  contingency.table
X-squared = 0.82737, df = 1, p-value = 0.363
</code>
Just a small note on the study design, 3 months is a long period of time and (as expected) just about everybody has heard of both brands in this time period.
Comment: A Fisher exact test can also be used (and would be preferable for a small sample size)
Comment: Although small observed counts generally result in small expected counts, the Fisher exact test is more precise for the latter, not necessarily for a smaller number of observed counts.

Stat Testing multiple response question


hook_tokens() implementation no longer being called

Question: We have a custom module in development, the purpose of which is to fetch the email addresses of the users who review content. Upon revisiting this module (after updating from Drupal-7.41 to Drupal-7.51) its hook_tokens() implementation is no longer being called in the same way it was before.
I cannot understand why this functionality no longer works. I thought this was a proper implementation of these functions. It now no longer fires on nodes, but when an entity is on a node.
Why would hook_tokens() not be called on a node? (The module is enabled, depends on tokens and workbench_access, both of which are enabled.)
Please forgive me if my question is framed inappropriately, I may have an inaccurate understanding of the hook function(s), but I've checked the API and haven't gained clarity. I know for a fact that this module worked earlier this year with Drupal-7.41, but I couldn't find any changes in the related API since that release.
function mymodule_token_info() {
   $info = array();
   $info['tokens']['node']['publisher_one'] = array(
     'name' => t('Section Publisher One'),
     'description' => t('Email address of sections primary publisher.'),
   );
   $info['tokens']['node']['publisher_two'] = array(
     'name' => t('Section Publisher Two'),
     'description' => t('Email address of sections secondary publisher.'),
   );
   return $info;
}

function mymodule_tokens($type, $tokens, array $data = array(), array $options = array()) {
   $replacements = array();
   if ($type == 'node' && !empty($data['node'])) {
      print_r('inside if conditional');
      $section_users = array();
      $users = entity_load('user');
      // Get the current Page's section ID (sID).
      $sID = key(_workbench_access_get_node_section_names($data['node']));
      $user_count = 0;
      // Is a given user 1) assigned to the same section as the node and also
      //  of the role identified as the one to be notified.
      // If so, their email address are acquired.
      foreach($users as $user) {
          $user_sections = _workbench_access_get_user_section_names($user);
          if(array_key_exists($sID, $user_sections) && $user_count < 2){
              $role_type = user_roles(TRUE)[variable_get('waemail_role', '0')];
              if(in_array($role_type, $user->roles)){
                  if($user_count == 0){
                      $section_users['publisher_one'] = $user->mail;
                      $user_count++;
                  }
                  else if($user_count == 1){
                      $section_users['publisher_two'] = $user->mail;
                      $user_count++;
                      break;
                  }
              }
          }
      }

      // Assign the values aquired above to the tokens.
      foreach ($tokens as $name => $original) {
          switch ($name) {
              case 'publisher_one':
                  if(!empty($section_users[$name]))
                      $replacements[$original] = $section_users[$name];
                  break;
              case 'publisher_two':
                  if(!empty($section_users[$name]))
                      $replacements[$original] = $section_users[$name];
                  break;
          }
      }
    } //end if($type == 'node'...
 return $replacements;
}

Comment: Your code looks correct, however, I noticed your hook_token_info() doesn't define a token type. I'm curious if this is what is preventing your $type == 'node' logic from getting missed. Trying adding a 'types' array to your $info in hook_token_info and see if that does the trick.
Comment: @TheRealWebGuy Thanks for the response! So I added this code in the [module-name]_token_info function prior to the other two tokens:
    `$info = array();
    $info['types']['node']['section-publishers'] = array(
        'name' => t('Publishers for Access Section'),
        'description' => t('Email addresses of the publishers of a given nodes section'),
    );`
I also added that prefix to the other tokens so they are now: ['tokens']['node']['section-publishers']... However, it still doesn't appear to fire. Is that what you meant by adding a type array?
Comment: @TheRealWebGuy Defining a token type is not required. Modules could use the existing ones, like [`poll_token_info()`](https://api.drupal.org/api/drupal/modules%21poll%21poll.tokens.inc/function/poll_token_info/7.x) does.
Comment: @kiamlaluno Are you still planning on amending your answer?
Comment: Yes, once I have time to write the code. That means, not before 6:00 PM my time (about 3 hours since now).
Answer: hook_tokens() is invoked only when token_generate() is called. Since that doesn't necessarily happens when a node is viewed (or similar events), but it happens when a module calls token_replace(), hook_tokens() not being invoked could not mean your code is wrong.
Assuming that the code you show is not causing any PHP error, that means that a module that was before calling token_replace() is not calling that function anymore, or it is calling it in very specific occasions.
For PHP error I mean:

The code is calling a function that doesn't exist anymore (e.g. _workbench_access_get_user_section_names())
It is calling a function that is returning a value of a different type from what it previously returned (e.g. _workbench_access_get_user_section_names() returns a value that is not an array)

There isn't any change in the token subsystem from Drupal 7.41 to Drupal 7.51 that could cause your code not to work anymore. The only reason for your hook_tokens() implementation not to be invoked in a change in the code of the module your hook implementation is using, or a change in the code of a module that was generating token when viewing a node (or a similar event).
To test your implementation of hook_tokens(), you should directly call token_replace() passing a string containing a token your module defines and a node object. If the token is not replaced, then you can check for errors in your code; if the token is replaced, then your code is working perfectly, and your hook_tokens() implementation is not invoked simply because no module is replacing tokens in a string when you are expecting it to happen.
I would use the following code, to put in a file in the same directory containing the index.php file that comes with Drupal.
/**
 * @file
 * Test page to check the hook implementation of a custom module work.
 */

/**
 * Root directory of Drupal installation.
 */
define('DRUPAL_ROOT', getcwd());

require_once DRUPAL_ROOT . '/includes/bootstrap.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);

// Load a node to use as context for the tokens.
// Change the argument for node_load() to match the node ID of
// an existing node.
$node = node_load(1);

// Change the string to the token name for the token that needs to
// be tested.
$token = 'publisher_one';

$result = token_replace("[$token]", array('node' => $node), array('clear' => FALSE));

if ($result == "[$token]") {
  // The token has not been replaced.
}

Comment: I will update my answer later.
Comment: I added example code that could be used to test a token implementation work. I will update the code if I think of something else that could be tested.
Comment: I would say it was just a matter of cache. If you are asking where to put the code I shown, you should not need it. Rather, I would investigate why clearing the cache made things work. Probably there is a module that should clear the cache and it is not doing it. It's hard to say that.
Comment: OK, thank you! I know it's not generating errors, those I tested when it was working before and I've double checked the functions exist and return the proper type, etc. I apologize for my ignorance, but I'm new to this type of development: How/where might I call the `token_replace()` method in this situation?
Comment: Any update on this? I've tried to include this a couple places, but I haven't been able to find proper instructions thus far.
Comment: Thank you very much. So I added this code cleared all the caches and it worked. However, I then removed the code and cleared all the caches and it still works. I'm not sure this is within the scope of the answer, but do you have any insight as to why this might be? Furthermore, is there a place where I could place this code so that it will only be run when a workbench node is saved (perhaps in a Rule)?


Angular RXjs Websocket

Question: Service code.

import { webSocket, WebSocketSubject } from 'rxjs/webSocket';
export class SocketioService {

  private socket$: WebSocketSubject<any>;
  private dataObs$: BehaviorSubject<any> = new BehaviorSubject(null);
  private socket;
  constructor() {

    this.socket$ = webSocket('ws://some url');
  }

  sendCmd(query) {

    this.socket$.next(query);

    this.socket$.subscribe(message => {
   //////// here i get duplicate responses on subsequent invocation from other components
      this.dataObs$.next(message);

    });

  }

  getData(): Observable<any> {
    return this.dataObs$.asObservable();
  }

}

appcomponent:

  this.dataservice.sendCmd('abc');

this.dataservice.getData().subscribe( data => {
if(data!=null){

    console.log(data);
}

});

y component:

      this.dataservice.sendCmd('xyz');
     this.dataservice.getData().subscribe( data => {
      if(data!=null){
          console.log(data);
      }
      });

Issue is when i send second command , in socket subscribe method response is coming twice and gets piled up
Example --- first command --- 1 response comes
-------  second command --- 4 response (2 for first command and 2 for second command) --- duplicates
--------third command ------------  6 response (3 for first command, 3 for second command, 3 for third command) -- duplicates
Answer: Because you create a new subscription each time your sendCmd method is called and you never unsubscribe from each of those subscriptions.
You don't actually need the dataObs$ subject:
import { Injectable } from '@angular/core';
import { share } from 'rxjs/operators';
import { webSocket } from 'rxjs/webSocket';

@Injectable({ provideIn: 'root' })
export class SocketioService {
  private readonly socket$ = webSocket('ws://some url');

  public readonly data$ = this.socket$.pipe(
    share(), // to make sure only one subscription is created
  );

  public sendCmd(cmd) {
    this.socket$.next(cmd);
  }
}

And when you want to subscribe to the data use:
this.dataService.data$.subscribe(/* ... */);

Comment: public readonly data$ = this.socket$.pipe(
    share(), // to make sure only one subscription is created
  );--- Can you please put full code for this function
Comment: `share` should be imported from `rxjs/operators`, i'll add it to the answer
Comment: thank you. one more questiion, how do we use this from component. Can you please paste component code to receive this response

Angular RXjs Websocket


Caret disappears on long pressing blank space in UITextView and Text Kit

Question: I'm using Text Kit to render some rich text on a text view.
My problem is there seems to be a bug in iOS 7 for caret placement. Whenever you long press on a blank area in a text view the caret seems to disappear and no pop over menu with (Cut, Copy, Select, etc) is presented.
You can understand the issue better via taking a look at this short video: http://cl.ly/1E0s2A2S0t2t
You can try it out yourself by downloading the IntroToTextKit sample code from Apple. Here's a link to the project: http://cl.ly/0h0T0V1Z0D3H
Any workarounds to this would be really appreciated.
Answer: Found a solution.
Subclass UITextView and add the following:
<code>    - (UITextPosition *)closestPositionToPoint:(CGPoint)point
{
    point.y -= self.textContainerInset.top;
    point.x -= self.textContainerInset.left;

    CGFloat fraction = 1;
    NSUInteger glyphIndex = [self.layoutManager glyphIndexForPoint:point inTextContainer:self.textContainer fractionOfDistanceThroughGlyph:&fraction];

    NSInteger index = glyphIndex;
    if (![[self.text substringFromIndex:self.text.length - 1] isEqualToString:@"\n"]) {
        if (index == [self.text length] - 1 && roundf(fraction) > 0) {
            index++;
        }
    }

    NSUInteger characterIndex = [self.layoutManager characterIndexForGlyphAtIndex:index];
    UITextPosition *pos = [self positionFromPosition:self.beginningOfDocument offset:characterIndex];
    return pos;
}
</code>


How do you not get lost between measures?

Question: How do you not get lost between measures? For example, if I start on measure 28 and the the next measure down is measure 40, how do I not play early or late?
Comment: If the next measure down is #40, there must be 12 other measures in the line above. If you play them, how do you get lost?
Comment: Related [question](http://music.stackexchange.com/q/44501/2600)
Answer: A few ways:

By counting the measures! It really is that simple. You start on measure 28, so measure 29 is your first measure of rest, then measure 30, then measure 31, etc. By the time measures 38 and 39 come up, you should be mentally and physically preparing to play again in measure 40. I always tried to interact physically in some way; typically I would use my hands to keep track in groups of five measures: measure 34 would be four fingers up, 35 all five fingers, 36 goes back to 1 finger, etc.
Through the use of musical cues. For instance, if you know that the oboe player comes in with a new theme in measure 38, you don't have to worry about counting until then. This is where very basic score study comes in; get your hands on a score and use the information you gain to your advantage! (You can also just count to determine when the oboe comes in, of course.)
Just by knowing the music. Honestly, this is how most professional musicians do it. If you go to an opera concert and look down into the pit, you'll see trombone players playing games on their smartphones until a few bars before they come in. They don't have to count, they don't have to look at the score, they just know the pieces inside and out and know when they come in. This comes with just knowing the piece; listen to it as much as you can, and try to listen to it with a score whenever possible!

Generally speaking, I recommend always counting in the first few rehearsals of a new piece, even if you think you know the piece. Eventually you'll feel comfortable enough to graduate to Step 2. Only when you really know the piece should you even think about moving to Step 3. (And some musicians will swear that you should never, ever do Step 3, just to be on the safe side!)
Comment: Re Step 3, it's worth pointing out that professional musicians who have to do a lot of counting often have a miniature score to follow what's going on in their 397 bars rest. But *real* trombonists don't play games on their cellphones - they disappear to the bar and reappear with just enough time to pick up the 'bone and hit the first note right on cue. (And sometimes they "forget" to put the bottle down before leaving the bar, if it's not quite empty...)
Comment: #3 doesn't come from intensive score study, it comes from doing the same damn show over and over again.  Broadway pit musicians usually get to a point where they don't even have to be actively paying attention, they can read a book or whatever while playing.
Comment: "But *real* trombonists don't play games on their cellphones..." This sentence could have ended one of two ways: the pretentious way, or the accurate way. I'm glad you chose correctly :-)
Comment: Re #2 -- you better have great faith in the **oboist's** ability to count and come in at the right place!
Answer: Richard's answer is great, and you can use all that stuff, but another thing is if you know the number of measures of rest then you can use it in your count like so: if there are 20 measures of rest in 4/4 then you count 1-2-3-4, 2-2-3-4, 3-2-3-4, ...... 19-2-3-4, 20-2-3-4. This way you easily keep count of the measures.
Answer: Richard's answer is correct and very useful, however misses points which are essential - to me at least. I'm going to fill in some important intermediate steps to reach the goals already outlined - which seems highly called for in the case of someone who is asking a question like this. (Note your question is not clear: Richard has assumed you're asking how to count many bars of rests. I'll also assume this.)
Counting: The key thing you need to know is how many bars you have to count - which should be trivially visible/countable on the score and comes with any knowledge of the piece. The example given is slightly misleading, because the actual bar #s are never relevent. (Other than the fact you can count a long gap by subtracting the bar# of the bar you finish on from the bar number you come in on.)
I don't recommend getting into the habit of making physical motions, although you can get away with just fingers if you really want to. It doesn't look good and will be noticed.
You then count the bars. Assuming 4/4 timing, you'd be counting in your head: 1,2,3,4... 2,2,3,4.... 3,2,3,4.... and so on and on upwards. I.e. you are replacing the "one"/first count of each bar with the bar number. This can very rapidly become easy and automatic. With experience, it can easily be done on new pieces you've never seen - the rhythm of counting is so ingrained you do it and read ahead to get the total # of bars to count at the same time.
Cues: Musical cues are essential for parts that don't play continuously, especially many percussion instruments. Score access/study is not important - it should become obvious where the major transitions are on your own part and what they correspond to aurally. Think tempo, dynamics, key changes, complete style changes, etc. These CAN be used to make educated guesses when you're totally lost. Richard's representation of this topic is a more advanced application of the technique: the same thing with more subtle markers that need more learning and possible more annotating your music.
Generally you will learn the sequence of major cues in a piece, and only need to count from one of these unmissable points closest to your entry.
The "shape" of the music is highly relevent. A huge volumne of music has a very regular structures, usually being based around 4 or 8 bar chunks which will be highly audible (although varying with style) and frequently quite visible on your part to the eye that's looking for it. Being able to hear when the whole ensumble passes one of these "checkpoints" is a key corrector of "off by one" counting errors i.e. gets you out of trouble when you're not sure if you dropped a bar or not, etc. This is a key skill which comes with general experience, and piece familiarity.
Jamerack beat me in the typing race with the same key point (and better formatting!) but... posting anyway since I bothered to, and there's some more info here.
Answer: When you practice by yourself at home, skip the rests. Honestly, why sit in silence for 30-something beats and waste your time when there is no one else playing with you? Just briefly stop to signify there's a rest, and then keep playing. When you play with other people, you can remember when to come in by what they're playing, or just count. 1-2-3-4, 2-2-3-4, 3-2-3-4, so on.


Different ANOVAs per species for same variable; how to proceed if only some species hold non-normal data

Question: I am conducting two-way ANOVAs to determine if plant height (mm) is affected by treatment (3 water regimes) in different growth medium types (2). I am also interested in the interactions that may occur between the water treatments and soil so my model is contracted as such.
I have multiple species of plant included in this study.  As such, I have decided that the best course of action to statistically analyse the data is to do seperate two-way ANOVAs per species (I am not all that interested in the fact that some plants will be taller than others; its a given).  However, after partitioning the data per species, it has become evident that ONLY SOME of the species' heigh values are normal (shapiro.test).
Can I transform the data of ONLY the species that aren't normal? Or should all (even the already normal ones) be transformed?
Comment: Unless there's more than one Levene test, the Levene test isn't a test of normality.
Comment: @Glen_b, Yes, sorry, copied from the wrong line of my code.  Edited question to shapiro.test
Answer: How many plants per species do you have?
First it's worth to explore the normality via something different than Levene's test (this refers to homoscedasticity assumption) so Shapiro-Wilk test or visual exploration of a QQ plot.
There's no need to transform all species, because those which follow normal distribution will lose it after an additional transformation. After transformation check how the distributions look like. Then for results presentation it will be worth to think about the way to do that effectively as transformed variables are not self-descriptive (i.e., if you use a log transformation than maybe a geometrical mean +/- its SD).
Why I asked about the N of plants per species? If it's rather small, than maybe instead of a two-way ANOVA it's more worth to run a mixed model with water regimen and medium as fixed effects and species as a random effect.
Comment: Thanks @Jakub,  I have around 18-20 plants per species-media-water permutation.  The study is unbalanced
Comment: there are only 4 species