Finding the biggest $k$ such $\sqrt{x_1^2+x_2^2+\dots+x_{n-1}^2+x_n^2} \geq k\min(|x_1-x_2|,|x_2-x_3|,\dots,|x_{n-1}-x_n|,|x_n-x_1|)$

Question: Given $n$ natural. Find the biggest real $k$ so for all $n$ real numbers $x_1,x_2,\dots,x_n$:
$$\sqrt{x_1^2+x_2^2+\dots+x_{n-1}^2+x_n^2} \geq k\min(|x_1-x_2|,|x_2-x_3|,\dots,|x_{n-1}-x_n|,|x_n-x_1|).$$
Tried by AMGM. But failed.
Comment: You can see this :http://math.stackexchange.com/questions/611302/how-find-this-inequality-max-left-min-lefta-b-b-c-c-d-d-e-e-a-ri
Comment: Stool can't get it from there.. But thanks
Answer: For any $n \ge 2$, let $k_n$ be the biggest $k$ that makes the inequality
$$\sqrt{\sum_{i=1}^n x_i^2} \ge k \min\bigg\{ |x_1-x_2|, \ldots, |x_{n-1}-x_n|,  |x_{n}-x_1| \bigg\}$$
valid for all $(x_1,\ldots,x_n) \in \mathbb{R}^n$. We are going to show $k_n$ is given by
the following formula:

$$k_n = \begin{cases}  \sqrt{\frac{n}{4}},& n \text{ even}\\
\sqrt{\frac{n+5}{4}}, & n \text{ odd} \end{cases}$$

Let $\mathcal{C}_n, \mathcal{C}'_n \subset \mathbb{R}^n$ be the set of $n$-tuples defined by
$$\begin{align}
\mathcal{C}_n &= \bigg\{ (x_1, \ldots, x_n )\in\mathbb{R}^n : | x_i - x_{i+1} | \ge 1, \forall 1 \le i < n \bigg\}\\
\mathcal{C}'_n &= \bigg\{ (x_1, \ldots, x_n )\in \mathcal{C}_n : |x_1 - x_n | \ge 1 \bigg\}
\end{align}$$
For any $x = (x_1, \ldots, x_n) \in \mathbb{R}^n$, let $\mathcal{V}(x)$ be the "unscaled " variances of $x_i$. More precisely,
$$\mathcal{V}(x) = \sum_{i=1}^n (x_i - \bar{x})^2 = \sum_{i=1}^n x_i^2 - n \bar{x}^2
\quad\text{ where }\quad \bar{x} = \frac{1}{n}\sum_{i=1}^n x_i$$
If $x_i \ne x_{i+1}$ for $1 \le i < n$ and $x_1 \ne x_n$, then we can scale $x$ by
$$\mu = \min\bigg\{\;|x_2 -x_1|, \ldots, |x_n - x_{n-1}|, |x_1 - x_n|\;\bigg\}$$
and make $\quad\displaystyle\frac{x}{\mu} = \left(\frac{x_1}{\mu},\ldots,\frac{x_n}{\mu}\right)\;\;$ and
$\;\;\displaystyle\frac{x-\bar{x}}{\mu} = \left(\frac{x_1-\bar{x}}{\mu},\ldots,\frac{x_n-\bar{x}}{\mu}\right) \in \mathcal{C}'_n$.
Notice
$$\mu^{-2}\sum_{i=1}^n x_i^2 \ge \mu^{-2}\sum_{i=1}^n (x_i - \bar{x})^2 =
\mu^{-2}\mathcal{V}(x-\bar{x}) = \mathcal{V}\left(\frac{x-\bar{x}}{\mu}\right) =
\mathcal{V}\left(\frac{x}{\mu}\right)$$
and this inequality becomes an equality when $\bar{x} = 0$. If one
compares this with the definition of $k_n$, we find:
$$k_n = \sqrt{ \inf \bigg\{\;\mathcal{V}(x) : x \in \mathcal{C}'_n\; \bigg\} }$$
There is another property of $\mathcal{V}(x)$ we need.
For any $x = (x_1,\ldots,x_m) \in \mathbb{R}^m$, $y = (y_1,\ldots,y_n)$$ \in \mathbb{R}^n$, we have
$$\mathcal{V}(x \oplus y) \ge \mathcal{V}(x) + \mathcal{V}(y)\quad\text{ where }\quad
x\oplus y = (x_1,\ldots,x_m, y_1,\ldots,y_n) \in \mathbb{R}^{m+n}$$
and the equality holds if and only if $\bar{x} = \bar{y}$.
One consequence of this is for any $x \in \mathcal{C}_{2k}$, $\mathcal{V}(x) \ge \frac{2k}{4}$.
We can prove this by induction on $k$.
The start case $k = 1$ is obvious. Assume this is true for a particular $k$. Then for any $x \in \mathcal{C}_{2k+2}$, we will rewrite it as $y \oplus z$ for some $y \in \mathcal{C}_2$, $z \in \mathcal{C}_{2k}$. This leads to
$$\mathcal{V}(x) = \mathcal{V}(y \oplus z) \ge \mathcal{V}(y) + \mathcal{V}(z) = \frac{2k}{4} + \frac{2}{4} = \frac{2k+2}{4}$$
and complete the induction step. Since $\mathcal{C}'_{n} \subset \mathcal{C}_{n}$,
we find for any even $n$,
$$\mathcal{V}(x) \ge \frac{n}{4} \quad\text{ for } x \in \mathcal{C}'_{n}.$$
In above inequality, the case of equality can be achieved by the configuration $$\left(\frac12,-\frac12,\ldots,\frac12,-\frac12\right) \in \mathcal{C}'_n,$$
From this, we can conclude $k_n = \sqrt{\frac{n}{4}}$ for even $n$.
Let us switch to the case for odd $n \ge 5$. For any $x = (x_1, \ldots, x_n) \in \mathcal{C}'_n$, consider following cyclic list of $n$ numbers:
$$x_2 - x_1,\;x_3 - x_2,\;\ldots,\;x_n - x_{n-1},\;x_1 - x_n$$
Since $n$ is odd, there is at least one successive pair whose sign is the same.
Since $\mathcal{V}(x)$ is invariant under cyclic permutation of components and under the
map $x \mapsto -x$. Without loss of generality, we only need to consider the case $x_1 < x_2 < x_3$. Once again,
rewrite our $x$ as $y \oplus z$ where
$$y = (x_1, x_2, x_3) \in \mathcal{C}_3 \quad\text{ and }\quad
  z = (x_4, \ldots, x_n ) \in \mathcal{C}_{n-3}$$
It is clear $\mathcal{V}(y) \ge 2$ and by the above discussion, $\mathcal{V}(z) \ge \frac{n-3}{4}$. Combining these, we get
$$\mathcal{V}(x) \ge \frac{n+5}{4}\quad\text{ for } x \in \mathcal{C}'_n$$
Once again, the case of equality is achievable. Consider the following configuration by
combining the equal-spacing and zero-hugging strategies in John Bentin's answer:
$$\left(-1,0,1,-\frac12,\frac12,\ldots,-\frac12,\frac12\right) \in \mathcal{C}'_{n}$$
From this, we can conclude $k_n = \sqrt{\frac{n+5}{4}}$ for odd $n \ge 5$. It is easy to check this formula also works for the case $n = 3$.
Comment: Very nice! I did stumble, though, on your third sentence "It is obvious $k_n$ is related to  $\mathcal{V}(x)$ through the relation [...]", which I read as saying that the result to be proved is obvious.
Comment: @JohnBentin I have expanded the answer a little bit. I hope it becomes obvious now.
Comment: The expansion is OK, although I didn't have an issue about these scaling details. The problem is that you introduce $k_n$ (which was not defined by the OP) at the beginning of your answer as $$k_n = \begin{cases}  \sqrt{\frac{n}{4}},& n \text{ even}\\
\sqrt{\frac{n+5}{4}}, & n \text{ odd} \end{cases},$$ and I took this to be the *definition* of $k_n$. Then the equation $$k_n = \sqrt{ \inf \bigg\{\;\mathcal{V}(x) : x \in \mathcal{C}'_n\; \bigg\} }$$ is not trivial: it is in fact a statement of what you go on to prove.
Comment: Good edit. I have taken the liberty of adding some small stylistic edits.
Answer: You need a positive lower bound for the differences $|x_j-x_{j+1}|$; otherwise there is no biggest $k$. Once such a bound, say $2a$, has been set, the answer depends on whether $n$ is odd or even. The easy case is when $n$ is even: then the LHS is minimized by $x_j=(-1)^ja$, and $k=\sqrt n/2$.
Now consider the case when $n$ is odd. Let us write $\mathbf{x}:=(x_1,...,x_n),$   $x_{n+1}:=x_1,$ and $\Bbb R_\neq^n:=\{x\in \Bbb R:|x_j-x_{j+1}|\neq 0\;(j=1,...,n)\}.$ For $\mathbf x\in \Bbb R_\neq^n,$ define $\lVert\mathbf x\rVert:=\sqrt{x_1^2+\cdots+x_n^2},$ $ \mu(\mathbf x):=\min\{|x_j-x_{j+1}|:j=1,...n\},$ and
$$\nu(\mathbf x):=\dfrac{\lVert\bf x\rVert}{\mu(\mathbf x)}.$$
The task is to minimize $\nu(\mathbf x)$ over $\mathbf x\in\Bbb R_\neq^n.$
Note first that $\nu(\xi \bf x) =\nu(\bf x)$ for any nonzero scalar $\xi.$ Thus we may scale $\bf x$ so that $\mu(\mathbf x)=2.$ Also, shifting the $x_j$ by a constant does not affect $\mu(\mathbf x);$ so we may take the mean of the $x_j$ to be $0$, to minimize the sum of their squares and hence $\lVert \bf x\rVert.$ In general, we try to follow the even case and place each $x_j$ as close to zero as possible; but the oddness of $n$ forces an outlier. So, taking $x_1,...,x_n$ to be regular and $x_n$ to be the outlier, we may choose
$$x_j=(-1)^j-\dfrac{3}{n}\;(j=1,...,n)\quad\text{with}\quad x_n=3-\dfrac{3}{n}$$
(the $-3/n$ term brings the mean to $0$). A straightforward calculation shows that $$\nu(\mathbf x)=\sqrt{\dfrac{(n-1)(n+9)}{4n}}.$$
However, observe that the outlier term $3-3/n$ is $2.4$ when $n=5,$ and its square makes a major contribution of 5.76 to the total sum of squares $\lVert \mathbf x\rVert^2=11.2.$ In this case, we can do better by equally spacing the $x_j$ around zero, with $x_1=-2, x_2=0, x_3=2, x_4=-1,$ and $x_5=1,$ so that $\lVert \mathbf x\rVert^2=10.$ When $n$ is odd and exceeds $5$, the equal-spacing strategy fails to beat zero-hugging with an outlier. Thus, for equal spacing, with $n\;(\geqslant 5)$ odd, we may take $x_1=(1-n)/2$ and $x_{j+1}\equiv x_j+2$ (mod $n$) for $j=1,...,n$ with $x_j\in\{(1-n)/2,...,(n-1)/2,$ and then the formula $\sum_{i=1}^ri^2=r(r+1)(2r+1)/6,$ where $r=(n-1)/2,$ gives
$$\nu(\mathbf x) = \sqrt{\dfrac{(n-1)n(n+1)}{48}},$$
and it is clear that
$$\sqrt{\dfrac{(n-1)(n+9)}{4n}} < \sqrt{\dfrac{(n-1)n(n+1)}{48}}$$
when $n\geqslant 7$.
In summary, $\nu(\bf  x)$ minimizes to $\sqrt n/2$ when $n$ is even, to $\sqrt 5/\sqrt 2$ when $n=5$, and to $\sqrt{(n-1)(n+9)/4n}$ when $n$ is odd and not $5.$
Comment: The zero hugging give us a good upper bound for the minimum but I failed to see why this upper bound is the minimum itself.
Comment: @achillehui: Thank you very much for the edit. (I wanted a square root without the vinculum; it seems that this isn't possible.) I agree that the minimality of zero-hugging with one outlier isn't proven here, although I'm convinced that it's true. I'm working on it!
Comment: Hmm.. a slight modification of the equal spacing strategy $$(x_1,x_2,\ldots) = -2,0,2,-1,1,-1,1,\ldots$$ gives us $\nu(x) = \sqrt{\frac{n+5}{4}}$. This beats the zero-hugging with one outlier strategy for all odd $n \ge 5$.
Comment: @achillehui: Agreed. Your pattern combines both strategies: It is the zero-hugger (and the equal-spacer) for $n=3$, and it continues zero-hugging for $n=5,7,9,...$; in the case $n=5$ only, it is just the equal-spacer.
Comment: The combined strategy is indeed the optimal one. see my answer.
Comment: unfortunately, the last one is $-1$ and we can't start at $0$.
Comment: @achillehui: With the first two terms inverted, your sequence is given by a beautifully simple procedure: "Hug zero, and accumulate two terms at a time". This works equally for the even and odd cases: respectively $1,-1;1,-1;...$ and $0;2,-2;1,-1;1,-1;...$. (A single arbitrary parity choice has to be made for the first nonzero term; the other choice generates the negative of the sequence.) We can start with $x_1=0$ in the odd case $n=1$ because min$\varnothing =\infty$ and $0/\infty=0$ by convention.
Comment: @Gory: As Achille Hui rightly points out above, my answer isn't quite there: his is the optimal one. I suggest that you transfer your acceptance to his more deserving answer.


require a module with webpack

Question: I use Webpack in order to build my javascript of my website.
Everything work perfectly but I would like to call require into a template (added dynamically).
I want to be able to require a module after the build. (require is not defined into the global context).
Is it possible ?
Thx
Answer: An option which is available to you now is to create a context which you expose globally on window. I've had success using the following snippet:
// Create a `require` function in the global scope so that scripts that have
// not been webpack'd yet can still access them.
window["require"] = function (module) {
    return require("./public_modules/" + module + ".js");
}

Basically what you're doing is exposing a folder to webpack and telling it to pack all the files in that folder in to a chunk. You can then type var moduleName = require("module-name") outside of a webpack'd script.
As long as the above snippet is inside a file which gets bundled and evaluated, you will have a function defined on window (coincidentally named "require" but you can call it anything) which will use webpack's require functionality.

require a module with webpack


Does $ \mathfrak{A} \models (\exists x) \phi $ imply that $ \phi[x / t] $ for some term $ t $. Second approach?

Question: If $ \mathfrak{A} \models (\exists x) \phi $, does it mean that $ \mathfrak{A} \models \phi[x / t] $ for some term $ t $?
$ \mathfrak{A} \models (\exists x) \phi $. It means that there exists $a \in A$ that $(\mathfrak{A}, s[x|a]) \models \phi$
So, the answer for problem is: Generally not, it depends.
If the term $t$ is such closed formula that $[t]_{\mathfrak{A}} = a$ the $\mathfrak{A} \models \phi[x/t] $ is satisfied. Otherwise, not.
Comment: Yes, we can add a constant, but, we have to add that constant to the signature of our strucutre. So, we modified a structure. Now, it is not the same structure $\mathfrak{A}$ still. So we cannot do it in that situation. Am I right? And thanks for referencing me to the book. It is really helpful.
Comment: Basically : YES. We can always "enlarge" the language adding a *constant* $\overline a$ denoting the objcet $a \in |\mathfrak A|$, i.e. such that $[\overline a] ^ {\mathfrak A} = a$. See : Dirk van Dalen, [Logic and Structure](https://books.google.it/books?id=u0wlXPHATDcC&pg=PA63) (5th ed - 2013) : **Definition 3.3.16**, page 63.
Comment: So, what is a model/structure? I was convinced that it is a triple: $\mathfrak{A} = <A, \Sigma^f_A, \Sigma^r_A$ where $\Sigma^f_A$ contains functional symbols, $\Sigma^r_A$ contains relations and $A$ is just universum for $\mathfrak{A}$. So, if we change one element ( we change a signature of functions) we change the triple.
Comment: Ok, So let $\mathfrak{A} = \langle A,R_1,\ldots, R_n, F_1,\ldots , F_m, \{ c_i \mid i ∈ I \} \rangle$. Now, I add the constant $a_c$. $a_c$ is a constant function- just name for $a$. So: $\mathfrak{A}_c = \langle A,R_1,\ldots, R_n, F_1,\ldots , F_m, a_c \{ c_i \mid i ∈ I \} \rangle $
Therefore, the structure $\mathfrak{A} \neq \mathfrak{A}_c$
Comment: ok, Does it depend on definition of the structure?
Answer: I think Mauro is answering a slightly different question than the one you're asking. There are examples of structures which "don't have enough terms" (structures and theories which do have enough terms are said to have the witness property or existence property). For example, any structure in a language which only has relation symbols! There are no terms at all in such a language (besides free variables), but of course we have plenty of true existential sentences - e.g. "$\exists x(x=x)$."
Mauro's point is that any structure $\mathfrak{A}$ has a canonical expansion $\mathfrak{A}_{+}$ where we add a new constant symbol for each element of the domain, and this expansion does indeed have the witness property. And it is frequently useful, in trying to understand $\mathfrak{A}$, to study $\mathfrak{A}_+$. However, the two are indeed different structures, and the general answer to you question is: no, the witness property does not always hold.
Comment: @logic Yes it is.
Comment: So, does my answer is correct?
Answer: We can see :

Herbert Enderton, A Mathematical Introduction to Logic (2nd ed - 2001), page 80 :

A structure for a first-order language will tell us :

What collection of things the universal quantifier symbol ($∀$) refers to, and
What the other parameters (the predicate and function symbols) denote.

Formally, a structure $\mathfrak A$ for our given first-order language is a function whose domain is the set of parameters [i.e. the symbols of the language] and such that

$\mathfrak A$ assigns to the quantifier symbol $∀$ a nonempty set $|\mathfrak A|$ called the universe (or domain) of $\mathfrak A$.
$\mathfrak A$ assigns to each $n$-place predicate symbol $P$ an $n$-ary relation $P^{$\mathfrak A} \subseteq |\mathfrak A|^n$; i.e., $P^{$\mathfrak A}$ is a set of $n$-tuples of members of the universe.
$\mathfrak A$ assigns to each constant symbol $c$ a member $c^{$\mathfrak A}$ of the universe $|\mathfrak A|$.
$|\mathfrak A|$ assigns to each $n$-place function symbol $f$ an $n$-ary operation $f^{$\mathfrak A}$ on $|\mathfrak A|$; i.e., $f^{$\mathfrak A} : |\mathfrak A|^n \to  |\mathfrak A|$.

Thus : YES, if we "enlarge" the language adding more constant symbols, we modifiy the structure because we have to modify the point 3 above of the mapping.

Setting apart the terminology, this is very similar to what happens in Computability & Logic, page 117 :

Let us say that in the interpretation $\mathcal M$ the individual $m$ satisfies $F(x)$, and write $\mathcal M \vDash F[m]$, to mean "if we considered the extended language $L \cup \{ c \}$ obtained by adding a new constant $c$ in to our given language $L$, and if among all the extensions of our given interpretation $\mathcal M$ to an interpretation of this extended language we
  considered the one $\mathcal M^c_m$ that assigns to $c$ the denotation $m$, then $F(c)$ would be true":

$\mathcal M \vDash F[m]$ if and only if $\mathcal M^c_m \vDash F(c)$.

(For definiteness, let us say the constant to be added should be the first constant not in $L$ in our fixed enumeration of the stock of constants.)
Comment: Therefore, my answer is correct in the sense of Enderton's definition, yes?


What is the SQL query to filter og Admin Accounts?

Question: I currently have the following SQL statement that gives me a list of all of my og nodes and their associated owner. I am having trouble nesting my JOIN statements to add the name of the owner from the users table. Any hints? Thanks
SELECT
    label AS `Group Name`,
    gid AS `Group ID`,
    etid AS `Node ID`,
    type AS `Type`,
    b.nid AS `Owner ID`
    FROM `prefix_og` a
        LEFT JOIN `prefix_node` b
            ON a.etid=b.nid

Answer: This worked nicely... how can I make this available in a view?:
SELECT
a.label AS `Group Name`,
a.gid AS `Group ID`,
a.etid AS `Node ID`,
b.type AS `Type`,
b.uid AS `Owner ID`,
c.name AS `Owner Username`,
d.realname AS `Owner Realname`,
e.rid AS `OG Role ID`
FROM `prefix_og` a
LEFT JOIN `prefix_node` b
ON a.etid=b.nid
LEFT JOIN `prefix_users` c
ON b.uid=c.uid
LEFT JOIN `prefix_realname` d
ON b.uid=d.uid
LEFT JOIN `prefix_og_users_roles` e
ON b.uid=e.uid


What are all the portlet classes in Spring mvc?

Question: In Spring MVC there seem to be two parallel class hierarchies, one with portlet, one without.
What is that? Why is it so and what should I use.
Answer: That's because

In addition to supporting conventional
  (servlet-based) Web development,
  Spring also supports JSR-168 Portlet
  development. As much as possible, the
  Portlet MVC framework is a mirror
  image of the Web MVC framework, and
  also uses the same underlying view
  abstractions and integration
  technology.

The Spring documentation (Chapter 16. Portlet MVC Framework) provides more information about the differences.
To answer your last question: you should use the Portlet MVC framework if you are developing portlets (web applications to be deployed in a portal). If you are developing conventional web applications you should use the Web MVC framework.
Answer: You mean as opposed to servlet?  The portlet MVC framework is specifically for development of JSR-168 (maybe JSR-286 too? not sure) portlets.  There is a separate portlet hierarchy because the portlet MVC workflow differs from the servlet MVC workflow.
If you're developing a portlet, you want the portlet MVC framework.  Otherwise, the Servlet MVC framework is what you need and you don't need to worry about the portlet stuff.


Derivative of an integral with parameter

Question: I want to know how to calculate the derivative of this integral, assuming that all our functions are bounded and smouths on some interval of $\mathbb{R}$:
$$
F(x)=\int_{\phi(x)}^{\psi(x)} f(x,t) dt
$$
Comment: http://www.econ.yale.edu/~pah29/409web/leibniz.pdf
Answer: The general formula is $$ F'(x) =\cfrac{d}{dx} \int_{\phi(x)}^{\psi (x) } f(x,t) dt = \cfrac{d \psi(x)}{dx} f(x,\psi(x)) - \cfrac{d \phi(x)}{dx} f(x,\phi(x)) + \int^{\psi(x)}_{\phi(x)} \cfrac{\partial f(x,t)}{\partial x} dt $$
For more: See this.
Answer: This is the Leibniz integral rule, aka differentiating under integral sign:
$$
F'(x)=f(x,\psi(x))\psi'(x)-f(x,\phi(x))\phi'(x)+\int_{\phi(x)}^{\psi x}\frac{\partial}{\partial x}f(x,t)\,\mathrm{d}t
$$
Answer: The Leibniz integral rule states that:
$$\frac{d}{dx}\int_{a(x)}^{b(x)}f(x,t)dt=f(x,b(x))\frac{db(x)}{dx}-f(x,a(x))\frac{da(x)}{dx}+\int_{a(x)}^{b(x)}\frac{\partial}{\partial_x}f(x,t)dt$$
and so if we have:
$$F(x)=\int_{\phi(x)}^{\psi(x)}f(x,t)dt$$
we get:
$$F'(x)=f(x,\psi(x))\psi'(x)-f(x,\phi(x))\phi'(x)+\int_{\phi(x)}^{\psi(x)}f_x(x,t)dt$$


ASP.NET CheckBox Control showing as a Literial

Question: I have a nested repeater that contains a CheckBox control.
<asp:Repeater runat="server" ID="optionalRepeater" OnItemDataBound="CheckCompCondiments">
    <HeaderTemplate>

            Product Extras

    </HeaderTemplate>
    <ItemTemplate>

            <asp:HiddenField runat="server" ID="salesMenuID" Value='<%#Eval("sales_menu_id") %>' />
            <asp:HiddenField runat="server" ID="minVal" Value='<%#Eval("minVal") %>' />
            <asp:HiddenField runat="server" ID="maxVal" Value='<%#Eval("maxVal") %>' />

                <asp:Label runat="server" ID="condHdr" style="text-decoration: underline;" Text='<%#Eval("sales_menu_desc") %>'></asp:Label>

            <asp:Repeater runat="server" ID="compMenuRadio">
                <HeaderTemplate>

                </HeaderTemplate>

                <ItemTemplate>
                    <asp:HiddenField runat="server" ID="hdPriLvl"/>
                    <input type="radio" name="compSelect" runat="server"/>
                </ItemTemplate>
                <FooterTemplate>

                </FooterTemplate>
            </asp:Repeater>

            <asp:Repeater runat="server" ID="compMenuCheck">
                <HeaderTemplate></HeaderTemplate>
                <ItemTemplate>

                    <asp:HiddenField runat="server" ID="hdPriLvl" Value='<%#Eval("pPriceLvl") %>' />
                    <asp:CheckBox runat="server" ID='compSelected' CssClass='<%# Eval("pcode") %>' Text='<%# Eval("pdesc") %> '/>
                    <%--<input type="checkbox" id="compSelect" runat="server" value='<%#Eval("pCode") %>'/>--%>
                    <%--  <%#Eval("pDesc") %>--%>

                </ItemTemplate>
                <FooterTemplate>

                </FooterTemplate>
            </asp:Repeater>

            <asp:DropDownList runat="server" ID="compSelect" Visible="False" style="width: 98%; margin: 5px 0px 5px 0px;"/>

    </ItemTemplate>
</asp:Repeater>

On my Server Side I have the following code:
if (optionalRepeater.Items.Count > 0)
{
    foreach (RepeaterItem compItem in optionalRepeater.Items)
    {
        HtmlInputHidden priLvlVal = (HtmlInputHidden)compItem.FindControl("hdPriLvl");

        foreach (Control compCtrl in compItem.Controls)
        {
            if (compCtrl.GetType() == typeof(CheckBox))
            {
                CheckBox checkBox = (CheckBox)compCtrl;
                CheckBox chk = (CheckBox) checkBox;

                if (checkBox.Checked)
                {
                    string prod = checkBox.CssClass;
                    string childGuiud = Guid.NewGuid().ToString("N").ToUpper();
                    hasCondiment = true;
                    ShoppingCart.Instance.AddItem(prod, childGuiud, mainGuid, Session["transactionGuid"].ToString(), priLvlVal.Value, hasCondiment, 1, null);
                    checkBox.Checked = false;
                }
            }

        }
    }
}

My code get as far as this line
if (compCtrl.GetType() == typeof(CheckBox))

But never makes it inside the if statement. When I am expecting the type to be CheckBox it says literal Control.
Can anyone see anything that I could be doing wrong, I have been looking at this for a while now and I can't seem to get any further.
Thanks,
Somango!
Answer: If you use an ItemTemplate you have to use FindControl to get the reference of the controls inside:
foreach (RepeaterItem compItem in optionalRepeater.Items)
{
    HtmlInputHidden priLvlVal = (HtmlInputHidden)compItem.FindControl("hdPriLvl");
    CheckBox compSelect = (CheckBox)compItem.FindControl("compSelect");
    if (checkBox.Checked)
    {
        // ...
    }
}

By looping the RepeaterItem.Controls property you just find a single Literal control which is the container for every control in the ItemTemplate. So you could loop compItem.Controls[0].Controls to find your CheckBox. But in my opinion using compItem.FindControl is much more readable.
Comment: Thanks for your response Time. I tried your solution but it was throwing an error because of my DropDown box with the same ID. I've updated the question to include the parent repeater as well. I should have done that in the first place.
Comment: @somango: then find your inner repeater first via `FindControl` and then loop that items and get the `CheckBox` via `innerItem.FindControl("compSelect")`. As an aside, why don't you use a `CheckBox` instead of `input type="radio"` if you need to access it on serverside?
Comment: I'm marking this as the correct answer. Although it wasn't actually what I used, it set me on the right track, I now have my application working as expected so Mr Tim Schmelter to you I say Vielen Dank!!


How to pop up a dialog box at 8pm (20:00 hours) every day using java?

Question: I have a written a java code to popup a dialog box every day at 8pm (20:00 hours). However the code worked for the first time only and didn't work later after I changed the time. This is my code:
import java.util.Calendar;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;
import javax.swing.JOptionPane;

public class PopUp {

public static void main(String[] args) {
    Timer timer = new Timer();
    TimerTask tt = new TimerTask() {
        @Override
        public void run() {
            Calendar cal = Calendar.getInstance();

            int hour = cal.get(Calendar.HOUR_OF_DAY);
            int min = cal.get(Calendar.MINUTE);
            int sec = cal.get(Calendar.SECOND);

            if (hour == 20 && min == 00 && sec == 0) {
                JOptionPane.showMessageDialog(null, "PopUp Success at "+new Date().toString());
                System.out.println("PopUp Success at "+new Date().toString());
            }
        }
    };
    timer.schedule(tt, 1000, 1000 * 5);
}

}

Is there anything wrong with my code? Plz help me out in solving this issue to popup the dialog box every day at 8pm.
Comment: The problem I'm seeing is that this would have to stay running in the background. I know if I got an update I would probably just quit the program and that would be it. Maybe create a bash script that is run on startup which then prompts the user by opening your dialog widow program. https://stackoverflow.com/questions/17394356/how-can-i-make-a-bash-command-run-periodically
Comment: There are loads of examples of similar programs out there. Use your search engine.
Comment: I had seen a lot of programs out there but none solved my problem. Can you plz give an example or atleast provide a link where I can get the solution?
Answer:
Is there anything wrong with my code?

Your timer task checks the time, precisely the hour, minute and second. You are scheduling this task with a periodic delay of 5 second (1000 * 5 milliseconds). This means that you are unlikely to hit 20:00:00 exactly. You may for example check at 19:59:57 and then again at 20:00:02, or even 20:00:03 since each check takes a bit of time and timing is never accurate.
Apparently you were lucky the first time but haven't been the succeeding times.
A possible fix is to use one of the two overloaded scheduleAtFixedRate methods with a period of 1 day. Then your timer task when invoked can trust that the time has come and needs not check. I would specify 1 day as TimeUnit.DAYS.toMillis(1), it's clearer to read and less error-prone than some multiplication.
You may also consider using the scheduling capability of your operating system rather than coding your own. Reinventing the wheel is often a poor investment.
Calendar is outdated
The Calendar class you are using is long outdated and poorly designed. I recommend you look into java.time, the modern Java date and time API, for a replacement.
Unfortunately scheduleAtFixedRate(TimerTask, Date, long) takes an argument of a type that is at least as outdated, java.util.Date. To obtain a Date using java.time:
    ZoneId zone = ZoneId.of("Asia/Chungking");
    ZonedDateTime at2000 = LocalDate.now(zone)
            .atTime(LocalTime.of(20, 0))
            .atZone(zone);
    if (at2000.isBefore(ZonedDateTime.now(zone))) {
        // Time has passed for today; use tomorrow
        at2000 = at2000.plusDays(1);
    }
    Date dateForScheduler = Date.from(at2000.toInstant());

Of course use your own time zone where I put Asia/Chungking.
Links

Oracle tutorial: Date Time explaining how to use java.time.
Timer.scheduleAtFixedRate documentation
Comment: Good to hear. Thx for reporting back. If your time zone uses summer time (daylight saving time) or other changes in time, the fixed rate of 1 day will not give you the correct time across such transitions. Then you will need some other solution.


How to check for linear constraints of coefficients in logistic regression in R?

Question: I have a logistic regression model with several variables. I want to test the hypothesis of, say $a \beta_i = b \beta_j$ for constants $a,b$. I know that this can be theoretically done with an $F$-test; but how do I technically do it in R?
What about in the case where I have a factor variables, to the different variables are in fact the dummy variables corresponding to the different levels?
Answer: In linear regression, you'd certainly use an F-test.
In logistic regression the distribution of the corresponding likelihood ratio test statistic (that for $-2 \log \Lambda$) is asymptotically chi-square.
[For some kinds of GLM, some people make an argument that an F-test should be used in GLMs with small samples (presumably because it's based on a ratio of scaled deviances). Despite its intuitive appeal, I haven't yet seen a convincing argument that this has better properties (specifically, either closer to nominal significance level, or better power, or both) than the chi-square one in small samples for those cases. But those arguments are for when the variance parameter, $\phi$ is estimated. I don't think those arguments apply to logistic regression, where $\phi=1$.]
The basic calculation is as follows:
Compute the deviance for the full model. Compute the deviance for the reduced model. Under the null, the difference should be chi-square, with df equal to the difference in degrees of freedom in the two models (with a single restriction such as yours, that would be 1 df).
So the question becomes 'how do we fit the reduced model to get the deviance?'
Some packages may let you specify such restrictions, but it's easy enough to do.
Let's say you have a model like: $\quad \eta = \beta_0 + \beta_1 x_1 + \beta_2 x_2 + \beta_3 x_3$
and you want to fit a reduced model which has $4 \beta_2 = 5 \beta_3 $.
Step 1: rewrite that so one of the variables is "by itself": $\beta_3 = \frac{4}{5} \beta_2$
Step 2: substitute for that lone variable in the original equation:
$\quad \eta = \beta_0 + \beta_1 x_1 + \beta_2 x_2 + \frac{4}{5} \beta_2 x_3$
Step 3: combine the $x$'s so that the repeated $\beta$ only appears once:
$\quad \eta = \beta_0 + \beta_1 x_1 + \beta_2 (x_2 + \frac{4}{5} x_3)$
Step 4: call that "combined" result a new x-variable, say $x_c$, and compute that combination of the other variables: $x_c = x_2 + \frac{4}{5} x_3$, creating a new set of values for the new independent variable.
Step 5: fit the corresponding model:
$\quad \eta = \beta_0 + \beta_1 x_1 + \beta_2 x_c$
That's the reduced model. If the change in deviance between that and the full model is large, you'll reject the null, and if it's small, you won't.
As for how to do it in R with factor variables, there may be a much more efficient way to do it, but I'd probably generate the indicator variables (the output of applying model.matrix to the model), do the above manipulations and convert to working as if  the factor or factors involving the relevant variables were 0-1 (numeric) variables (but leaving any  untouched factors as factors).
However, it looks like there are packages that will help with that; the package mcprofile looks like it will do linear restriction fits and contrasts for you (e.g. orglm.fit). I've never used this.
See also comments on this question.


Help me understand 'equivalence classes' and relations

Question: I'm reading up on binary relations and I understand them to be a mapping from one set into another.
However I'm having problems understand 'equivalence classes'. My book only gives a pretty dry explanation.
If you could give a good tangible explanation of equivalence relations and equivalence classes, that would be great!
Comment: Can you explain in what sense a binary relation is a mapping from one set into another?
Comment: @anon In the sense that binary relations can be seen as sort of "loose" functions (may not be defined everywhere and may have more than one image). To be able to define the properties of equivalence relations you need that the "domain" and the "codomain" are one and the same, though.
Answer: Let $X$ be a finite set and $R \subseteq X^2$ be some binary relation. Then $R$ is very similar to a directed graph that has elements of $X$ as vertices, or in other words, $R$ can be drawn as dots and arrows. The following example depicts a graph and corresponding relation.
$$
\begin{array}{ccc}
1 &\to& \stackrel{\curvearrowright} 2 \\
\downarrow & & \updownarrow\\
3 & \gets & 4
\end{array}
$$
$$
\{(1,2),(1,3),(2,2),(2,4),(4,2),(4,3)\}
$$
Now, to talk about equivalence classes we need an equivalence relation. How an appropriate graph looks like?

It has to be reflexive, that is, each vertex $v$ has to have a loop $\stackrel{\curvearrowleft}v$ like $2$ in the previous example.
It has to be symmetric, i.e. each edge of the graph has to be bidirectional, like $\{2,4\}$ in the above diagram. If all the edges are bidirectional, then such graph is called undirected.
It has to be transitive. This means that the graphs includes all the possible "shortcuts", i.e. if you can get from vertex $u$ to $v$, then there is an edge $u \to v$, or in case of undirected graphs $u \leftrightarrow v$.

The above conditions together imply that if some two vertices are connected, then they belong to a clique (a graph that has all the possible edges, modulo loops), that is, each connected component forms a clique. These cliques are precisely the equivalence classes. In the following diagram we have two: $\{1,2,3,4\}$ and $\{5,6,7\}$ (loops omitted for clarity).
$$
\begin{array}{ccc}
1 &\leftrightarrow & 2 &  & 5 & \leftrightarrow & 6\\
\updownarrow & \swarrow\hspace{-10pt}\nearrow\hspace{-10pt}\nwarrow\hspace{-10pt}\searrow & \updownarrow & &\updownarrow & \swarrow\hspace{-10pt}\nearrow\\
3 & \leftrightarrow & 4 & & 7
\end{array}
$$
Observe, that if we would add edge $4 \to 5$ then symmetry would require also $5  \to 4$ and then transitivity would add all the other edges. The two clusters would merge into a single equivalence class, i.e. the graph would become the $K_7$ clique.
This intuition also holds for infinite sets, but it's hard to draw infinite graphs.
I hope this helps $\ddot\smile$
Comment: I never thought of equivalence relations as groupoids, thanks!
Comment: @A.P. See [here](http://en.wikipedia.org/wiki/Groupoid#Equivalence_relation). Also, [MathWorld](http://mathworld.wolfram.com/Groupoid.html) suggests an inverse intuition: <>
Comment: @A.P. On the other hand, I prefer the graph-theory-based intuition. In fact, this was my primary intention and I was quite surprised by your comment. Anyway, I'm glad I could help $\ddot\smile$
Comment: Thanks for the pointers. I just happen to be biased towards recognising category-like graphs as such. ;)
Comment: very nice!.....
Answer: An equivalence relation on a set $X$ is a binary relation $R\subset X\times X$ such that the following three properties hold:

Reflextivity: $xRx$, or $(x,x)\in R$ for every $x$ in $X$.
Symmetry: $xRy \leftrightarrow yRx$ or $(x,y)\in R$ if and only if $(y,x)\in R$.
Transitivity: $xRy \wedge yRz \rightarrow xRz$, or that if $(x,y), (y,z)\in R$, then $(x,z)\in R$.

An equivalence class is a subset $E$ of $X$ such that the following holds: if $x,y\in E$, then $(x,y)\in R$ (i.e. $xRy$), and if $x$ is an element of $E$ and $y$ is an element of $X$ such that $xRy$, then $y$ is also an element of $E$.  That is, it is closed under the relation and only contains the elements that are 'equivalent'.
The idea is that an equivalence relation gives us a new way of saying whether or not two objects should be viewed as essentially the same thing; the equivalence classes are then the sets after grouping all the equivalent things together, and they form a way of partitioning the set into these 'sets of equivalent things'.
This mention of partitions is actually an important thing; it ends up that a partition of a set uniquely determines an equivalence relation, and vice-a-versa.  It is not hard to show that the set of equivalence classes is a partition of $X$ and given a partition, we can define a relation $R$ where $(x,y)\in R$ if and only if $x$ and $y$ lie in the same part of the partition; it can be checked rather easily that this is an equivalence relation.
Answer: I will assume that you know the definition of an equivalence relation on a set $A$.
Here is an example which may help:  Consider the set of all integers, $\mathbb{Z}$, and define and equivalence relation on $\mathbb{Z}$ by $a$ ~ $b$ if $a = b + 3k$ for some integer $k$.  Then there are three equivalence classes, $A_0, A_1, A_2$ where $A_j$ represents all the integers that leave a remainder of $j$, $0 \leq j \leq 2$ when divided by the number $3$.  Note that we have decomposed $\mathbb{Z}$ as $A_0 \cup A_1 \cup A_2 = \mathbb{Z}$ and that the sets $A_j$ are disjoint.
Answer: Actually, binary relations are more like "loose" mappings: they do not need to be defined everywhere on their domain and any point can have more than one image.
Formally, an equivalence relation on a set $X$ is a binary relation $\rho$ defined on $X$, that is a subset $\rho$ of $X\times X$, such that for every $x,y,z\in X$:

$x\rho x$ (reflexivity)
$x\rho y$ implies $y\rho x$ (symmetry)
$x\rho y$ and $y\rho z$ imply $x\rho z$ (transitivity)

where we (customarily) write $x\rho y$ for $(x,y)\in\rho$. Now, from these properties we can see that $\rho$ induces a partition on $X$, namely a collection $P$ of subsets of $X$ such that

$\varnothing\notin P$
the union of all elements of $P$ is the whole space $X$
$S_1\cap S_2=\varnothing$ for any two distinct $S_1,S_2\in P$

Indeed, for every $x\in X$ define $[x]=\{y\in X : x\rho y\}$. Then:

by reflexivity $x\in[x]\neq\varnothing$
$X\supseteq \bigcup_{x\in X} [x] \supseteq \bigcup_{x\in X} \{x\} = X$
$z\in[x]\cap[y]\neq\varnothing$ implies $x\rho y$ by transitivity and symmetry, which then implies that $[x]=[y]$

Therefore the set $P=\{[x]:x\in X\}$ is indeed a partition of $X$. The equivalence classes of $\rho$ are exactly the elements of this partition.
Vice-versa, a partition $Q$ of $X$ induces an equivalence relation $\sigma$ on $X$ simply by defining $x\sigma y$ iff $x,y\in S$ for some $S\subseteq X$ (prove it!).
Finally, it is a nice, not so difficult, exercise to show that those two operations are actually the inverse of each other: the partition $P$ induced by a relation $\rho$ induces again $\rho$ and the relation $\sigma$ induced by a partition $Q$ induces again $Q$.
Answer: Binary relations and equivalence classes are two basic notions that we all learn at the very beginning of school. By this I am saying that you actually very well know what they are and how they work.
It is only due to the bad influence of Bourbaki, the formalism that was important to address some problem in logic (like consistency) that those dry expositions have permeated areas of mathematics in which they are absolutely not needed, and even become detrimental.
I will use pictures to explain what are these two notions. I will use pictures because it is with pictures we (I) learned (in the first year we entered school in our life) what this concepts are.
Binary relation
In kindergarten they used to gives us pictures of a row of bees and a row of flower pots.
We were supposed to draw arrows indicating what flowers each bee likes. There were different requirements about the preferences depending on the exercise and the skill the teacher wanted to teach. But a totally freely chosen set of arrows going from the bees to the flowers is what a relation is.
If we require, for example, that a bee has only one favorite flower then we get a a relation that is what we call a function from bees to flowers.
If we add to this the requirement, for example, that each flower should have no more than one bee that likes it, they we get a relation that is what we call an injective function from the bees to the flowers.
And so on.
Equivalence class
We had this other type of exercise in kindergarten. We were given a figure with many objects: flowers, tools, people, ...
We were given a feature, and we were supposed to enclose in blobs figures that had that feature in common.
For example, we could be told to group figures by color, or by use, or by kingdom, etc.
Something like this.

This breaking into classes is what an equivalence relation is.
Comment: I suggested an improvement, because I think your post is a bit misleading (notice that I did not downvote). However, nobody forces you to take good advice (I won't edit your answer against your will). On the other hand, I would say that your last comment is dangerously close to name-calling and there are users that might take offence. Perhaps you have a bad day, it happens to all of us. Nevertheless, people in this community have generally good intentions, please consider this the next time you will be writing a reply.
Comment: Your example deals with a very specific equivalence relation, namely one where there are two objects in each equivalence class. You picked a nice approach, but that's a bad example.
Comment: Indeed, in elementary school we are given some basics about set theory and binary relations. I would like to point out, though, that you only described binary relations in general (without a word about *equivalence* relations). Moreover, what you describe as equivalence classes are just subsets. For example suppose we are asked to group the figures in the picture by colour: then the paint bucket would go in the same set as the brush, which would go in the same set as the baseball glove. Thus by transitivity the bucket and the glove are in the same subset, although they don't share any colour.


Ember.js route transitionTo method not working

Question: I have a nested route, and from the action I am transitioning to a different route with query-params, but transitionTo does nothing, doesn't even report an error.
The {{link-to}} helper works fine, though. But I need to do it with an action.
routes.js:
this.route('parent-route', function() {
    this.route('child-route1');
    this.route('child-route2', {path: '/child-route1/child-route2/:param1/:param2'});
  });

child-route1:
actions: {
    doTransit() {
        this.transitionTo('parent-route.child-route2', {query-params: {'param1': '1', 'param2': '2'}});
    }
}

I have never seen this problem before, what could I be doing wrong?
May be the extra route-name I put in the routes.js file in child-route2? But I need that path there so the URL shows that stuff. Any help, please?
Answer: Maybe try using
this.transitionToRoute('parent-route.child-route2', '1', '2')


Solving the recurrence: $h(i) = h\left(\left\lfloor\frac{i+1}{d}\right\rfloor\right)+1 $

Question: I want to solve the following recurrence:
\begin{equation}
h(1) = 0\\
h(i) = h\left(\left\lfloor\frac{i+1}{d}\right\rfloor\right)+1
\end{equation}
What are some basic "methods" I can use to guess a closed form of this recurrence? I see that I am dividing by $d$ and this would mean that I am doing repeated division which would imply some sort of $\log_d$ term. Is this correct?
What is the closed form of this recurrence?
Comment: Do you mean $h(0) = 0$, not $h(1) = 0$? You'll need $h(0)$ to compute $h(i)$ for any $i < d-1$.
Answer: If it's
$$\begin{equation}
h(0) = 0\\
h(i) = h\left(\left\lfloor\frac{i+1}{d}\right\rfloor\right)+1
\end{equation}$$
then
$$h(i)=\left\lfloor \log_{d}{\frac{d-1}{d-2}i}\right\rfloor+1$$
Solution (I believe that it contains mistake I couldn't find because it gives different result):
Will use this later $$a\leq\left\lfloor\frac{i+1}{d} \right\rfloor < b \Longleftrightarrow ad-1\leq i < bd-1$$
Also such definition will be useful
$$a_n=\min \left\{ i \vert f(i)=n\right\}$$
Then (without proof here)
$$f(i)=n \Longleftrightarrow a_n \leq i<a_{n+1}$$
Because $f(i)=n+1$ iff $f\left(\left\lfloor\frac{i+1}{d}\right\rfloor\right)=n$
$$f(i)=n+1 \Longleftrightarrow a_n \leq \left\lfloor\frac{i+1}{d}\right\rfloor<a_{n+1}\\
f(i)=n+1 \Longleftrightarrow da_n-1 \leq i < da_{n+1}-1$$
So
$$a_{n+1}=da_n-1, \ a_1=1, a_2=d-1$$
gives
$$a_n=d^{n-1}-d^{n-2}-...-d-1=2d^{n-1}-\frac{d^n-1}{d-1}=\frac{(d-2)d^{n-1}+1}{d-1}$$
Next step is to get $n$ from inequalities $\frac{(d-2)d^{n-1}+1}{d-1}\leq i < \frac{(d-2)d^{n}+1}{d-1}$:
$$\frac{(d-2)d^{n-1}+1}{d-1}\leq i < \frac{(d-2)d^n+1}{d-1}\\
(d-2)d^{n-1}+1\leq (d-1)i < (d-2)d^n+1 \\
(d-2)d^{n-1}\leq (d-1)i-1 < (d-2)d^n \\
d^n\leq d\frac{(d-1)i-1}{d-2} < d^{n+1} \\
n=\left\lfloor \log_{d}{\frac{(d-1)i-1}{d-2}}\right\rfloor+1
$$
And $h(i)$ is equal to this value of $n$.


how to prevent windows server massive login tries

Question: i've been looking to a windows 8 web server eventlog on security option and i'm wordless with the ammout of audit failure logs.
what i'm trying to understand is that i've very, very much audit failures with the "Failure Reason: Unknown user name or bad password." i've seen too that failures are tries with multiples account names for multiple ports.
Some idea how can i prevent that? i've no idea how to start...
Comment: http://serverfault.com/questions/201298/why-should-i-firewall-servers
Answer: There will, even under normal operation, be audit failures constantly as services try legacy methods and such.  However, if you see consistent remote authentication failures with random usernames or actual usernames, it's a bruteforce attack.  The source port is probably not relevant.
If the server doesn't need to be listening to the internet on the service that is being attacked, it shouldn't.  Firewall it.  In fact, you should generally have a firewall around the server that denies access to everything except what is necessary.  What specifically those things are depends very much on your environment and what the server is for (there is no One True Firewall Ruleset).
If the login attempts are on a service that you do need to be listening on, you should consider deploying an IPS of some kind to help limit the bruteforce.  Keep in mind also that with strong passwords, the odds of an attack like this succeeding are comparable to the odds of winning a lottery.
If you notice that the failed attempts seem to be coming from your internal network and aren't related to someone fat-fingering a password or a service of some kind automatically trying to log in with the wrong password (a certain number of authentication failures are normal in all environments), investigate the possibility of a compromised host.


Semi-direct v.s. Direct products

Question: What is the difference between a direct product and a semi-direct product in group theory?
Based on what I can find, difference seems only to be the nature of the groups involved, where a direct product can involve any two groups and the semi-direct product only allows a normal subgroup $N$ of some group $G$ and another subgroup of $G$ that intersects trivially with $N$.
Is this all? What are the significance? Thank you.
Comment: You can define an "external" semidirect product that has as input two groups $G, H$ and a homomorphism $\phi : G \to \text{Aut}(H)$ ( http://en.wikipedia.org/wiki/Semidirect_product#Semidirect_products_and_group_homomorphisms ). It reduces to a direct product if $\phi$ is trivial, so direct products are a special case of semidirect products.
Comment: Direct product of Abelian groups ia always abelian while even semi direct product of cyclic groups need not be abelian. Is this significant enough?
Comment: In the direct product of $H$ and $K$, elements $h \in H$ and $k \in K$ commute, so $kh = hk$.  In the semidirect product, we have $kh = \varphi(h)k$ for some automorphism $\varphi$ of $h$.  Thus, as Qiaochu mentioned, we need a homomorphism from $K$ into $Aut(H)$ in order to make this action make sense.  If that homomorphism is trivial, we have $kh = \varphi(h)k = hk$ and therefore have the direct product.
Comment: @retro: Note that in $H\times K$, elements of the form $(h,1)$ and $(1,k)$ commute with each other.  You identify $H$ with the subgroup $H\times 1 \le H
\times K$, and similarly $K$ with $1 \times K$ and see that elements in those subgroups commute with elements in the other.  Conversely, if you have a group written $G$ where each element is written uniquely in the form $hk$, and $hk = kh$, then $G\cong H \times K$
Comment: @Carl: Thank you. Isn't the direct product of the form $(h,k)\in H\times K$ so that the $h$'s and $k$'s are separated? But then how can they commute?
Comment: @Carl: Thanks for the explanation.
Comment: @QiaochuYuan: Thanks.
Comment: @KannappanSampath: Yes, it is significant enough :) Thanks.
Answer: Let's look at three related concepts, in increasing order of complexity:

Direct products. We say that $G$ is (isomorphic to) a direct product of $M$ and $N$ if and only if there exist subgroups $H$ and $K$ of $G$ such that:

$H\cong M$ and $K\cong N$;
$H\triangleleft G$ and $K\triangleleft G$;
$H\cap K=\{e\}$;
$G=HK$.

Semidirect products. We say that $G$ is (isomorphic to) a semidirect product of $M$ by $N$ if and only if there exist subgroups $H$ and $K$ of $G$ such that:

$H\cong M$ and $K\cong N$;
$H\triangleleft G$;
$H\cap K=\{e\}$;
$G=HK$.

Extensions. We say that $G$ is (isomorphic to) an extension of $M$ by $N$ if and only if there exists a subgroup $H$ of $G$ such that

$H\cong M$;
$H\triangleleft G$;
$G/H\cong N$.

1 and 2 look very similar. In fact, 1 is a special case of 2 (when $K$ is normal); and 2 is a special case of 3: if $G=HK$, $H\triangleleft G$, and $H\cap K=\{e\}$, then $K$ maps isomorphically onto $G/H$ via the natural projection (the intersection with the kernel is trivial, so the projection restricted to $K$ is one-to-one; and every element of $G$ can be written as $x=hk$ with $h\in H$ and $k\in K$, so $Hx = Hk$, hence the map is onto when restricted to $K$).
But each one is a more general construction than the previous one, yielding more general types of groups.
For instance, in Direct Products, the conditions immediately imply that elements of $H$ commute with elements of $K$:
Lemma. Let $G$ be a group, and let $H$ and $K$ be normal subgroups of $G$. If $H\cap K=\{e\}$, then $hk=kh$ for all $h\in H$ and $k\in K$.
Proof. Consider $hkh^{-1}k^{-1}$. Since $K$ is normal in $G$, then
$$hkh^{-1}k^{-1} = (hkh^{-1})k^{-1} \in (hKh^{-1})K = KK = K;$$
and since $H$ is normal in $G$, then
$$hkh^{-1}k^{-1} = h(kh^{-1}k^{-1}) \in H(kHk^{-1}) = HH = H.$$
Therefore, $hkh^{-1}k^{-1}\in H\cap K = \{e\}$, so $hkh^{-1}k^{-1}=e$. Multiplying on the right by $kh$ gives $hk=kh$, as desired. $\Box$
So, for example, if all you know are direct abelian groups, then direct products will only give you abelian groups. If both $M$ and $N$ have exponent $k$, then direct products will give you a group of exponent $k$. (In fact, any identity satisfied by both $M$ and $N$ will be satisfied by $M\times N$; but this is perhaps a little advanced for you right now, so don't worry too much about it).
By contrast, semidirect products are more complicated, because that second subgroup doesn't have to be normal. The argument above is invalid, and we don't always get that elements of $H$ and elements of $K$ commute (if they do, then you have a direct product). The smallest example is $S_3$, the nonabelian group of order $6$ viewed as the permutations of $\{1,2,3\}$, with $M=C_3$, the cyclic group of order $3$, $N=C_2$, the cyclic group of order $2$, and $H=\{I, (1,2,3), (1,3,2)\}$, $K = \{I, (1,2)\}$ (other choices of $K$ are possible).
In a semidirect product, the fact that $H$ is normal means that for every $k\in K$ you have $kHk^{-1}=H$; that is, each $k$ induces an automorphism of $H$. So we can define a homomorphism $K\to \mathrm{Aut}(H)$, by letting $k$ map to the homomorphism $h\mapsto khk^{-1}$. If this map is trivial, you get the direct product of $H$ and $K$. If the map is not trivial, then you get more interesting groups. Different homomorphisms may lead to nonisomorphic groups, so that now we have to be careful: while there is one and only one way to construct a "direct product" of two groups $M$ and $N$, there may, in general, be many (non-equivalent) ways of constructing semidirect products of $M$ by $N$.
Note that it is now possible to have a semidirect product of abelian groups that is not abelian (as in the $S_3$ example). And it is no longer true that if both $M$ and $N$ are of exponent $k$, then a semidirect product will also have exponent $k$. For example, take $M=C_2\times C_2 = \{1,x\}\times\{1,x\}$, which is of exponent $2$, take $N=\{1,n\} = C_2$, also of exponent $2$, and let the nontrivial element of $N$ act on $M$ by the rule $n^{-1}(a,b)n = (b,a)$. Then $(x,1)n$ has order $4$:
$$\begin{align*}
\bigl((x,1)n\bigr)^2 = (x,1)n(x,1)n &= (x,1)(n^{-1}(x,1)n) = (x,1)(1,x) = (x,x)\\
\bigl((x,1)n\bigr)^3 = (x,x)(x,1)n &= (1,x)n\\
\bigl((x,1)n\bigr)^4 = (1,x)n(x,1)n &= (1,x)(n^{-1}(x,1)n) = (1,x)(1,x) = (1,1).
\end{align*}$$
Extensions are even more complex: in essence, every finite group can be viewed as a sequence of extensions of simple groups (hence, in part, the interest in classifying all finite simple groups). Not every extension is a semidirect product (or a direct product). For example, $\mathbb{Z}_4$, the cyclic group of order $4$, is an extension of $\mathbb{Z}_2$ by $\mathbb{Z}_2$: the subgroup $H=\{\overline{0},\overline{2}\}$ is cyclic of order $2$ and normal, and the quotient $\mathbb{Z}_4/H$ is of order $2$, hence cyclic of order $2$. If it were a semidirect product of $\mathbb{Z}_2$ by $\mathbb{Z}_2$, then being abelian it would necessarily be a direct product, and so would have exponent $2$; so it cannot be written as a semidirect product.
As I mentioned, every group can be expressed as a sequence of extensions using simple groups. By the Jordan-Hölder Theorem, although the sequence is not unique, the precise simple groups that occur is (counting multiplicity).
The definitions look quite similar: we just drop the condition of normality for one factor when going from direct product to semidirect product; we just exchange "there is a subgroup isomorphic to $N$ that maps isomorphically onto the quotient" with "the quotient is isomorphic to $N$" in going from semidirect product to extension. But the consequences of these "little changes" is large. Much like the difference between "finite abelian group" and "finite group" looks very small (just a single line dropped), but the implications in our ability to classify/understand the objects in question are enormous.
Comment: Wow! Thanks for the very detailed explanation!!
Comment: Fantastic. Great... Thanks for this impressive answer...
Comment: @Shaun: The standard notation is for external constructions (external direct product, external semidirect product), not for internal ones; and extensions have no standard notation.
Comment: @Shaun: Sorry, but what are you talking about? I **do** say what I mean; I'm including the definition of "extension of $M$ by $N$" as I use the term. So what exactly is it you want me to include beyond exactly the definition I am using?
Comment: @Junglemath: The definition given under "direct products" **is** the definition of an internal direct product of $H$ and $K$. The distinction is, ultimately, utterly useless. Internal direct products and external direct products are naturally isomorphic.
Comment: @ArturoMagidin does that imply that if H and N form a semidirect product, then N and H form one too (in the same order)? Also I think you answered all I needed to know with that comment, thanks. Sorry for being nonsensical. But you do realize that G=HK is a complete shorthand, and its not obvious that the definition with a set you gave is the one used, right?
Comment: @Arturo, Is there a general expression for the exponent of the semidirect product?
Comment: Shouldn't $G$ be an extension of $N$ by $M$ in 3?
Comment: @user92156: see http://math.stackexchange.com/questions/64573/history-of-the-vocabulary-for-group-extensions/64580#64580
Comment: It would help to include how they're denoted in your definitions.
Comment: @ArturoMagidin No, I mean perhaps you could include some standard notation, like $\times$ for the direct product.
Comment: @ArturoMagidin Where do internal direct products fit into your definitions? Are they included in direct products (first definition)?
Comment: @ArturoMagidin: By assumptions in 1 of your answer, does $G=HK$ isomorphic to $K\times H$?
Comment: @C.F.G. Of course; because $H\cong M$ and $K\cong N$, so $H\times K\cong M\times N$.
Comment: What do you mean, G=HK? Is it 'for all $h\in H$ and $k \in K$, $h k $ produces all G?' or is it 'for all $h\in H$ and $k \in K$, $h k$ AND $k h$ produce all G?'
Comment: @MondoDuke: Exactly what it says: that the group $G$ is equal to the set $HK=\{hk\mid h\in H,k\in K\}$. What is unclear about that? Neither of the things you write makes any sense whatsoever: they are both utterly nonsensical.
Comment: @MondoDuke: The definition has **four** parts. To talk about the semidirect product of $H$ *by* $K$, you need $H$ to be a normal subgroup and $K$ to be a subgroup. To talk about the semidirect product of $K$ by $H$ you need $K$ to be a normal subgroup and $H$ to be a subgroup. Why would that imply that if you can form the semidirect product of $H$ by $K$, then you can also form the semidirect product of $K$ by $H$? Why do you think you can just ignore a condition (normal subgroup)?
Comment: @MondoDuke: "But you do realize that $G=HK$ is a complete shorthand and its[sic] not obvious that the definition with a set you gave is the one used, right?" No, **wrong**. It is **standard notation**. If you don't know it, then it's because you don't know standard notation, not because it is not obvious. And even if you don't know standard notation, what you wrote was *utter nonsense*, and that has nothing to with notation;  it has to do with what the words mean.

Semi-direct v.s. Direct products


Erro no posicionamento de divs

Question: Olá, estou fazendo uma aplicação e estou querendo criar cards utilizando html e css, eu já consegui criar os cards, mas não estou coseguindo posicionar um ao lado do outro, alguém sabe como posso fazer isso?
O layout está ficando assim, mas eu quero que quando acabar o espaço o próximo cartão desça.

CSS dos cartões:
@font-face{
    font-family: 'IndieFlower';
    src: url("../fontes/IndieFlower.ttf");
}

*{
    padding: 0;
    margin: 0;
    border: 0;
}

.w3-card-4{
    width: 400px;
    float: right;
    top: 10px;
    left: 330px;
    position: absolute;
    background-color: #FFFFFF;
}

header{
    background-color: #FF6861;
    color: #FFFFFF;
}

footer{
    background-color: #FFFFFF;
    border-top: 1px solid #FF6861;
    height: 55px;
    text-align: right;
}

.w3-container p{
    font-family: 'IndieFlower';
}

.acoes{
    border: none;
    display: inline-block;
}

Código do cartões
<?php
    require_once dirname(__FILE__) . '/../classes/Tarefa.php';

    $tarefas = TarefaDAO::listarTarefas($usuario->getId());
    if($tarefas != null):
        foreach ($tarefas as $tarefa):
?>

<?php echo $tarefa->getNome();?>

            <?php echo $tarefa->getDescricao();?>

        <form>
            <input class="acoes" type="image" src="imagens/favoritar.png"/>
            <input class="acoes" type="image" src="imagens/lixeira.png"/>
            <input class="acoes" type="image" src="imagens/atualizar.png"/>
        </form>

    <?php endforeach;?>
    <?php endif?>

Código da tela principal

        <meta charset="UTF-8">
        <link rel="stylesheet" href="css/inicio.css"/>
        <link rel="stylesheet" href="css/modal.css"/>
        <link rel="stylesheet" href="css/w3.css"/>
        <link rel="stylesheet" href="css/cards.css"/>

        <meta name="viewport" content="width=device-width, initial-scale=1"/>
        <link rel="shortcut icon" href="imagens/todoIcone.ico"/>
        <title>TODO List | Inicio</title>
        <?php
            require_once dirname(__FILE__) . '/includes/sessaoDeUsuario.php';
            require_once dirname(__FILE__) .'/dao/TarefaDAO.php';
           loginObrigatorio();
        ?>
        <?php
            $caminhoImagem = "";
            if($usuario->getFotoPerfil() != null){
                $caminhoImagem = $usuario->getFotoPerfil();
            }else{
                $caminhoImagem = "imagens/iconSemFoto.gif";
            }
        ?>

                    <img id="fotoUsuario" src="<?php echo $caminhoImagem;?>"/>

<?php echo $usuario->getNome();?>

<?php echo $usuario->getEmail();?>

_____________________________

                    Nova Tarefa

                    Atualizar Tarefa

                    Atualizar Perfil

                    Favoritas

___________

        <?php include './includes/cardsTarefas.php';?>
        <?php include './includes/modalAddTarefa.php';?>
        <?php include './includes/modalAtualizarPerfil.php';?>

Comment: Com position absolute vc não vai conseguir fazer isso.
Answer: FLOAT e OVERFLOW
1º - A classe .w3-card-4 sugiro que seja um

ul li.w3-card-4 {
...
}
2º - Não utilize float: right, a menos que seja extremamente necessário. E remova o position: absolute
ul li.w3-card-4 {
float: left;
position: relative
}
3º - Coloque um overflow:hidden no
 para que não haja transbordamento.
ul {
overflow: hidden;
}
Comment: Por que a classe .w3-card-4 deve ser um ?
Comment: Realmente não deve, mas acredito ser a melhor prática para estes casos.
Answer: Evite utilizar a propriedade position nos elementos, a não ser que realmente precise.
Coloque os cards dentro de uma div pai para alinhar apenas esse elemento de acordo com a estrutura de sua página.
Nos cards, utilize margin para tratar do espaçamento entre seus elementos e adicione display: inline-block para que eles fiquem um ao lado do outro.
Abaixo tem um exemplo resumido de como ficaria.

.w3-card-4{
    width: 180px;
    display: inline-block;
    background-color: #FFFFFF;
    margin: 10px;
}

header{
    background-color: #FF6861;
    color: #FFFFFF;
}

div 1

div 2

div 3

div 4

Erro no posicionamento de divs


Spam registrations even after adding domain to Mollom blacklist

Question: I have a problem with spambots from itregi.com and drupaler.org that registers accounts on my clients Drupal site. I have Spamicide and Mollom installed and I have also added the domains to Molloms blacklist in the following format:
Author e-mail   contains    itregi.com
But they still get accounts with these domains as email.
I don't know what to do more or if I am using the blacklist wrong? Any suggestions?
Comment: If Mollom module you are using is not doing what it advertises, it's a bugreport, and should be posted in module's issue queue, not here.
Comment: Yes but I am not certain that I am using it right or that it is intended to work like this. I haven´t found any documentation on it.
Comment: You are using this module: https://www.drupal.org/project/mollom ?
Comment: Yes that is the one. I am fairly new to Drupal so I don´t know where to look for all the answers I need yet and when to post where.
Answer: Try using Honeypot, it's a module specially designed for spambot filtering...
Comment: I'm going to be the bearer of bad news.  Honeypot will not stop this.  I have Honeypot running on my heavy traffic site and it helps a lot but I am still getting itregi.com and drupaler.org registrations.  I'm going to probably write a little custom code to block those domain names in my Drupal instance.
Comment: Thanks I think Spamicide is supposed to do the same thing as Honeypot but I will look into it.
Comment: @lovelainen yes, spamicide uses the same technique, but it's hard to predict whose implementation of it will be more effective now. It's a constant armaments race between authors and spammers.
Comment: Installed Honeypot hopefully it will help.
Comment: Oh I was afraid of this. :S Thanks for the heads up!
Answer: I was having the same problem in the last few days and every time i delete the created account by the spammer or block it, the spammer re-register again.
At my website the email@example.com did create too many nodes using the (Forum Module).
Solution in my case was to use User restrictions module
I am using User restrictions module now for 2 days without any problem and the spammer can not post any node and can not even register.
Advice: The module send an error message that the email (e.g. email@example.com) that is used to register is not allowed, may be you change this message to something tricky like (the email syntax is not correct), in case it is a human spammer not machine spammer.
I hope this can help.
Answer: I know this does not necessarily answer the question as such but it might aid you.  If you use something like Captcha during registration (https://www.drupal.org/project/captcha) it will prevent loads of the spambots to successfully register.  You can then set your permission to deny posting unless registration was completed.
Comment: Yes we use Mollom for captcha. :) But it still doesn't prevent them all sadly.
Comment: Unfortunately these are not spam bots.  They are human beings.  I've been fighting itregi.com and most recently drupaler.org registrations for over a month.  I'm going to have to resort to some custom code to stop it.
Answer:
BOTCHA
Fail2Ban

A site we just inherited also just got hit last night. Around 11pm I got an alert mail for the account using a bit more than expected bandwidth. Quickly saw that the site was being overrun with spam. New registrations with the same (and more) domains as OP.
I blocked new user registrations and disabled new content creation permission. Then added fail2ban with a few filters to pick up the problem botnet attempts and block them and went to bed (not a critical time for this site).
Today we tweaked the fail2ban filters and also added BOTCHA. When we removed the spam accounts we also took note of the account names the botnet created.
The new Fail2Ban filters apply to three jails, one for failed login attempts by the botnet's previously created accounts (now deleted), one for BOTCHA and one for incorrect CAPTCHA (for log entries from before today when we used Honeypot).
PS: I can only guess that it's a botnet - the IPs change all the time and still hit the site now with thousands already blocked.
I prefer not using off-site services like Mollom or reCAPCHA. But BOTCHA will work with them too if you want.
Answer: Thanks @LarS for pointing me in the right direction.  I've removed the evil core hack.  Here's the code for the same functionality using hooks if it's helpful to anybody.
This code can be used in the template.php file of your theme or in a custom module, however it should be put in a custom module because it is functionality, not visuals. If you were to change your theme you would still want to keep this.
Replace THEME_OR_MODULE_NAME with your own theme or module name.
<code>/**
 * Implements hook_form_FORM_ID_alter().
 *
 * Alter the user registration form to add custom validation.
 */
function THEME_OR_MODULE_NAME_form_user_register_form_alter(&$form, &$form_state, $form_id) {
  // Add a custom validate function.
  $form['#validate'][] = 'THEME_OR_MODULE_NAME_user_validate_form';
}

/**
 * Implements hook_form_FORM_ID_alter().
 *
 * Alter the user edit form to add custom validation.
 */
function THEME_OR_MODULE_NAME_form_user_profile_form_alter(&$form, &$form_state, $form_id) {
  // Add a custom validate function.
  $form['#validate'][] = 'THEME_OR_MODULE_NAME_user_validate_form';
}

/**
 * Custom validation for the user register and edit forms.
 */
function THEME_OR_MODULE_NAME_user_validate_form(&$form, &$form_state) {
  $mail = $form_state['values']['mail'];

  if (!THEME_OR_MODULE_NAME_user_validate_mail_not_spam($mail)) {
    form_set_error('mail', t('The e-mail address %mail is not valid.', array('%mail' => $mail)));
  }
}

/**
 * Validate an email address against known spam domains.
 *
 * @param string $mail
 *   The email address to validate.
 *
 * @return boolean
 *   Returns TRUE if the email passes validation and FALSE otherwise.
 */
function THEME_OR_MODULE_NAME_user_validate_mail_not_spam($mail) {
  if (preg_match("/@tattooideas1.com/i", $mail)) {
    return FALSE;
  }
  if (preg_match("/@saccatalyst.com/i", $mail)) {
    return FALSE;
  }
  if (preg_match("/@cowgirljules.com/i", $mail)) {
    return FALSE;
  }
  if (preg_match("/@drupaler.org/i", $mail)) {
    return FALSE;
  }
  return TRUE;
}
</code>
Comment: Please, never hack core! Instead you should try the hook system, for example see [Hook into Drupal registration and validate user info against business logic](http://stackoverflow.com/questions/2264301/hook-into-drupal-registration-and-validate-user-info-against-business-logic).
Comment: I made some tweaks to the code to adhere to Drupal coding standards and add more comments. I also added a note that this can (and should) go in a custom module instead of a theme template.php.
Answer: Instead of a custom module, I simply created a rule using the Rules module.

Rules

+Add new rule

(call it whatever you want.  Registration Blacklist maybe?)
Events

Before saving a user account
After saving a new user account

Conditions

Text comparison
Parameter: Text: [account:mail], Matching text: drupaler.org

(Make sure it is set to "contains")
Actions

Block a user
Parameter: User: [account]
Delete entity
Parameter: Entity: [account]

If a person wanted to, they could setup the action to ban the IP address instead or in addition to blocking the user.
The reason for the two events is because you can't delete the account until after it's been saved.  Ideally, I wish Rules would simply kick them out and not even create an account period, but that's beyond my knowledge at this point.
If a person wanted to have some fun, they could setup a page redirect and send the bot/user to some funky webpage, ideally a redirect loop page.  For example, I setup another action rule that redirects the dupraler.org people to a page that will cause a modern browser to hang: http://www.neocodex.us/forum/topic/118146-redirectshtml-pranktroll-page/
Answer: I wrote a little module to help me with this: Its not on Drupal.org at this time but it is available on GitHub here: https://github.com/coralnexus/regstop
RegStop is very straightforward to use - though it is fresh - like 2 days old ;-)
If anyone has suggestions for improvements, let me know.
Thanks, Derek
Answer: Not to step on Derek's toes, but I was also working on a module for the very same issue. I did not see this until now though, but do plan on adding even more validation to the user registration form down the road.
It started as a project for a client of mine, he was getting hammered with at least a dozen human spam registrations a day from the drupaler.org and yandex.com e-mail domains. Put this together for him this week, so it is pretty young as well.
Registration validation


Player with 350 or more goals in domestic league

Question: When Messi passed 350 goals for Barcelona, I asked this question, but couldn't find an answer anywhere. Who has scored more goals than Messi for a single club?
Edit: I was specifically asking for the goals in the domestic league.
Answer:
Josef Bican 534 with Slavia Prague
Pelé 643 with Santos
Ferenc Puskás 387 with Budapest Honved
Gerd Muller with Bayern Munchen
Cristiano    Ronaldo with Real Madrid
Answer: Andry porter scored 357 goals in domestic league
Comment: Welcome to Sports Stack Exchange! You might want to expand your answer to include more details, e.g. for which club he played.


Validating a react-final-form form with yup and custom validations

Question: I have a form created with react-final-form and a validation function that looks like this
export const validate = async (values, schema) => {
  if (typeof schema === 'function')
    schema = schema();

  try {
    await schema.validate(values, { abortEarly: false });
  } catch (e) {
    return e.inner.reduce((errors, error) => {
      return setIn(errors, error.path, error.message);
    }, {});
  }
};

So when i render my form it looks something like this
<Form
  onSubmit={handleSubmit}
  validate={values => validate(values,schema())}
/>

Schema is a Yup schema that is defined as such
const schema = () =>

    yup.object().shape({
        name: yup
            .string()
            .max(255)
            .required(REQUIRED_FIELD),
        number: yup
            .string()
            .required(REQUIRED_FIELD),
        exp_year: yup
            .number()
            .required(REQUIRED_FIELD),
        exp_month: yup
            .number()
            .min(1,'Invalid')
            .max(12,'Invalid')
            .required(REQUIRED_FIELD),
        cvc: yup
            .number()
            .required(REQUIRED_FIELD),

    });

This works fine, as long as i use Yup methods, however, the credit card service i am using provides their own validation functions, such as 'Provider.validateCardNumber' from an external script.
What i cant seem to figure out is where and how to add custom validation so that i can continue to use the Yup validation for other fields, but my external library methods for custom validation of the cvc and credit card number.
Is there a way to add a custom callback function within my yup schema and return the value of the function such as my Provider.validateCardNumber within yup so i dont need to change my validate function? and if so, how can i access the values within the schema, which were passed to the validate function...
OR
how should i modify my validate function so that it will run the Yup schema validation, AND the external script validations, so in the end it returns an empty object to the validate prop of react-final-form
In other words, I want to run an external method as part of my validation, but continue using Yup schema if possible.
Comment: This is more of a Yup question, so I can't really help you much. All RFF cares about is that the errors be returned via a resolved `Promise`, like you're doing in your `catch`.
Comment: Thanks Erik, indeed it was a Yup issue, and i managed to fix it using one of the yup methods, i just wasnt sure how to access the values but after a thorough check of their docs i found it!
Answer: The answer lies within the Yup documentation and their method test() so in the end i just needed to extend the schema and use the test method to be able to pass in an external true/false test
number: yup
            .string()
            .test('Card Test',
                'Invalid Card Number',
                value=>Provider.validateNumber(value)
            )


How to identify time signature from notation

Question: I have a fair idea of the meters, and can identify from a time signature whether it is simple or compound, duple, triple, quadruple etc.
However,  I cannot figure out the reverse: the time signature from the notes, particularly in the cases that end up being compound.
How can I identify the time signature from a measure of notation without the time signature specified?
Comment: From the notations -- for example if you get the notes in one measure, how would you find the signature
Answer: I may extend this later to consider irregular time signatures but for the moment I'll only cover the usual suspects.
To start, count the beats: usually two to four. Often this is made clear by beaming. At other times, you could tell by the choice of rest. For example, two quarter-note rests, and an eight-note rest followed by a dotted quarter-note rest, both add to the same value. However, the first might belong to a 3/4 measure and the second to a 6/8 measure. Ties will often give you some hint, for example a quarter note followed by two tied eighth-notes followed by another quarter note is likely a giveaway for compound time as it is going across the beat.  It should be clear from the notation whether your beats are half-notes, quarter-notes, eight-notes, or others.
If you have a simple time, you will be writing 2, 3, or 4 as the top number. If you have a compound time, you will be writing 6, 9, or 12. The bottom number will be 2 for a half-note beat, 4 for a quarter-note beat, and so on. It will be 4 for a dotted half-note beat, 8 for a dotted quarter-note beat, and so on.
Note well!
A time signature matching a given measure can always be given, but it may not prove to match the rest of the music. Even when it does, it may not match the time signature actually present.
Is this 3/4 or 6/8?

Without more information we can't be sure. This extract is from Chopin Op 53. The beaming suggests 6/8, but this work is in 3/4. The music has been written this way to clarify phrasing.
Is this 3/2 or 6/4?

This is from J. S. Bach BWV 663. Both answers are correct, there is no way to tell which he wrote.
Comment: And that's before we consider Lenny's 'America'...
Comment: @Tim sometimes you really can have your cake and eat it.


Busca em tuplas com Python e Mysql

Question: Olá, Boa Noite!!!
Sou novato na programação Python, e recentemente recebi um trabalho na faculdade de implementar um programa similar ao akinator, utilizando a linguagem desejada, por ter mais facilidade, resolvi utilizar o Python. A ideia é fazer perguntas ao usuário, e retornar apenas um valor com base nas respostas obtidas. Fiz isso em um banco teste mysql, de forma estática, com perguntas "chumbadas" no código, e um select ao final utilizando todos os parâmetros. Porém, este método ficará muito trabalhoso para criar o banco e para o usuário responder, pois teria que responder 50 questões para que o resultado seja único. Pensei então em fazer uma tabela de perguntas e uma de resultados. Minha ideia é apresentar perguntas aleatórias e utilizar um id na pergunta para realizar o select.
Exemplo:
- O carro é da marca Fiat?
De acordo com a resposta, gostaria de fazer um select, armazenando os resultados que satisfaçam a condição, e após isso realizar uma nova pergunta aplicando novo select apenas nestes valores já filtrados. Com isso acredito que o número de perguntas ficaria menor, e as mesmas poderiam ser feita de forma aleatória (um dos requisitos do professor). Porém, não faço ideia de como aplicar isso na prática, ou seja, como armazenar os resultados em algum lugar, e realizar o novo select apenas nestes valores armazenados. Esse laço seria realizado até que o resultado apresentado seja = 1. Poderiam me ajudar? Segue o que havia feito até agora.
import pymysql

con = pymysql.connect('localhost', 'root', '', 'python')

with con:
    cur = con.cursor()
    cur.execute("SELECT VERSION()")
    version = cur.fetchone()
    print("Database version: {}".format(version[0]))

print("Ola eu sou o adivinhator!!!")
print("Pense em alguma coisa e eu vou adivinhar!!!")
print("Responda as perguntas utilizando 's' para SIM e 'n' para NÃO seguido da tecla ENTER!!!")
comecar = input("Podemos começar?\n")
if comecar == "S":
    print("La vai a primeira pergunta")
else:
    print("esperando voce")
vmarca = input("O carro e da marca FIAT?\n")
vportas = input("O carro tem 2 portas?\n")
vpotencia = input("O carro é 1.0?\n")
vtipo = input("O carro é utilitário?\n")
vtipo2 = input("O carro é hatch?\n")
qry_p = ("SELECT nome  FROM resultados where fiat = '"+vmarca+"'AND 2portas='"+vportas+"'AND pot='"+vpotencia+"'AND utilitario='"+vtipo+"'AND hatch='"+vtipo2+"'")
cur.execute(qry_p)
result = cur.fetchone()
print("O carro que pensou é", result)

Answer: Você pode armazenar os id's das linhas após cada resposta e usar isso como condição na próxima pergunta com WHERE id IN (id1, id2, id3,...,idn). Vai perguntando até a lista de id's ter somente 1 elemento.
Comment: No seu exemplo, eu armazenaria os ID dos resultados, com base no select é isso? A minha principal dúvida neste caso, seria como armazenar esta tupla/lista de ID e depois realizar o próximo select apenas nestes valores armazenados, conseguiria me dar um exemplo?

Busca em tuplas com Python e Mysql


Consider the following system of differential equations

Question: Consider the following model. Find the general solution
$\frac{dx}{dt}=-2y$,
$\frac{dy}{dt}=8x$
So far this is what I have:
$$\frac{dx}{dt}=-2y$$
$$x'=-2y$$
$$y=-\frac{x'}{2}$$
$$y=-\frac{x''}{2}$$
and then
$$\frac{dy}{dt}=8x$$
$$y'=8x$$
$$-\frac{x''}{2}=8x$$
$$-x''=16x$$
$$x''+16x=0$$
Is this correct so far? What step should I take next?
Comment: Why do you self-duplicate your questions?
Comment: If $r^2+16=0$ then $r= \pm 4i$ hence you get $\sin(4t), \cos (4t)$ as fundamental solutions for $x$. ( I have not checked your steps)
Comment: @nathan.j.mcdougall why did you change the values of the constants in the question by removing the decimal points?
Comment: Well, this question is thoroughly hosed now due to an editing error which occurred _because OP did not use MathJax in the first place._ And then instead of correcting the error and explaining what happened (so that the answers would still make sense), OP copied the original to a new question. What a mess!
Comment: @JoelReyesNoche Good question. Several reasons. Firstly, it was very unclear that these were decimal points. They seemed to be some crude form of manual formatting. I did not dismiss that possibility initially, but when a .8 was doubled it became a .16 in the working (???) so I assumed it couldn't have been a decimal point.

This was apparently an error. And I apologise. The edit was in good faith, but I have learnt my lesson: assume nothing.
Answer: Although not the usual way I've seen this done (usually I have seen the eigenvalue/eigenvector method done), your approach works.
Now you need to know that the general solution to $x''+16x=0$ is $c_1 \cos(4x) + c_2 \sin(4x)$. One way to see this is to get the characteristic polynomial $\lambda^2+16$ which has roots $\pm 4i$. So from this you get a general solution of $c_1 e^{4ix} + c_2 e^{-4ix}$ for complex constants $c_1,c_2$. That can then be rearranged into the previous form.
Comment: how do you know the general solution c1e4ix+c2e−4ix can be rewritten as c1cos(4x)+c2sin(4x) is that from Euler's formula?
Comment: @Lil That's right; it is not too hard to see from Euler's formula that $\cos(x)=\frac{e^{ix}+e^{-ix}}{2}$ and $\sin(x)=\frac{e^{ix}-e^{-ix}}{2i}$.
Comment: alright, how do I go about finding the value of c1 and c2?
Comment: @Lil For the general solution you don't have to; the general solution has two arbitrary constants in it. You get the constants from initial conditions.
Comment: alright. The equations represent a fictions situation of two people and I'm suppose to analyze which person would suffer more. Do I need the constants for that?
Comment: @Lil I don't think I have enough specifics to answer your question.
Comment: Let us [continue this discussion in chat](http://chat.stackexchange.com/rooms/22822/discussion-between-lil-and-ian).
Answer: The next step is to slove the last equation you have:
$$
x'' + 16 x = 0$$
with the ansatz that
$$x(t) = e^{kt}$$
You quickly find that
$$x'' = k^2 e^{kt} \\
k^2 + 16 = 0\\
k = \pm 4i
$$
and since the equation in linear the general solution is the arbitrary llinear combination
$$x(t) = c_1 e^{4it} + c_2 e^{-4it}$$ which can be rearranged to
$$x(t) = A \sin(4t) + B \cos (4t)$$
Finally, you read off $y(4)$ as $$y(t)=-\frac12 \frac{dx}{dt} = -\frac{A}{2} \cos (4t) + \frac{B}{2} \sin (4t)$$
Comment: how do I go about finding the coefficients, A and B?
Comment: You asked for the general solution of the system of equations.   Any values you choose for $A$ and $B$ work and solve the system.  For a problem with boundary values or initial conditions, $A$ and $B$ may be determined by those constraints.  For example, if I told you that $y(0) = 1, y'(0) = 2$ then that would force $A=2$ and $B=1$.
Answer: $$\frac{dx}{dt}=-2y$$
$$\frac{dt}{dx}=-\frac{1}{2y}$$
By chain rule:
$$\frac{dy}{dx}=\frac{dy}{dt}\cdot\frac{dt}{dx}$$
$$\frac{dy}{dx}=8x\cdot-\frac{1}{2y}$$
$$\frac{dy}{dx}=-\frac{4x}{y}$$
$$y\cdot\frac{dy}{dx}=-4x$$
$$\int y\cdot\frac{dy}{dx}dx=\int-4xdx$$
$$\int ydy=-4\int xdx$$
$$\frac{y^2}{2}+c_1=-4\cdot\frac{x^2}{2}$$
$$y^2+c_2=-4x^2$$
$$y^2+4x^2+c_2=0$$
Where $2c_1=c_2$, and $c_1$ is a constant of integration.


The condition for an open set to satisfy the barrier postulate

Question: Barrier Postulate:
there exist for each $\eta \in \partial \Omega$ a function $Q_{\eta}(x) \in C^0(\bar{\Omega}) \cap \sigma(\Omega),$ for which
$ Q_{\eta}(\eta)=0, Q_{\eta}(x)<0$ for $ x \in \partial \Omega, x \neq \eta. $
$\Omega \subset \mathbb{R}^n$ open, bounded and connected and $\sigma(\Omega)$ denotes the set of functions subharmonic in $\Omega$.
The problem is:
Show that the open set $\Omega$ satisfies the barrier postulate if for each $\eta \in \partial \Omega$, there exists a ball $B(\xi,\rho)$ such that $\bar{B}(\xi,\rho)$ and $\bar{\Omega}$ have just the point $\eta$ in common.
Here is a hint ask me to use for $-Q_{\eta}(x)$ a fundamental solution with spherical symmetry about the point $\xi$, but I don't understand how to find a suitable linear function that vanishes at certain point and negative on the others.
Is there any idea to deal with this problem?
Answer: Hi and welcome on MSE,
We need to make a distinction of cases depending on the dimension. For simplification I just consider the case $n\geq 3$. Following your hint we consider
\begin{equation*}
b(x)=|x-\xi|^{2-n}
\end{equation*}
which is the fundamental solution multiplied by a constant (to make life a bit easier).
This function satisfies $b(\eta)=\rho^{2-n}$. Hence, it is natural to subtract the constant $\rho^{2-n}$:
\begin{equation*}
\tilde{b}(x)=|x-\xi|^{2-n}-\rho^{2-n}
\end{equation*}
Now all that needs to be done is to check that the other conditions on the barrier are satisfied.
Comment: Thanks for your help, I finally figure it out.


Duplicator does not have enough permission

Question: I cannot duplicate my wordpress site to local this is the error message:
<code>Fail   [/srv/bindings/16b097b7aa994cd3b3e1a45c65bfaa5c/code/wp-snapshots]
Fail   [/srv/bindings/16b097b7aa994cd3b3e1a45c65bfaa5c/code/wp-snapshots/tmp]

If Duplicator does not have enough permissions then you will need to manually create the paths above.   The root WordPress path [/srv/bindings/16b097b7aa994cd3b3e1a45c65bfaa5c/code/] is currently not writable by PHP.
</code>
Answer: You need to manually create those directories using your FTP software (if you don't have direct server access) and chmod them to be writeable by the app. Start with 755 and see if that works, and tweak down from there.
Comment: still permission denied
Comment: What do you all mean by 755 and 777? Windows server IIS? I've already used duplicator on the same files ones. I'm reinstalling but now getting this all of a sudden.


How to determine the key and write melodies for a chromatic chord progression?

Question: I've been playing around with some chromatic chord progressions recently but I am having a hard time analyzing the changes and figuring out the key for melody/soloing purposes. How do you know which chords are the passing chords and which are the diatonic ones?
For example, something like:
F#m - F - Esus2 - E♭m7♭5 - Dmaj7
My first instinct would call it D Major E Major because the half diminished E♭ (or in this case D#) makes sense as a vii chord. But it could also be F# minor with the D being the VI. To my ear, F# minor pentatonic seems to work, but not perfectly.  Can I even use just one scale/mode for the whole melody, or do need to I change the scale with each chord change?
Comment: Diminished and m7b5 are not the same.They have the same lower three notes, but the other differs. In Ebo it's Dbb (C) but Ebm7-5 it's Db.
Comment: I'm confused. In D major, the VII chord is C# (not Eb)and it is *half* diminished, and not diminished (like @Tim said)
Comment: That Ebm7-5 could be D#m7-5, making the key E maj.
Comment: sorry..you guys are right. I meant E major.
Comment: When you have such special chord progressions, with chromatic based melody, the key is neither major or minor, but something completely different (may not even follow any official scale pattern).
Answer: It is possible to have multiple keys in a song. Charles Mingus in 'Nostalgia in Times Square' changed 3 keys in as many bars. He used chromatic notes in the melody as well. So, don't try to narrow your progression down to only one possible key.
Now, let's say you are in D major:

F#m -> 3rd chord of the scale.
F -> chromatic. The bass goes F# to F(natural) to E.
Esus2 -> 2nd chord of the scale.
E♭m7♭5 -> Chromatic (of some kind). If it was Eb7, it would be a tritone substitution of the dominant chord of your scale (the dominant is A7 and you substitute it with Eb7) which is a really common substitution. But it is not. So, it could be the 2nd chord of the D Phrygian mode. But we are not in D Phrygian mode. It could also be the 2nd chord of the Db minor scale. But we are not in Db minor scale.
Dmaj7 -> 1st chord of your scale.

So, your progression could work on the D major scale, with an addition of a few notes if you want the chromatics to be pointed out.
Comment: I think that E♭m7♭5 will be a D#m7♭5 or a #iø.
Answer: It's difficult to tell which are the passing chords from your example because there's no time values.  Passing chords are of short duration and/or occur on off-beats.
So absent that, I would look at the chord tones for each to determine what melody to play.

F#m: F# A C# ("color tones": E G# B D)
F: F A C ("color tones": E G Bb D)
Esus2: E B F#
Ebm7b5: Eb Gb(F#) Bbb(A) Db(C#)
Dmaj7: D F# A C# ("color tones": E G B)

(The "color tones" are known by a number of names, including "chord extensions" and are the natural or altered 7th, 9th, 11th and 13th notes above the chord triad of 1 (b)3 5.)
An easy way to choose melodies based on note sets is to look for good motion between the note sets.  I would use scalar/chromatic moves, arpeggios, interval jumps and ornaments, looking forward and backward on the chord progressions.
So for example, I might choose a basic melody skeleton and add fleshy bits to something like:

F# F E D# D

for a chromatic motion or

F# C F# A D

for something a little more angular and more solidly in D major.
Sometimes thinking in terms of chords and key centers works best and sometimes thinking in terms of sets of notes works best.  It's a subtle distinction but an important one.


Isomorphism between $\ell^p$ spaces

Question: I want to show that there is an isomorphism between the dual of $\ell^1$ and $\ell^\infty$. I don't really know where to start so any help is appreciated
Comment: Start with a map from $l^\infty$ to the dual of $l^1$ . How do you  think you would define such a map?
Comment: I don't know, I'm having trouble understanding what exactly the dual of $l^1$ is. I have the definition but I don't understand it entirely
Comment: Let $F = \mathbb{R}$ or $\mathbb{C}$.  If $(V, || \cdot ||)$ is a normed vector space over $F$, the dual $V^{\ast}$ of $V$ is defined to be the set of *bounded* linear functionals, i.e. all linear transformations $f: V \rightarrow F$ for which there exists a constant $N > 0$ such that $$|f(v)| \leq N ||v||$$ for all $v \in V$.  Then $V^{\ast}$ is also a normed vector space over $F$.
Answer: To a sequence $x = (x_1, x_2, ...) \in \ell^{\infty}(\mathbb{N})$, associate a linear functional
$$T_x: \ell^1(\mathbb{N}) \rightarrow \mathbb{C}$$
by $$T_x(y_1, y_2, ...) = \sum\limits_{i=1}^{\infty} x_iy_i$$
$T_x$ is a well defined function, because
$$\sum\limits_{i=1}^{\infty} |x_iy_i| \leq ||x||_{\infty} \sum\limits_{i=1}^{\infty} |y_i| = ||x||_{\infty} \space ||y||_1$$
and so that sum convergences absolutely.  Now you need to prove that $T_x$ is bounded, $T_{cx+y} = cT_x + T_y$, $||x||_{\infty} = ||T_x||$, and that the map $x \mapsto T_x$ is a surjective linear transformation (injectivity follows from being norm preserving).
Comment: What are the relations that $T_x$ has to adhere to in order to be isomorphic?
Comment: What you wrote doesn't make sense.  The *function* $\ell^1(\mathbb{N}) \rightarrow \ell^{\infty}(\mathbb{N})^{\ast}$ which sends $x$ to $T_x$ is the thing you want to show is an isomorphism.  You have to show that this function is a linear transformation which is injective and surjective.
Comment: But you said $T_x$ is a well defined function, so is x mapped onto a function?
Comment: Yes $\space \space$

Isomorphism between $\ell^p$ spaces


Can't add custom fields to Calendar

Question: I've created a new content type event (With title, body and date), but I can't select the type when editing my calendar view (screenshot included).
How come I can only select comments and dates, ..?

edit: it's because I added a view from template (Comments). How do you change the type of this view from comments to content? Is that possible?
Answer: You cannot change View types (i.e. Users to Content or Content to Comments etc.).
You will have to start the view from scratch.
Comment: Why aren't there any calendar view templates using content instead of comment? It would make a lot more sense to me to use them over comments. Or am I not seeing this right?
Comment: I updated my answer with a feature I made that should help you figure out the correct configuration for your view.
Comment: Link is now 404.

Can't add custom fields to Calendar


Get all documents from an index - elasticsearch

Question: How can I get all documents from an index in elasticsearch without determining the size in the query like
GET http://localhost:8090/my_index/_search?size=1000&scroll=1m&pretty=true'-d '{"size": 0,"query":{"query_string":{ "match_all" : {}}}}

Thanks
Answer: According to the ES scan query documentation, size parameter is not just the number of results:

The size parameter allows you to configure the maximum number of hits
  to be returned with each batch of results. Each call to the scroll API
  returns the next batch of results until there are no more results left
  to return, ie the hits array is empty.

To retrieve all the results you need to do subsequent calls to the API in the manner described in the aforementioned documentation, or to use some ready made implementation, like there is in python. Here is an example script to dump resulting jsons on stdout:
import elasticsearch
from elasticsearch.helpers import scan
import json

es = elasticsearch.Elasticsearch('https://localhost:8090')
es_response = scan(
    es,
    index='my_index',
    doc_type='my_doc_type',
    query={"query": { "match_all" : {}}}
)

for item in es_response:
    print(json.dumps(item))

Answer: As per the latest documentation, you will have to use the search_after parameter to retrieve records more than 10,000 from an index. take a look here https://www.elastic.co/guide/en/elasticsearch/reference/current/paginate-search-results.html#search-after


Using both $L_2$ regularization and early stopping when training ANN's

Question: I came across an ANN that's used for approximating a noisy sine function. On one hand it uses a validation set for early stopping, and then again uses the same validation set for fine tuning the regularization parameter. I wondered if this was a legit approach and common practice because of two reasons:

I thought early stopping itself was a form of regularization, isn't it then redundant to use both a regularization parameter and early stopping?
If one were to take this approach wouldn't it be better to two different validation sets? One for the early stopping and one for fine tuning the regularization parameter?
Answer:
It is 'redundant'. Early stopping essentially works because the weights start small, and $L_2$ regularization tries to keep them small. However, you are using gradient descent,  so it's pretty random, and you are reduced to trial and error aka cross validation.
Using the same validation set sounds fine - you are cross validating the double parameter (stopping time, $L_2$ regularization). Obviously better to do k-fold cross validation than using single validation set.


Qual é a diferença entre o evento canplay e canplaythrough?

Question: Ambos os eventos canplay e canplaythrough são semelhantes, mas qual é a diferença principal entre usar um e o outro?
Comment: O `canplaythrough` é disparado quando não só é possível tocar a mídia, mas tocar até o final sem parar.
Answer: A diferença é subtil, canplay indica que um objeto está disponível para poder iniciar a apresentação/visualisação. O evento canplaythrough é disparado quando suficiente conteúdo desse objeto já estiver em memória para o browser ter a certeza que é possível mostrar o resto do conteúdo sem interrupções.
Assim se o utilizador iniciar a apresentação antes de canplaythrough ter disparado é possível que haja pausas devido ao browser não conseguir carregar o conteúdo a tempo de visualizar o instance que o browser mostra/toca. Enquanto que depois do canplaythrough ser disparado o browser já tem "tudo o que precisa" para mostrar o conteúdo sem interrupções.
Comment: Qual é o melhor para mim utilizar? por exemplo, para informar a o usuário que o vídeo está pronto para ser reproduzido.
Comment: @marquinho depende muito. Depende do tipo de conteúdo (se é do tipo de conteúdo que só se vê poucos segundos, ou se o ideal é tocar sem interrupções); depende da qualidade da ligação dos utilizadores e que tipo de transparência a app/interface deve dar ao utilizador; etc