What is the proof that the total number of subsets of a set is $2^n$?

Question: What is the proof that given a set of $n$ elements there are $2^n$ possible subsets (including the empty-set and the original set).
Comment: To form a subset, you must decide, for each element of the set, whether or not it will belong to the subset. There are $2$ ways to decide what to do with the first element of the set, $2$ ways to decide what to do with the second element, etc. we will have $2 \cdot 2 \cdot .... \cdot 2 = 2^n$
Answer: Suppose you want to choose a subset. For each element, you have two choices: either you put it in your subset, or you don't; and these choices are all independent.
Remark: this works also for the empty set. An empty set has exactly one subset, namely the empty set. And the fact that $2^0=1$ reflects the fact that there is only one way to pick no elements at all!
Comment: Another way to say this is that each subset can be tagged with a binary number constructed by using $ \ n \ $ digits and writing "0" or "1" at each digit according to whether the $ \ k^{th} \ $ element is in the subset.  The numbers range from $ \ 000 ... 000 \ $ for $ \ \varnothing  \ $  to  $ \ 111 ... 111 \ $ for the full set of $ \ n \ $ elements.  So if the set has five elements, for instance, the binary numbers run from $ \ 00000 \ $ to $ \ 11111 \ $ , or 0 to 31 ; thus, $ \ 2^5 \ = \ 32 \ $ subsets.
Comment: @TrevorWilson Well, sure it is. $2$ choices for each element, so $\underbrace{2\cdot 2\cdot 2\cdots 2\cdot 2}_n=2^n$ possible choices in total.
Comment: Okay, I guess the argument in this answer and in the comment below it are more or less complete proofs if we define $2^n$ as the number of functions from $n$ to the set $\{0,1\}$, rather than by recursion.
Comment: @PedroTamaroff When a proof uses "...", recursion is usually hiding.  Looking at the tags, I got the sense the OP might want something more formal.
Comment: @RecklessReckoner Yes, and I should not have jumped to criticize this answer without asking the OP which definition of $2^n$ he or she was using.
Comment: And where does the $2^n$ come from?  This isn't really a complete proof yet.
Comment: @TrevorWilson  Marie's answer is one based on combinatorics (in fact, it's a problem that gets asked pretty early on).
Answer: Here is a proof by induction on $n$.  This proof assumes that we have defined $2^n$ by recursion as $2^0 = 1$ and $2^{n+1} = 2^n \cdot 2$.
This is true for $n=0$ because $\emptyset$ has exactly one subset, namely $\emptyset$ itself.
Now assume that the claim is true for sets with $n$ many elements. Given a set $Y$ with $n+1$ many elements, we can write $Y = X \cup \{p\}$ where $X$ is a set with $n$ many elements and $p \notin X$.  There are $2^n$ many subsets $A \subset X$, and each subset $A \subset X$ gives rise to two subsets of $Y$, namely $A \cup \{p\}$ and $A$ itself.  Moreover, every subset of $Y$ arises in this manner.  Therefore the number of subsets of $Y$ is equal to $2^n \cdot 2$, which in turn is equal to $2^{n+1}$.
Answer: We must show that $${n\choose 0}+{n\choose 1}+{n\choose 2}+\cdots +{n\choose n}=2^n$$ is the number of subsets of an $n$-element set $S$ where $n\geq0$.
Every subset of $S$ is a $k$-subset of $S$ where $k=0,1,2,...,n$. We know that ${n\choose k}$ equals the number of $k$-subsets of S. Thus by the Addition Principle $${n\choose 0}+{n\choose 1}+{n\choose 2}+\cdots +{n\choose n}$$ equals the number of subsets to the set $S$. We can count the same thing by observing that each element of the set $S$ has two choices, either they are in a subset or they are not in a subset. Let $S=\{x_1,x_2,x_3,...,x_n\}$. So, $x_1$ is either in a subset or it is not in a subset, $x_2$ is either in a subset or it is not in a subset,..., $x_n$ is either in a subset or it is not in a subset. Thus by the Multiplication Principle there are $2^n$ ways we can form a subset of the set $S$. Hence ${n\choose 0}+{n\choose 1}+{n\choose 2}+\cdots +{n\choose n}=2^n$.
Another approach is to consider the Binomial Theorem $$(x+y)^n=\sum_{k=0}^n {n\choose k}x^{n-k}y^k.$$ Letting $x=1$ and $y=1$ we obtain$$2^n=\sum_{k=0}^n{n\choose k}.$$
Comment: I agree with you. I just wanted to present Celeritas a thorough combinatorial proof to his question. It is to help him understand the problem better. He can only benefit from reading all the extra stuff.
Comment: I agree, especially if he/she is taking a combinatorics class.  It's just that the extra stuff is only necessary if you want to prove that the two things (1) the number of subsets of an $n$ element set and (2) $2^n$ are, as well as being equal to one another, both equal to a third thing (3) $\sum_{k=0}^n \binom{n}{k}$.  So I was scratching my head over the logical structure of the proof until I realized that you wanted to prove this extra thing also.
Comment: It seems like the proof is entirely contained in the part saying "$x_1$ is either in a subset or it is not in a subset, $x_2$ is either in a subset or it is not in a subset,.... Thus by the Multiplication Principle there are $2^n$ ways we can form a subset of the set $S$."  The other stuff is of course correct and generally useful, but it doesn't seem to fit into the proof of what the OP is asking for a proof of.
Answer: Here is proof by binary numbers. A set of up to N items can be represented as a vector of binary digits. When a digit is 1, it indicates that the corresponding item is present. 0 means that it is absent.
In fact, this representation is used in computer programming as a way of representing sets which has good worst-case memory efficiency, as well as other attributes such as simplicity of implementation.
So for instance a set of 32 items can be represented as a string of 32 1's.  And then we can represent subsets of these items, by flipping some of these 1's to 0's in various combinations.
All possible subsets are therefore, simply, all possible 32 bit numbers, and there are $2^{32}$ such numbers.
In other words, the count of subsets is related to the fact that set membership is a binary proposition: something is or is not an element of a set. Yes or no, true or false, one or zero.
Answer: If $S$ is a finite set with $|S| = n$ elements, then the number of subsets of $S$ is $|\mathcal{P}(S)| = 2^n$. This fact, which is the motivation for the notation $2^S$, may be demonstrated as follows,
We write any subset of $S$ in the format $\{x_1, x_2, \ldots, x_n\}$ where $x_i , 1 \le i \le n$, can take the value of $0$ or $1$. If $x_i = 1$, the $i$-th element of $S$ is in the subset while the $i$-th element is not in the subset otherwise. Clearly the number of distinct subsets that can be constructed this way is $2^n$.
Answer: \begin{align}
  \sum_{k=0}^n{n \choose k}=2^n
\end{align}
can be solved using proof by induction.
for $n=1$;
it is true (put n=1);
for $n=k$;
assume to be true.
\begin{align}
     \sum_{k=0}^n{n \choose k}=2^n
   \end{align}
for $k=n+1$;
\begin{align}
   \sum_{k=0}^{n+1}{n+1 \choose k}=2^{n+1}\end{align}
\begin{align}
{n+1 \choose k}={n \choose k}+{n \choose k-1}
\end{align}
substituting this equation leads to the final result.
Answer: To write out some details of the discussion under this answer. Consider the two element set $\{0,1\}$ where you think of $1$ as meaning in the subset and $0$ as meaning not in the subset. In this way any function $f\colon S \to \{0,1\}$ defines a subset of $S$, where $s$ is in that subset if and only if $f(s)=1$. So then our question is how many such functions are there? For each of the $n$ elements of $S$ there are two choices for what $f(n)$ can be, so making these $n$ choices independently, there are $2^n$ options.
Answer: Here's a combinatoral proof
$$\sum_{k=0}^n{n \choose k}=2^n$$
These both count the number subsets in an $n$ element set.
The right hand side counts them directly (related to Marie's answer) and the left hand side counts the number of $k$-element subsets and then sums over $k$. This equation can also be verified by the binomial theorem with $x=y=1$.
Answer: Let us consider the following cases:

Let a set be $\{a\}$, then its subsets are: $\{a\}, {\emptyset}$ . Therefore the number of subsets is $2^1$
Let another set be $\{a,b\}$, then its subsets are: $\{a\},\{b\},\{a,b\}, {\emptyset}$ Therefore the number of subsets is $2^2$
Let another set be $\{a,b,c\}$, then its subsets are: $\{a\},\{b\},\{c\},\{a,b,c\},\{a,b\},\{b,c\},\{a,c\}, {\emptyset}$. Therefore, the number of subsets is $2^3$

$\therefore$  (1), (2) & (3) $\Rightarrow $ If there are $n$ sets, then the number of subsets is $2^n$
Comment: This is a useful illustration, but I don't think that checking three cases is enough to be sure that something holds for all natural numbers $n$.
Comment: This is more on route to prove by induction. As Trevor Wilson said, because a pattern follows for $n=1,2,3$ does not imply that it holds for all $n$
Comment: Related: https://mathoverflow.net/questions/15444/examples-of-eventual-counterexamples


Double series convergent to $2\zeta(4)$?

Question: Using a computer I found the double sum
$$S(n)= \sum_{j=1}^n\sum_{k=1}^n \frac{j^2 + jk + k^2}{j^2(j+k)^2k^2}$$
has values
$$S(10) \quad\quad= 1.881427206538142 \\ S(1000) \quad= 2.161366028875634 \\S(100000) =  2.164613524212465\\$$
As a guess I compared with fractions $\pi^p/q$ where $p,q$ are positive integers and it appears
$$\lim_{n \to \infty} S(n) = \frac{\pi^4}{45} =  2\zeta(4) \approx 2.164646467422276 $$
I'd be interested in seeing a proof if true.
Comment: More of an exercise in coding just to see what happens with summands that have symmetric structure like this..
Comment: I think you mean $\frac{\pi^4}{45}$. Also, can I ask how you came up with this? I would be shocked if it's true, but still intriguing.
Comment: @TomHimler: Thank you - typo fixed.
Comment: Note that there are inverse symbolic calculators, like this one: https://isc.carma.newcastle.edu.au/
Answer: So before I start, I've never even attempted to evaluate a double sum before, so there could very well have been an easier way.
$$\sum_{j=1}^\infty\sum_{k=1}^\infty \frac{j^2+jk+k^2}{j^2k^2(j+k)^2} =  \sum_{j=1}^\infty\sum_{k=1}^\infty \frac{1}{k^2(j+k)^2} +\sum_{j=1}^\infty\sum_{k=1}^\infty \frac{1}{jk(j+k)^2} + \sum_{j=1}^\infty\sum_{k=1}^\infty \frac{1}{j^2(j+k)^2}= $$
$$ 2\sum_{j=1}^\infty\sum_{k=1}^\infty \frac{1}{k^2(j+k)^2} +\sum_{j=1}^\infty\sum_{k=1}^\infty \frac{1}{jk(j+k)^2}$$
Through partial fraction decomposition the above equals:
$$\sum_{j=1}^\infty\sum_{k=1}^\infty \frac{1}{j^3k} -\frac{1}{j^3(j+k)}-\frac{1}{j^2(j+k)}+2\sum_{j=1}^\infty\sum_{k=1}^\infty \frac{2}{j^3(j+k)}-\frac{2}{j^3k}+\frac{1}{j^2k^2}+\frac{1}{j^2(j+k)^2} $$
Collecting like-terms:
$$3\sum_{j=1}^\infty\sum_{k=1}^\infty \frac{1}{j^3(j+k)}-3\sum_{j=1}^\infty\sum_{k=1}^\infty \frac{1}{j^3k} +\sum_{j=1}^\infty\sum_{k=1}^\infty \frac{1}{j^2(j+k)^2} + 2\sum_{j=1}^\infty\sum_{k=1}^\infty \frac{1}{j^2k^2} =   $$
The final sum clearly equals $2\zeta(2)^2$ or $\frac{\pi^4}{18}$. I then evaluate the first two sums by combining them to get:
$$3\sum_{j=1}^\infty\sum_{k=1}^\infty \frac{1}{j^3}(\frac{1}{j+k}-\frac{1}{k}) $$
Interchanging j and k to and averaging the two sums to get:
$$\frac{3}{2}\sum_{j=1}^\infty\sum_{k=1}^\infty \frac{1}{j^3}(\frac{1}{j+k}-\frac{1}{k})+\frac{1}{k^3}(\frac{1}{j+k}-\frac{1}{j}) $$
This can be rewritten as:
$$-\frac{3}{2}\sum_{j=1}^\infty\sum_{k=1}^\infty \frac{1}{j^2k(j+k)}+\frac{1}{k^2j(j+k)}= -\frac{3}{2}\sum_{j=1}^\infty\sum_{k=1}^\infty \frac{1}{j^2k^2} = -\frac{3}{2}\zeta{(2)}^2 = -\frac{\pi^4}{24}$$
So putting that back into the original problem:
$$\sum_{j=1}^\infty\sum_{k=1}^\infty \frac{1}{j^2(j+k)^2} + \frac{\pi^4}{18} -\frac{\pi^4}{48} = \sum_{j=1}^\infty\sum_{k=1}^\infty \frac{1}{j^2(j+k)^2} + \frac{\pi^4}{72}  $$
This is all I got to. I couldn't evaluate the other sum the way I did before. Using a calculator there is a very good chance it equals $\frac{\pi^4}{120}$.
Just for fun I was able to write the remaining sum as:
$$\sum_{j=1}^\infty\sum_{k=1}^\infty \frac{1}{j^2(j+k)^2} = \sum_{n=1}^\infty \frac{\zeta(2,n+1)}{n^2}$$
Where $\zeta(x,y)$ is the Hurwitz Zeta Function. Wolfram Alpha was able to calculate the sum as $\frac{\pi^4}{120}$ as desired.
Answer: $$S(\infty)=\sum_{j=1}^\infty\,\sum_{k=1}^\infty \frac{(j+k)^2 - jk}{j^2(j+k)^2k^2} = \underbrace{\Big(\sum_{k=1}^\infty \frac{1}{k^2}\Big)^2}_{=\zeta(2)^2} -
\underbrace{\sum_{j=1}^\infty\,\sum_{k=1}^\infty \frac{1}{j\,k}\int_0^\infty dt \,t \,e^{-t(j+k)}}_{:=U},$$
where the first step is algebra and the second is use of the Euler representation of the $\Gamma$ function. Interchange sums and integral and sum in terms of $\log$ to find
$$U=\int_0^\infty dt \,t \, \log^2(1-e^{-t}) = -\int_0^1 \frac{du}{u} \log\,u \log^2{(1-u)} =$$
$$-\frac{\partial}{\partial s} \frac{\partial^2}{\partial v^2} \int_0^1 u^{s-1} (1-u)^{v-1} \, du \Big\vert_{s=0,v=1}= -\frac{\partial}{\partial s} \frac{\partial^2}{\partial v^2}\frac{\Gamma(s) \Gamma(v)}{\Gamma(s+v)}\Big\vert_{s=0,v=1}$$
where the first step follows from a simple substitution $u=e^{-t}$ and the second is writing the integral in terms of something that is known, the beta integral.  Use your favorite CAS to do the partial derivatives to get $U=\pi^4/180.$ Combine with $\zeta(2)^2 = \pi^4/36$ to finish the proof of the OPs hypothesis.
Answer: $$
\begin{align}
\frac{m^2+m\,n+n^2}{m^2\,(m+n)^2\,n^2}\, &=\frac{m^2+m\,n+n^2\,\color{red}{+m\,n-m\,n}}{m^2\,(m+n)^2\,n^2} \\[2mm]
&=\,\frac{(m+n)^2-m\,n}{(m+n)^2\,m^2\,n^2} \\[2mm]
&=\,\frac{1}{m^2\,n^2}-\frac{1}{m\,n\,(m+n)^2} \\[2mm]
&=\,\frac{1}{m^2\,n^2}-\frac{1}{m^3}\left(\frac{1}{n}-\frac{1}{m+n}-\frac{m}{(m+n)^2}\right) \\[2mm]
&=\,\color{brown}{\frac{1}{m^2\,n^2}}\color{green}{-\frac{1}{m^3}\left(\frac{1}{n}-\frac{1}{m+n}\right)}\color{blue}{+\frac{1}{m^2}\frac{1}{(m+n)^2}}
\end{align}
$$

$$
\begin{align}
\color{brown}{\large S_{\small 1}\,} &=\sum_{m=1}^{\infty}\sum_{n=1}^{\infty}\frac{1}{m^2\,n^2}=\sum_{m=1}^{\infty}\frac{1}{m^2}\sum_{n=1}^{\infty}\frac{1}{n^2}=\left(\zeta(2)\right)^2=\color{brown}{\frac{\pi^4}{36}} \\[4mm]
\color{green}{\large S_{\small 2}\,} &=\sum_{m=1}^{\infty}\sum_{n=1}^{\infty}\frac{1}{m^3}\left(\frac{1}{n}-\frac{1}{m+n}\right)=\sum_{m=1}^{\infty}\frac{1}{m^3}\sum_{n=1}^{\infty}\left(\frac{1}{n}-\frac{1}{m+n}\right) \\[2mm]
&=\sum_{m=1}^{\infty}\frac{1}{m^3}\sum_{n=1}^{\color{red}{m}}\frac{1}{n}=\sum_{m=1}^{\infty}\frac{H_{m}}{m^3}=\frac{5}{4}\zeta(4)=\color{green}{\frac{\pi^4}{72}}\tag{1} \\[4mm]
\color{blue}{\large S_{\small 3}\,} &=\sum_{m=1}^{\infty}\sum_{n=1}^{\infty}\frac{1}{m^2}\frac{1}{(m+n)^2}=\sum_{m=1}^{\infty}\frac{1}{m^2}\sum_{n=1}^{\infty}\frac{1}{(m+n)^2} \\[2mm]
&=\sum_{m=1}^{\infty}\frac{1}{m^2}\,\sum_{\color{red}{n=m+1}}^{\infty}\,\frac{1}{n^2}=\sum_{m=1}^{\infty}\frac{\psi^{\small (1)}(m+1)}{m^2} \\[2mm]
&=\sum_{m=1}^{\infty}\frac{1}{m^2}\left[\zeta(2)-\sum_{k=1}^{m}\frac{1}{k^2}\right]=\left(\zeta(2)\right)^2-\sum_{m=1}^{\infty}\frac{H_{m,2}}{m^2} \\[2mm]
&=\left(\zeta(2)\right)^2-\frac{1}{2}\left[\left(\zeta(2)\right)^2+\zeta(4)\right]=\frac{1}{2}\left[\left(\zeta(2)\right)^2-\zeta(4)\right]=\color{blue}{\frac{\pi^4}{120}}\tag{2}
\end{align}
$$
$$ \color{red}{\Longrightarrow\quad S}\,=S_1-S_2+S_3=\,\color{red}{\frac{\pi^4}{45}} $$

$\,H_m\,\,\,$ : Harmonic Number , $\,\{1\}\,$ : Equation (19) ,$\,\{2\}\,$ : Equation (43)
$\,{\large\psi}^{\small (1)}\,\,$ : Polygamma Function
Answer: An alternative approach:
$$ S = \lim_{n\to +\infty}S(n) = \sum_{j,k\geq 1}\frac{1}{j^2 k^2}-\sum_{k,j\geq 1}\frac{1}{jk(j+k)^2}=\zeta(2)^2-\sum_{k,j\geq 1}\int_{0}^{+\infty}\frac{e^{-(j+k)x}}{jk}\,x\,dx $$
leads to
$$S = \zeta(2)^2-\int_{0}^{+\infty}x\log^2(1-e^{-x})\,dx=\frac{\pi^4}{36}+\int_{0}^{1}\frac{\log^2(1-x)\log(x)}{x}\,dx$$
or to
$$ S = \frac{\pi^4}{36}+\int_{0}^{1}\frac{\log(1-x)}{1-x}\log^2(x)\,dx = \frac{\pi^4}{36}-\sum_{n\geq 1}\frac{2H_n}{(n+1)^3}$$
since $\frac{-\log(1-x)}{1-x}=\sum_{n\geq 1}H_n x^n$ and $\int_{0}^{1}x^n\log^2(x)\,dx = \frac{2}{(n+1)^3}$. Rearranging
$$ S = \frac{\pi^4}{36}-2\sum_{n\geq 1}\frac{H_{n}}{n^3}+2\,\zeta(4) = 2\,\zeta(4) = \frac{\pi^4}{45}$$
since the middle term is a linear Euler sum, which can be computed from the Theorem 2.2 here (Flajolet and Salvy, a masterpiece).
Comment: Agree that Euler sums are a way to get there, but probably less well-known than derivatives of the $\Gamma$ function.  But it doesn't hurt to get another method's name out there.
Comment: essentially skbmoore's
Comment: @skbmoore: the intro is the same, but while you use derivatives of the Beta function I use linear Euler sums.
Answer: $\newcommand{\bbx}[1]{\,\bbox[15px,border:1px groove navy]{\displaystyle{#1}}\,}
 \newcommand{\braces}[1]{\left\lbrace\,{#1}\,\right\rbrace}
 \newcommand{\bracks}[1]{\left\lbrack\,{#1}\,\right\rbrack}
 \newcommand{\dd}{\mathrm{d}}
 \newcommand{\ds}[1]{\displaystyle{#1}}
 \newcommand{\expo}[1]{\,\mathrm{e}^{#1}\,}
 \newcommand{\ic}{\mathrm{i}}
 \newcommand{\mc}[1]{\mathcal{#1}}
 \newcommand{\mrm}[1]{\mathrm{#1}}
 \newcommand{\pars}[1]{\left(\,{#1}\,\right)}
 \newcommand{\partiald}[3][]{\frac{\partial^{#1} #2}{\partial #3^{#1}}}
 \newcommand{\root}[2][]{\,\sqrt[#1]{\,{#2}\,}\,}
 \newcommand{\totald}[3][]{\frac{\mathrm{d}^{#1} #2}{\mathrm{d} #3^{#1}}}
 \newcommand{\verts}[1]{\left\vert\,{#1}\,\right\vert}$
\begin{align}
&\bbox[#ffd,10px]{\ds{\sum_{j = 1}^{\infty}\sum_{k = 1}^{\infty}
{j^{2} + jk + k^{2} \over j^{2}\pars{j + k}^{2}k^{2}}}} =
\sum_{j = 1}^{\infty}\sum_{k = 1}^{\infty}
{j^{2} + jk + k^{2} \over j^{2}k^{2}}\
\overbrace{\bracks{-\int_{0}^{1}\ln\pars{x}x^{j + k - 1}\,\dd x}}
^{\ds{1 \over \pars{j + k}^{2}}}
\\[5mm] = &\
-\int_{0}^{1}\ln\pars{x}
\pars{\sum_{j = 1}^{\infty}x^{j}
\sum_{k = 1}^{\infty}{x^{k} \over k^{2}} +
\sum_{j = 1}^{\infty}{x^{j} \over j}
\sum_{k = 1}^{\infty}{x^{k} \over k} +
\sum_{j = 1}^{\infty}{x^{j} \over j^{2}}
\sum_{k = 1}^{\infty}x^{k}}\,{\dd x \over x}
\\[5mm] = &\
-\int_{0}^{1}\ln\pars{x}
\bracks{2\sum_{j = 1}^{\infty}x^{j}
\sum_{k = 1}^{\infty}{x^{k} \over k^{2}} +
\pars{\sum_{j = 1}^{\infty}{x^{j} \over j}}^{2}}\,{\dd x \over x}
\label{1}\tag{1}
\end{align}

Note that $\ds{\sum_{\ell = 1}^{\infty}{x^{\ell} \over \ell^{s}} =
\,\mrm{Li}_{s}\pars{x}}$ where $\ds{\mrm{Li}_{s}}$ is the Polylogarithm Function. Moreover,
  $\ds{\mrm{Li}_{1}\pars{x} = -\ln\pars{1- x}}$,
  $\ds{\mrm{Li}_{s + 1}\pars{z} = \int_{0}^{z}{\mrm{Li}_{s}\pars{t} \over t}\,\dd t}$ and
  $\ds{\sum_{j = 1}^{\infty}x^{j} = {x \over 1 - x}}$.

\eqref{1} becomes
\begin{align}
&\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\bbox[#ffd,10px]{\ds{\sum_{j = 1}^{\infty}\sum_{k = 1}^{\infty}
{j^{2} + jk + k^{2} \over j^{2}\pars{j + k}^{2}k^{2}}}} =
-2\int_{0}^{1}{\ln\pars{x}\,\mrm{Li}_{2}\pars{x} \over 1 - x}\,\dd x -
\int_{0}^{1}{\ln\pars{x}\ln^{2}\pars{1 - x} \over x}\,\dd x
\\[5mm] = &\
-2\int_{0}^{1}\overbrace{\ln\pars{1 - x} \over x}^{\ds{-\mrm{Li}_{2}'\pars{x}}}\,\
\mrm{Li}_{2}\pars{1 - x} \,\dd x -
\int_{0}^{1}{\ln\pars{x}\ln^{2}\pars{1 - x} \over x}\,\dd x
\label{2}\tag{2}
\end{align}
where we set $\ds{x \mapsto 1 - x}$ in the first integral. With Euler Reflection Formula
$\ds{\mrm{Li}_{2}\pars{1 - x} = -\mrm{Li}_{2}\pars{x} + {\pi^{2} \over 6} -\ln\pars{x}\ln\pars{1 - x}}$. \eqref{2} becomes:
\begin{align}
&\bbox[#ffd,10px]{\ds{\sum_{j = 1}^{\infty}\sum_{k = 1}^{\infty}
{j^{2} + jk + k^{2} \over j^{2}\pars{j + k}^{2}k^{2}}}}
\\ = &\ -\
\overbrace{\int_{0}^{1}\totald{\mrm{Li}_{2}^{2}\pars{x}}{x} \,\dd x}
^{\ds{\pi^{4} \over 36}}\ +\
{\pi^{2} \over 3}\
\overbrace{\int_{0}^{1}\mrm{Li}_{2}'\pars{x}\,\dd x}
^{\ds{\pi^{2} \over 6}}\ +\
\overbrace{\int_{0}^{1}{\ln\pars{x}\ln^{2}\pars{1 - x} \over x}\,\dd x}^{\ds{-\,{\pi^{4} \over 180}}}
\\[5mm] = &\
\bbx{\large{\pi^{4} \over 45}}
\end{align}


Create a view with user selected fields

Question: I need to create a view with user selected fields. My basic requirement is data export. My site contains around 1500 nodes and each node has around 25 fields. I have a view for data export with 5 fields.
My specific need is to create a control panel for selecting the fields i want – and in a following step I have to create a view with the selected fields.
Answer: Sounds as you need Views Dynamic Fields. From the project page:

The Views Dynamic Fields module provides a filter for use with Views module. This filter allows the user to pick and choose which fields to display for a rendered instance of a view for that user. This provides a customized view instance for each user.
This module provides additional advantages when used with the Views Bonus Pack module or the Views Excel Export module to generate an xls file from a view. The xls file will only display the fields you have chosen on the rendered view instance in browser.

Create a view with user selected fields


Analysis interesting exercise. How can I use continuity here?

Question: Consider the following problem.
Let $f\colon [0,1]\to\mathbb{R}$ be a continuous function such that $f> 0$ and suppose $\int_{0}^{1}f(t)dt=3$.
Show that there exists $\delta>0$ such that, for every $x\in [0,\delta]$ there is a unique $y\in [0,1]$ such that
\begin{equation}
\int_{x}^{y}f(t)dt=2.
\end{equation}
My attempt:
If we find such $\delta>0$, and if $x_{0}\in[0,\delta]$, then the function
\begin{equation}F(y)=\int_{x_{0}}^{y}f(t)dt
\end{equation}
seems to be stricly increasing (because $f> 0$) and hence the unicity will follow from this fact together with the continuity of $F$.
About existence of $\delta>0$, I have no idea. Thought for a while on how to use continuity of the function itself of the definition of the integral but I'm having a hard time. Help will be appreciated.
Also, is the unicity argument ok? Thank you.
Comment: Uniqueness of $y$ for each $x$ is clearly not true. It is entirely possible that $f(x)>0$ for $x\in(1,\frac12)$, then $f=0$ on $[\frac12,\frac34]$ and finally $f>0$ on $(\frac34,1)$, and everything such that $\int_0^{1/2} f\,dx=2$ and $\int_{3/4}^1 f\,dx=1$. Then, every $y\in \frac 34$ will work for $x=0$.
Comment: I think this could be a mistake by my part of interpreting a "positive function" as it is written in the text I found as $f\geq 0$ instead of $f>0$.  Oh I see, we need strictly increasing, obviously
Comment: It's the first sentence.
Answer: Hint: Pick $\delta$ so that $\int_{\delta}^1 f(t) dt = 2$. (You still need to argue why such a $\delta$ exists, but it does.)
Further hint: Then for $x_0 \leq \delta$, $\int_{x_0}^1 f(t) dt \geq \int_{\delta}^1 f(t) dt = 2$ and $\int_{x_0}^{x_0} f(t) dt = 0$, so you can use the intermediate value theorem to produce a $y$, and the strict monotonicity you observed to prove it is unique.
(Oops: a G. Sassatelli points out -- you don't have strict monotonocity. You need to assume that $f > 0$.)
I don't think continuity of $f$ is strictly necessary, but maybe it is included in the problem so you are guaranteed that $\int_a^b f dt$ ,makes sense, and so that you can use the fundamental theorem of calculus.  (Though maybe I'm missing something.)
Comment: Thank you man. I think I can finish now
Comment: @Shoutre You're welcome :-)
Answer: The unicity argument is correct.
A hint for the existence: show that there is some $\delta>0$ for which $$\int_\delta^1f(t)dt>2$$
and then show that this $\delta$ meets the requirements.


PostgreSQL syntax error at or near "$1"

Question: sql"""copy updateTable
from $path
credentials 'aws_access_key_id=<my_access_key_id>;aws_secret_access_key=<my_secret_access_key>'
json '<path_to_s3_repository>'
gzip;""".update().apply()

Above command gives
org.postgresql.util.PSQLException: ERROR: syntax error at or near "$1"

when run on spark streaming using scala. What might be the issue? The resultant query runs fine when run from command line.
Comment: Do your access_key_id or secret_access_key strings contain '$1'?
Answer: You cannot use a parameter with COPY.
You have to add the literal value of $path to the statement string and execute that.
Comment: As I said, you have to create a string that looks like `COPY updatetable FROM '/path/where/file/is' ...` and send that to the database. I don't know anything about scala or spark, but that's the answer from the PostgreSQL side.

PostgreSQL syntax error at or near "$1"


How can I create a FactoryGirl factory for a Product that belongs_to a User?

Question: I have read the FactoryGirl documentation, but I can't seem to figure this out. I know that it must be simple.
Here is my setup:
Rails 3.2.6
User has_many Products

FactoryGirl.define do
  factory :product do
    sequence(:identifier, 1000) {|n| "ABC#{n}" }
  end
end

This fails because there must be a user_id associated with the Product. In my tests, I am creating a user during login. So my tests have access to the user object. I just don't know how to pass the user object in to the Product factory using FactoryGirl.
Answer: Assuming you already have a User factory (i.e factory :user do) you can add the following line in your :product factory:
association :user

That will automatically create a user factory (as defined) and assign it to your product.
When you create the object in your test though, you can still do something like:
FactoryGirl.create(:produce, user: some_user)

in order to assign a different user variable, because the Factory sees the association from the line you just added.
Hope this helps.


cl.exe when launched via CreateProcess does not seem to have write permissions

Question: I'm calling CreateProcess to launch cl.exe (VS2010 on Win7 64 bit). I get the following error..
cl : Command line error D8037 : cannot create temporary il file; clean temp directory of old il files
Calling the same command line with the same environment variables in a cmd window succeeds. I've checked the temp directory and there are no old files. It seems like the process that is created does not have write permissions. I've been trying different approaches.. CreateProcessAsUser, Set the security attributes to grant all standard permissions to the Everyone user group, with and without inheriting handles, etc. None of them seem to fix it.
And here's the basic code...
<code>SECURITY_ATTRIBUTES sa;
sa.nLength = sizeof( SECURITY_ATTRIBUTES );
sa.bInheritHandle = TRUE;
sa.lpSecurityDescriptor = NULL;

const char* _szSourceFile = "c:\\temp\\test\\src\\foo.cpp";

char szOptions[ 2048 ];
sprintf_s( szOptions,
    "c:\\temp\\compile\\cl.exe "
    "/Gd "
    "/Fo\"c:\\temp\\test\\out\\\" "
    "/Fe\"c:\\temp\\test\\out\\\" "
    "/Fd\"c:\\temp\\test\\out\\\" "
    "/D \"WIN32\" "
    "/D \"_DEBUG\" "
    "/D \"_WINDOWS\" "
    "/D \"_USRDLL\" "
    "/D \"_WINDLL\" "
    "/D \"_MBCS\" "
    "/I\"c:\\Program Files (x86)\\Microsoft SDKs\\Windows\\v7.0A\\Include\" "
    "/MDd "
    "/I\"c:\\Program Files (x86)\\Microsoft Visual Studio 10.0\\VC\\include\" "
    "/LDd "
    "%s "
    "c:\\temp\\test\\lib\\Uuid.Lib "
    "c:\\temp\\test\\lib\\oldnames.lib "
    "c:\\temp\\test\\lib\\msvcrtd.lib"
    , _szSourceFile );

STARTUPINFO si;
PROCESS_INFORMATION pi;
ZeroMemory( &si, sizeof( STARTUPINFO ) );
ZeroMemory( &pi, sizeof( PROCESS_INFORMATION ) );
si.cb = sizeof( STARTUPINFO );

BOOL bSucceeded = CreateProcess( "c:\\temp\\compile\\cl.exe", szOptions, NULL, NULL, FALSE, NORMAL_PRIORITY_CLASS, "PATH=c:\\temp\\Compile;%PATH%\0TEMP=c:\\temp\\test\\tmp\0\0", "c:\\temp\\test\\", &si, &pi );
</code>
In case you're wondering about the weird paths, I copied over the most minimal set of required tools, libs, etc to build a dll directly from a cpp file. The command in the code works on a regular command line with the path that is set in the enviroment variables block.
Also, in case you're wondering what this is for, I'm trying to have an app that can dynamically reload a dll. The app is being used for debugging/visualization and the idea is to be able to tweak the visualization code on the fly and have the app reload the dll.
I've been at this for 4 days googling and trying out different things. Any ideas?
Comment: The spawned process should have the same permission as the calling process; is the calling process able to create files in the temporary path?
Comment: Possibly the same as here: http://stackoverflow.com/questions/8584811/c-msvs-what-file-cleanup-should-i-be-doing-cl-error-d8037
Comment: @PeterRitchie, Yes the calling process can create and write files in all the possible temp folders. I used GetEnvironmentVariable to get the locations for TMP as well as TEMP. Both point to c:\users\xxxxx\AppData\Local\Temp folder. The 3rd folder is the TEMP var I pass into CreateProcess (TEMP=c:\temp\test\tmp).
Comment: @alk, Nope. None of my temp locations have those files mentioned.
Answer: Found the issue.
I used the Process Monitor to monitor cl.exe to see what was failing.
Process monitor can be downloaded from http://technet.microsoft.com/en-us/sysinternals/bb896645.
Turns out that it was failing to load rsaenh.dll in the windows system folder. cl.exe could not resolve %SystemRoot% environment variable. Since I was overriding the environment variables, it got reset. Adding SystemRoot=c:\Windows to the environment variables fixed it. The proper fix would be to get the environment variables for the current process, parse and modify it to make your path additions and then pass that in. That way you inherit all the environment variables.
Comment: Adding "SystemRoot=c:\Windows" to the system environment worked for me thanks. But it needs windows restart.


Botão de buscar/confirmar e limpar campo

Question: Preciso que quando o usuário clicar sobre o botão "BUSCAR/CONFIRMAR" abra uma nova janela no navegador pedindo para SELECIONAR uma das categorias que vem diretamente do banco de dados, e ao selecionar a mesma janela fecha e o valor escolhido vai pro campo e só seria possível mudar a categoria clicando no botão "LIMPAR CAMPO" e fazendo todo processo novamente.
É tudo através de javascript, mas infelizmente não tenho esse conhecimento.
Input e os botões: (O input por padrão é desativado):

Categoria            :
        <input type="text" disabled="disabled" name="categoria" size="65">

Buscar/Confirmar
        Limpar o Campo

Categorias.php (Nova janela)

 Selecione
    ID
    Nome da Categoria

<?php
$sql_pai = "SELECT * FROM cms_news_cat ORDER BY ID";
$res_pai = mysql_query($sql_pai) or die(mysql_error());
while($row=mysql_fetch_array($res_pai)){ ?>

 <input type="radio" value="<?php echo $row['nome']; ?>" />
<?php echo $row['id']; ?>
<?php echo $row['title']; ?>

    <?php } ?>

Answer: Adicione um onclick em cada  para chamar duas funções: uma para abrir a nova janela e outra para limpar o campo:
Buscar/Confirmar
 Limpar o Campo

E adicione o script com as funções:

Onde tem "..." no window.open você pode definir as propriedades da
  janela (veja aqui as opções).

No arquivo categorias.php você deve dar um mesmo name para cada input radio, por exemplo:
<input type="radio" name="categoria" value="<?php echo $row['nome']; ?>" />

E nesse mesmo arquivo categorias.php, insira o script:

Ao selecionar um radio, o seu value será lançado no input da página principal e a janela se fechará.
Comment: Obrigado amigo, funcionou perfeitamente!


How do I find the limit of $\lim_{x \to 0}{\frac{1-(\cos{kx})^k}{x^2}}$?

Question: As the title suggests, how do I find: $\;\;\displaystyle\lim_{x \to 0}{\frac{1-(\cos{kx})^k}{x^2}}?$
Our professor showed us how to find $\lim_{x \to 0}{\frac{1-\cos{kx}}{x^2}}$ by applying $1-\cos{x} = 2(\sin{\frac{x}{2}})^2$, but I have no idea how to even start this one.
We're not supposed to use derivatives, as we haven't reached that point or anything higher (obviously).
Comment: ${\large\textbf{Hint :}}$ \begin{aligned}1-\cos^{k}{\left(kx\right)}=\left(1-\cos{\left(kx\right)}\right)\sum_{j=0}^{k-1}{\cos^{j}{\left(kx\right)}}\end{aligned}
Comment: It's odd that $k$ has two unrelated roles in an easy two-parameter generalization. Was that definitely intended?
Comment: @CHAMSI Thank you for the hint! I managed to do it this way. Much appreciated!
Comment: @C.Dubussy Doesn't l'Hospital make use of derivatives?
Comment: @C.Dubussy The question explicitly asks that differentiation not be used.  You can't L'Hospital without a derivative...
Answer: We can use Taylor expansion of the cosine function near the origin:
$$\cos(kx)=1-\frac{k^2}{2}x^2+o(x^2)$$
We can derive this formula, also, looking at the asymptotic relations:
$$\cos(kx)\;\;\sim\;\; 1-\frac{k^2}{2}x^2$$
In this case, it's not necessary to use the $o(x^2)$. I will keep using it because it's more formal.
So:
$$1-\cos(kx)^k=1-\left(1-\frac{k^2}{2}x^2+o(x^2)\right)^k=\frac{k^3}{2}x^{2}+o(x^2)$$
The limit becomes:
$$\lim_{x \to 0}{\frac{1-(\cos{kx})^k}{x^2}}\;\;\sim\;\; \lim_{x\to 0}\frac{\frac{k^3}{2}x^2+o(x^2)}{x^2}=\frac{1}{2}k^3$$
Question for you: what about the limit $$\lim_{x \to 0}{\frac{1-(\cos({\alpha x}))^{\beta}}{x^2}}$$
Comment: The question explicitly asks that derivatives not be used, which seems to imply that tools which are introduced *after* differentiation is introduced should also not be used.  How do you justify the use of Taylor series in a setting where derivatives cannot be used?
Comment: @Xander Henderson: I have edited my answer. I hope it will fit the question. Thanks.
Answer: Notice that :

 For $k = 2$ :
$$\dfrac{1 - \cos^2(2x)}{x^2} = \dfrac{1 - \cos(2x)}{x^2} + \cos (2 x) \dfrac{1 - \cos(2x)}{x^2}$$
 For $k = 3$ :
$$\dfrac{1 - \cos^3(3x)}{x^2} = \dfrac{1 - \cos(3x)}{x^2} + \cos (3 x) \dfrac{1 - \cos(3x)}{x^2} + \cos^2(3x) \dfrac{1 - \cos(3x)}{x^2}$$
 In general :
$$\dfrac{1 - \cos^k(kx)}{x^2} = \dfrac{1 - \cos(kx)}{x^2} + \cos (kx) \dfrac{1 - \cos(kx)}{x^2} + \cdots + \cos^{k - 1}(kx) \dfrac{1 - \cos(kx)}{x^2}$$


How to detect user interaction with `MapControl` on Windows Phone 8.1?

Question: I have a MapControl and want to detect if the user has panned or zoomed the map (or basically generated any pointer events).
I've tried a number of approaches but haven't been able to detect the pointer events. E.g. MyMapControl.PointerPressed += ..., MyMapControl.AddHandler(UIElement.PointerPressedEvent, ..., true), Window.Current.CoreWindow.PointerPressed +=, ((Page)this).PointerPressed +=, but they aren't called. The events for the page and the window are emitted when touching down outside the MapControl, but never when touching down inside the MapControl.
If I put something that covers the MapControl, e.g. a Rectangle, it gets the events, but it also consumes them so they don't reach the MapControl. I'm hoping that it's possible for the overlay to see the events but not consume them, but haven't succeeded so far.
Any help is appreciated!
Answer: The MapTapped event handles tapping the map, the generic Tapped event doesn't work.
As for panned or zoomed, I use the LoadingStatusChanged event and look for mapControl.LoadingStatus == MapLoadingStatus.Loaded to know when the user has stopped manipulating the map.
Note that things like drawing elements on the map will also trigger LoadingStatusChanged.  If that is a situation you need to deal with, you can store the map's center and zoom level somewhere, and then compare these values to the current center/zoom level of the map when the even fires to know if the map was really manipulated.
If you're using Interactivity, I wrote a behavior that does all of this if you want it.
Comment: Thanks Paul!
`MapTapped` is only fired when the user taps the map, not when they pan or zoom, so it doesn't solve my problem.
`LoadingStatusChanged` is also fired when I programatically manipulate the map, e.g. calls `TrySetViewAsync()`
Comment: The `CenterChanged` and `ZoomLevelChanged` events will let you know when interaction is occurring.


How to facilitate meetings / events with participant registration, agenda and documents?

Question: How to manage meetings in Drupal? I would like to do the following:

Participants can register for an event or be added by the admin.
The meeting has an agenda, consisting of a number of agenda points.
Documents can be attached to the various agenda points.
Participant details, the agenda and documents are shown.
Record that the meeting is one in a series of meetings of the same group.

An example of what is needed is here, but the site is Joomla and it seems to be a custom module.
Comment: I'm voting to close this question as off-topic because it is about a feature to implement for which just a short description and a off-site link is given.
Answer: There are many options in Drupal allowing you to add registrations to content. So if you add a content type of 'meeting', you can add file fields, dates and an agenda text field. Add a taxonomy field for grouping by type.
Then with any of the registration modules you can register users.

Entity Registration
Node registration
RNG (Drupal 8)

Basically it is not one module, but a combination of fields and modules to get the desired functionality.
Answer: Use a distribution
Have a look at Open Atrium. Here are some details about it (from its project page):

A new architecture for Drupal 7 that is built upon Organic Groups and Panopoly and intended as an extensible collaboration framework. Adds the ability to have private "sections" within a collaboration space with granular access control. Drag/drop layout control with dozens of widgets that can be placed on dashboards and landing pages. Comes with Discussions, Events, Files, Issue tracking, and Document Wiki out of the box, along with the dashboards to manage it all.

Use modules that fit your needs
If you'd rather want to roll your own cookies, then there are quite some contributed modules that should help to get you going. Refer to my answers to these questions for more details:

How to implement RSVP Functionality?
How to limit access to a meeting content type to only the participants specified via Entity Reference?


Load balancing or high availability tomcat with network switch?

Question: i was wondering if it is possible to load balance and create a high availability environment using network switches? Or do i need a real apache server in front of the tomcat servers?
Answer: To expand on Guacamole's answer a little bit.
Proper switch design is a large part of a proper HA solution. However, you are working at the wrong level to think that they will make your tomcat installation HA. Switches are a Layer 2 (sometimes also 3) device, while you are talking about making layer 7 HA.
To get a proper HA solution in place, you need to take a look at your stack from the ground (Layer 1) up (layer 7) and ask your self "what would happen if this piece of the stack no longer existed." Then you can start to design a scalable HA solution for your stack.
There are many great options out there from the paid F5 and Cisco gear to the Open Source HAProxy, LVS, etc. But first you need to evaluate your entire infrastructure and find out exactly where your single points of failure are and put the right solutions in. You may find after doing some evaluations, that there are products that will fix multiple SPoFs that you would have overbought for otherwise.
Answer: There are many web services load-balancing solutions available...

Many  companies use F5 BigIP LTM for load-balancing solutions.
Cisco's ACE is also an option; see this ACE link if the original above is dead (which Cisco seems to do almost monthly)

There are a few open-source solutions as well...

HAProxy
loadbalancer.org - An appliance that uses HAProxy, and includes commercial support

The real answer to the question depends on how you plan to load-balance... will it depend on your server's http response time, CPU utilization, bandwidth, per-http-session, etc...  The options above may or may not be so great at your particular use-case... although as a general solution, it's hard to beat F5.


Coin flip need help on error

Question: Im writing code that is a random coinflipper that will have one person input their guess. I can't touch anything in the main as that is the directions for the assignment. I'm getting this error though when I try to run it

Error:(15, 34) java: incompatible types: void cannot be converted to java.lang.String

The error is happening in the main on this line:   coin=flip();   but I can't change anything in the main. Please help this is due tonight! Here is my code:
public class CoinFlip {

static String side = "";
static String user = "";
static String winner = "";

public static void main(String args[]) {
    String coin;

    greeting();

    do
    {
        user=IO.getString("Would you like: (H)- Heads or (T)- Tails");
        coin=flip();
        winner=compare(user,coin);
        output(user,coin,winner);

    }while( repeat() );
}

public static void greeting() {
    System.out.println("In a second, choose heads or tails. A coin flip will show and a winner will be shown.");

}
public static void flip() {

    int random = (int) Math.floor(Math.random() * 2);
    if (random = 0)
        side = "H";
    else if (random = 1)
        side = "T";
}
public static void compare(String args[]) {
    if (user = side)
        winner = "Winner";
    else
        winner = "Loser";
}
public static void output() {
    System.out.println(side);
    System.out.println(winner);
}
public static void  repeat() {
    String again;
    if (again = "yes")
        main();
    else if (again = "no")
        System.out.println("Thanks for playing!");
}
}

Comment: `void flip()` doesn't return anything, but you're trying to assign the result to `coin` when you say `coin=flip();`. You need to make `flip()` return a `String`, or say `flip(); coin = side;`.
Comment: you are supposed to ``return`` the ``"H"`` or ``"T"``, but that's not possible with a method type of ``void``. Change ``void flip()`` to ``String flip()``.
Answer: Change public static void flip() { to public static String flip() { and add (at the end of flip)
 return side;

Answer: Your method flip() should return the result either "H" or "T" based on code.
So, flip() method signature need to change from void return type to String.

Coin flip need help on error


Datepicker works in IE error in Firefox or Chrome

Question: Web form with date picker, one of the fields is cdate , I use jsdatepick for this field.

<form method="POST" action="insert_record.php">

 Call Date:

<input type=text id="cdate" name="cdate"  size=40 style="color: black;background-color:#FFFF66; width: 270px;">

and the form submit php is
<?
$cdate=$_POST['cdate'];
$db="call";
$link = mysql_connect("localhost", "sql", "sql");
//$link = mysql_connect("localhost",$_POST['username'],$_POST['password']);
if (! $link)
die("Couldn't connect to MySQL");
mysql_select_db($db , $link) or die("Select Error: ".mysql_error());
$result=mysql_query("INSERT INTO data (cdate) VALUES ('$cdate')")or die("Insert Error: ".mysql_error());
mysql_close($link);
print "Record added\n";
?>

however once submitted I get message saying ::

Notice: Undefined index: cdate in d:\web\apache\htdocs\callz\submit_record.php on line 4

this message only occurs in Firefox or Chrome, works fine in any version of IE
any ideas? Note there are other variables besides cdate, all of those variables enter into the table without issue, just seems to be the datepick one.  I have tried another datepick and this doesn't happen, only with the jsdatepick, but jsdatepick is so much more suitable. Any ideas?
thanks
Answer: You never closed your form tag.
So essentially Chrome and FF close the form tag for you and you get this:
<form method="POST" action="insert_record.php"> </form> << NOTHING HERE!

 Call Date:

<input type=text id="cdate" name="cdate"  size=40 style="color: black;background-color:#FFFF66; width: 270px;">

Also PLEASE DO NOT USE mysql_* FUNCTIONS
Try using prepared functions with PDO or mysqli instead (see this big red box).
What you have is prone to a HUGE bobby table issue...
Comment: My guess is this is simply a small set of the actual markup. OP hasn't posted everything.


SQL Error :"No such table"

Question: I am trying to troubleshoot why my code returned null for all my queries and finally found that sql query returns nothing. I created a new AIR document (s:WindowedApplication) with minimalistic code:
<fx:Script>
        <![CDATA[
            import mx.events.FlexEvent;

            private var sqlConnection:SQLConnection;
            private var select:SQLStatement;
            private var databaseFile:File;

            protected function windowedapplication1_creationCompleteHandler(event:FlexEvent):void
            {
                var dbPath:String = "Movie Manager Settings/moovioDB2.db";
                databaseFile = File.userDirectory.resolvePath(dbPath);
                sqlConnection = new SQLConnection();
                select = new SQLStatement();

                sqlConnection.addEventListener(SQLEvent.OPEN, onDatabaseOpen);
                sqlConnection.openAsync();
            }

            private function onDatabaseOpen(event:SQLEvent):void
            {
                select.sqlConnection = sqlConnection;
                var query:String = "SELECT title FROM movies";
                select.text = query;
                select.addEventListener(SQLEvent.RESULT, done);
                select.execute();
            }

            private function done(event:SQLEvent):void{
                var res:SQLResult = select.getResult();
            }

        ]]>
    </fx:Script>

Other than this code theres is just the standard tags created by Flex. Upon execution I get this error:
Error #2044: Unhandled SQLErrorEvent:. errorID=3115, operation=execute , message=Error #3115: SQL Error. , details=no such table: 'movies'

I have checked the database file with 2 different sqlite programs and executed the query successfully. Both 'movies' table and 'title' column exists. In case it matters movies is one of 3 tables and has over 10 columns all with values present.
What am I doing wrong? I used identical code(I thought) before with expected results, but after some changes now I can even get this basic code in a new document to work. Please check it out and see if I am making a stupid mistake because I can't see it :)
Answer: Can you verify that the path of the database you open is the one of that file you checked with external tools? You can use the database_list pragma from within you AS3 code. Just execute it as any other SQL statement:
[user@host ~]$ cd /tmp
[user@host tmp]$ sqlite3 foo.db
SQLite version 3.7.11 2012-03-20 11:35:50
Enter ".help" for instructions
Enter SQL statements terminated with a ";"
sqlite> pragma database_list;
0|main|/tmp/foo.db

Comment: Did you mean just replace "query" with "var query:String = "PRAGMA database_list"; "? If so I gen an error "Error #2044: Unhandled SQLErrorEvent:. errorID=3115, operation=execute , message=Error #3115: SQL Error. , details=PRAGMA is not allowed in SQL." If not can you specify how to execute this query in AS?
Comment: Doh! This must be the silliest mistake i've made in a while, I never passed the location of the database file to the "openAsync()". :)
Comment: Accepting the answer as it did make me see the problem, thanks :) Please update ur answer to include the fix for anyone else who might be having same issue. instead of "sqlConnection.openAsync();" it should be "sqlConnection.openAsync(databaseFile);"

SQL Error :"No such table"


How to show that z/(z^2+1) is less than or equal to 1/2 when dom(z) is the line segment from 2 to 2+i? (ML formula for integration)

Question: I am having a problem solving this one :-
Use the ML formula to show that |integral over C (z/(z^2+1))dz| is less than or equal to 1/2, where C is the straight line segment from 2 to 2+i. (I am struggling to use codes to show the question in proper form here, i am sorry.)
I have calculated L which should be the distance from 2 to 2+i and it is 1 unit but I can not show that the modulus of the function f(z)= z/(z^2+1) is less than or equal to 1/2 (I am trying to find M so that M*L becomes 1/2). Can you please help me? Thank you.
<code>My calculations are showing that |z| needs to be 1 for |z/(z^2+1)| to be less than 1/2.
</code>
Comment: You're comparing a nonreal number with $1/2$.  This makes no sense.
Comment: Did you mean $|f(z)|$?
Comment: Yes yes my bad.
Answer: Hint: Take $0 \leq t \leq 1$ and show that $|\frac {2+it} {((2+it)^{2}+1}| \leq \frac 1 2$ or $4(4+t^{2})\leq ((5-t^{2})^{2}+16t^{2})$. My calculations show that this inequality is correct.


Serving Static Files with Common Lisp

Question: I'm writing a minimal web server in Common Lisp, and want it to be able to have some basic static file serving ability. The idea is for this to be used in development, testing and other low-traffic situations, so it doesn't have to be particularly efficient. It also won't have to deal with large files. It does, however, have to work, and this errors when attempting to serve images:
...
(with-open-file (s path :direction :input :element-type 'octet)
             (let ((buf (make-array (file-length s) :element-type 'octet)))
               (read-sequence buf s)
               (write! (make-instance
                'response :content-type mime
                :body buf)
                   sock))
             (socket-close sock))
...

Specifically, it gives me the error
The value 137 is not of type CHARACTER.
   [Condition of type TYPE-ERROR]
...

The relevant part of write! looks like
...
(write-string "Content-Length: " stream) (write (length body) :stream stream) (crlf stream)
(crlf stream)
(write-sequence body stream)
(crlf stream)
...

I've tried changing it to
...
(write-string "Content-Length: " stream) (write (length body) :stream stream) (crlf stream)
(crlf stream)
(write-string (flexi-streams:octets-to-string body) stream)
(crlf stream)
...

whereupon the error disappears, but the client gets a mangled version of the file. You can see more context around the above code here.
What am I doing wrong?
The system is built on top of :usocket and uses :flexi-streams for octet. The above is taking a very similar approach to Hunchentoot (see the static file snippet here; that code does chunking and a few other checks before-hand, but otherwise seems to be doing the same thing I am above). I'm running the latest stuff out of :quicklisp for everything, and running it on SBCL 188.8.131.52.debian on top of 64-bit Debian stable.
Comment: Set the flexi-stream external format to the appropriate encoding. Probably utf-8.
Comment: @WhiteCat - Any hints on how to make a `socket-stream` into a `flexi-stream`? The naive `(flex:make-flexi-stream (socket-stream sock) :external-format :utf-8)` results in getting type errors when I try to write to the result (it reports that the stream is not a binary output stream). I also can't find the code that does this job in Hunchentoot (though it must at some point; a socket starts off with `usocket:socket-accept` in `acceptor.lisp`, and ends up being written to through `write-sequence` in `misc.lisp`).
Answer: Thanks to jasom and Bike from #lisp for the answer:
If you want to serve static files from a usocket-based server, you need to

Include flexi-streams
Make sure to create binary streams when accepting
Make the streams bivalent before doing anything (otherwise character/string writes/reads are going to error on you)

The first point is easy enough. Either call (ql:quickload :flexi-streams), or add #:flexi-streams to the :depends-on line of your .asd.
The second point involves calling socket-accept with the additional argument:
(socket-accept ready :element-type 'octet)

Third, instead of passing around a socket and writing to (socket-stream socket) everywhere, you'll need to do a make-flexi-stream call.
(let ((stream (flex:make-flexi-stream (socket-stream sock) :external-format :utf-8)))
    ;;; stuff you want to do
    )

Depending on your specific situation, it might make sense either to wrap every write/read in the above, or do it once (right after you call socket-accept) then pass the flexi-stream around along with the socket.

Serving Static Files with Common Lisp


How to perform android app synchronization with the server?

Question: I have an android application (minSdkVersion=7), which should send/receive some data to the server once per day. What is the best way to organize such synchronization?
In my previous application I used background Service which checks every X mins if 1 day is passed. But I don't like this approach since the service is always running. Is there any other way to achieve the same?
What is synchronization should happen not once per day, but once per hour? Does it change the approach?
One more item to be considered - I perform synchronization only if wi-fi connection is available. If it is not, I shouldn't wait for 1 more day. The app should try to perform another synchronization let's say in 15 minutes.
Comment: possible duplicate of [Running task periodicaly(once a day/once a week)](http://stackoverflow.com/questions/8615543/running-task-periodicalyonce-a-day-once-a-week)
Answer: If you know in advance the time to do something, ie once a day, in four hours or so, you can use Android AlarmManager and a BroadcastReceiver. In that way you do not need to have a Service that spends most of its time waiting.
An example can be found here.


How can I impute a large multivariate dataset?

Question: I am researching a medical dataset that has a large number and complexity of variables (> 900 variabes, > 3000 with dummy variables). Not only biomarkers and the patient's demographical data is included, but also questionnaires (continuous, non-ordered categorical and ordered categorical, non-respectively). Due to this complexity I have not managed to use MICE in R or Python, it errors out and states message that the data is numerically impossible to solve.
This lead me to try to impute the questionnaires apart from the other variables, because they are the largest part of the dataset and because the correlation between missing data has the highest probability. Because it is a longitudinal study, some people might not have been able to fill out the first questionnaire for example, because they were not yet included in the study, so by using the other questionnaires we might be able to impute for the missing data of the first questionnaire.
The method I tried to use to impute for the questionnaires was MICE, which failed, again. The other method I tried was order the questions according to missing data, where v1 had the least amount of missing data and vn the largest amount. I then tried to find variables that had no overlapping missing data with v1, let's call them [ v2 ... vn]. I then tried to create a logistic regression between variables [v2 ... vn] after deleting the patients with missing data, the problem was that the logistic regression could not converge, because only 1 of the two classes was available (there were no 1's available in the data after deleting the patients with missing data for the predictor variables: [v2 ... vn])
Because this also failed I am currently going to try to do this: find the 10% most correlating questions with v1 that do not have any overlapping data with v1: [v2 ... vn], impute these predictors ([v2 ... vn]) with their mean and then logistically regress them with the non-missing data in v1. Then I will predict the missing data in v1 with the non-missing data from [v2 ... vn]. Now, even though this is likely to work, it does not seem very statistically correct and that is my main question, is this a solid method to use for imputing a large multivariate dataset, if not, what can I improve or are there other methods that I have overlooked?
Answer: The algorithm you have described at the bottom is basically one "chaining" iteration of MICE [1], so it is less crazy than you'd guess...
From your description, you have a lot of columns and they are of mixed type (categorical, numeric). Now, if the proportion of missing values is large per column, then it is close to hopeless to let an algorithm solve that problem. On the other hand, if the amout of missing values is typically small per column (5% or so), then you can give a try to MICE with e.g. random forest as model technique. Why? Because it can deal with categorical (not dummy coded!) and numeric fiels. Furthermore, they work quite well without tedious hyperparameter tuning.
Then, depending on the purpose of the analysis, you can use multiple imputed versions of the data set, run your analysis on each of them and then pool the results of the analyses (this is the tricky part of multiple imputation).
Let me illustrate with my own R version [2] of imputation by random forests, a fast alternative to [3] based on the very efficient ranger package [4]:
# install.packages(devtools)
library(devtools)
install_github("mayer79/missRanger")

library(missRanger)

# Generate data with missing values in all columns
set.seed(39)
head(irisWithNA <- generateNA(iris))

# Show data set with missings
      Sepal.Length Sepal.Width Petal.Length Petal.Width Species
1          5.1         3.5          1.4         0.2  setosa
2          4.9         3.0          1.4         0.2  setosa
3          4.7         3.2          1.3         0.2  setosa
4          4.6          NA          1.5         0.2  setosa
5          5.0         3.6          1.4         0.2    <NA>
6          5.4         3.9          1.7          NA  setosa

# Impute missing values
head(irisImputed <- missRanger(irisWithNA, pmm.k = 3, seed = 75757))

# Gives
  Sepal.Length Sepal.Width Petal.Length Petal.Width Species
1          5.1         3.5          1.4         0.2  setosa
2          4.9         3.0          1.4         0.2  setosa
3          4.7         3.2          1.3         0.2  setosa
4          4.6         3.7          1.5         0.2  setosa
5          5.0         3.6          1.4         0.2  setosa
6          5.4         3.9          1.7         0.4  setosa

Just run with different seeds to get realisticly varying versions of the same data. The "predictive mean matching" aspect is crucial if you are doing multiple imputation.
[1] Van Buuren, S., Groothuis-Oudshoorn, K. (2011). mice: Multivariate Imputation by Chained Equations in R. Journal of Statistical Software, 45(3), 1-67. http://www.jstatsoft.org/v45/i03/
[2] https://github.com/mayer79/missRanger
[3] Stekhoven, D.J. and Buehlmann, P. (2012), 'MissForest - nonparametric missing value imputation for mixed-type data', Bioinformatics, 28(1) 2012, 112-118, doi: 10.1093/bioinformatics/btr597
[4] Wright, M. N. & Ziegler, A. (2016). ranger: A Fast Implementation of Random Forests for High Dimensional Data in C++ and R. Journal of Statistical Software, in press. http://arxiv.org/abs/1508.04409.


CSS3 border-radius on display:table-row element

Question: This is my layout:

        ....

And the CSS:
.divContainer{
    display:table;
    border-spacing:0 5px; //bottom spacing
    width:100%;
}

.item{
    display:table-row;
    height:45px;
   -moz-border-radius:10px;
   -webkit-border-radius:10px;
   border-radius:10px;
}

.itemHeader, .itemBody, .itemFlag{
    display:table-cell;
}

.itemHeader{
    width:100px;
}

.itemBody{
    width:150px;
}

.itemFlag{
    width:20px;

}

The round borders don't appear on the item elements.
If I put them separately in itemHeader and itemFlag they appear.
But I'd really like to clear some code and put them in the item
Also can't get the radius to work on the divContainer class. I want a rounded container which contains rounded rows.
What is the problem? Maybe another part of CSS is messing it up, but I don't thing that is the case.
Answer: I'm afraid this there is no way to apply border radius on table rows. However, the workaround is pretty simple: just apply the background color and the border radius to the cells.
If you remove the background color from the table rows, and you can add this:
.item > div {
  background-color: #ccc;
}

.item > div:first-child {
  border-radius: 10px 0 0 10px;
  -moz-border-radius: 10px 0 0 10px;
}

.item > div:last-child {
  border-radius: 0 10px 10px 0;
  -moz-border-radius: 0 10px 10px 0;
}

It will work even if you change your class names.
You can see it in action here:
http://jsfiddle.net/jaSs8/1/
Comment: border collapose with div:first-child hack . https://codepen.io/chriscoyier/pen/NWKrXQx
Answer: Maybe the problem is in divContainer class. Try to change the display attribute to table-row.
Comment: I can't have a table-row inside a table-row. There has to be a table element
Answer: You also can fix this issue by setting float:left; on the table element. It doesn't effect the behavior of the table flexibility and works like a charm.
table {
 float: left;
 display: table;
 width: 100%;
 border-collapse: collapse;
}
tr {
 display: table-row;
 width: 100%;
 padding: 0;
}
td {
 font-weight: bold;
 background: #fff;
 display: table-cell;
 border-radius: 10px;
}

Comment: the question to ask about css display table-row. not for table element bro
Answer: I think best solution for this case is to create wrapper for table tag and apply all border styles to it.

{tableContent}


MySQL How to place same records into a separate columns?

Question: Fiddle: http://sqlfiddle.com/#!9/4d4288/6
DDL and DML:
CREATE TABLE User(
  id INT,
  Name VARCHAR(50)
);

INSERT INTO User (id, Name)
VALUES
(1, 'Name 1'),
(2, 'Name 2'),
(3, 'Name 3');

CREATE TABLE Log(
  Id INT,
  Description VARCHAR(255));

INSERT INTO Log (id, Description)
VALUES
(1, 'This is issue 1 ...'),
(2, 'This is issue 2 ...'),
(3, 'This is issue 3 ...'),
(4, 'This is issue 3 ...');

CREATE TABLE LogActions(
  id INT,
  LogID INT,
  UserID INT,
  Status ENUM('Approved', 'Refused'));

INSERT INTO LogActions (id, LogID, UserID, Status)
VALUES
(1,1,1,'Approved'),
(2,1,2,'Approved'),
(3,2,1,'Approved'),
(4,2,3,'Approved');

Output
SELECT
  l.id,
  l.description,
  u.name,
  la.status
FROM Log l
LEFT JOIN
  LogActions la ON l.id = la.LogID
LEFT JOIN
  User u ON u.id = la.UserID

---------------------------------------------
id  description             name    status
1   This is issue 1 ...     Name 1  Approved
1   This is issue 1 ...     Name 2  Approved
2   This is issue 2 ...     Name 1  Approved
2   This is issue 2 ...     Name 3  Approved
3   This is issue 3 ...     (null)  (null)
4   This is issue 4 ...     (null)  (null)

Summary
Here I can see which user marked specific log number and also which records havent.
Within the .NET application, I ensure the records are marked by 2 different users and no more than 2 records are checked off.
Goal
This is my desired output.
id  description             name1      name2    status1  status2
1   This is issue 1 ...     Name 1     Name 2   Approved Approved
2   This is issue 2 ...     Name 1     Name 3   Approved Approved
3   This is issue 3 ...     (null)     (null)   (null)   (null)
4   This is issue 4 ...     (null)     (null)   (null)   (null)

This is what I aim to achieve. Essentially, I am needing to see 1 of each log number id, and on the same row show the users name and status that have/haven't marked this record.
This is the best solution I have at the moment, I'll be happy to hear for any alternatives.
Purpose
The main purpose of this is to have each log number in 1 row instead of multiple and visually inspect who  has marked it or whether it is blank.
Comment: What is your version of MySql?
Comment: @forpas `8.0.18`
Answer: With FIRST_VALUE() window function:
SELECT DISTINCT
  l.id,
  l.description,
  FIRST_VALUE(u.name) OVER (PARTITION BY l.id ORDER BY la.id) name1,
  FIRST_VALUE(u.name) OVER (PARTITION BY l.id ORDER BY la.id DESC) name2,
  FIRST_VALUE(la.status) OVER (PARTITION BY l.id ORDER BY la.id) status1,
  FIRST_VALUE(la.status) OVER (PARTITION BY l.id ORDER BY la.id DESC) status2
FROM Log l
LEFT JOIN LogActions la ON l.id = la.LogID
LEFT JOIN User u ON u.id = la.UserID

See the demo.
Results:
> id | description         | name1  | name2  | status1  | status2
> -: | :------------------ | :----- | :----- | :------- | :-------
>  1 | This is issue 1 ... | Name 1 | Name 2 | Approved | Approved
>  2 | This is issue 2 ... | Name 1 | Name 3 | Approved | Approved
>  3 | This is issue 3 ... | null   | null   | null     | null
>  4 | This is issue 4 ... | null   | null   | null     | null

Comment: Just realized. The `name1` and `name2` is filled even when 1 record has been marked. e.g. https://dbfiddle.uk/?rdbms=mysql_8.0&fiddle=0287cddcc64e30955e356f6822f61aa9 see this line `INSERT INTO LogActions (id, LogID, UserID, Status)
VALUES
(1,1,1,'Approved'),
(2,1,2,'Approved'),
(3,2,1,'Approved'),
(4,2,3,'Approved'),
(5,3,3,'Approved')
;`. The `name2` should be empty if 2nd user has not marked it.
Comment: @LV98 what do you mean by *1 record has been marked*?
Comment: @LV98 Something like this: https://dbfiddle.uk/?rdbms=mysql_8.0&fiddle=c21c179619e4910138a4a48fa6e411b0
Comment: Sorry, was just creating an example on fiddle link and editing my question regarding your question. But yeah, that's right :) How did you learn SQL so effectively?
Comment: What language you used first?
Comment: Fortran and later Pascal.
Comment: You must of coded for years... at any point do you still use older languages rather than modern?
Comment: No, I don't use any of them. Depending on the requirement I may use Java, maybe Kotlin and rarely VB/VBA, apart from SQL.
Comment: Do you have a favorite :)?
Comment: No, although Kotlin is a bit more fun since it's the newest.
Comment: What would you recommend for desktop development? WPF by any chance? I like the use of XAML and the flexibility to design the UI.
Comment: I have never used WPF. For desktop apps I have used only VB.NET and C# in the early days of .NET.
Comment: What about Excel? Have you touched on that? Including VBA script, I find that much more complicated compared to like C#, Javascript, python
Comment: Excel is a special case. VBA for Excel is much simpler than the other languages you mention.
Comment: I probably say that - because I haven't had any projects using VBA..


Horário saindo com resultado inesperado

Question: Estou executando um código que printa as horas no terminal porém quando eu uso o código abaixo ele me trás um valor totalmente errado na hora:
Código:
from time import gmtime, strftime
print(strftime("%a, %d %b %Y %H:%M:%S +0000", gmtime()))

Segue o valor que ele retorna:
Comment: E como podemos saber o que está errado? Pra mim está certo. Por acaso isto dá o resultado que espera? `print(strftime("%a, %d %b %Y %H:%M:%S +0000", localtime()))`
Comment: Sim, assim foi sem nenhuma anomalia, por acaso saberia me dizer onde poderia estar o erro em meu código? Pois segui exatamente o código de sua documentação
Comment: A resposta resolveu sua dúvida? Acha que pode aceitá-la? Veja o [tour] se não souber como faz. Isso ajudaria muito indicar que a solução foi útil para você. Também pode votar em qualquer pergunta ou resposta que achar útil no site todo.
Answer: Você quer imprimir a hora local e a função correta para isto é a localtime(), e não a gmtime() que te dá a hora chamada universal (sem fuso horário).
from time import localtime, strftime
print(strftime("%a, %d %b %Y %H:%M:%S +0000", localtime()))

Veja funcionando no ideone. E no repl.it. Também coloquei no GitHub para referência futura.
Só tome cuidado porque em muitos casos o correto é trabalhar com hora universal e não local. Inclusive vemos várias perguntas aqui de pessoas com dificuldade por começarem usando errado em sistemas e depois não consegue arrumar mais.
Conceitualmente já há um erro nesse +0000 fixo que dá uma informação enganosa, e mesmo um +0300 só estará certo por coincidência em certas épocas do ano. Mas o assunto é absurdamente extenso para colocar aqui.

Horário saindo com resultado inesperado


Get page title form url

Question: How can I get the page title by its URL, for example http://example.com/en/news-events, which is not for the current page?
Comment: There is no easy solution, see https://drupal.stackexchange.com/questions/178790/get-title-from-route. You can see what you would need to do in the path based breadcrumb builder: https://api.drupal.org/api/drupal/core%21modules%21system%21src%21PathBasedBreadcrumbBuilder.php/function/PathBasedBreadcrumbBuilder%3A%3Abuild/8.3.x
Comment: Is that URL alias of views page OR node URL alias ?
Comment: @parth.k This is an URL alias to my view page.
Answer: From below code example you can get the page title as your requirement
<code> $path = \Drupal::service('path.alias_manager')->getPathByAlias('/news-events');
 if(preg_match('/node\/(\d+)/', $path, $matches)) {
  $node = \Drupal\node\Entity\Node::load($matches[1]);
 }
 echo $node->getTitle();
</code>
Hope this helps. :)
Comment: There is an extra ")" in your last line code. I used your code in my custom block hook and get the error: _Call to a member function getTitle() on null_
Comment: removed extra ")"
Comment: Yep. I removed extra ")" and still got same error.
Answer: Try this solution for get title from view page url.
in your custom module
==> .module file
<code>use Drupal\views\ViewExecutable;

function display_form_mode_views_post_render(ViewExecutable $view) {
   print($view->getTitle($title));
}
</code>
Hope this helps.
Comment: Your answer is too specific, since OP never mentioned whether it was on a Views page or not
Comment: Richard mentioned in his comment it was his view page URL
Comment: The question also says the URL is not for the current page, which means that any hook invoked for the current page is not invoked for the view associated to the given URL.

Get page title form url


How to generate a set of points that are equidistant from each other and lie on a normal distribution

Question: I am trying to generate n points on a normal distribution(say, mean \mu and standard deviation \sigma) that are equidistant(Let's say the distance between pints is d) from each other in C. Points at normal distribution are from (-3\sigma + \mu) to (3\sigma + \mu). I am trying to have beads on the Gaussian curve, where beads are at equal distance (curved length).
Thank you in advance for the answer.
Comment: What does it mean for points to be "on a normal distribution"? Are you intending to graph the function
$$
f(x) = \frac{1}{\sqrt{2 \pi}} e^{-\frac{1}{2}x^2}
$$
or something?
Comment: @MattiP. yes, I am trying to generate equidistant points on this function.
Comment: Bad news: In general, the length of a curve is not integrable in closed form, which means no luck doing this analytically.
Comment: What do you mean with "generate"? Just substitute the equidistant $x$ into the formula and you are done.
Comment: Do you mean Euclidian distance?
Comment: @Moti 'equidistant by arc length'
Comment: You can make this task substantially easier by drawing the points at constant intervals along the $x$-axis, instead of using the arc length. How would that sound to you? This way, the problem becomes basically trivial and visually, it would look only slightly different (at least if you have more than a few points).
Answer: Curve length of a function in $x$ can be found as
$$\ell_f(a, b) =\int_a^b \sqrt{1+\left(\frac{df(x)}{dx}\right)^2}dx$$
Which is nasty enough that in general we don't get an integrable result out of it; in our case we need to perform the integral and then invert it, and this is a recipe for sadness.
So what we'll do instead of this is do it numerically, replacing integration with the Riemann sum and differentiation with the difference quotient and doing a little simplifying.
$$\ell_f(a, b) = \lim_{\Delta x \rightarrow 0} \sum_{t=\frac{a}{\Delta x} + 1}^{\frac{b}{\Delta x}}\sqrt{\Delta x^2+\left(f(t\Delta x)-f((t-1)\Delta x)\right)^2}$$
Which still looks kinda mean but is possible to plug & chug by picking a reasonable value for $\Delta x$.
Of course, that only works forward, and we have to work backwards.  Our best bet, since this is a series, is to do linear interpolation: draw straight lines between the points that make up the series.  This gives a monotonic piecewise linear function, which is trivial to invert.
The procedure
We have our function $f(x)$, a low and high end of the interval in question $p$ and $q$, and a number of intervals to break the function into $n$.
Calculate $\Delta x = \frac{q-p}{n}$
For each integer $k$, $x_k = a + k\Delta x$, $y_k = f(x_k)$.
$d_k = \sqrt{(x_k - x_{k-1})^2 + (y_k - y_{k-1})^2} = \sqrt{\Delta x^2 + (y_k - y_{k-1})^2} $
$\ell_k = \sum_{i=1}^{k} d_k$
$m_k = \frac{\Delta x}{d_k}$
$b_k = x_k - \ell_k m_k$
And now we have a piecewise linear function: $x_f(\ell) = m_k \ell + b_k \text{ for } x_{k-1} \le \ell < x_k$
Now we wish to place $m$ spaces between points, so we take values $\frac{\ell_ni}{m}$ for $i$ in $0 \le i \le m$, find their $x$ values from the piecewise linear function above, and then from there the $f(x)$ values.
Example
Our star today is the standard normal distribution density function, $$f(x) = \frac{1}{\sqrt{2\pi}}e^{-\frac{x^2}{2}}$$
over the interval $-3 \le x \le 3$. I'll use $n = 6$ here for relative brevity and for relatively nice $x$ values.

$x$
$y$
$d$
$\ell$
$m$
$b$
formula
interval

$-3$
$0.004432$

$-2$
$0.053991$
$1.001227$
$1.001227$
$0.998774$
$-3.000000$
$0.998774\times \ell -3.000000$
$0.000000\le \ell < 1.001227$

$-1$
$0.241971$
$1.017515$
$2.018742$
$0.982787$
$-2.983993$
$0.982787\times \ell -2.983993$
$1.001227\le \ell < 2.018742$

$0$
$0.398942$
$1.012245$
$3.030987$
$0.987903$
$-2.994322$
$0.987903\times \ell -2.994322$
$2.018742\le \ell < 3.030987$

$1$
$0.241971$
$1.012245$
$4.043232$
$0.987903$
$-2.994322$
$0.987903\times \ell -2.994322$
$3.030987\le \ell < 4.043232$

$2$
$0.053991$
$1.017515$
$5.060747$
$0.982787$
$-2.973635$
$0.982787\times \ell -2.973635$
$4.043232\le \ell < 5.060747$

$3$
$0.004432$
$1.001227$
$6.061974$
$0.998774$
$-3.054544$
$0.998774\times \ell -3.054544$
$5.060747\le \ell < 6.061974$

at this point I want to point something out: the curve length of this function is only about 1% more than the width of our interval in $x$.  There isn't going to be much difference between evenly spaced on $x$ and evenly spaced along the curve!  In fact when we get our points, the largest difference between the two is about $0.008$.  Still, the point here is a reasonably general procedure, so let's continue.
Now that we've got our piecewise linear function, we'll just plug in evenly-spaced $\ell$ values.

$\ell$
$x$
$y$

$\ell$
$x$
$y$

$0.000000$
$-3.000000$
$0.004432$

$3.030987$
$0.000000$
$0.398942$

$0.303099$
$-2.697273$
$0.010498$

$3.334086$
$0.299432$
$0.381453$

$0.606197$
$-2.394546$
$0.022689$

$3.637185$
$0.598864$
$0.333452$

$0.909296$
$-2.091818$
$0.044744$

$3.940283$
$0.898296$
$0.266493$

$1.212395$
$-1.792467$
$0.080026$

$4.243382$
$1.196705$
$0.194954$

$1.515494$
$-1.494586$
$0.130572$

$4.546481$
$1.494586$
$0.130572$

$1.818592$
$-1.196705$
$0.194954$

$4.849579$
$1.792467$
$0.080026$

$2.121691$
$-0.898296$
$0.266493$

$5.152678$
$2.091818$
$0.044744$

$2.424790$
$-0.598864$
$0.333452$

$5.455777$
$2.394546$
$0.022689$

$2.727888$
$-0.299432$
$0.381453$

$5.758876$
$2.697273$
$0.010498$

$6.061974$
$3.000000$
$0.004432$

And we can plot these.
Comment: could you please tell how m_k is generated in the table since the m_k expression is \delta x * d_k does not match with the values given in the table. Also could you please inform me how to generalise it for general mean and variance. What changes I need to make there?
Comment: ah, typesetting error, I had the braces but not the \frac


How to implement navigation in a single page web application in flutter?

Question: I am creating a bit complex in terms of UI single page web application in flutter.
As a last piece I am struggling with implementing navigation, all examples foundable online are focused on multi-page usecases.
AppBar(
 Row(
   children: [
     Button("Gallery"),
     Button("Faq"),
    Button("Contact"), #after clicking this button
   ]
  ),
),
SingleChildScrollView(
  child: Column(
    children: [
      GallerySection(...),
      FaqSection(...),
      ContactSection(...), #scroll to this section/container
    ]
  ),
);

The idea is to implement navigation that after pressing one the appBar buttons user is being scrolled to requested section.
I do not care that much for the url formatting it can stay www.flutter-single-page.com/#but having back navigation would be outstanding :-), but optional.
Do you know a way how this can be accomplished?
Answer: You could use a scrollController to scroll to a widget with it's ensureVisible method.  Then you just assign a key to each section and call ensureVisible for navigation.
Check this answer as an example
Comment: I think it's not a dupicate since it's related to flutter web and web ui navigation patterns. So anyone who searchs for this pattern is more likely to find this question since they might not even know what a scrollController/ScrollView is
Comment: Thanks man, no idea how I missed it.

Since my question is more of a duplicate and does not bring lots of new content over the problem you linked.

Would you notify moderator or simply delete it?


How does 'diatonic' refer to 'heptatonic scale that includes 5 whole tones and 2 semitones'?

Question: I have not studied Ancient Greek, but the 'diatonic scale' seems misnamed because 'diatonic' seems an inaccurate adjective. Its etymology fails to distinguish between Half and Whole Tones; or refers to only (through the) whole tones, while neglecting any mention of the 2 half tones.
1. So did 'diatonic' shift semantically?

1 below differs from 2-4: am I correct about this discord? Which etymology is correct then?

[1.] diatonic (adj.)
  c. 1600, from French diatonique, from Latin diatonicus,
  from Greek diatonikos, from diatonos "extending; pertaining to the diatonic scale,"
  from dia- (see dia-) + teinein "to stretch," from PIE root *ten- "to stretch."
[2.] The word "diatonic" = "dia" (through) + "tonic" (tones), or literally "through the tones."
[3.] Diatonic scale: Greek for "through the tones", any scale that has exactly one pitch for each letter name in the musical alphabet
[4.] 8:28
   This major scale is also an example. What is called a Diatonic Scale. Dia between two tonics.
Comment: "Tone: (1) A musical or vocal sound with reference to its pitch, quality, and strength. ... (3) A basic interval in classical Western music..." (Ref: https://en.oxforddictionaries.com/definition/tone). It also has meaning (1) in other languages derived from Latin, e.g. French and Italian. "Through [all] the *notes*" would be just as good a translation of the Greek as "through the *intervals of a whole tone.*"
Comment: I don't know what you mean by stretching. "any scale that has exactly **one pitch for each letter name** in the musical alphabet". C D E F G A B is a diatonic scale. So is A B C D E F G. Notice they each have one pitch per letter and they include all seven letters. "Through all the tones" as in "through all the notes" as in "passing through all the notes" as in "passing through each note exactly one time". Dia doesn't **only** mean "stretch", it also means "through".
Comment: Doesn't the text after the 3 quoted above explain it? As in through all the note names?
Comment: @ToddWilcox So the stretching concerns ALL the 'tones'? Also, 2-4 also differ from 1.
Comment: Google's etymology is : early 17th century (denoting a tetrachord divided into two tones and a lower semitone, or ancient Greek music based on this): from French diatonique, or via late Latin from Greek diatonikos **'at intervals of a tone'**, from dia 'through' + tonos 'tone'. Is that possibly a better example of the 'clash with reality'?
Comment: The 'any scale that has exactly one pitch for each letter name in the musical alphabet' definition seems an incorrect definition too - because there are seven letter names, that effectively just means 'Any heptatonic scale' - which would be wrong.
Answer: Bear in mind the historical context. The chromatic scale wasn't invented until the 13th century.  To the Greeks, scales were composed of a series of notes above (and sometimes below) a centrism, with various intervals.  What's more, these intervals were neither exact half steps nor exact whole steps; the equally tempered scale didn't come until the 15th century (or later, depending who you wish to credit).  Instead, the gaps between notes were determined by physics, in particular the lengths of strings or pipes in the ratios of whole numbers.
Even up through the 1800's, there was no single standard scale, and musicians and composers could invent different types of scales for different purposes, e.g. Kirnberger tuning.  Even Bach's Well-Tempered Clavier may not have been intended for equal temperament-- the purpose of the preludes and fugues instead may have been meant to demonstrate the beauty of Bach's own tuning, where he tended to make thirds a bit sharp (citation) to allow for enharmonics in his compositions.
 This allowed him to compose pieces that modulated in ways far more complex than his peers.
So what is a diatonic scale?  Well, you can be derive one yourself very easily:

Pick a note, and cut a string to length so that it will produce that note
Take another string and cut it shorter than the first, in a ratio of exactly 2:3.  This will be a perfect fifth above.
Repeat step 2.  This will be two fifths above, or a ninth. Now, this will be  a bit high, so now double it in length so that it stays in the right octave.
Keep cutting strings a fifth above/an octave below, working your way around the circle of fifths, until you reach a note that is just a bit higher than your first note (and sounds really bad).
Stop right there.

If you follow this process, you end up with a scale that has seven notes. It happens to be in Lydian mode, but we can get the other modes through inversion, including the Ionian "major" mode/scale.  You don't even need to think about half steps or whole steps. For convenience, you can name these notes with letters A through G. Presto, a diatonic scale!
Now this will sound very different from the modern, equally-tempered scale, which doesn't use the 2:3 ratio at all. Instead, it uses a ratio computed as the 12th root of 2 (~1.0594)-- the only way to get twelve half steps that are exactly equal, or to get the modern whole step.  And the Greeks did not approach it that way at all.
So you see, if you look at the physics of music in use by the Greeks, the very notion of a half step or a whole step is non sequitur. It doesn't even fit into the equation.  A diatonic scale is just something that has seven notes in it, with whole number ratios that yield a pleasant sound.


Find all the numbers $n$ such that $\frac{6n-8}{2n-5}$ can't be reduced.

Question:
Find all the numbers $n$ such that $\frac{6n-8}{2n-5}$ can't be reduced.

Attempt:
It can't be reduced when $\gcd(6n-8,2n-5)=\color{red}1$
$$1 = \gcd(6n-8,2n-5)=\gcd(4n-3,2n-5)=\gcd(2n+2,2n-5)=\gcd(7,2n-5)$$
that's equale to one when $2n-5\not\equiv 0 \pmod 7$ i.e $n\not\equiv 6 \pmod 7$
Is my attempt correct?
Answer: Yes, that is correct. By the way you can get $1 = \gcd(6n - 8, 2n - 5) = \gcd(7, 2n - 5)$ directly by applying on step of the Euclidean algorithm.
Comment: OP did in fact apply the Euclidean algorithm, but in subtractive (vs. mod) form.
Comment: Yes, but I meant the version with Euclidean division. But thanks for stating that out!
Answer: Your attempt is completely correct. It might be fun to check what happens when $n \equiv 6 \pmod{7}.$ In this case you can write $n = 6 + 7k$ for some $k$. Then the fraction can be written as
$$
\frac{6(6+7k)-8}{2(6+7k)-5}=\frac{28+42k}{7+14k}=\frac{4+6k}{1+2k}.
$$
By the same argument as yours we find that $$\gcd(4+6k,1+2k)=\gcd(1,1+2k)=1$$
for all $k$. We already knew from your findings that this has to be the case of course.


Removing structure with a known functional form from the covariance matrix

Question: I have a set of timeseries data $X^B = \begin{bmatrix} {X^B_1},{X^B_2},\dots, X^B_n \end{bmatrix}$ consisting of observations recorded at different spatial locations.
There is crosstalk between the underlying signals $X$, which are also corrupted by additive Gaussian noise:
$$
X^B = M(X + \epsilon) ;\;  \epsilon \sim \mathcal{N}(0, \sigma)
$$
The mixing matrix $M$ has a known functional form:
$$
M = I + \alpha e^{-(D / \lambda)^2}
$$
where $D_{ij}$ is the Euclidean distance between locations $i$ and $j$, $\alpha$ is the amplitude of the crosstalk, and $\lambda$ is the length constant.
I'd like to estimate the values of the unknown parameters $\hat{\alpha}$ and $\hat{\lambda}$, construct $\hat{M}$, then use this to remove the correlations in $X^B$ arising due to the crosstalk.
I thought I might be able to use this identity:
$$
cov(MX) = Mcov(X)M^T \\
cov(X^B) = M(cov(X) + \sigma^2 I)M^T
$$
However, the structure of $cov(X)$ is unknown and non-trivial. One thing I can be certain of is that $cov(X)$ is not influenced by $D$.
Given $X^B$, $D$, and the known functional form of $M$, is it possible to estimate $\hat{\alpha}$, $\hat{\lambda}$ and $\hat{X}$?
Comment: Does $\sigma$ denotes the variance or the standard deviation? Also, is it known, or unknown?
Comment: Sorry. To clarify, $\sigma$ is the standard deviation, and it is also unknown
Comment: Do I understand correctly that the matrix $M$ is of the form (if say it was $2\times 2$)
Comment: $$M= \left[ \begin{matrix}
1 & 0\\
0 & 1\\
\end{matrix}\right] + \alpha\left[ \begin{matrix}
\exp{\{-D_{11}/\lambda\}} & \exp{\{-D_{12}/\lambda\}}\\
\exp{\{-D_{21}/\lambda\}} & \exp{\{-D_{22}/\lambda\}}\\
\end{matrix}\right]$$
Comment: That would be $exp[-(D_{ij}/\lambda)^{2})]$, but apart from that you're correct
Answer: The covariance matrix, $cov(X^B)$, has $\frac{n(n+1)}{2}$ unique elements.  That means you have $\frac{n(n+1)}{2}$ equations in your equation, if you see what I mean.  How many unknowns do you have?  Well, $cov(X^B)$ has $\frac{n(n+1)}{2}$ unknowns.  Then there are $\alpha$ and $\lambda$.  So, you have $\frac{n(n+1)}{2} + 2$ unknowns.  So, there is not a unique solution.
You can see the same thing another way.  Suppose you have measured $cov(X^B)$.  I tell you that I know that $cov(X^B)=cov(X)$ and that $\alpha=0$.  How could you disprove this?
Comment: OK, perhaps a unique solution is not possible, but what about the fact that $cov(X)$ is not influenced by distance? If you told me that $cov(X^{B}) = cov(X)$, couldn't I look for a relationship between the covariances for each pair of signals in $X^{B}$ and their distance $D_{ij}$, as described above. If I find such a relationship, I would say that it's very unlikely that $cov(X^{B}) = cov(X)$, since I expect the true $cov(X)$ to be flat w.r.t.$D$.
Comment: Yes, that  would work, but lots of other things would work also.  All you have to do is put enough structure on $cov(X)$ (that is, make enough assumptions about $cov(X)$) to reduce the number of free parameters in it by at least 2.  Maybe you could use a Bayesian approach in which you specify a prior which puts heavy weight on $cov(X)$ being flat in distance.


Android layout bug in 1.6 vs 2.2

Question: I have a strange "bug" in my layout file. I am new to Android, so perhaps I am missing something. I stripped the example down to the bare minimum to ease your understanding of the problem:
I have a simple list, with a ListAdapter, which should display a line of text with an icon next to it. The icon should be centered vertically if the text is higher then the icon.
If I leave the attribute "center" out, the sample works (the list item gets the correct heigth), but as soon as I include it, I get a bug.
Any ideas on how to solve this issue? (btw, I need the tableLayout for streching columns, not sure if there is another way for this)
The XML source for the row looks like this:
<code><TableLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:stretchColumns="1">
<TableRow>

    <TextView
            android:height="30dp"
            android:width="30dp"
            android:background="@color/blue"
            android:layout_gravity="center_vertical"
            />

    <TextView
            android:layout_height="wrap_content"
            android:text="TextView"
            android:textSize="22dp"
            android:layout_width="120dp"
            android:layout_gravity="left"
            android:background="@color/yellow"
            android:id="@+id/simple_list_row_text1"/>

</TableRow>
</code>

The desired result (which works on higher versions of android without any problems) is:

And the image on Android 1.6
Comment: is this a Xperia Mini/Pro running 1.6? (just asking, not specific to question)
Comment: Its a Xperia X8, and I just found a solution, see own answer to post :-)
Answer: Give the whole TableRow a center_vertical gravity. And of course move the fixed width/height from the TextView to the TableRow, and leave the TextView to wrap_height
Comment: No. the fixed height of the textview (the first one) is only to simulate, normally there is an image with fixed width and height. I will try the first one though.
Comment: No, does not work. I think its a bug, see also here:http://stackoverflow.com/questions/3436832/buttons-in-tablelayout-cropped-on-android-1-6-and-2-1-but-not-on-1-5-or-2-2
Comment: Now I remember that there was some annoying thing with the Tables, maybe it was  that (I very rarely use them so I am not sure). You can replace the table layout with a vertical linear that contains horizontal linears (for rows) - I always use this. And your code doesn't need the second linear, change it with the one from my answer (Table Row will become the single Linear). Of course do this if you want to have one less linear, not that there is something wrong with your code
Answer: Solution workaround is:
<code> <LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal" android:layout_width="fill_parent"
    android:layout_height="wrap_content">

<LinearLayout android:layout_width="wrap_content"
              android:layout_height="fill_parent"
              android:gravity="center">

    <TextView
            android:layout_height="30dp"
            android:layout_width="30dp"
            android:background="@color/blue"
            />
</LinearLayout>

<TextView
        android:layout_weight="1"
        android:layout_height="wrap_content"
        android:text="TextView"
        android:textSize="22dp"
        android:layout_width="120dp"
        android:layout_gravity="left"
        android:background="@color/yellow"
        android:id="@+id/simple_list_row_text1"/>
</code>

Android layout bug in 1.6 vs 2.2


Transaction rollback in innodb mysql/php with mysql_query not working

Question: I am trying to execute a bunch of statements inserting into multiple tables within a transaction, but when I call for a rollback, everything returns without error but the data is inserted!
//Returns "YES"
$supports = mysql_query( "SELECT SUPPORT FROM INFORMATION_SCHEMA.ENGINES WHERE ENGINE = 'InnoDB'" );

//Start transaction
mysql_query( "SET AUTOCOMMIT=0" );
mysql_query( "START TRANSACTION" );

//Do some inserts
mysql_query( "INSERT INTO ...." );
$lastId = mysql_query( "SELECT LAST_INSERT_ID() as lastId" );
mysql_query( "INSERT INTO...." );

//Try to rollback
mysql_query( "ROLLBACK" );
mysql_query( "SET AUTOCOMMIT=1" );

The tables are all created as InnoDB tables. Running SHOW CREATE TABLE <table_name> shows all tables are created as:
CREATE TABLE `mytable` (
    ...the columns...
) ENGINE=InnoDB AUTO_INCREMENT=61 DEFAULT CHARSET=latin1

What am I doing wrong?
Comment: Are the only commands within the transaction `INSERT` commands?
Comment: @eggyal One other command: `SELECT LAST_INSERT_ID() as lastId`
Comment: Are you able to use an interactive client to narrow down whether the problem lies with your command sequence or PHP?
Comment: @eggyal if you mean mysql from command line, yes. I will try executing those exact statements. Do you see anything wrong with them? Any special connection flags I should be setting?
Comment: No, nothing there appears to be wrong.  If I had to guess right now, I'd be leaning towards investigating whether the calls to `mysql_query()` are taking place in the same database session, but let's eliminate one thing at time...
Comment: @eggyal It appears rollback is working within the mysql command line interface. I set autocommit, started the transaction, inserted, read the insert id, inserted into the second table, called a rollback and neither table has the data.
Comment: let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/51770/discussion-between-eggyal-and-don-rhummy)
Answer: @eggyal led to the answer. My START TRANSACTION was inside a loop instead of outside it, so it was starting multiple transactions and only rolling back the last one.


My code returning incorrect values

Question: In my PHP code I run the following statement:
$stmt = $pdo->prepare("SELECT * FROM `tb_services` WHERE tb_services.user_id = :var1 AND
(tb_services.user_id = :var1 OR tb_services.user_id = (SELECT subuser_owner_id FROM tb_users WHERE user_id = :var1))
AND tc_services.sub_id = :var2");
$stmt->bindParam(":var1", $_GET['var1']);
$stmt->bindParam(":var2", $_GET['var2']);

However doing $stmt->rowCount() returns 0, but when I run this exact statement(filled with the same values that I'm inputting instead of the :var1, :var2) it finds the row perfectly.
while($info = $stmt->fetch(PDO::FETCH_ASSOC)) {
The above is the code that is not running. As the return of the rowCount() is 0 and the while loop is not running, that just shows to me that it is for some reason not finding the row. If I input static values into the SQL statement, it works perfectly.
Comment: Probably not a good question, but are using the `execute()` call before `rowCount()`?
Comment: can you print stmt and make sure the values are inputting properly
Comment: @themerlinproject I wanted to do that but I don't know how to print it out with the values replaced.
Comment: Yes. This is the if statement: if($stmt->execute()) {
    echo $stmt->rowCount();
Comment: I'll add more information to my orginal post to clarify a few things
Comment: if($stmt->execute()) {
    echo $stmt->rowCount();

     while($info = $stmt->fetch(PDO::FETCH_ASSOC)) {
Answer: I have found the error. I was overlooking my code and saw the stupid mistake I made. For anyone out there that might experience a similar problem, the following MySQL statement:
$stmt = $pdo->prepare("SELECT * FROM `tb_services` WHERE tb_services.user_id = :var1 AND
(tb_services.user_id = :var1 OR tb_services.user_id = (SELECT subuser_owner_id FROM     tb_users WHERE user_id = :var1))
AND tc_services.sub_id = :var2");

should be
$stmt = $pdo->prepare("SELECT * FROM `tb_services` WHERE(tb_services.user_id = :var1 OR     tb_services.user_id = (SELECT subuser_owner_id FROM     tb_users WHERE user_id = :var1))
AND tc_services.sub_id = :var2");

Removing the first tb_services.user_id = :var1 as that caused the error.

My code returning incorrect values


Surds question grade 10

Question: I am a student and need help answering this question. I need a step by step solution.
Simplify:
$ \sqrt {18}$ - $ \sqrt {9}$
What I tried:
($ \sqrt {9}$ × $ \sqrt {2}$) - 9
= (3$ \sqrt {2}$ ) - 9
I don't know what to do next.
Thank you and help is appreciated.
Comment: You have to simplify
Comment: Why did you cancel the $\sqrt\ $ in the first passage?
Answer: this is $$\sqrt{2\cdot 9}-\sqrt{9}=3\sqrt{2}-3$$
Comment: $=3(\sqrt{2}-1)$, sorry OCD
Answer: Here is a mistake you've made:
Going from the first step to the second step, you should have put the square root: $$\sqrt{18}-\sqrt{9} \implies (\sqrt{9}\times \sqrt{2})-\color{red}{\sqrt{9}}$$
Can you take it from here?
Comment: Thank you for helping me answer this question

Surds question grade 10


Theme rendering

Question: I have a question.
I am using commerce kickstart and i want to display field group under the pictures and text.
Now in node--product--type.tpl.php are the attributes for rendering.
The code I am using is the following.

    <div<?php print $content_attributes; ?>>
      <?php
        // We hide the comments and links now so that we can render them later.
        hide($content['comments']);
        hide($content['links']);
        print render($content);
      ?>

   <div<?php print $content_attributes; ?>>
      <?php
        // We hide the comments and links now so that we can render them later.
       print render($content['comments']);
      ?>

How can I put field group (I have created 3 tabs) in
?
I don't know how to find print render($content['???']); where ???? stands for the attribute.
Answer: You can group fields using field group module.

These are the steps on how to use field group module.

Download the module at https://drupal.org/project/field_group
Enable the module
Go to the manage display settings, where you want to add your field group
At the bottom of the page you will see add new group fill up the field and label of the field group; after that you can now drag and drop the field inside the field group that you created
Comment: @Chevap please do not [chameleon](http://meta.stackexchange.com/q/43478/225745). Are you 100% sure your edit only clarifies and does not change the question's meaning?
Comment: @ Mołot The problem is i didn't know how to ask the question in the first place. But in my poste above ---EDIT---- i said My question is how can i put group field (i have created 3 tabs) in  . So i didn't ask using what module can i display grouped fields because i told that i have group fields (i have created 3 tabs). I belive that implies that i have group field module and have created 3 tabs with that have xzy number of fields attached to them. My question is the rendering . How can i put group field in .
Comment: I am sorry if i wasn't clear bu i never said i needed a module for grouping fields , etc. And please don't call me a chameleon :) ... I have writen a lot of my modules but never used them like this so i have no experiances with theming and rendering. I have tried to hide other content attributes but that does not do nothing. I used
  hide($content['sku']);   . I can show only SKU using print render($content['SKU']);. So how can i show only group field.
Answer: Ok,
In the 'node--product--type.tpl.php' file.
I got it working by the principle of hide in the first container and render where you want it.
For me (using commerce kickstart 2)it looks like this:

 <?php
print render($content['title_field']);

print render($content['product:field_images']); ?>

 <div<?php print $content_attributes; ?>>
      <?php
    // We hide the comments and links now so that we can render them later.

hide ($content['group_koffie']);

hide($content['comments']);
        hide($content['links']);
        print render($content);
      ?>

    <?php
print render($content['group_koffie']);

print render($content['comments']);

    ?>

An extra thing to be aware of is that (again in my case) you have to name the field ($content['group_koffie']) when it is a display-field.
(or ($content['field_regio']) if it is not a group but a single field)
When it is a product-item/ variation-field you name the field ($content['product:field_images'])
Took me a long stare to find that.

Theme rendering