Exercising divergent summations: $\lim 1-2+4-6+9-12+16-20+\ldots-\ldots$

Question: I'm trying to make sense of some (assumed to be) simple exercises in divergent summation. One example I cannot resolve.
First I assume the sequence of binomialcoefficients $ \{ b_k = \binom k2 \}_{k=2\to\infty}=\{1,3,6,10,15,...\}$
Then to assign a meaningful value to the alternating sum $ S= 1-3+6+10.... $ I compute the Abel-sum
$ \qquad S = \lim_{x \to 1} 1-3x+6x^2-10x^3+...-... = {1 \over (1+x)^3 } = 1/8 $ (Abel)
But I want to proceed one more step. The sequence of partial sums may be denoted as
$ \{ c_k \}_{k=0\to\infty}=\{1,-2,4,-6,9,-12,16,-20,...\} $
Q - my question is: what is the sum $ T = 1-2+4-6+9... $ ?

I tried two approaches, but I'm lost.
The generating function is simply $ 1/(1+x)^3/(1-x) $ but here I cannot let x approach 1, so the simple application of the Abel-sum is impossible. Also the Euler-sum seems to not to converge; instead I get increasing partial sums like k/16 for the k'th partial sum .
On the other hand, I observe, that the coefficients are near the squares, so if I consider the alternating $\zeta$ (usually called Dirichlet-$\eta$)
$ \qquad \qquad \begin{eqnarray} X &=& 1 - 2.25 + 4 - 6.25 + 9 - 12.25 + ...  \\ &=&( 4 - 9 + 16 - 25 + ... - ...)/4 \\ &=& (1-\eta(-2))/4 \\ &=& (1-0)/4 = {1 \over 4} \end{eqnarray}$
then in T I had just each second coefficient $1/4$ above that of the $\eta$-series in X and possibly could go along something like
$ \qquad \qquad \begin{eqnarray} T &=& 1 - (2.25-0.25) + 4 - (6.25-0.25) + ... - ... \\
&=& X + 0.25*\zeta(0) \\
&=& X-1/8 = {1 \over 8} \end{eqnarray}$
But surely this is only an outline how I could come nearer to a solution. How could I actually proceed here?
[update]: One more idea was to make use of reordering summation. The coefficients $c_k$ can be seen as rowsums of the following matrix:
$\qquad \small
\begin{array} {rrrrr}
 1 & . & . & . & . & . &\ldots\\
 -3 & 1 & . & . & . & . \\
 6 & -3 & 1 & . & . & . \\
 -10 & 6 & -3 & 1 & . & . \\
 15 & -10 & 6 & -3 & 1 & . \\
 -21 & 15 & -10 & 6 & -3 & 1 & \ldots \\
 ... & ... \\
 \end{array}
$
so that all columns evaluate to $1/8$ due to the Abel-summation. If I add all that columnsums, I should have to write $\zeta(0)*1/8 $ and evaluate $T=-1/16$ (Q&D) now. But this is all fumbling, because I not even reflect the infinite application of downshifting by rows when evaluating the columns...
[update2]: Hmm. I played with the reciprocals of the series. I just did the "paper&pen" divisions and got:
$ \small \qquad \qquad 1 \qquad : 1-3x+6x^2-10x^3+15x^4-21x^5+...-...=1+3x+3x^2+1x^3=(1+x)^3=|_{x=1}8 $
and
$ \small \qquad \qquad 1 \qquad : 1-2x+4x^2-6x^3+9x^4-12x^5+...-...=1+2x-2x^3-1x^4=(1+x)^3(1-x)=|_{x=1}0 $
So this is also immediately what Lubos pointed out. Good for my intuition, I hope this model is not too much misleading in other obvious cases....
Comment: Re-Ordering the matrix is only allowed if you keep the same shape of both the summation, which isn't the case here, because you screw up limits, as the lenght of the summation on both sides of the matrix is not defined.  Take note that regularized value squared of a sum isn't equal to the sum squared. For an example see https://math.stackexchange.com/questions/1470036/i-think-i-found-a-flaw-in-riemann-zeta-function-regularization/1477245#1477245
Comment: An simple example would be $(\sum_{n=1}^{\inf} 1)^2 != \zeta(0)^2=(-1/2)^2$ which is wrong. Reordering diagonally would give $\sum_{n=1}^{\inf} \sum_{c=1}^{n} 1)=\sum_{n=1}^{\inf} n)=-1/12$ Also wrong, and correct would reordering squared (if you square things keep things squared). $\sum_{n=1}^{\inf} 2n-1)=2*\zeta(-1)-\zeta(0)=1/3$
Answer: Dear Gottfried, as you correctly observe, the sum is the Taylor expansion of
$$ \frac{1}{(1+x)^3 (1-x)} $$
for $x=1$. This function has a pole at $x=1$, so the result is a genuine divergence, the standard number "infinity" (without a specification of the phase) that is inverse to zero. The fact that some seemingly divergent sums have finite values doesn't mean that all of them have finite values.
Your second method is illegitimate because it clumps the neighboring values of $n$ - the exponents in the powers of $x$ - which means that the justification isn't robust under any infinitesimal deformations of the parameters. Note that it wasn't really legitimate that you wrote $1+1+1+\dots = \zeta(0)$. In fact, $\zeta(0)-n$ for any integer $n$ - and in fact, not only integer - would be equally (un)justified. In fact, none of them gives the right result.
It's a misconception that $1+1+1+\dots = -1/2$ "always" holds. It's only true if the terms $1$ are associated with values of $n$ that go over positive integers. But if they go over non-negative integers, the result would be $+1/2$, and so on.
Comment: Dear Lubos, thank you for the kind answer. Yes, I'm also trying to get a grip of how to keep such sum-notation "in a context" either as limit of a power- or of a dirichlet-series, letting the indeterminate x or s approach 1. Here I understand, that the introduction of the x or s-parameter serves also as an index for an unique context for each coefficient (for instance also to prevent arbitrary reordering of conditionally convergent series). I'll have to "meditate" on your answer a bit today...:-)
Comment: Dear Gottfried, thanks for your interest in these matters. I would still warn you that it may be ill-advised to attribute a finite answer to any series with individual numbers. Those things may sense if there's some glimpse of a functional dependence of the terms, and even in that case one should avoid the ad hoc random clustering of the terms - this is how the convergent sums may be calculated, but that's exactly how the divergent things can't be treated. A simple example: $1-1+1-1+1-1...$ is equal to $1/2$ in any sensible definition.
Comment: But if you combine the neighbors into pairs, you may get 0+0+0... = 0, or if you single out the first 1, you get 1-0-0-0=1... The right result $1/2$ is actually the arithmetic average of these guesses, but things are usually not that simple in general.
Comment: Dear Lubos - may I ask you to give my new answer a look and to comment about the applicability of the general ansatz?
Answer: I have an answer, applying a principle of which I do not yet know how far this is applicable in general or whether at all. It assumes, that as far as a given series can be expressed as linear combination of (unshifted) formal zeta- and (Dirichlet)-eta series then the evaluation of the series can be taken by evaluation of the same combination of zeta and eta-values, even if divergent (possibly with the exception of the zeta at 1).
So this would give the following regularized result:
Denote the original series by $T$, then let
$$ f(s) = {1\over 1^s }-{2\over 2^s}+{4\over 3^s}-{6\over 4^s}+{9\over 5^s}- \cdots + \cdots \tag 1$$ of course attempting to justify $ T = \lim_{s \to 0} f(s)$.
This is convergent for $s \gt 3$ . For this cases we can decompose
$$ \begin{array}{rcrll} 8 f(s) &=& & {8\over 1^s }-{16\over 2^s}+{32\over 3^s}-{48\over 4^s}+{72\over 5^s}- \cdots + \cdots \\
&=& 1(&{1\over 1^s }+{1\over 2^s}+{1\over 3^s}+{1\over 4^s}+{1\over 5^s}+ \cdots + \cdots &)\\
& & + 1(&{1\over 1^s }-{1\over 2^s}+{1\over 3^s}-{1\over 4^s}+{1\over 5^s}- \cdots + \cdots&) \\
& & + 4(&{1\over 1^s }-{2\over 2^s}+{3\over 3^s}-{4\over 4^s}+{5\over 5^s}- \cdots + \cdots & ) \\
& & + 2(&{1\over 1^s }-{4\over 2^s}+{9\over 3^s}-{16\over 4^s}+{25\over 5^s}- \cdots + \cdots & ) \\
&\underset{s \gt 3}=& &1 \zeta(s)+1\eta(s)+4\eta(s-1)+2\eta(s-2)
\end{array}  \\ \phantom{dummy } \\
f(s) \underset{s \gt 3} = {\zeta(s)+\eta(s)\over 8} + {\eta(s-1)\over 2} + {\eta(s-2)\over 4} \qquad \qquad \qquad \tag 2
$$
and from this, assuming it is regularizable for setting $s=0$
$$ T = f(0) \underset{\mathcal Z}{=} {\zeta(0)+\eta(0)\over 8} + {\eta(-1)\over 2} + {\eta(-2)\over 4} = 0 + {1\over4}\cdot{1\over 2} + 0 = {1\over 8}
\tag 3$$
$\qquad \qquad $ where "$\mathcal Z$" means zeta-regularization
This is surely a nice consideration and general scheme, however I don't know from which general theorems for divergent series I can extract this as an explicite recipe (and for what, possibly limited, cases).
Comment: Dear Gottfried, it's the most convincing proof of the finite value yet. But I still believe that the fact that the arguments are shifted from $s$ to $s-1$ and $s-2$ and you are combining several of them,even though the original sum had a uniform argument $s$, if you get my point, is illegitimate in the zeta regularization. There may be a set of rules in which your would be an allowed value - but maybe those rules would be allow *any* value. I sort of feel why your calculation would produce physically wrong results in physics.
Answer: Let me try to give one more method for the computation of this divergent series, which resorts to $\zeta$-function regularization only in the very last step.
First, let us recall that the finite sums
$$
\mathcal T_p(N) \equiv \sum_{m=1}^N (-1)^{m-1} m^p = 1-2^p+3^p+\ldots \pm N^p
$$
can be computed as the derivatives at the origin of the generating function
$$
G_N(z) =\sum_{p=0}^\infty \mathcal T_p(N) \frac{z^p}{p!}=\sum_{m=1}^N(-1)^{m-1}\sum_{p=0}^\infty \frac{(mz)^p}{p!}=
\sum_{m=1}^N(-1)^{m-1}e^{mz}=\frac{1+(-1)^{N+1} e^{Nz}}{1+e^{-z}},
$$
In particular
$$\begin{aligned}
\mathcal T_1(N)=&\ 1-2+3-4+\ldots\pm N=\frac{(-1)^{N+1}(2N+1)-1}{4}, \\
\mathcal T_2(N)=&\ 1-4+9-16+\ldots\pm N^2=\frac{(-1)^{N+1}}{2}N(N+1).
\end{aligned}$$
Furthermore, the formal limit $N\to\infty$ gives the Euler sum of the corresponding divergent series:
$$
s_p=\sum_{n=1}^\infty (-1)^{m-1}m^p=1-2^p+3^p+\ldots
$$
are obtanied from the generating function
$$
G(z)=\sum_{p=0}^\infty s_p \frac{z^p}{p!}=\frac{1}{1+e^{-z}},
$$
which gives
$$\begin{aligned}
s_0=&\ 1-1+1-1+\ldots=\frac{1}{2}\ ,\\
s_1=&\ 1-2+3-4+\ldots=\frac{1}{4}\ ,\\
s_2=&\ 1-4+9-16+\ldots=0.
\end{aligned}
$$
After these preparations we get,
$$
S=\sum_{n=2}^\infty (-1)^n\frac{n(n-1)}{2}=\frac{1}{2}(s_1-s_2)=\frac{1}{8},
$$
and
$$
T=\sum_{n=2}^\infty \sum_{l=2}^n (-1)^l \frac{l(l-1)}{2}=\frac{1}{2}\sum_{n=1}^\infty\left( \mathcal T_1(n)-\mathcal T_2(n)\right)=\frac{1}{8}\sum_{n=1}^\infty((-1)^{n-1}-1)=\frac{1}{8}.
$$
In the last step we have used both that $s_0=1/2$ and $\zeta(0)=-1/2$.
Comment: This is perhaps ironic, or perhaps sweet... I did a regression-procedure taking the sequence of T-coefficients as Y-variable, and assuming we need a decomposition by zeta- and (Dirichlet-) eta-series (because it is not Abel summable with occurence of a term $\lim _{t\to1} 1/(1-t)$)  I took as vector of X-variables the sequences according to $\zeta(0),\zeta(-1),\zeta(-2),\zeta(-3),\eta(0),\eta(-1),\eta(-2),\eta(-3) $. The regression gave immediately the perfect decomposition as  $T= (\zeta(0)+\eta(0)+4\eta(-1)+2\eta(-2))/8 = 1/8 $ This must have been be too simple ...
Comment: Very nice, thank you! I'll go later through this lucid explanation!
Comment: Upps, just noticed I had that solution in principle in my older answer, but without that argument of Abel-nonsummability leading to the requirement of using zeta-regularisation and the nice quickshot of simply using multiple regression ...
Answer: The elementary Ramanujan sum of $1-2+4-6+9-\cdots$ is 1/4 and the series belongs to the class $R=2$.
In general, for $f(x)=b(x)/(1-x)$ and $b(x)$ Abel summable, the sum of $f(1)$
is $-b'(1) + b(1)/2$, with $b'(x)=xdb(x)/dx$.
Edit 1. Verification.
$$
\frac{1}{(1+x)^3(1-x)}=\frac{x}{8(1-x)}+\frac{8+7x+4x^2+x^3}{8(1+x)^3}~.
$$
The first term on the right-hand side corresponds to
$$
\frac{1}{8}(1+1+1+\cdots)=-\frac{1}{16}
$$
and the second term is Abel summable to $5/16$ (the value at $x=1$).
Linearity implies that the sum is $-1/16 + 5/16 = 1/4$.
Edit 2. The shifted series $0+1-2+4-\cdots=1/8$.
The shifted series corresponds to $x$ times the previous series, thus
$$
\frac{x}{(1+x)^3(1-x)}=\frac{x}{8(1-x)}-\frac{x}{8}+\frac{8x+7x^2+4x^3+x^4}{8(1+x)^3}~.
$$
As before, linearity implies that the sum is $-1/16-1/8+5/16=1/8$.


Eclipse: Could not open the editor: No editor descriptor for id org.eclipse.jdt.ui.CompilationUnitEditor

Question: When I updated Eclipse using "Help -> Check for Updates" I got a problem.
If I try to start Eclipse, Eclipse opens but show a error message like this:
  Could not open the editor: No editor descriptor
  for id org.eclipse.jdt.ui.CompilationUnitEditor

And inside "Details" of the error, I have the following description:
    org.eclipse.ui.PartInitException: No editor descriptor for id org.eclipse.jdt.ui.CompilationUnitEditor
    at org.eclipse.ui.internal.EditorReference.createPartHelper(EditorReference.java:601)
    at org.eclipse.ui.internal.EditorReference.createPart(EditorReference.java:465)
    at org.eclipse.ui.internal.WorkbenchPartReference.getPart(WorkbenchPartReference.java:595)
    at org.eclipse.ui.internal.PartPane.setVisible(PartPane.java:313)
    at org.eclipse.ui.internal.presentations.PresentablePart.setVisible(PresentablePart.java:180)
    at org.eclipse.ui.internal.presentations.util.PresentablePartFolder.select(PresentablePartFolder.java:270)
    at org.eclipse.ui.internal.presentations.util.LeftToRightTabOrder.select(LeftToRightTabOrder.java:65)
    at org.eclipse.ui.internal.presentations.util.TabbedStackPresentation.selectPart(TabbedStackPresentation.java:473)
    at org.eclipse.ui.internal.PartStack.refreshPresentationSelection(PartStack.java:1245)
    at org.eclipse.ui.internal.PartStack.handleDeferredEvents(PartStack.java:1213)
    at org.eclipse.ui.internal.LayoutPart.deferUpdates(LayoutPart.java:400)
    at org.eclipse.ui.internal.PartSashContainer.handleDeferredEvents(PartSashContainer.java:1409)
    at org.eclipse.ui.internal.LayoutPart.deferUpdates(LayoutPart.java:400)
    at org.eclipse.ui.internal.WorkbenchPage.handleDeferredEvents(WorkbenchPage.java:1495)
    at org.eclipse.ui.internal.WorkbenchPage.deferUpdates(WorkbenchPage.java:1485)
    at org.eclipse.ui.internal.WorkbenchPage.closeEditors(WorkbenchPage.java:1459)
    at org.eclipse.ui.internal.WorkbenchPage.closeEditor(WorkbenchPage.java:1514)
    at org.eclipse.ui.internal.EditorPane.doHide(EditorPane.java:61)
    at org.eclipse.ui.internal.PartStack.close(PartStack.java:537)
    at org.eclipse.ui.internal.EditorStack.close(EditorStack.java:206)
    at org.eclipse.ui.internal.PartStack$1.close(PartStack.java:120)
    at org.eclipse.ui.internal.presentations.util.TabbedStackPresentation$1.handleEvent(TabbedStackPresentation.java:83)
    at org.eclipse.ui.internal.presentations.util.AbstractTabFolder.fireEvent(AbstractTabFolder.java:269)
    at org.eclipse.ui.internal.presentations.util.AbstractTabFolder.fireEvent(AbstractTabFolder.java:278)
    at org.eclipse.ui.internal.presentations.defaultpresentation.DefaultTabFolder.access$1(DefaultTabFolder.java:1)
    at org.eclipse.ui.internal.presentations.defaultpresentation.DefaultTabFolder$1.closeButtonPressed(DefaultTabFolder.java:71)
    at org.eclipse.ui.internal.presentations.PaneFolder.notifyCloseListeners(PaneFolder.java:631)
    at org.eclipse.ui.internal.presentations.PaneFolder$3.close(PaneFolder.java:206)
    at org.eclipse.swt.custom.CTabFolder.onMouse(CTabFolder.java:1598)
    at org.eclipse.swt.custom.CTabFolder$1.handleEvent(CTabFolder.java:261)
    at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:84)
    at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:1258)
    at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java:3588)
    at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:3209)
    at org.eclipse.ui.internal.Workbench.runEventLoop(Workbench.java:2696)
    at org.eclipse.ui.internal.Workbench.runUI(Workbench.java:2660)
    at org.eclipse.ui.internal.Workbench.access$4(Workbench.java:2494)
    at org.eclipse.ui.internal.Workbench$7.run(Workbench.java:674)
    at org.eclipse.core.databinding.observable.Realm.runWithDefault(Realm.java:332)
    at org.eclipse.ui.internal.Workbench.createAndRunWorkbench(Workbench.java:667)
    at org.eclipse.ui.PlatformUI.createAndRunWorkbench(PlatformUI.java:149)
    at org.eclipse.ui.internal.ide.application.IDEApplication.start(IDEApplication.java:123)
    at org.eclipse.equinox.internal.app.EclipseAppHandle.run(EclipseAppHandle.java:196)
    at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.runApplication(EclipseAppLauncher.java:110)
    at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.start(EclipseAppLauncher.java:79)
    at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:344)
    at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:179)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:601)
    at org.eclipse.equinox.launcher.Main.invokeFramework(Main.java:622)
    at org.eclipse.equinox.launcher.Main.basicRun(Main.java:577)
    at org.eclipse.equinox.launcher.Main.run(Main.java:1410)
    at org.eclipse.equinox.launcher.Main.main(Main.java:1386)

What can I do to solve this problem? I don't do anything, I just update Eclipse from their own "Check for Updates".
Answer: As you can see here, a workaround for your problem is just move the "~/.eclipse" to another folder.
So:

Close Eclipse
Open "Terminal"
Type the following command:

e.g.:
mv ~/.eclipse somewhereYouWant

When I got this problem, I just:
mv ~/.eclipse home/paladini/Downloads

Comment: in windows ?
what to do
Answer: Had a similar error when I removed Eclipse Typescript plugin
Tried to open typescript(*.ts) files and got this error:
No editor descriptor for id com.palantir.typescript.text.typeScriptEditor

And I was not allowed to move the workspace.
On Eclipse Oxygen, Window -> Perspective -> Close All  worked for me.
Answer: To resolve this issue, reset the editor to the default configuration:
in eclipse (or STS....) menu bar got to :
Windows > Preferences > Editors >: Restore Defaults ; Apply and Close

Cordially,
Answer: In Windows.

Open Eclipse folder
Copy all the files and folder in it
Paste it to other location
Start the Eclipse from the new location
Change the workspace location
start.
Answer: The other solutions here didn't work for me.
Perhaps my problem was as the result of trying to get eclipse setup the first time and re-installed different versions of it: a c++ version and then a plain base version + separately installed add-ons.  (Since I also want to use it for other languages I was confused how to set it up.)
Solution: I closed eclipse, then renamed: ~/eclipse, ~/workbench and ~/.eclipse;  (in other words, remove them), and finally reinstalled, and restarted.
cd ~
mv .eclipse           .eclipse~            #renames
mv  eclipse            eclipse~
mv  eclipse-workspace  eclipse-workspace~

~/nobak/Installers/eclipse/eclipse-installer/eclipse-inst    #reinstall

eclipse/cpp-2018-09/eclipse/eclipse   #restart

My box:
OS: GNU/Linux Debian 9.5 (x86-64);
Cinnamon desktop: 3.2.7;
Linux Kernel: 4.9.0-8-amd64;
Processor: Intel Core 2 Duo P8800;
Graphics Card: AMD/ATI RV710/M92 Mobility Radeon HD 4530/4570/545v


Divide a rectangle $a \times b$ in half and solve for the ratio $x=\frac{b}{a}$ given the ratio remains the same.

Question: I'm doing some Calculus. The instructor gave this example:
$$x = \frac{b}{a} = \frac{a}{b/2} = \frac{2a}{b} = \frac{2}{b/a} = \frac{2}{x}$$
I have this problem right here:
$$x = \frac{2a}{b} = \frac{b}{a/2}$$
and another problem just like it:
$$x = \frac{a}{b} = \frac{b}{a/3}$$
I'm taking an introduction to Calculus on Coursera and although I think it's a great resource they kind of go through topics very quickly and don't explain much. So I am very confused as to how to solve this equation.
Any help would be much appreciated. Thanks.
EDIT: I think this image will help more.

I can't embed images yet.
Comment: will you please define $x$ ? what does it represent?
Comment: I think it is of the essence that when you cut the rectangle in half, we demand that the ratio stays the same between the width and height. so $x= \frac{b}{a}$ AND also, $x= \frac{a}{b/2}=\frac{2a}{b}$ then multiplication of these two equalities gives:
$$ x \cdot x = \frac{b}{a}  \cdot \frac{2a}{b}=2 \implies x^2 =2$$
we probably want a positive ratio so $x = \sqrt{2}$
Answer: An example of your setting is the A series of ISO paper format.
For instance, if you take a sheet of A$4$ paper and fold it along the line cutting it in halves along the line connecting the middle points of the longer sides, you end up with two sheets of A$5$ paper.
The property is that the ratio "long side/short side" remains constant under the operation of halving the sheet in the way described above.
Thus, if $x$ is this ratio and $a$ and $b$ are the lengths of the sides, with $a<b$, when you halve the sheet, the sides become $a$ and $b/2$ (with $b/2<a$).
The required property is that the ratio remains invariant: then
$$
x=\frac{b}{a}\qquad x=\frac{a}{b/2}
$$
Now
$$
\frac{a}{b/2}=\frac{2a}{b}=\frac{2}{b/a}=\frac{2}{x}
$$
Hence
$$
x=\frac{2}{x}
$$
and therefore $x^2=2$, so $x=\sqrt{2}$.
Indeed the A series is exactly defined this way. An A$0$ sheet has the sides $a$ and $b$ so that $b/a=\sqrt{2}$ and the area is $1\,\mathrm{m}^2$. Therefore $ab=1\,\mathrm{m}^2$ and, since $b=a\sqrt{2}$, we get that
$$
a=\frac{1}{\sqrt[4]{2}}\,\mathrm{m}\approx 841\,\mathrm{mm}
\qquad
b=\sqrt[4]{2}\,\mathrm{m}\approx 1189\,\mathrm{mm}
$$
The physical lengths are rounded at the millimeter.
Dividing each time by $2$ and switching the sides:
\begin{align}
\text{A}0&& a&=841\,\mathrm{mm} & b&=1189\,\mathrm{mm}\\
\text{A}1&& a&=594\,\mathrm{mm} & b&=841\,\mathrm{mm}\\
\text{A}2&& a&=420\,\mathrm{mm} & b&=594\,\mathrm{mm}\\
\text{A}3&& a&=297\,\mathrm{mm} & b&=420\,\mathrm{mm}\\
\text{A}4&& a&=210\,\mathrm{mm} & b&=297\,\mathrm{mm}\\
\text{A}5&& a&=148\,\mathrm{mm} & b&=210\,\mathrm{mm}
\end{align}
which agrees with ISO 216 on Wikipedia
Comment: nice explanation and example
Answer: I'm guessing about the meaning of this: are you supposed to rewrite the third term so that the second term (and hence $x$) reappears?
$$
x = \frac{2a}{b} = \frac{b}{\frac{a}{2}} = \frac{2}{\frac{a}{b}} = \frac{4}{\frac{2a}{b}}=\frac{4}{x}
$$
Comment: I've included a link to an image I think will help explain it better.
Answer: This is how the $A_0,A_1,A_2,\cdots$ sheet formats are defined.
Let the ratio of the long size over the short one be $$x=\dfrac ba.$$ Then the half sheet has the same ratio and
$$x=\dfrac a{\frac b2}=\frac{2a}b.$$
Mutiplying the two equations, we obtain
$$x^2=2,$$ i.e. $$x=\sqrt 2.$$

Knowing that the $A_0$ is $1\,m^2$,
$$1=ab=\frac{b^2}x$$ and
$$b^2=\sqrt2,$$ $$b=\sqrt[4]2\,m,\\a=\frac1{\sqrt[4]2}\,m.$$
Comment: great answer Yves


Identify the misprint in a sequence

Question: Given the sequence, 1,3,11,31,69,113,223,351,521,739.
Identify the misprint.
I tried reasoning out but couldn't. Do I have to do some numerical analysis like forward differences? Have no clue. Kindly help.
Comment: The sequence BTW is $b_n = n^3 + n + 1$.
Answer: If you take the forward differences, you get
$$2,8,20,38,44,110,128,170,218\;.$$
And if you take the second differences, you get
$$6,12,18,6,66,18,42,48\;.$$
It would be nice if we could replace $6,66,18$ by $24,30,36$, as the sequence would then be arithmetic. That would require changing $44$ to $62$ and $110$ to $92$, which in turn would accomplished if we changed $113$ to $131$.
Comment: Thank you. I tried using the same method to the sequence,25,21,18,18,27,45,76,123 and got the third order difference as 2,6,0,4,3. How do I identify which terms has to be replaced?
Comment: @user46697: You're welcome. I'd have to stare at that new sequence for a bit; it's not immediately evident to me just what's going on there.
Answer: $1, 3, 11, 31, 69, 131, 223, 351, 521, 739, \ldots$ is OEIS sequence A071568.  I found it by doing a search for 521,739.
EDIT:  In general, suppose you have a finite sequence $a_0, \ldots, a_n$
and you suspect that there is a polynomial $f(x)$ of degree $< n$ such that $f(j) = a_j$ for all but one of $j = 0, \ldots, n$.  The polynomial
interpolating $f(j) = a_j$ for $j \in S$ is
$$ P_S(x) = \sum_{j \in S} a_j \prod_{i \in S \backslash \{j\}} \dfrac{x - i}{j-i}$$
The coefficient of $x^{|S|-1}$ in this polynomial is $$c_S = \sum_{j \in S} \dfrac{a_j}{\prod_{i \in S \backslash \{j\}} (j-i) }$$
which you want to be $0$.
In your example $[a_0, \ldots, a_{9}] = [1,3,11,31,69,113,223,351,521,739]$,
the coefficient $c_{\{0\ldots,9\} \backslash j} = 0$ only for $j = 5$, and we have $P_{\{0,1,2,3,4,6,7,8,9\}}(x) = x^3 + x + 1$.
In the other example you mentioned to Brian Scott, $[a_0, \ldots, a_7] = [25,21,18,18,27,45,76,123]$, $c_{\{0,\ldots,7\}} = 0$ only for $j = 3$,
and $P_{\{0,1,2,4,5,6,7\}}(x) = x^3/2 - x^2 - 7 x/2 + 25$.  This matches the data except for $P(3) = 19$ instead of $18$.
Answer: take 3 orders of backward differences to get 1,2,3,1,11,3,7,8 and note that if you change 113 to 131 the differences become 1,2,3...8
Answer: Technically speaking a sequence can be anything.  The assumption is that there is some simple rule.  But if we don't know the rule we have to guess.
As a rule of thumb I start by looking at the differences to see if that gives me a hint.  The differences are 2,8,20,38,44,110,128,170,218 the 44 looks out of place.  The differences of those are 6,12,18,6,66,18,42,48,  I'm seeing sums of 6.
If the differences were 6,12,18,24,30, 36,42,48 things would be ....better.  That would make the previous difference be 2,8,20,38,62,92,128,170,218 which would make the first series 1,3,11,31,69,131,223,351,521, 739.
The 131 was mistyped as 113.
===
BTW to get the sequence:
6,12,18,24,30, 36,42,48 => $c_n = 6*n$
2,8,20,38,62,92,128,170,218 => $b_n = 2 + \sum 6i = 2 + 3(n-1)n$
1,3,11,31,69,131,223,351,521, 739 => $a_n = 1 + \sum something_to_do_with_square_powers = something_to_do_with_cube_powers$.
(I can never remember nor derive the damned sum equations and even if I did I just know I'm going to make a careless arithmetic error.  It'd be impossible for me not to...)
So $a_n = an^3 + bn^2 + cn + d$.  $a_0 = 1$, $a_1 = 3$, $a_2 = 11$ and $a_3=31$ is enough for me to conclude the sequence is $a_n = n^3 + n + 1$.

Identify the misprint in a sequence


Multiple peak fit - decomposing a graph into visible and hidden peaks of the same probability distribution

Question: I have a graph as a set of coordinates (x, y), where x is a progressing time and y is proportional to an amount of molecules (chromatography results).
Visible peaks on the graph look like of gamma distribution (but not necessarily, could be Weibull, Poison or Normal-skewed).
I need to decompose the graph into multiple signals of the same probability distribution (gamma or other),  which are presented either by visible peaks or by internal/hidden ones, located anywhere under graph's curve.
Desired results would look like this:

The existence of the internal ones is inferred after fitting distributions to visible peaks first and then calculating differences between the sum of visible peaks fitted models slopes and the original graph curve.
nls() will not work for this problem, since it will miss the internal peaks/signals (besides the fact that it is sensitive to start parameters).
And probably ALS package (or others) would do the job, but I am loosing myself in its input structure and descriptions. My math knowledge is not sufficient.
Looking for some existing elegant solution/tool in R.
Could anybody please advise!
Comment: It is enough that the "pick the count and throw it in a pile" can  take a while.  I'm thinking of resampling using an ecdf, then using k-means to find centers then adjust on variances, then use EM.  We will see how it goes.  That is a fairly stiff stack of peaks.  Fun.  Thank you.
Comment: Do the physical processes of retention and elution suggest particular distributions? I see that depending on the type of dectector you use, the intensity at a given time may be Poisson-distributed as in σ² (I) = E (I). But I guess for I (t) a distribution with continuous t should be chosen).
Comment: The type of distribution is unknown. I would like to build a generic tool in which i could change the distribution formula each time.
Comment: Can you give basic params for a dummy problem?  Pseudocode?  Note: there is a proximity in the peaks where all the samples in the world don't work - the basis is incapable.
Comment: Not sure what you mean by basic params. The time on x-axis has a step of 0.02 second, the peaks widths are about several hundred points. Because of the dummy problem, i have tried to fit to each peak gamma distribution separately using optim. But i see that it's sensitive to start params. Posted here some code and params: [link](http://stats.stackexchange.com/questions/202964/optim-convergence-in-fitting-gamma-distribution-to-separate-peaks-of-time-seri)
Comment: Would you consider the metMUD1 data from the ChemoSpec library to be representative?
Comment: Yes, i guess so. Only i am in a resolution of a single sample (30000 points long).  I don't find a way to put data file here
Comment: I've seen links to dropbox or such.
Comment: [here](https://www.dropbox.com/s/ez1epmbv462aa8r/EngrStudent.1.data?dl=0) is one data example, and [here](https://www.dropbox.com/s/v9d9wui6g3jm2wy/EngrStudent.2.data?dl=0) is another one, just in case. Thank you so much for your time!
Comment: Question: would you ballpark that at ~30 peaks?  How many components do you expect in the final result?  What do you think typical peak-widths are?  Are you sure the basis is gamma?
Comment: The ballpark is about 60-70 peaks for a sample. Peaks widths may vary from 1 to 30-40 seconds(multiplied by 50 for points amounts) approximately. As for the basis, it's known that it does the job if gamma distribution is assumed, so the main goal is to end up with gamma's shape/scale parameters for each peak. However an option to try other distributions would be very valuable.
Comment: Tremendously appreciate it!
There is one more thing, which could make fitting to stiff peaks easier.  Since the data didn't go through baseline correction - each individual discovered gamma signal may start not from the very zero (x-axis), it can start from a step (a delta).
So eventually each gamma peak should be characterized by: shape, scale and delta.
P.S. 60-70 is the ballpark of total final peaks (visible and internal ones), most likely around 30 of them are the visible ones.
Answer: It is called a "finite mixture model".
Here is the first one, by Pearson.

http://ms.mcmaster.ca/peter/mix/demex/excrabs.html
http://blog.mrtz.org/2014/04/22/pearsons-polynomial.html

Some general references

https://en.wikipedia.org/wiki/Mixture_model
http://repec.org/snasug08/deb_fmm_slides.pdf

Here are libraries for handling it:

https://cran.r-project.org/web/packages/flexmix/vignettes/flexmix-intro.pdf
ftp://www.r-project.org/pub/R/web/packages/mixtools/vignettes/mixtools.pdf
http://exploringdatablog.blogspot.com/2011/08/fitting-mixture-distributions-with-r.html
https://www.stat.washington.edu/research/reports/2012/tr597.pdf
Comment: The peaks are [Cauchy](https://en.wikipedia.org/wiki/Cauchy_distribution), not Gaussian.  Starting with the right basis is going to make EM work much more effectively.  Is it okay to smooth the data some first?
Comment: Thanks. These might be usefull tools, the problem is they all are accommodated to a one-dimensional vector of data points as an input. While i have a time-series, meaning that my data is a y-axis coordinates, i have somehow to transform them into a proper vector of points first, in order to apply these tools. I am new in the field, so i know this could sound like a dummy problem to most of the people here.
Comment: It should be an action opposite to density() or hist() function. Could anybody advise please
Comment: Yes, of course.  May i ask you how did you infer Cauchy is the basis?


Asynchronous execution of test cases in JS test driver

Question: We are having CI build servers where different JS TestCases are to be executed parallely (asynchronously) on the same instance of JS test driver server.  The test cases are independent of each other and should not interfere with each other.  Is this possible using JS test driver?
Currently, I have written two test cases, just to check if this is possible:
Test Case 1:
GreeterTest = TestCase("GreeterTest");

GreeterTest.prototype.testGreet = function() {
  var greeter = new myapp.Greeter();
  alert("just hang in there");
  assertEquals("Hello World!", greeter.greet("World"));
};

Test Case2:
GreeterTest = TestCase("GreeterTest");

GreeterTest.prototype.testGreet = function() {
   var greeter = new myapp.Greeter();
   assertEquals("Hello World!", greeter.greet("World"));
};

I have added the alert statement in test case 1 to make sure that it hangs there.
I have started the JS test driver server with the following command:
java --jar JsTestDriver-1.3.5.jar --port 9877 --browser <path to browser exe>

I am starting the execution  of both the test cases as follows:
java -jar JsTestDriver-1.3.5.jar --tests all --server http://localhost:9877

The Test Case 1 executes and hangs at alert statement. Test Case 2 fails with an exception (BrowserPanicException). The conf file is proper, as the second test case passes if executed by itself.
Is there any configuration changes required to make the second test case pass, while the first test case is still executing?
Answer: This issue is caused by the "app" (the jsTestDriver slave, running the tests) cannot really run them in parallel.  This is because it's written in javascript, which is single threaded.
The implementation probably loops all tests and runs them one by one, thus, when an alert pops, the entire  "app" is blocked, and cannot even report back to the jsTestDriver server, resulting in a timeout manifested in a BrowserPanicException.
Writing Async Tests won't help since the entire "app" is stuck.


Help with integral $\int_{-1}^6\frac{dx}{\sqrt{9+16x^2}}$

Question: $$\int_{-1}^6\frac{dx}{\sqrt{9+16x^2}}$$
What identities should I be using here?
Answer: What about
$$\frac{1}{\sqrt{9+16x^2}}=\frac{1}{3}\frac{1}{\sqrt{1+\left(\frac{4x}{3}\right)^2}}$$
and then trying the substitution
$$\frac{4}{3}x=\sinh u\Longrightarrow dx=\frac{3}{4}\cosh u\,du \ldots$$
Comment: When I took $\,9\,$ out of the root as to have $\,\sqrt{1+A^2}\,$ , which is a expression that reminds of hyperbolic functions because of $\,\cosh^2x-\sinh^2x=1\,$
Comment: That helps a lot more. Just a quick question, where do you get (4x/3)^2 from?
Comment: I see what you did but Im still a little stuck. I dont know what I am doing wrong.
Comment: I think of it this way. If we had $16x^2=9u^2$, we would get a common $9$ which comes out as a $3$. So we want $4x=3u$.
Answer: Hint: $\frac{d}{dx}(sinh^{-1}(x))=\frac{1}{\sqrt{1+x^2}}$. Now what are the suitables substitutions


Create Latest Comments View Per Group OG 7.2

Question: Hello it has been a while since i used OG Groups (and Panels) and im struggling a bit to create a view for the group home page showing the latest comments within the group. Its all to do with the Relationships and Contextual Filters. There seems to be so many relationships and filters available to me that its making me struggle a bit.
Could anyone advise me on how to make a view that will display the comments for that group? I think once i see the Relationships used there will be no holding me back from various other things.
Thanks
Comment: ah finally OG membership: OG membership from Node for the relationship and OG membership: OG membership from Node as the contextual filter not forgetting to sort the validation criteria
Answer: OG membership: OG membership from Node for the relationship and OG membership: OG membership from Node as the contextual filter not forgetting to sort the validation criteria


Bindings doesn't work on nested template loaded by JSON in KnockoutJS

Question: Yesterday I make this question:
How can I refresh or load JSON to my viewModel on Knockout JS with complex models
Everything works OK with the fixes but when I try to use a complex json to load in the viewModel some of the buttons (specifically on Groups) doesn't work.
To resume the problem. I have a json with the previous serialized data. I use that json to fill the viewModel, this works, load correctly the data but the problem are in the "group" template, because the data is loaded but the buttons doesn't work, the only button which is working is the "remove group".
(Please refer to the image)
Any idea to fix this? Thanks.
Jsfiddle example with the problem
http://jsfiddle.net/y98dvy56/26/
!Check this picture.
The red circles indicates the buttons with problems.
The green circles indicates the buttons without problems.
Here is the body html

Knockout.js Query Builder

      Example Output

    <input type="submit" value="Save" data-bind="click: Save"/>

Condition.js:
window.QueryBuilder = (function(exports, ko){

  function Condition(){
    var self = this;

    self.templateName = 'condition-template';

    self.fields = ko.observableArray(['Points', 'Goals', 'Assists', 'Shots', 'Shot%', 'PPG', 'SHG', 'Penalty Mins']);
    self.selectedField = ko.observable('Points');

    self.comparisons = ko.observableArray(['=', '<>', '<', '<=', '>', '>=']);

    self.selectedComparison = ko.observable('=');

    self.value = ko.observable(0);
  }

  exports.Condition = Condition;
  return exports;

})(window.QueryBuilder || {}, window.ko);

Group.js
window.QueryBuilder = (function(exports, ko){

  var Condition = exports.Condition;

  function Group(){
    var self = this;

    self.templateName = 'group-template';
    self.children = ko.observableArray();
    self.logicalOperators = ko.observableArray(['AND', 'OR']);
    self.selectedLogicalOperator = ko.observable('AND');

    // give the group a single default condition
    self.children.push(new Condition());

    self.addCondition = function(){
        self.children.push(new Condition());
    };

    self.addGroup = function(){
        self.children.push(new Group());
    };

    self.removeChild = function(child){
        self.children.remove(child);
    };
  }

  exports.Group = Group;
  return exports;

})(window.QueryBuilder || {}, window.ko);

ViewModel.js
window.QueryBuilder = (function(exports, ko){

  var Group = exports.Group;

  function ViewModel() {
    var self = this;
    self.group = ko.observable(new Group());

    self.load = function (data) {
        ko.mapping.fromJS(data, self);
    }

    self.Save = function () {
        console.log(ko.toJSON(self));
    }
  }

  exports.ViewModel = ViewModel;
  return exports;

})(window.QueryBuilder || {}, window.ko);

Comment: your issue is caused by the fact that the mapping plugin makes your data observable, but doesn't add the add, remove, etc... functions. If you do a console log for the json data when it's inserted into the view model you will notice that the data is observable but the functions are missing. You need to provide a mapping to customize your Group, Condition, etc.. constructors as explained here http://knockoutjs.com/documentation/plugins-mapping.html
Comment: Are you able to provide a jsfiddle with your code?
Comment: @omerio Yes, this is the jsfiddle code. http://jsfiddle.net/y98dvy56/26/
Comment: @omerio Can you give me a simple example based on my code? It will be help me a lot.
Answer: Your issue is caused by the fact that the mapping plugin makes your data observable, but doesn't augment your data with the functions in your model such as the add, remove, etc... functions. If you do a console log for the json data when it's inserted into the view model you will notice that the data is observable but the functions are missing. You need to provide a mapping to customize your Group, Condition, etc.. constructors. Because the children array in your case is of mixed types (condition or group) Here is a custom mapping to take care of that:
var childrenMapping = {
    'children': {
        create: function(options) {
            var data = options.data;
            console.log(data);
            var object;
            switch(data.templateName) {
                case 'condition-template':
                    object = new QueryBuilder.Condition(data);
                    break;
                case 'group-template':
                    object = new QueryBuilder.Group(data);
                    break;
            }
            return object;
        }
    }
};

Then you simply need to provide this mapping in your initial mapping
ko.mapping.fromJS(json.group, childrenMapping, vm.group);

Then inside the constructor of the Group object:
 function Group(data){

   var self = this;

   self.templateName = 'group-template';
   ...

   ko.mapping.fromJS(data, childrenMapping, this);
}

You also need to update the Condition constructor to accept the data provided by the mapping, but since conditions don't have children you do not need to provide the childrenMapping here:
 function Condition(data){

     var self = this;

     self.templateName = 'condition-template';

     ...

     ko.mapping.fromJS(data, {}, this);
 }

I've the mapping at the end of both function so that the mapped values override you initial value.
The updated jsfiddle here:
http://jsfiddle.net/omerio/y98dvy56/32/
This answer is related:
knockout recursive mapping issue
Comment: Thanks for your time. I was so close about the mapping, the only difference (and missing on my code) is the switch by template name.


PHP: Having all the important code in 1 php page or having it only on pages that require it

Question: I'm going to start making an open source forum and I have the following question:
Should I include all the important code in one php page that i require once on each page or having it on each page.
i.e: A code that connects to the MySQL database, another code that secures the input before executing a query.
Answer: I personally prefer to do things as modular as possible.  That way when you need to change something a few years down the road, you don't have to change it in 100 places.
Answer: In case you are using procedural code you should group functions by their context. For example into: database.php, input.php...
In case you are using classes you should have one class in only one file and include it. With classes you can also use the spl_autoload_register function to autoload classes only when needed.
If you have common code that you know you are always going to need you should create a front controller and include it only there.
Answer: You should look into various frameworks that provide tools for implementing better code reuse, bootstrapping, etc.  For example, Symfony, Zend Framework, Yii, etc.
Answer: of course you should put repeating blocks in one file and then include it.
Usually it connect.php, functions.php, header.php, menu.php and footer.php
Answer: I believe that the nomenclature in programming languages gives you a good starting point for how to structure your code.
function -> does (only) 1 thing, and that good.
class    -> collection of functions that belong together

as for the "all in 1 page" part.. you should only have the parser read through code that it will need to accomplish its current task. if a single "page" is supposed to do more than 1 thing, you should only require() the classes/functions you need when you need them.
Answer: In fact it doesn't matter, do the way you like. Among the reasons and good examples given in other answers, if you have many files, probably you don't need to load all of them on each request.
Having all in one file assures that on migrate or distribute it you need to move or copy a single file.
If I remember correctly RedBeans is just a single file, while for example Prado has lots of them.


Deep Learning based time series forecasting

Question: According to the paper "Statistical and Machine Learning forecasting methods: Concerns and ways forward", it looks like the recent DNN-based approach has weaker predictive power in extrapolation, i.e. time series forecasting than statistical algorithm like VAR or ARIMA.
The benchmark result is contrary to the current Deep-Learning-beats-it-all trend. Is the reason behind the result from the fact that DNN algorithms require a large-sized data?
Answer: You can't meaningfully talk about DNNs or ARIMA being "better at time series forecasting". It depends enormously on what kind of series you are looking at: short vs. long series, many vs. few or only one related series, causal drivers or not etc.
Anyone who makes sweeping statements here is like a salesman who knows exactly what kind of car you need - without bothering to find out whether you need to drive offroad, commute two miles to work, need to move a Little League baseball team, or want to transport cattle.
As a very rough rule of thumb, classical methods perform competitively if you have few short series. DNNs may work better if you have many related series. (It depends heavily on whether the person setting them up knows what she or he is doing.)
Comment: Thank you very much for the advice from deep experience!
Answer: You might also consider the drivers behind 'Deep-learning-beats-all' trend you mention. Much of the hype around these techniques comes from the superiority of these methods in image recognition and natural language problems. These domains are defined by exceptionally large datasets (e.g. ImageNet > 14 million images, it's possible to find very large text corpora). So just by understanding why these methods are popular in the first place more or less answers why they are less used for time series (since time series datasets are much smaller).
As an example of how short important time series datasets can be very small consider that if you wanted to model US GDP, the Federal Reserve has quarterly data going back to 1929, which is only about 360 datapoints!
Comment: Yes. As I read papers, textbooks, and other lectures, I learn that it's better to select a right algorithm to a given problem domain and data set in time series forecasting task. Than you!
Answer:
Is the reason behind the result from the fact that DNN algorithms require a large-sized data?

There are parallels to time-series and tabular data. A recent work Tabular Data: Deep Learning is Not All You Need shows similar trends that DNN does not out perform conventional models on tabular data. However, it is right that the learning capacity of DNNs are advantageous when there are very large datasets. More justice to deep learning would be to say this is an open research area and DNNs have great potential over conventional time-series models.
PS: To give link to paper Statistical and Machine Learning forecasting methods: Concerns and ways forward lead by Cypriot researcher
Answer: Statitical tools applied to time series forecasting are very developed and approach-oriented methods. You find many technics arima sarima sarimax var varimax vecm.... And each method had been developed  for a particular situation and type of data and serie.
In the other hand DNN such as RNN, LSTM.. Are challenging models that have not been very used in this field, so haven't experienced many situation so they can been evaluated and updated in a large scale.
I had the chance to work for a system of medels, combined, for a platform that forecast time series of eco, demo, social... Indicators and it happen that sometimes LSTM get a better result.
What I can claim is that DNN are not good when it comes to random trend chocs.
Comment: Thank you for sharing precious information.


Android SQLite Database onCreate error

Question: I am new to SQLite and am trying to go about creating a basic database for learning purposes.
In my Main I declare a new DbHelper and SQLiteDatabase..
    // Open Database
    DbHelper dbHelper = new DbHelper(Main.this);
    SQLiteDatabase db = dbHelper.getWritableDatabase();

My DbHelper class..
public class DbHelper extends SQLiteOpenHelper
{
private static final String TAG = "DbHelper";

public static final String DB_NAME = "exerciseDB";
public static final int DB_VERSION = 1; // User defined - up to you
public static final String TABLE = "Exercises";

// Try keep column names consistent with object names
public static final String C_ID = "_id"; // "_id" special
public static final String C_PARENTEXERCISE = "parentExercise";
public static final String C_SETNO = "setNo";
public static final String C_REPSANDWEIGHT = "repsAndWeight";

public String sql;

Context context;

public DbHelper(Context context)
{
    super(context, DB_NAME, null, DB_VERSION);
}

@Override
public void onCreate(SQLiteDatabase db)
{
    // SQL commands
    sql = String.format(
            "CREATE TABLE %s (%s INT PRIMARY KEY %s TEXT %s INT %s TEXT);",
            TABLE, C_ID, C_PARENTEXERCISE, C_SETNO, C_REPSANDWEIGHT);

    // Prints out sql String to Logcat
    Log.d(TAG, "onCreate sql: " + sql);

    db.execSQL(sql); // Executes the SQL commands
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
{
    // Maintain users data first
    db.execSQL("drop table if exists " + TABLE); // Deletes table if it
                                                    // exists

    Log.d(TAG, "onUpdata dropped table" + TABLE);

    // Recreate database
    this.onCreate(db);
}

public String getSQLcmd()
{
    return sql;
}

}
The LogCat output of the sql command is as I believe it should be..
onCreate sql: CREATE TABLE Exercises (_id INT PRIMARY KEY parentExercise TEXT setNo INT repsAndWeight TEXT);

LogCat also says:
 11-10 17:44:14.702: E/SQLiteLog(13053): (1) near "parentExercise": syntax error

But I can't seem to see anything wrong with anything parentExercise related.
Any help would be greatly appreciated.
Cheers.
Comment: Add commas(`,`) between the columns in the sql `String`.
Answer: your query should look like
CREATE TABLE Exercises (_id INT PRIMARY KEY, parentExercise TEXT, setNo INT, repsAndWeight TEXT)

Android SQLite Database onCreate error


is Android 4's face detection API dependant on specific phones?

Question: I'm trying to develop a face recognition system for Android, and I opted to use Android 4 as it has the built in face detection API. I'm using a Samsung nexus s and despite being as up to date as possible and a really new model phone the .getMaxNumDetectedFaces() method returns 0.
Am I doing something wrong or can this phone actually just not detect faces?
I thought the face detection would be included in the Android software and not the phone specific software.
Answer: There are two different face detection APIs in Android. FaceDetectorListener which depends on getMaxNumDetectedFaces() is hardware dependent so it might not be enabled on phones even if they run the latest version of Android. FaceDetector on the other hand runs in software and is supported since Android 1 so you might try that. Another option is to install OpenCV for Android.
See also, the answers on this question: Android face detection MaxNumDetectedFaces
Comment: Yeah, it is ported by the OpenCV team specifically for Android. A co-worker is running it and it looked pretty fast. This doesn't help you but apparently if you are running it on a Nexus 7 or Galaxy Nexus it uses hardware acceleration...
Comment: I will try that thanks.
Is OpenCV for Android a ported version of OpenCV? because what I am doing at the moment is importing the c++ OpenCV library as a native library
Comment: that is pretty cool, I will have to look at upgrading my app to use it in the future


Firestore getting Javascript Date instead of Timestamp

Question: I'm using Angular 6 and Firestore to develop an application where I'm saving my dates as Javascript's Date object. The issue is that when I do snapshotChanges(), It returns a Unix Timestamp instead of the Date object that is in my database.
I searched the solutions online (this, and this) and found this config option for Firestore:
{ timestampsInSnapshots: false }
I'm trying to apply this in my app component like this:
constructor(private _db: AngularFirestore) {
    _db.firestore.settings({ timestampsInSnapshots: false });
  }

But then I get this error:
Firestore has already been started and its settings can no longer be changed. You can only call settings() before calling any other methods on a Firestore object.
I've also tried to change the settings before calling snapshotChanges() but, that also does not have any effect on the behaviour.
Note: I'm also using AngularFirestoreModule.enablePersistence()
Update:
I tried this and it gives me this error:
@firebase/firestore: Firestore (5.0.3):
The behavior for Date objects stored in Firestore is going to change
AND YOUR APP MAY BREAK.
Any suggestions would be great.
Answer: Hmm, try calling _db.app.firestore().settings({}) because you are making app wide changes/configurations. And since you have mentioned that you need offline support by enablePersistence(), try calling that in your component in this case, instead of root module, but after calling settings().
In your component :
constructor(private _db: AngularFirestore) {
    _db.app.firestore().settings({ timestampsInSnapshots: false });
    _db.app.firestore().enablePersistence();
}

Comment: Actually, By calling `enablePersistence()` right after the settings in my `App Module` fixes the issue, but should I be worried about the breaking changes? What should I do to make it compatible?
Comment: `Property app does not exist on AngularFirestore` and `_db.firestore(): there is no such function`.
Comment: Okk. What happens when you are doing ` _db.firestore.settings({ timestampsInSnapshots: false });` in your component and call `enablePersistence()` right after that?
Comment: I still get `Firestore has already been started` error. And If I do it in my appModule, I get the `AND YOUR APP MAY BREAK` error.
Comment: That is odd. `app` should exists as you might see here in the source.

[angular2](https://github.com/angular/angularfire2/blob/master/src/firestore/firestore.ts)

Please share your Firebase and AngularFire2 version. Also if possible your repo.
Comment: ` "@angular/core": "^6.0.3",`
`"firebase": "^5.0.3"`
`"angularfire2": "^5.0.0-rc.10"`
Comment: Well, the warning simply means the Firebase have been using Date() - this is the default behaviour. But is planning to change to Timestamp values by default soon. Since you are not using Timestamp, you are getting that warning.

Please follow this 2 important links to know more about it.

[issue726](https://github.com/firebase/firebase-js-sdk/issues/726)

and

[this](https://github.com/invertase/react-native-firebase/issues/1024)
Comment: Thanks, Is it possible to change make `{ timestampsInSnapshots: false }` only for a single service while keeping offline persistence?
Comment: Could be possible if you are able to get `FirebaseApp` instance from `AngularFirestore` injectable service. I am not sure.
Answer: I was able to achieve the required functionality by adding the following code to my app controlled.
constructor(private _db: AngularFirestore) {
  _db.firestore.settings({ timestampsInSnapshots: false });
  _db.firestore.enablePersistence();
}

Remember, Don't AngularFirestoreModule.enablePersistence() if you intend to use the above code. Simply adding AngularFirestoreModule is enough.


Does retrofit interfaces support templated callbacks

Question: I have an API the returns a standard reply for all requests that gets parsed by gson/retrofit.
public class ServerReply<T> {
    @Expose
    private String status;
    @Expose
    private T data;
    @Expose
    private String message;
}

I have an interface for Retrofit that will return a list of users inside of serverReply.
public interface Test {
    @POST("/Test")
    void runTest(@Body Body body, Callback<ServerReply<List<User>>> response);
}

I would like to get a different list of objects depending on the content of the body. Is it possible to use templating/generics to accomplish this?(see below)
public interface Test<T> {
    @POST("/Test")
    void runTest(@Body Body body, Callback<ServerReply<List<T>>> response);
}

Answer: No, but it's a Java limitation not a missing Retrofit feature. Due to type erasure there is no way for Retrofit to resolve what the type variable T actually is to pass to the deserializer without a concrete class.
Comment: Would `public interface SpecificService extends GenericService { @GET("/user") User getUser(); }` work? I have some shared abstract code that I'd like to be able to use getUser but I don't mind making the service again for the specific code that uses the abstract code


Prove that for any integer $m>1$, $\ \ (z+a)^{2m}-(z-a)^{2m}=4maz\prod_{k=1}^{m-1}[z^2+a^2\cot^2(k\pi/2m)]$.

Question:
Prove that for any integer $m>1$,
  $$(z+a)^{2m}-(z-a)^{2m}=4maz\prod\limits_{k=1}^{m-1}[z^2+a^2\cot^2(k\pi/2m)].$$

This how tried to do it:

Expand the two brackets on the right hand side and end up with, after cancelling the $a^{2n}$ terms (where the variables are multiples of squares):
$$2\sum\limits_{r=1}^{m} \binom{2m}{2r-1}z^{2m-r}a^{2r-1}=4maz \sum\limits_{r=1}^{m} \frac{1}{2m}\binom{2m}{2r-1}z^{2(m-r)}a^{2(r-1)}$$

But now what? How is that series on the left hand side related to the product in the question? Furthermore this question comes from Schaum's Outline Complex Variables, but I tried and failed at integrating complex numbers into this, so complex numbers method would be appreciated here.
BTW you don't have to provide a full proof, just a few hints should be enough.
Answer: Using my answer here we can see that
$$z=ia\cot(k\pi/2m)\,\,\text{for}\,\,k=\pm 1,\pm 2, \cdot ,\pm m-1 \tag 1$$
comprise $2m-2$ roots of the equation
$$\left(\frac{z-a}{z+a}\right)^{2m}=1 \tag 1$$
We also have the obvious root $z=0$.  Thus, we can rearrange $(2)$ in polynomial form, and write the polynomial in factored form in terms of these roots in $(1)$ as
$$\begin{align}
(z+a)^{2m}-(z-a)^{2m}&=Cz\prod_{k=1}^{m-1}\left(z-ia\cot(k\pi/2m)\right)\left(z+ia\cot(k\pi/2m)\right)\\\\
&=Cz\prod_{k=1}^{m-1}\left(z^2+a^2\cot(k\pi/2m)\right)\tag 3
\end{align}$$
where $C$ is the coefficient on the leading term $z^{2m-1}$.  Note that in $(3)$, we exploited the fact that $\cot x=-\cot (-x)$.
Finally, using the binomial expansion, we find that $C$ is
$$C=2\binom{2m}{2m-1}a=4ma$$
and therefore, we have
$$\bbox[5px,border:2px solid #C0A000]{(z+a)^{2m}-(z-a)^{2m}=(4ma)\,z\,\prod_{k=1}^{m-1}\left(z^2+a^2\cot(k\pi/2m)\right)}$$
as was to be shown!
Comment: As an alternative to binomial expansion, you can obtain $C$ by dividing both sides of equation (3) by $2a$, then taking $a\to 0$ and recognizing the LHS as a derivative.
Comment: nope, this is brilliant, thank you very much!
Comment: You're welcome.  And my pleasure.  And thank you for the nice compliment. I'm recovering at home from surgery 3 weeks ago.  Your kind words just made my day!
Comment: Hope you get well soon! :)
Comment: @Semiclassical YES, I know noticed that too!
Comment: @semiclassical Yes you're absolutely correct.  I thought using the binomial expasion was quick and aligned with the OP's work shown in the post.
Comment: here the power is 2m. So it should have 2m roots.  $$\pm1,\pm2,.....,\pm(m-1)$$ that is 2m-2 amount of roots also z=0 is a root, a total of 2m-1 roots. Where is the last one? Is it because $Z^{2}$ is present in the factorization?
Comment: @ALvi1993 Actually, the polynomial $(z+a)^{2n}-(z-a)^{2m}$ is of order $2m-1$, not $2m$.
Answer: No; if you notice that the RHS is a finite product of quadratic factors, then this immediately suggests a factorization in complex conjugate pairs.  The idea is to observe the identity $$x^{2m} - y^{2m} = \prod_{k=1}^{2m} (x - \zeta_{2m}^k y)$$ where $\zeta_{2m} = e^{i \pi/m}$ is a primitive $2m^{\rm th}$ root of unity.  This identity may look more familiar when $y = 1$ and for a general positive integer $2m \to n$; i.e., $$x^n - 1 = \prod_{k=1}^n (x - \zeta_n^k).$$  But since we restrict the power to a positive even integer $2m$, we can pair up linear factors in complex conjugate pairs, and the real-valued factors also pair up naturally:  $$\begin{align*} x^{2m} - y^{2m} &= (x - y)(x + y) \prod_{k=1}^{m-1} (x - \zeta_{2m}^k y)(x - \zeta_{2m}^{-k} y) \\ &= (x^2 - y^2) \prod_{k=1}^{m-1} \bigl( x^2 + y^2 - xy (\zeta_{2m}^k + \zeta_{2m}^{-k}) \bigr) \\ &= (x^2-y^2) \prod_{k=1}^{m-1} \Bigl( x^2 + y^2 - 2xy \cos \frac{k \pi}{m} \Bigr). \end{align*}$$  Now we substitute $x = z + a$, $y = z - a$:  we get $$x^2 - y^2 = 4az,$$ and $$\begin{align*} x^2 + y^2 - 2xy \cos \frac{k \pi}{m} &= 2z^2 + 2a^2 - 2(z^2 - a^2) \cos \frac{k \pi}{m} \\ &=  2 \biggl(1 + \cos \frac{k\pi}{m} \biggr) \Biggl( z^2 + a^2 \biggl(\frac{1 - \cos \frac{k\pi}{m}}{1 + \cos \frac{k\pi}{m}} \biggr)\Biggr) \\ &= 4 \cos^2 \frac{k\pi}{2m} \Bigl( z^2 + a^2 \cot^2 \frac{k \pi}{2m} \Bigr). \end{align*}$$  So all that remains is to show that $$\prod_{k=1}^{m-1} 4 \cos^2 \frac{k \pi}{2m} = m.$$  I leave this as a relatively simple exercise for you to complete.  Hint:  observe $\cos \frac{-k\pi}{2m} = \cos \frac{k\pi}{2m}$.

There is very likely a more elegant and simple approach but this is the solution I came up with off the top of my head.
Comment: No this was really nice, I learned the $x^{n}-y^{n}$ identity, so it was very useful, thank you!


Ajuda com Async C# / WinForms

Question: bom dia!
Montei um pequeno projeto para estudo onde eu coleto dados de um site e jogo para um DataGridView usando o Selenium.
Tenho 3 Classes

Robot.cs -> Onde tenho o métodos de navegação e coleta de dados.

<code>//NAVEGAR PARA O SITE(URL)
public void GoToUrl(string Url)
{
    RoboDriver.Navigate().GoToUrl(Url);
}
//PROCURAR POR XPATH LER E RETORNAR VALOR
public string ReadByXPath(string XPath, string attribute)
{
    string SetRead;
    Wait.Until(d => RoboDriver.FindElementByXPath(XPath));
    SetRead = RoboDriver.FindElementByXPath(XPath).GetAttribute(attribute);
    return SetRead;
}
</code>

RobotNavigation.cs -> Responsável pela navegação.

<code>        //METODO PARA BUSCAR E PREENCHER AS COTAÇÕES DO DATAGRIDVIEW
    public void GetQuotes(DataGridView dataGridView, ProgressBar progressBar)
    {
        //ZERAR BARRA DE PROGRESSO
        progressBar.Value = 0;
        //DEFININDO VALOR DA BARRA DE PROGRESSO
        progressBar.Maximum = dataGridView.RowCount;
        //PERCORRER REGISTROS DO DATAGRIDVIEW
        foreach (DataGridViewRow row in dataGridView.Rows)
        {
            //TRAVAR DATAGRIDVIEW
            dataGridView.AllowUserToAddRows = false;
            string codActive = row.Cells[0].Value.ToString();
            //MONTAR URL DE NAVEGAÇÃO COM CÓDIGO OBTIDO
            string url = "https://www.fundamentus.com.br/detalhes.php?papel=" + codActive;
            //NAVEGAR PARA SITE (URL)
            GoToUrl(url);
            //PREENCHER COLUNA DO DATAGRIDVIEW COM A COTAÇÃO OBTIDA NO SITE
            row.Cells[1].Value = ReadByXPath("/html/body/div[1]/div[2]/table[1]/tbody/tr[1]/td[4]/span", "innerHTML");
            //INCREMENTAR BARRA DE PROGRESSO
            progressBar.PerformStep();
        }
        //FECHAR ROBO
        RobotQuit();
        //HABILITAR DATAGRIDVIEW
        dataGridView.AllowUserToAddRows = true;
    }
}
</code>

Form1.cs -> Onde executo a navegação através de um botão.

<code>        private void bntPlay_Click(object sender, EventArgs e)
    {
        RobotNavigation robotNavigation = new RobotNavigation();
        robotNavigation.GetQuotes(dgvMain, pBar);
    }
</code>
Gostaria de uma ajuda para tornar esse projeto assíncrono para que o form e os componentes não travem enquanto o robo navega, coleta dados e trabalha com os componentes passados via parâmetro.
Comment: Você deve implementar uma thread que roda a logica de coleta dos dados, assim a thread da aplicação não ficara travada até o termino da operação. Da uma olhada aqui https://docs.microsoft.com/pt-br/dotnet/api/system.threading.threadpool.queueuserworkitem?view=netframework-3.5
Answer: Você vai precisar usar uma task para rodar a lógica:
<code>private async void bntPlay_Click(object sender, EventArgs e)
{
    Task tks = Task.Run(() =>
    {
        RobotNavigation robotNavigation = new RobotNavigation();
        robotNavigation.GetQuotes(dgvMain, pBar);
    });

    await tks;
}
</code>
Comment: Olá! Bom dia! Já havia tentado isso envolvendo os componentes em um void{} e invocando usando o Invoker.... mas ñ rolou... acredito que vou ter q mudar essa estrutura pra dar certo...
Answer: bom dia!
Acabei alterando a estrutura do projeto para obter o resultado que esperava e sendo assim fiquei somente com os arquivos Robot e Form1.
Segue repositório caso queiram ver o resultado final.
https://github.com/lbert1/Pepe-Robot
Form1.cs
<code>   public void GetQuotes()
    {
        Robot robot = new Robot();
        MethodInvoker invPBarStart = delegate
        {
            //ZERAR BARRA DE PROGRESSO
            pBar.Value = 0;
            //DEFININDO VALOR DA BARRA DE PROGRESSO
            pBar.Maximum = dgvMain.RowCount;
        };
        Invoke(invPBarStart);
        //PERCORRER REGISTROS DO DATAGRIDVIEW
        foreach (DataGridViewRow row in dgvMain.Rows)
        {
            MethodInvoker invDgvStart = delegate
            {
                //TRAVAR ADICONAR NO DATAGRIDVIEW
                dgvMain.AllowUserToAddRows = false;
            };
            Invoke(invDgvStart);
            string codActive = row.Cells[0].Value.ToString();
            //MONTAR URL DE NAVEGAÇÃO COM CÓDIGO OBTIDO
            string url = "https://www.fundamentus.com.br/detalhes.php?papel=" + codActive;
            //NAVEGAR PARA SITE (URL)
            robot.GoToUrl(url);
            //PREENCHER COLUNA DO DATAGRIDVIEW COM A COTAÇÃO OBTIDA NO SITE
            row.Cells[1].Value = robot.ReadByXPath("/html/body/div[1]/div[2]/table[1]/tbody/tr[1]/td[4]/span", "innerHTML");
            //INCREMENTAR BARRA DE PROGRESSO
            MethodInvoker invPBarStep = delegate
            {
                pBar.PerformStep();
            };
            Invoke(invPBarStep);
        }
        //FECHAR ROBO
        robot.RobotQuit();
        MethodInvoker invDgvEnd = delegate
        {
            //HABILITAR DATAGRIDVIEW
            dgvMain.AllowUserToAddRows = true;
        };
        Invoke(invDgvEnd);
    }

    private async void bntPlay_Click(object sender, EventArgs e)
    {
        //CHAMAR METODO GETQUOTES DE FORMA ASSINCRONA
        await Task.Run(() => GetQuotes());
    }
</code>

Ajuda com Async C# / WinForms


Loop through all entities with rules

Question: I have a content type (called Issue dates with fields called field_issue_date (date type) and field_issue_type (term_reference)) and by using Rules module 7.x-2.9 I want to check if the taxonomy field has been set to "Double", If so I want to list and set the next Issue Dates content type to be unpublished e.g
"Magazine Issue Date 2017-04-07 (Double)"
"Magazine Issue Date 2017-04-14" this should now be set as unpublished
"Magazine Issue Date 2017-04-21" this should be/remain published
Note: If Rules isn't the way to go, what would be a better way to unpublish a piece of content
Comment: I've now added field_ for fields that I have included in my content type "Issue Dates". When you add new content  "Issue Dates" the date and (if set to (Double)) is generated by Automatic Nodetitles 7.x-1.0 and tokens 7.x-1.7 is appended to the content title. Point 1, **Rule Event** if content is new or has been updated. **Rule Condition** if content taxonomy name has been set to "Double" **Rule action** then loop through all the content type (Issue dates) and if content type (Issue dates) field_issue_date is =< +7days of field_issue_date of Rule event content then set to unpublished.
Comment: field_issue_type is a multiple value
Answer: Have a look at this, rather basic, rule (in Rules export format):
{ "rules_check_taxonomy_term" : {
    "LABEL" : "Check Taxonomy Term",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ON" : { "node_insert" : [], "node_update" : [] },
    "IF" : [
      { "entity_has_field" : { "entity" : [ "node" ], "field" : "field_issue_type" } },
      { "list_contains" : { "list" : [ "node:field-issue-type" ], "item" : "4" } }
    ],
    "DO" : [
      { "drupal_message" : { "message" : "A node containing the tag [node:field_issue_type] just got created or updated." } }
    ]
  }
}

Here is what this rule does:

Rules Event: After saving new content, After updating existing content
Rules Conditions:

Entity has field "field_issue_type", which is the machine name of the term reference field I want to check for.
List contains item "node:field-issue-type" and with Taxonomy term identifier value "4" (which is the term id of the term I want to check in this Rules Condition).

Rules Action: Show a message on the site (which is "A node containing the tag [node:field_issue_type] just got created or updated." (with [node:field_issue_type] the actual term with term id = 4).

What is crucial in the above rules example in the context of this question, are the 2 Rules Conditions. Especially because of your extra comment "field_issue_type is a multiple value" (only "List contains item" is the Rules Condition that will do the trick ...).
Use the Rules UI to import the above rule in your site. Here are the tweaks you'll need to make it fit your case:

Within the Rules Conditions, adapt the "term id" (= "4") to fit your case.
Replace the Rules Action by what you want to happen as per the "set the next Issue Dates content type to be unpublished" in your question, which should really be a different (followup?) question.

PS: This answer applies to D7.

Loop through all entities with rules


Simple Group isomorphic to $\mathbb{Z}_p$

Question: Let $G$ be a group, $H$ and $K$ normal subgroups of $G$ such that $H$ and $K$ are simple, $G=HK$, and $H\cap K = \langle e \rangle$. Show that either

$H\cong K\cong \mathbb{Z}_p$ for $p$ a prime, or
The only normal subgroups of $G$ are $\langle e\rangle$, $H$, $K$, and $G$.
Comment: By "$H\cap K$ is the generator $e$," do you mean $H\cap K=\langle e\rangle$? (The first is nonsense, the second isn't. Also, almost always the letter $e$ is reserved for the *identity* element of a group, and it seems this is not the case here.) Where in the world does $N$ come from in your last sentence?
Comment: What is N? And you should really be more careful with the way you write: it's very hard to understand what you say...for example, it **seems* to be that $\,H\cap K=\{e\}\,$ , which means $\,H,K\,$ have trivial intersection...
Comment: I've edited your question for readability - can you verify that you meant what I've written?
Comment: I really need help with this problem, have been stuggling with it for a long time. Thanks.
Answer: Hints:
Assuming Alex's effort is the correct answer: since $\,H\,,\,K\lhd G\,\,,\,\,H\cap K=1$ then their product is isomorphic with their direct product:
$$G=HK\cong H\times K$$
Thus any normal subgroup of $\,H\,$ or $\,K\,$ is normal in $\,G\,$ , and if $\,N\lhd G\,$ , then $\,N\cap K\lhd K\;,\;\;N\cap K\lhd K\,$ .
Complete now the argument.
Comment: Hi, yes the way you wrote the intersection of H and K is correct. Sorry for the confusion. The last part, I checked the question is correct. The N just suddently appear at the end, it says, if N is normal to G, then N = e (inside the diamond sign), H, K, or G.
Comment: Stop saying "e (inside the diamond sign)"...:) . In group theory we use to denote $\,\langle x\rangle\,$ the *cyclic* group generated by $\,x\,$...this is what is meant here.
Comment: Hi Antonio, thanks for the hint, I know about the direct product part. But how you relate it to H is isomorphic to K and Zp? I thought if H and K are simple groups, then their order is either equal to G or identity? I assume identity is 1? I am new to abstract algebra.
Comment: Hahahha....I know the diamond sign is silly, but I was afraid I said it wrong. Ok then. I won't say it again =)
Comment: Well, *one* possibility is $\,H=K=\Bbb Z_p\,$ . Remember that any cyclic group of order a prime is trivially a simple group. the hint tries to help you to deal with the case when $\,H,K\,$ are NOT the cyclic group of order $\,p\,$...BTW, now that I read the editing of your question, there is one more possibility: that $\,H,K\,$ are cyclic group of order *different* primes. Check this...Did you take this question from some book?
Comment: Aside from the direct product, the book provides hint that elements in H commutes with elements in K. So is it means that HK is a subgroup of G? but I don't know if this can help to solve the Zp part.
Comment: The book doesn't says anything about different primes. Hmmm...do you think that is what the book says?
Comment: I think the book says different primes, because the intersection of H and K is the cyclic group generated by identity. Don't you agree? If H=K=Zp, then the intersection won't be that.
Comment: Oh, the can be *different*, though isomorphic, cyclic groups, @Lila...but I think I know what they mean here. I shall come back later with more since I must go now.


jquery ajax call question

Question: In a jQuery ajax statement I want to receive a payload from the server and process it in another function.  I am just having trouble with the syntax of the function.

    $.ajax({
    url: 'mypgm.pgm',
    type:'POST',
    dataType: 'json',
    data:   'action=add' +
             '&techno=' + techno +
             '&activity=' + activity,
    success: ajax_callback(msg),
    error:function (xhr, ajaxOptions, thrownError){
                    alert(xhr.status);
                    alert(thrownError);
        }
    });
}

    function ajax_callback(msg) {

        alert(msg);
    }

Response

{"response": {
    "success": "0",
    "message": "The Activity has been added."
    }
}
Comment: It looks like `mypgm.php` is responding, per the response you have here - what exactly is the problem?
Answer: A success callback handler for $.ajax() can take in the following values:
success(data, textStatus, jqXHR)

Source: http://api.jquery.com/jQuery.ajax/
So your function callback would be something like this:
function ajax_callback(data, textStatus, jqXHR)
{
  alert(data.response)
}

Note how I created a named function this way, instead of assigning it to a var. If you only care about the data, you can just leave the last 2 parameters off:
function ajax_callback(data)
{
  alert(data.response)
}

Comment: Does this look like this? success: success(data, textStatus, jqXHR),
Comment: I'm not sure what you're asking. The format of a callback handler for success is just as you have pasted, and just as I have laid out in my code. Please give it a try and let me know if you have an issue.
Comment: @bob data is simply a parameter of the function ajax_callback. You could call it anything you wanted within the rules of javascript variable names. It could be cow, dog, lemon, whatever you want. What gives it a value is that the JQuery `$.ajax` code, upon successful completion of an AJAX code, passes the data, the text status, and the ajax object to the callback you defined.
Comment: @bob In turn, data gets assigned the data, textStatus gets assigned the text status, and jqXHR gets assigned the value of the ajax object.
Comment: Hi onteria - thanks for your patients. I revised my original example above. however I still get 'msg not defined error'
Comment: @bob `success: ajax_callback(msg)` This is the issue, you don't need the (msg) after it. Just do `success: ajax_callback`
Answer: Try this:
$.ajax({
    url: 'mypgm.php',
    type: 'POST',
    dataType: 'json',
    data: 'action=add' + '&techno=' + techno + '&activity=' + activity,
    success: function(data) {
        alert(data)
    }
});

Comment: Thanks. I would like break the success function out.
Answer: You callback should be defined before the ajax call and change the signature of the function to:
var ajax_callback = function(data, textStatus, xhr) {
    // parse the data.responseText to json
}

You could alternatively just use $.getJSON()
Comment: not sure if we are sticking with json. .ajax seems more flexible.

jquery ajax call question


Porque o Clang não reconhece o header básico (iostream)?

Question: Linha de comando :
clang++ "C:\caminho\completo\helloworld.cpp" -o "C:\caminho\completo\helloworld.exe"
Código :
#include <iostream>
using namespace std;
int main(){
    cout << "Ola Mundo" << endl;
    return 0 ;
}

Erro :
C:\caminho\completo\helloworld.cpp:1:10: fatal error: 'iostream' file not found
#include <iostream>
         ^
1 error generated.

Já dei uma olhada pela internet e pelo breve que entendi deve-se usar a libc++ do minGW, se for assim, qual propósito de existir o clang ?
Answer: Pelo que sei, a Apple criou o CLANG pq o GCC utiliza licensa GPL. A Apple precisava implementar algumas "melhorias" na linguagem para suportar os seus produtos, e se implementassem essas melhorias no GCC, deveriam liberar o código para a comunidade GNU.
Criando o CLANG, eles utilizaram outro tipo licensa, que permitia que a Apple tivesse branchs privados do CLANG e não fosse obrigada a liberar os codigos fonte.
No seu caso, caso vc tenha a necessidade de usar o CLANG, instale a libstdc++ que tudo vai funcionar.
Comment: a Apple é um grande usuário e contribuidor do clang, mas não me parece que a Apple "criou o clang"
Comment: "Apple chose to develop a new compiler front end from scratch, supporting C, Objective-C and C++.[11] This "clang" project was open-sourced in July 2007.[13]" (https://en.wikipedia.org/wiki/Clang) Pode ser q o wikipedia esteja errado...
Comment: usar esse clang é muito complicado, consegui compilar mas so com o minGW instalado e com path. Não existe um compilador c++ que preste nesse mundo
Comment: Existe e se chama GCC brotha. Vc tá desenvolvendo em C++ no Windows e utilizando compiladores open source (pq uma licença do Visual Studio custa uma nota). O problema não é o compilador. Instale o Eclipse CDT, configure o seu compilador e debugger e verá que o seu problema pode ser mais de ambiente de desenvolvimento que o próprio compilador.
Comment: Apesar de uma licença profissional do Visual Studio ser cara, só precisam dela empresas com mais de 250 computadores ou com um redimento anual de mais de 1 milhão de dolares. Acredito que ambos não são o caso do usuário que fez a pergunta. Eu recomendaria para qualquer usuário do Windows a utilização do [Visual Studio Community](https://www.visualstudio.com/pt-br/vs/community/) para desenvolvimento. Na minha opinião, sua utilização e seu processo de configuração são bem mais amigável para quem esta acostumado a utilizar Windows.


VBA SQL Server Query Connecting but not Returning Records

Question: I have this VBA code that issues a SQL Server query after a successful connection but the query returns no records (e.g., -1)
Function invested_funds() As Integer
Dim c As ADODB.Connection
Dim rs As ADODB.Recordset
Dim connectionstring As String
Dim sql As String

connectionstring = "Provider=SQLOLEDB;Data Source=DESKTOP-2TTG3GQ\SQLEXPRESS;" & _
                   "Initial Catalog=DB;" & _
                   "Integrated Security=SSPI;"

Set c = New ADODB.Connection
Set rs = New ADODB.Recordset
c.Open connectionstring

sql = "select [DB].[dbo].[db].[CSRoot] " & _
      "from [DB].[dbo].[db] "

If c.State = adStateOpen Then
    Debug.Print ("Connected") 'This prints!
End If

Set rs = c.Execute(sql)
Debug.Print (rs.RecordCount)
invested_funds = CInt(rs.RecordCount)

End Function

However, I know records exist and the exact same query in SSMS does indeed return records
select  [DB].[dbo].[db].[CSRoot]
from [DB].[dbo].[db]

Many records, in fact.
How can this be?
Comment: Don't rely on `RecordCount`. Try iterating through record set.
Comment: `select [DB].[dbo].[db].[CSRoot] from [DB].[dbo].[db]` is not the same query as `select CSRoot from [DB].[dbo].[db]`. The first query is not even valid t-sql syntax.  Change your VBA code to use the second query
Comment: @squillman you're right. That was a typo on my part. Edited. Thanks for pointing it out.
Comment: I think you edited the wrong part of your question.
Comment: @Parfait you were absolutely right! `RecordCount` says -1 yet when I iterate through the set I see my records. Is it common knowledge that `RecordCount` is unreliable? Feel free to turn your comment into a question for credit.
Comment: If you do a `MoveLast` and then a `MoveFirst` you can typically get a reliable count.  When the cursor first opens it's positioned on the first record (assuming you got some hits from your SQL) - until you fetch all the records using `MoveLast` or by looping to `rs.EOF` you'll not know how many there are.  It's possible the database has sent you the first records before it has completed the query.
Comment: @TimWilliams thanks for this bit of knowledge. I had no idea.
Answer: You can get the number of records using the rs.getRows function.
Function invested_funds() As Integer
    Dim c As ADODB.Connection
    Dim rs As ADODB.Recordset
    Dim connectionstring As String
    Dim sql As String

    connectionstring = "Provider=SQLOLEDB;Data Source=DESKTOP-2TTG3GQ\SQLEXPRESS;" & _
                       "Initial Catalog=DB;" & _
                       "Integrated Security=SSPI;"

    Set c = New ADODB.Connection
    Set rs = New ADODB.Recordset
    c.Open connectionstring

    sql = "select [DB].[dbo].[db].[CSRoot] " & _
          "from [DB].[dbo].[db] "

    If c.State = adStateOpen Then
        Debug.Print ("Connected") 'This prints!
    End If

    Set rs = c.Execute(sql)

    Dim arr As Variant, n As Integer

    arr = rs.GetRows
    n = UBound(arr, 2) + 1
    'Debug.Print (rs.RecordCount)
    Debug.Print n
    invested_funds = n

End Function

Answer: A RecordCount of -1 does not mean that your query did not return any records (documentation):

The property returns -1 when ADO cannot determine the number of records or if the provider or cursor type does not support RecordCount.
[...]
The cursor type of the Recordset object affects whether the number of records can be determined. The RecordCount property will return -1 for a forward-only cursor; the actual count for a static or keyset cursor; and either -1 or the actual count for a dynamic cursor, depending on the data source.

The default value of CursorType is adOpenForwardOnly, so this behavior is expected. To get an actual count, use a CursorType of adOpenStatic or adOpenKeyset instead.


Calculating Confidence Interval

Question: How would one go solving for this?
You are told that a 95% CI for expected lead content when traffic flow is 15, based on a sample of n = 12 observations, is (468.1, 591.7). Calculate a CI with confidence level 99% for expected lead content when traffic flow is 15. (Round your answers to one decimal place.)
Thanks
Comment: We welcome questions like this, @JDAWG92, but we treat them differently. Please tell us what you understand thus far, what you've tried & where you are stuck, & we'll try to provide hints to get you unstuck. Please edit your question to add this information. To better understand the process, you should read the [wiki](http://stats.stackexchange.com/tags/self-study/info) for the `[self-study]` tag.
Comment: I added the `self-study` tag because this is a homework question. Also, you should show us what you've tried so far to attempt to answer the question.
Answer: A $c$% confidence interval for data $x_1,\ldots,x_n$ is defined as
$$ (\bar{x} - q_c\frac{s}{\sqrt{n}}, \bar{x} + q_c\frac{s}{\sqrt{n}})$$
where

$n$ is the number of samples,
$s$ is the sample standard deviation, and
$q_c$ is the appropriate quantile, the $(100-(100-c)/2)$th percentile of an appropriate distribution (usually the normal or t distribution, see below). In the case of $c=95\%$, $q_c$ is the $100-(5/2)=97.5$th percentile.

Assuming your data is normally distributed, you can use the t distribution with $n-1$ degrees of freedom for the quantiles: you can look the quantiles up in tables or use a software package.
Defining the standard error as $\sigma_M=s/\sqrt{n}$, the confidence interval can be written
$$ \;(\bar{x} - q_c\sigma_M, \bar{x} + q_c\sigma_M)$$
For further background search for "t confidence intervals". Khan academy is good and wikipedia is worth a look too.
That's the theory. To solve your problem what you need to do is:

Figure out what $q_c$ is for the given confidence interval with $c=95\%$ and $n=12$, looking up using the appropriate t distribution.
Given the width of the confidence interval, and the distance either side of the mean to the boundaries, solve for $\sigma_M$ and $\bar{x}$.
Figure out what $q_c$ is for the required confidence interval with $c=99\%$ in a similar way to what you did in step 1.
Use your new $q_c$ and $\sigma_M$, $\bar{x}$ to calculate the new confidence interval.

Calculating Confidence Interval


Gelfand triples form Brezis book

Question: Consider $H$ to be Hilbert space and $V$ to be a Banach space. Assume that $V\subset H$ is a linear subspace that is dense in $H$. Assume that injection $V\subset H$ is continuous. Brezis says: there is a canonical map $T\colon H^*\to V^*$ that is the restriction to $V$ of continuous linear functionals $\varphi$ on $H$, i.e.,
$$\langle T\varphi,v\rangle_{V^*\times V}=\langle \varphi,v\rangle_{H^*\times H}.\qquad (1)$$
What stands behind the existance of $T$? Why can we write (1)?
Answer: Let $S:V\to H$ be the inclusion, and set $T=S^*$.  Then for all $\varphi\in H^*$ and all $v\in V$ we have
$$T\varphi(v)=\varphi(Sv)=\varphi(v),$$
which is precisely $(1)$.

Gelfand triples form Brezis book


Using yiidocsgenerator extension to generate documentation

Question: I posted in the Yii forum with no luck. I am hoping someone in this community got this extension working because I really need it!
I used the yiic docs check command, and all the models seem to finally pass the check. So, I proceeded to executing this command:
yiic docs C:\path to my site\protected\models

And at first this appears onscreen:
Building.. : MyApplication Class Reference
Version... : 1.1.7
Source URL:

And then this error pops up:
Building model...
PHP Error[2]:include<GxActiveRecord.php>: failed to open stream: No such file or directory in file C:\path-to-my-app\yii\framework\YiiBase.php at line 396

Where, at that line, I have the following code:
include($className.'.php');

I don't understand why it is looking for a class I do not have!! I found it here, but I don't know in what specific folder that class should reside, or better yet why I should have to download it separately when it's not specified in the instructions. Thanks.
Comment: Turn on error logging to file, and check the backtrace of that error. You will see the call trace, and you can deduct where that class is required. Or just search your code base to locate that class. Probably it was generated using the giix tool and later the tool was removed.
Comment: @Pentium10 How do I turn on error logging to file?
Comment: Google it, there are plenty of articles on yii logging
Answer: Looks like you've generated models from giix which have GxActiveRecord as a base class and the doc parser does not find this base class, usually you've defined this as an import in your application config, so this may be an expected behavior.
You could try importing something like 'ext.giix.components.GxActiveRecord' in every one of your model classes  or copy GxActiveRecord into your models directory just for generating the docs.
Comment: Excellent! Thank you very much, I copied the GxActiveRecord class into my models directory and the problem was solved!


Pandas .pivot_table() reorder the index in chronological order

Question: Im trying to create a pivot table out of the seaborn flights dataset. When I come to make a pivot table for a heat map the index column is ordered alphabetically when I want to order it chronologically from Jan to Dec. Does anyone know how to do this? I have deleted the values in the pivot table to make it look tidier when I copied and pasted from Jupyter notebooks.
import pandas as pd
import seaborn as sns

#Loading dataset
flights = sns.load_dataset('flights')

#Calling dataset
flights

year    month   passengers
0   1949    January 112
1   1949    February    118
2   1949    March   132
3   1949    April   129
4   1949    May 121
... ... ... ...
139 1960    August  606
140 1960    September   508
141 1960    October 461
142 1960    November    390
143 1960    December    432

flights.pivot_table(values='passengers',index='month',columns='year')

year 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960
month
April   Values.....
August
December
February
January
July
June
March
May
November
October
September

Comment: what pandas version are you on with `pd.__version__`. I don't have this issue on `1.1.3`.
Comment: ^^^ Edit: it appears the issue might be the version of seaborn (not pandas) that you are on from StupidWolf's answer. Try upgrading to the latest version of seaborn if you can.
Answer: One way would be just reindex and provide the index list as follows:
Code :
import  calendar

month_names = [calendar.month_name[i] for i in range(1,13)]
# ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']

newdf = df.reindex(month_names)

Answer: I am on seaborn '0.10.1' and if you look at the data, it is categorical and sorted in the correct order:
flights.month.dtype

CategoricalDtype(categories=['January', 'February', 'March', 'April', 'May', 'June',
                  'July', 'August', 'September', 'October', 'November',
                  'December'],
                 ordered=False)

If you do pivot, it should be sorted correctly. Else you set it as a category:
flights['month'] = pd.Categorical(flights['month'], categories=flights.month.unique())


Unable to retrieve node object in a block without access permission to said node

Question: I'm trying to do a little statistics on nodes and display it on a block. I utilized menu_get_object('node', 1, $path) to get the node object of those nodes with the properties that I want.
So my problem is, in admin accounts, this works fine and well. however, in a normal user account, menu_get_object('node', 1, $path) returns null for any node that the normal user has no access to. is there any way to circumvent this?
So far I've tried using node_load(), and I also tried putting all the data analysis code inside a hook_cron(). Neither worked.
Using db_query() is not an easy task either, as I'm trying to obtain the node's parent node,and that parent's node parent node. That data is serialized. If it matters, I'm using Open Atrium, and I'm trying to obtain the topmost Space for a particular node.
Answer: What you can do is impersonate another user for a while. More details here https://www.drupal.org/node/218104
At the start of the function:
$session_prev_status = drupal_save_session();
drupal_save_session(FALSE);
global $user;
$actual_user = $user;
$impersonated_user = user_load(1); // This will impersonate user 1, an administrator.
$user = $impersonated_user;

Then, at the end of the function:
$user = $actual_user;
drupal_save_session($session_prev_status);


psql excluding records base on another table

Question: i am using postgres and wishing to exclude users that are currently in one table from another. at present i am trying do this via the ActiveRecord system within Rails.
So i need it to get the ids from my Availability table, then return that id into my User table to remove them if they are in the Availability table.
@availabilities = Availability.where(:event_id => params[:id]).all
@players = User.where('team_id = ? and id <> ?', current_user[:team_id], @availabilities).all

this is returning the following error
PG::Error: ERROR:  argument of WHERE must be type boolean, not type record
LINE 1: SELECT "users".* FROM "users"  WHERE (team_id = 1 and id <> ...
                                             ^
: SELECT "users".* FROM "users"  WHERE (team_id = 1 and id <> 101,102,103)

changed code as mentioned below, though the way i am doing it is still probably not ideal
@availabilities = Availability.where(:event_id => params[:id]).all
@exclude = Availability.where(:event_id => params[:id]).select(:user_id).pluck(:user_id)
if @exclude.count > 0
  @players = User.where('team_id = ? and id NOT IN (?)', current_user[:team_id], @exclude).all
else
  @players = User.where('team_id =?', current_user[:team_id])

Comment: If you don't want to hit the database again you could do `@exclude = @availabilites.map { |a| a.user_id }` instead.
Answer: You could do something like this:
@availabilities = Availability.where(event_id: params[:id]).pluck(:id)
@players = User.where(team_id: current_user[:team_id])
@players = @players.where('id NOT IN (?)', @availabilities) unless @availabilities.empty?

Using pluck() will return an array of IDs, then you can exclude them by using NOT IN (?)
Comment: only issue i have is if its null
Comment: Do you mean if the id array is empty? I've updated my answer.
Answer: Try:
id not in

The way pg engine sees it is ((team_id=1 and id <> 101), 102, 103). Thus the error you see.
Use it as:
User.where('team_id = ? and id not in (?)', current_user[:team_id], @availabilities).all


Adicionando mais input com jQuery

Question: Galera tenho um formulário simples com 3 input. Preciso informar uma quantidade no input 'qtd', e com isso preciso que o jQuery multiplique a tabela com o formulário, e mudando o 'name'.
Exemplo;
Se eu informar 3 no input 'qtd' vai aparecer 3 tabelas com os seguinte input: 'nome1','nome2','nome3','sexo1','sexo2','sexo3'.
Alguém sabe como posso fazer isso?

<input type='text' class='form_campos' name='qtd'>

      <input type='text' class='form_campos' name='nome1'>

      <input type='text' class='form_campos' name='sexo1'>

Answer: Creio ser isto que quer:

$('input[name="qtd"]').on('keyup click', function(){
  var qtd = $(this).val();
  $('#inputs table').remove();
  if(qtd > 0) {
      var appending = '
';
      for(var i = 1; i <= qtd; i++) {
         appending += '
\
                         nome' +i+ ': \
                             <input type="text" class="form_campos" name="nome' +i+ '" placeholder="nome' +i+ '">\
                         	\
                         sexo' +i+ ': \
                             <input type="text" class="form_campos" name="sexo' +i+ '" placeholder="sexo' +i+ '">\
                         	\

';
      }
      appending += '
';
      $('#inputs').append(appending);
  }
});

  <input type="number" class='form_campos' name='qtd' min='0'>

Comment: muito legal, é isso mesmo, mas teria como ele funcionar sem a necessidade de ter que clicar no botão enter? Ou seja, assim que eu alterar o valor ele ja monta o formulário
Comment: Assim não tem @HugoBorges. está no evento keyup/click. Mudei o input para ser number
Comment: era isso mesmo que eu quero, muito obrigado ;)
Comment: Ok, me tira uma dúvida? appending += é a variável que recebe o meu formulário certo. O problema e que o formulário que eu tenho aqui e muito grande, e fica complicado colocar tudo em 1 única linha, fica difícil para dar manutenção. como posso adicionar o html com a edentação do html?
Comment: @HugoBorges, editado em cima.. Assim fica mais legível
Comment: Desta maneira você só faz o append a tudo no fim, escusa de fazer uma vez por loop dentro do for que fica muito pesado @HugoBorges. Ainda simplifiquei mais o código agora, retirando o `else`
Answer: Eu consegui assim desta maneira, mas sem JQuery

function gera(){
var x = document.getElementById("qt").value;
 tab=document.getElementById("tables");
      tab.innerHTML='';
  for(i=1; i<=x ; i++)
    {

    tab.innerHTML+="

Nome "+i+":<input type='text' class='form_campos' name='nome"+i+"'>

Sexo "+i+":<input type='text' class='form_campos' name='sexo"+i+"'>

";
    }

}
<input type='text' class='form_campos' name='qtd' onkeyup="gera()" id="qt">

Comment: muito bom, e isso mesmo. So que teria como ele funcionar sem a necessidade de clicar no botão gerar? Ou seja criar um evento onChange, ou seja quando o usuário mudar o valor do input ele executa.
Comment: Já alterei o código ;)
Comment: muito bom, ficou bem simples ;) vlw
Comment: @PedroLuzio com esse codigo você está a adicionar várias tabelas (``)

Adicionando mais input com jQuery