What is the practical difference between abstract index notation and "ordinary" index notation

Question: I understand that in "normal" index notation the indexes can be thought of as coordinates of scalar values inside a tabular data structure, while in the abstract index notation they can not. However, I am not clear on what practical difference this makes when actually doing math. If your are doing numerical calculations then you need to plug actual components into your tensors, so that is not abstract, but is there any difference if you are doing symbolic/algebraic computations? The notations look identical, and even though the interpretation is different, expressions in both cases ultimately denote tensors. As far as I know the algebraic laws are the same. Are there manipulations that are valid in one but not in the other? If you see some tensor calculations, how can you tell if abstract index notation is being used? If you are doing differential geometry with indexes do you need to decide if your indexes are abstract or not? Or am I just missing something?
Comment: Normal index notation is the usual tensor calculus notation with indexes and Einstein summation convention. Abstract index notation, invented by Penrose, looks exactly the same but the semantics are a little more subtle http://en.wikipedia.org/wiki/Abstract_index_notation. My question is when/how do the semantic differences matter in practice?
Comment: What is "normal index notation" compared to "abstract index notation"?
Answer: First I'd like to share my understanding of abstract index notation. I think this understanding is simpler and more intuitive than Penrose and Rindler's original definition. Your question will be answered later with an example.
Abstract index notation is merely a labelling of the "slots" of the tensor. For example, $T_{ab}{}^c$ is just an abbreviation of
$$T(-_a, -_b, -^c).$$
Each "slot" is a parameter as the tensor is viewed as a multilinear map $T:V\times V \times V^* \to \mathbb R$.
You may be already familiar with the labelling slots interpretation. But what does "labelling" a slot exactly mean? Here is my understanding: it means we can fill a specific slot with a vector (or dual vector) by specifying the label of the slot. For example, if we fill the slot labelled $a$ with a vector $u$, and fill the slot labelled $b$ with a vector $v$, and fill the slot labelled $c$ with a dual vector $\omega$, we get $T(u, v, \omega)$, that is
$$
T(-_a, -_b, -^c)(\{a=u, \; b=v, \; c=\omega\}) = T(u, v, \omega).
$$
Note here a set-like notation $\{a=u, \; b=v, \; c=\omega\}$ is used meaning that the order is irrelevant, $\{b=v, \; a=u, \; c=\omega\}$ and $\{a=u, \; b=v, \; c=\omega\}$ are just the same.
There are two observations from this definition of filling slots:

The position order of the slots is significant.
$$S_{ab} \neq S_{ba}$$
in the sense that
$$
S(-_a, -_b)(\{a=u, \; b=v\}) = S(u, v) \neq S(v, u) = S(-_b, -_a)(\{a=u, \; b=v\}).
$$
An index letter can be substituted with any Latin letter, since it's just a label for the slot. For example $T_{ab} = S_{ab}$ implies $T_{cd} = S_{cd}$. Because $T_{ab} = S_{ab}$ means for any vector $u$ and $v$
$$
T(-_a, -_b)(\{a=u, \; b=v\}) = S(-_a, -_b)(\{a=u, \; b=v\}),
$$
that is
$$
T(u, v) = S(u, v).
$$
And $T_{cd}=S_{cd}$ is equivalent to $T(u, v) = S(u, v)$ too. Note this index substitution is different from index reordering in observation 1, index substitution must be applied on both sides of an equation, We can't exchange $a$ and $b$ from only one side of the equation $S_{ab}=S_{ab}$ to get $S_{ab}=S_{ba}$.

Now we can use abstract index notation to denote tensor product, and contraction operation in a coordinate-free way. For example $U_{abcd} = T_{ab}S_{cd}$ denotes the tensor product
$$
U(-_a, -_b, -_c, -_d) = T(-_a, -_b) \cdot S(-_c, -_d).
$$
And $T_{ae}{}^{ed}$ denotes the contraction with respect of slots $b$ and $c$ of $T_{ab}{}^{cd}$
$$
T_{ae}{}^{ed} = C_b{}^c(T_{ab}{}^{cd}) =
\sum_{\sigma}T(-_a, \frac{\partial}{\partial x^\sigma}, \mathrm dx^\sigma, -^d).
$$
Another important operation is (partial) application, but since it's equivalent to a tensor product followed by a contraction, there is no need to introduce a new notation. For example applying a vector $u$ to the slot $a$ of $T_{ab}$ is
$$
T(u, -_b) = T_{ab}u^a.
$$
where $T_{ab}u^a$ is a tensor product of $T$ and $u$ followed by a contraction: $C_a{}^c(T(-_a, -_b)\cdot u(-^c))$. The result has one free slot left, so it's a (0, 1) tensor. That is, a (0, 2) tensor partially applied with a vector is a (0, 1) tensor.
Example
Consider the following problem: suppose
$$T_{abc} = \mathrm dx^\sigma_a \mathrm dx^\mu_b \mathrm dx^\nu_c,$$
where $\sigma$, $\mu$, and $\nu$ are 3 concrete numbers, then what is $T_{abc} + T_{bca}$?
This example more or less answers your question: what is the practical difference between abstract index notation and "ordinary" index notation. Abstract index notation is easier to read and understand especially when abstract indices and concrete indices are mixed.
In abstract index notation, there is a convention that abstract indices use Latin letters while concrete indices use Greek letters. So in this example we can easily see that $a$, $b$, and $c$ are abstract indices while $\sigma$, $\mu$, and $\nu$ are concrete indices.
The notation $\mathrm dx^\sigma_a$ is not very common, but it makes sense. The dual vector $\mathrm dx^\sigma$ is naturally a function that can act on a vector. The equation $T_{abc} = \mathrm dx^\sigma_a \mathrm dx^\mu_b \mathrm dx^\nu_c$ which is just an abbreviation of
$$
T(-_a, -_b, -_c) = \mathrm dx^\sigma(-_a) \cdot \mathrm dx^\mu(-_b) \cdot \mathrm dx^\nu(-_c)
$$
means when slot $a$ is filled with a vector $u$, $\mathrm dx^\sigma$ will act on that $u$.
To solve the problem, use index substitution, we can get $T_{bca} = \mathrm dx^\sigma_b \mathrm dx^\mu_c \mathrm dx^\nu_a$. So
$$
\begin{aligned}
T_{abc} + T_{bca} &= \mathrm dx^\sigma_a \mathrm dx^\mu_b \mathrm dx^\nu_c +
    \mathrm dx^\sigma_b \mathrm dx^\mu_c \mathrm dx^\nu_a \\
&= \mathrm dx^\sigma_a \mathrm dx^\mu_b \mathrm dx^\nu_c +
    \mathrm dx^\nu_a \mathrm dx^\sigma_b \mathrm dx^\mu_c \\
&= (\mathrm dx^\sigma \otimes \mathrm dx^\mu \otimes \mathrm dx^\nu + \mathrm dx^\nu \otimes \mathrm dx^\sigma \otimes \mathrm dx^\mu)(-_a, -_b, -_c).
\end{aligned}
$$
This is quite straightforward. On the other hand, if you use concrete index notation to solve this problem, first you need to figure out that the components of $T$ are all zero except
$$T_{\xi\eta\zeta} = 1, \text{when}\; \xi=\sigma, \eta=\mu, \zeta=\nu.$$
Or $T_{\sigma\mu\nu}=1$. But what is $T_{bca}$? $T_{\mu\nu\sigma}$? No. You need to define another tensor $S_{\xi\eta\zeta}=T_{\eta\zeta\xi}$, and figure out that its components are all zero except
$$
S_{\xi\eta\zeta} = 1, \text{when}\; \xi=\nu, \eta=\sigma, \zeta=\mu.
$$
Then finally find the sum $T_{\xi\eta\zeta} + S_{\xi\eta\zeta}$. This procedure is quite complex and error-prone.
If you'd like to translate the equation
$$
T_{abc} = \mathrm dx^\sigma_a \mathrm dx^\mu_b \mathrm dx^\nu_c
$$
to concrete index notation
$$T_{\xi\eta\zeta} = \mathrm dx^\sigma_\xi \mathrm dx^\mu_\eta \mathrm dx^\nu_\zeta.
$$
It doesn't help much. Now $\mathrm dx^\sigma_\xi$ is a tensor whose components are all zero except
$$
\mathrm dx^\sigma_\xi = 1, \text{when}\; \xi=\sigma.
$$
You still need to concern about components. This is not natural. And 6 indices are mixed together, 3 of them are fixed numbers, very confusing.
Comment: Nice! Is there a way in which this fits with the notation $x^iy_j$ for the outer product?
Comment: Good answer, thank you. So just to clarify further: an abstract index is like an unbound variable, whereas a concrete index is like a bound variable or numeric value?
Comment: ... and I suppose each concrete index comes with an implicit specification of the basis, besides.
Comment: @Noldorin a concrete index is a counter in a tuple, same as in programming: it signifies the position of an element in an ordered set (such as a frame), but an abstract index is just a label, which meaning we both are trying to explain in our answers. Both abstract and concrete indices may appear free or bound, depending on the expressions that they are used in.
Comment: @YuriVyatkin Okay, but I think my second point still applies... that with a concrete index there is an (implicit) specification of the basis (treated as an ordered set). Whereas with an abstract index, we just say, "we don't care what basis we're in, these are just slot labels"?
Comment: @Noldorin correct. The whole point of the abstract index notation is to work in a coordinate-free manner, while retaining the mental mapping to familiar equations.
Comment: @YuriVyatkin Right, thanks. Between this and the above answers, I think I'm all on board with it now.
Answer: The expressions in the abstract index notation and the normal index notation look identical on purpose. This is done in order to retain the calculational flexibility of indices but have a coordinate-free treatment of the subject. The Wikipedia's article is well enough written, but it would also make sense to read the original Penrose's book where one finds most of the details. Examples are given throughout that book, by the way. Be sure, that you have read the digest of the first volume's chapter in the beginning of Volume 2  (I find that brief summary very illuminating). To be honest, I have to admit that Penrose's monograph is rather hard for the first reading, and a beginner should better consult with the first three chapters of the textbook of R. Wald, General relativity, where I personally found the cure against the fear of the abstract indices.
The conventions for abstract indexes are made so that the calculations' appearance is indistinguishable from the same calculations in concrete indices. Indeed, everything must be preserved if one introduces a frame to convert abstract indices into "normal" tensor indices.
So what would be the advantages of the abstract index notation? The main thing is that it is coordinate free. For instance, the Riemann curvature operator in abstract indices can be denoted by $R_{a b}{}^{c}{}_{d}$ at any point and the manifold, but if a coordinate chart or just a frame $\{E_{i}|i=1,\dots,n\}$ has been chosen (which is usually can be done only locally), one can pass to the components of the tensor $R_{a b}{}^{c}{}_{d}$ in this chart as follows
$$
R_{i j}{}^{k}{}_{l} = R_{a b}{}^{c}{}_{d} E^{a}{}_{i} E^{b}{}_{j} E_{c}{}^{k} E^{d}{}_{l}
$$
where the RHS is understood as
$$
R(E_{i},E_{j},E_{l})E_{k},
$$
Notice that in the above equations the indices from the range $a,b,c,\dots$ are seen as abstract, so whenever the same such index appears twice an action of a linear operator on an element of a vector space is assumed. In contrast with that, the indices form the range $i,j,k,\dots$ have numerical values ($1,2,\dots,n$), so when they pair up, the Einstein summation convention takes place.
Another advantage is that the abstract index is quite economical, and the expressions often look much shorter that in the usual coordinate-free notation, especially when one deals with tensor symmetries (compare, for instance the Bianchi identity in both notations).
Caveat. One needs to be told that the abstract indices are used, and also the index ranges must be specified, for instance, $a,b,c,\dots$ would be tensor indices, whereas $A,B,C,\dots$ can represent spinor or tractor indices, and so on.
A simple example of a calculation with abstract indices one can find, for instance, in this answer
Slightly more advanced examples are given here and also here.
Comment: Hi, I am not very good at these index related calculations. Can you please suggest a source where I should begin, or perhaps some advice to get better at calculations.


Calculate $\gcd(2a+4b, 2a +8b)$, if $a\equiv b \pmod{\! 5},\ 6a+11b = 5$

Question: Given:

$\ \ a$ is even

$\ \ \color{#90f}{6a+11b=5}$

$\ \ \color{#0af}{a\equiv b\pmod{\! 5}}$

Q: Calculate $\gcd(2a+4b,2a+8b)$

My try:
We know there is some $i$ such that $a=2i$, plus from 3 we know there is some $j$ such that: $a-b=5j$ which means $b=a-5j=2i-5j$. From 2, we get: $34i-55j=5$
So, $$\gcd(2a+4b,2a+8b)=\gcd(12i-20j,20i-40j).$$
I'm stuck here, how to continue?
Comment: I think the older version was easier for readers...
Comment: Welcome to the site!
Comment: @Buraian thanks, I have made more changes too :)
Comment: The answer below is probably more helpful, but right away you can factor a 4 out of both of your transformed versions :)
Comment: Have you tried finding examples $a,b?$
Answer: Use the property that $\gcd(m,n) = \gcd(m \mod n , n)$.
$$ (2a + 8b) \mod (2a+4b) = 4b \mod (2a+4b)$$
So, we have:
$$ \gcd(2a+ 4b, 2a+8b) = \gcd(2a+4b,4b)$$
Repeating the process, we have $$ \gcd(2a+4b,4b) = \gcd(2a,4b)= 4\gcd( \frac{a}{2},b)$$
Can you finish now?
Comment: you can't continue from here as we don't know gcd of half a and b
Comment: I discuss the gcd property in this [shameless self promotion vide](https://www.youtube.com/watch?v=tWig3Z5ABJw)
Answer: This helps with the last step after @Buraian's answer.
Now $\gcd(a,b) \in \{1,5\}$ because there is an integral linear combination of $a$ and $b$ that sums to $5$; in particular, $6a+11b=5$.
Meanwhile, as $a$ is even, it follows that $\frac{a}{2}$ is an integer, and as $\gcd(2,5)=1$, if $5|a$ then $5|\frac{a}{2}$. [In fact, let $k$ be any integer satisfying both $\gcd(k,5)=1$ and $k|a$, such as $k=2$. Then as $\gcd(a,b) \in \{1,5\}$, it follows that $\gcd\left(\frac{a}{k},b\right) = \gcd(a,b)$.] So from this it follows that $\gcd\left(\frac{a}{2},b\right)=\gcd(a,b)$.
So let us now calculate $\gcd(a,b)=\gcd\left(\frac{a}{2},b\right)$. Then from the first answer by @Buraian, $4\times \gcd(a,b) = \gcd(2a+4b,2a+8b)$.
Now, we claim that both $a$ and $b$ divide $5$. [Indeed, let $a \pmod 5 = r$. Then $b \pmod 5 =r$ as well, by the condition that $5|(a-b)$. However, on the one hand, (a) $6a+11b \pmod 5$ is $a \pmod 5 + b\pmod 5$ which is $2r$. As, on the other hand, (b) $6a+11b = 5 \equiv_5 0$ by hypothesis, it follows from putting (a) and (b) together that $2r \equiv_5 0$, so $r$ must be $0$, and thus indeed, both $a$ and $b$ divide $5$.] So $\gcd(a,b)$ must be a multiple of $5$. However, as noted already, $\gcd(a,b)$ is either $1$ or $5$, and so $\gcd(a,b)$ must indeed be exactly $5$.
As noted above, $\gcd(2a+4b,2a+8b)=4\gcd(a,b)$, so $\gcd(2a+4b,2a+8b)$ must be $4 \times 5 = 20$.
Comment: 6a+11b=5 taken mod 2  gives b= 1 meaning that b is odd. Since b has no factor of 2 , a/2 can be multiplied by any power of 2 and rhe equality holds. I don't understand how you deduced the equality from considering mod 5
Comment: @Buraian, Well, but you already know $\gcd(a,b)$ divides $5$, and so the gcd must already be **odd**, by the fact that there is an integral linear combination of $a$ and $b$ that gives $5$. So all that remains is to check whether both $a$ and $b$ divide $5$.
Comment: Ah right I see now. Thank you.
Comment: @Buraian It's much easier if we use use the basic relationship between the gcd and its linear transformation - see my answer.
Answer: Taking (2) and (3) mod 5 shows that $a+b=0$ and $a-b=0$ over ${\mathbb Z}/5{\mathbb Z}$. Clearly both $a$ and $b$ are multiple of $5$. Hence by (1), one may write $a=10a'$ and $b=5b'$. Using (2), one has $$6(10a')+11(5b')=5$$ $$\Leftrightarrow 12a'+11b'=1,$$ which implies that $\gcd(a',b')=1.$ Now since $a$ is even,$$\gcd(2a+4b,2a+8b)=4\gcd\left(\frac a 2+b,\frac a 2+2b\right)$$ $$=4\gcd(5a'+5b',5a'+10b')=20\gcd(a'+b',a'+2b')$$
$$=20\gcd(a'+b',b')=20\gcd(a',b')=20,$$ where one uses $\gcd(a,b)=\gcd(a-b,b),$ etc.
Answer: Below are a couple proofs that work generally for problems of this type. They highlight the key role played by the coprimality of the determinant $\color{#c00}{\Delta}$ of gcd linear transformations.

A quick, easy way via gcd laws: by $\,a\,$ even we can renotate $\,a\to 2a,\,$ so by $\,\rm\color{#c00}T \!=\,$this Theorem
$\qquad d := (4a\!+\!4b,4a\!+\!8b) = 4(a\!+\!b,a\!+\!2b)\overset{\bf\color{#c00}T}= 4\color{#0a0}{(a,b)}= \bbox[5px,border:1px solid #c00]{4\cdot\color{#0a0}5}\ $ by $\,\color{#c00}{\Delta = 1}\,$ in $\rm\color{#c00}T,\,$ and by
$\qquad (2)\ \&\ (3)\Rightarrow\! \begin{align} 12a\!+\!11b &= 5\\ 2a\ -\,\ b &= 5c\end{align}\, $ therefore $\,\color{#0a0}{(a,b)} \overset{\bf\color{#c00}T}= (5,5c)\!=\!\color{#0a0}5,\,$ by $\ \color{#c00}{\Delta = -34}$ coprime to $\color{#0a0}5$
We used the gcd distributive law to factor $\,4\,$ from the gcd in the first displayed equation above.

Alternatively we can avoid $\:\!\rm\color{#c00}T\,$ by using $(a\!+\!b,a\!+\!2b) = (a\!+\!b,b) = \color{#0a0}{(a,b)}\,$ by Euclid, and then finish using the following $\rm\color{#90f}{Bezout}$-based characterization of certain $\rm\color{#0a0}{gcds}$.
Thm $ $ $\,\ \color{#90f}{j\,a+k\,b\:\! =\:\! c}\ \:\!$ & $\:\!\ (c,\color{#c00}{j\!+\!k})\!=\!1\,\Rightarrow\,$ below are equivalent:
$(1)\qquad\! \color{#0af}{a\!\equiv\! b \pmod{\!c}}$
$(2)\qquad\! c\mid a,b$
$(3)\qquad\!\! \color{#0a0}{(a\,,b)=c}$
Proof
$(1\Rightarrow 2)\,\ \bmod c\!:\ 0\!\equiv\!\color{#90f}{c\!=\!ja\!+\!kb} \!\overset{\color{#0af}{a\,\equiv\,b_{\phantom |}}}\equiv\! (j\!+\!k)b$ $\smash{\overset{\times\ (\color{#c00}{j+k})^{-1}\!\!}\Longrightarrow}$ $b\!\equiv\! 0,\,$ so $\, a\!\equiv\! b\!\equiv\! 0.\,$
$(2\Rightarrow 3)\,\ $ a $\rm\color{#90f}{linear}$ common divisor $\,\color{#90f}{c}\,$ is greatest: $\,d\mid \color{#90f}{a,b}\Rightarrow d\mid \color{#90f}{c\!=\!ja\!+\!kb}$
$(3\Rightarrow 1)\,\ \ \color{#0a0}{c\mid a,b} \,\Rightarrow\, \color{#0af}{\bmod c\!:\,\ a\equiv 0\equiv b}$
Remark $ $ Note Thm is a special case of Theorem $\rm\color{#c00}{T},\,$ applied to the linear system ${\begin{align}\color{#0af}{a \:\!-\:\! b\:\! }&= \color{#0af}c\:\!d\\[-.1em]
\color{#90f}{ja\!+\!kb}&\color{#90f}=c\end{align}}\,$ with determinant  $\, \color{#c00}{\Delta =j\!+\!k}\ $ (similar to the first proof).


How do I set a variable to the value of a field another field?

Question: How do I set a variable to the value of a field another field?
For example, what is the equivalent of the following code, which should set the value of video_Source to the value of the field that is not empty/null?
{% set video_Source = content.field_video_upload or content.field_video_youtube %}

Answer: This is something better suited for preprocess in my opinion (I don't like a lot of conditional etc logic in twig files):
$variables['node_video'] = NULL;

if ($node ... field_a has value) {
  $variables['node_video'] = // set to render element for field a in 'content';
}

if ($node ... field_b has value) {
  $variables['node_video'] = // set to render element for field b in 'content';
}

Then in twig:
{% if node_video %}
  {{ node_video }}
{% endif %}

Basically, if this variable is not null, it should point to one of the $variables['content']['field...'] items from the preprocess code, then render it. {{ node_video }} in this case is the equivalent of {{ content.field_name }}, to spare a lot of IF/ELSE/OR stuff in Twig.
But what is likely easier is leveraging Media and Media Youtube with Media Video and using one field. That should scale. Imagine you want to add Vimeo, Twitch, or other supported Media sources in the future, you would have to keep expanding on this code.


If $2s=a+b+c$ , show that $16s(s-a)(s-b)(s-c)=2b^2c^2+2c^2a^2+2a^2b^2-a^4-b^4-c^4$

Question: If $2s=a+b+c$ , show that $\begin {align}16s(s-a)(s-b)(s-c)&=2b^2c^2+2c^2a^2+2a^2b^2-a^4-b^4-c^4\end{align}$
$\begin{align} \implies 16s(s^2-as-bs+ab)(s-c)&=2b^2c^2+2c^2a^2-c^4-(a^4-2a^2b^2+b^4)\end{align}$
$\begin{align}16s(s^3-cs^2-as^2+acs-bs^2+bcs+abs-abc)&=c^2(2b^2+2a^2-c^2)-(a^2-b^2)^2\end{align}$
$\begin{align}16s[(s^3-as^2)+(abs-bs^2)+(acs-cs^2)+(bcs-abc)]&=c^2(2b^2+2a^2-c^2)-(a^2-b^2)^2\end{align}$
$\begin {align}16s[s^2(s-a)+bs(a-s)+cs(a-s)+bc(s-a)]&=c^2(2b^2+2a^2-c^2)-(a^2-b^2)^2\end {align}$
$\begin {align}8(a+b+c)[s^2(s-a)-bs(s-a)-cs(s-a)+bc(s-a)]&=c^2(2b^2+2a^2-c^2)-(a+b)^2(a-b)^2 \end {align}$
So if I keep going on the left hand side, I will get the original equation $16s(s-a)(s-b)(s-c)$, while on the right hand side this is the extent of what I can do. The problem is I feel I am no closer to making the left hand side having the same equation as the right hand side. I feel like the left hand side can be left alone as $16s(s-a)(s-b)(s-c)$, while I need to find a way to manipulate the right hand side to produce a $2s=a+b+c$ term somehow. But I can't see how to do that. Any help would be appreciated. Thanks.
Comment: The same techniques from the other [question](https://math.stackexchange.com/questions/4685979/if-2s-abc-show-that-s-a3s-b3s-c33abc-s3) work here, too.
Answer: drop the $s$ as soon as possible. I am making everything become the difference of squares, as much as possible. At the very end we square a trinomial...
$$   LHS = 2s \; \;2(s-a) \;\;2(s-b) \;\; 2 (s-c)  $$
$$ LHS = (a+b+c) (-a+b+c)  (a-b+c)   (a+b-c)  $$
$$  (b+c +a) (b+c - a) \; \; (a+ (b-c))   (a-(b-c))  $$
$$  \left(  (b+c)^2 -a^2 \right)  \; \;   \left( a^2 - (b-c)^2  \right)  $$
getting there, give me a minute
$$  \left(b^2 + 2bc + c^2 - a^2 \right)        \left( a^2 - b^2 + 2bc - c^2\right)          $$
$$  \left( 2bc + (b^2 + c^2 - a^2)  \right)  \left( 2bc - (b^2 + c^2 - a^2)  \right)   $$
$$  LHS =   4 b^2 c^2 -  (b^2 + c^2 - a^2)^2  $$
need:
$$ (b^2 + c^2 - a^2)^2 = a^4 + b^4 + c^4 +2b^2 c^2 -2c^2 a^2 -2a^2b^2 $$
$$  LHS =   4 b^2 c^2    - a^4 - b^4 - c^4 -2b^2 c^2 +2c^2 a^2 +2a^2b^2 $$
$$  LHS =   2 b^2 c^2      +2c^2 a^2 +2a^2b^2    - a^4 - b^4 - c^4 $$
Answer: You are basically trying to prove the famous Heron's formula. It's absolutely possible to just brute force expand and cancel term by term and I genuinely think beginners should do this. But a simpler way is to start from the end. Group the right-hand side as:
$$f(a) = -(a^4-2a^2(b^2+c^2) +(b^2+c^2)^2-4b^2c^2) = -((a^2-b^2-c^2)^2-(2bc)^2) = ...$$
and so on. But I do suggest  you solve it by brute force expanding once. It's a useful skill if you are learning olympiad geometry and inequalities.


A new method to solve a SAS triangle: $\tan B =\frac{AC \sin C}{BC- AC \cos C}$. Should I publish?

Question: I've discovered a new method to solve SAS triangles without using the law of cosines:

In $\triangle ABC$, if sides $AC$ and $BC$, and angle $C$, are known, then: $$\tan B =\frac{AC \sin C}{BC- AC \cos C}$$

Putting in mind that I'm still a preparatory school student, which means that this is a great achievement for me, should I write a paper about this? or would it be a waste of time?
Comment: Congratulations on the discovery, both of the result itself and of the *satisfaction* mathematicians feel each time this happens. ... The result nicely abbreviates a bit of work that, eg, @MatthewDaly's answer shows, but since that work is pretty straightforward, the general benefit is reduced: it might take more effort to memorize your additional result than to just duplicate the steps. (In practice, a proof in a journal article or somesuch would typically skip these kinds of details anyway, leaving the reader to fill in gaps.) While I wouldn't consider this paper-worthy, it's pretty neat.
Comment: @jkabrg I know but I found another formula which can be used instead of the law of cosines (and the proof doesn't include the use of the law of cosines or sines)
Comment: Can you give a proof (or sketch of one) for your formula? Also I assume the x in the top is just "multiply", is that right?
Comment: A minor suggestion: such expressions almost always looks better with angles $\alpha,\beta,\gamma$
and sides $a,b,c$.
Answer: Not groundbreaking, but well observed!

With $\overline{AD}\perp\overline{BC}$,
$$\tan B=\frac{AD}{BD}=\frac{AD}{BC-CD}=\frac{AC\sin C}{BC-AC\cos C}$$
Comment: @AhmedM.Elsonbaty The discouraging thing is that all of the easy math has already been discovered.  ^_^  But this is the same process of discovery that will persist throughout a mathematical career!
Comment: and that's the same method I used."Not groundbreaking, but well observed!" ok I won't publish it but I will just leave it here
Comment: Beat me by a minute; +1 anyways.
Answer: Take the law of sines $$\frac{a}{\sin A}=\frac{b}{\sin B}$$ and rearrange to get $$\frac{a}{b}=\frac{\sin A}{\sin B}.$$
Divide both sides by $\sin C$ to get $$\frac{a}{b\sin C}=\frac{\sin A}{\sin B\sin C}$$ and write $A$ in terms of $B$ and $C$ to get
$$\frac{a}{b\sin C}=\frac{\sin(\pi-(B+C))}{\sin B\sin C}=\frac{\sin (B+C)}{\sin B\sin C}.$$
Using an identity, we get $$\frac{\sin(B+C)}{\sin B\sin C}=\csc B\csc C\sin (B+C)=\cot B+\cot C$$ and we have $$\cot B+\cot C=\frac{a}{b\sin C}.$$
Rearrange to get $$\cot B=\frac{a}{b\sin C}-\cot C$$ and write the RHS as a single rational expression:
$$\cot B=\frac{a}{b\sin C}-\frac{\cos C}{\sin C}=\frac{a-b\cos C}{b\sin C}.$$
Finally, reciprocate both sides to get $$\tan B=\frac{b\sin C}{a-b\cos C}$$ as desired.  This comes from the law of sines, after all.


Semilocal commutative ring with two or three maximal ideals

Question: Is there any equivalence condition for a commutative ring to have exactly two or three maximal ideals?
Comment: Not sure what you are after here exactly, but such rings are easy to construct. For example, consider the ring obtained from $\mathbb Z$ by inverting all integers relatively prime to $6$. This ring has two maximal ideals, those generated by $2$ and by $3$.
Comment: @user The ideals of that ring are precisely the extended ones from $\mathbb Z$, and all other primes meet the multiplicatively closed set, so they become the unit ideal in the ring of fractions.
Comment: @JohnBrevik That one is particularly interesting since it's also a domain, and therefore not semiperfect. The four idempotents of $R/J(R)$ can't lift to the two idempotents in $R$.
Comment: Right. A similar thing happens when you take the integral closure of the local ring of a node on a curve.
Comment: @JohnBrevik How can you prove that there is no maximal ideals other than $(2)$ and $(3)$?
Answer: I don't know if this could be usefull: I give to you some tricks to compute the number of maximal ideals of some kind of rings.
Consider the Jacobson radical $J(A)$ of a semilocal ring $A$ with maximal ideals $M_1, \dots , M_n$, then
$$ A/J(A) \simeq A/M_1 \oplus \dots \oplus A/{M_n} $$
Now, compute the number of factors of  $$ A/M_1 \oplus \dots \oplus A/M_n$$ is easy by looking at the primitive idempotents (I think there are serveral algorithms that do this, for example looking at the Kernel of the map that sends $x$ to $x^2$).
If $A$ is a finitely generated $k$ algebra, with $k$ algebrically closed, you have just to look at the $rank$ of $A/J(A)$ as $k$-module.
As an easy consequence of this fact, we can easy look at number of factors of a polynomial $p$ of $k[x]$:
If $p=\prod_1^n p_i$ (we can easy reduce to the case of a squarefree polynomial considering $p/GCD(p,p')$) we can consider
$$k[x]/(p) \simeq k[x]/(p_1) \oplus \dots \oplus k[x]/(p_n) $$
and count the number of idempotents in the $k$ algebra above!
For some algorithms to compute idempotents you can look at P.Gianni,V. Miller,B. Trager -  Decomposition of Algebras
Other ways:
If $A$ is a finetely generated $k$-alebra (say $k[x_1, \dots , x_n]/I$), then the number of its maximal ideals is the number of closed points of $V(I)$.
To find the number of this closed points, compute the reduced Grobner base $RG$ of $I$ and count the number of lattice points in the sub-escalier of $RG$.
You can find a better description of this metod in my answer Here
Comment: The maximal ideals of $A$ correspond exactly to those of $A/J(A)$, and since the latter is just a product of fields ($n$ of them, say) then it is elementary that there are $n$ maximal ideals.
Comment: You're reasoning is trivial "a posteriori", if you  "a priori" don't know anyting on the number of Maximal ideals but know someting about the jacobson radical (as in the the case of $k[x]/(p)$), well just look at $A/J(A)$ and compute its primitive idempotents.
Comment: Observe that, if you don't know the number of maximal ideals, you can't compute the number of fields in the product....
Comment: I didn't realize you were looking for a way to determine $n$, sorry. I took the decomposition for granted. Regards
Answer: The most straightforward characterization that comes to mind is this:

A commutative ring $R$ has only two (resp three, or $n$) maximal ideals iff $R/J(R)$ is isomorphic to the direct product of two (resp three, or $n$) fields. ($J(R)$ denotes the Jacobson radical of $R$.)

I guess you are probably looking for something along the lines of the nice characterization of local rings in terms of elements. I have not heard of a nice counterpart for more maximal ideals, not even the special cases of $2$ or $3$.
There is only one nice theorem I have ever heard regarding rings having exactly two maximal ideals:

The endomorphism ring of a nonzero uniserial right module (one in which the submodules form a chain) has exactly one or exactly two maximal right ideals.

If I recall correctly, one of the ideals is comprised totally of non-surjective endomorphisms, and the other is non-injective endomorphisms (see page 22 for example. It can also be found in Lam's First Course in Noncommutative Rings) It is problematic, of course, to know when these endomorphism rings would be commutative.


NSNumber from AppDelegate won't compare correctly

Question: What I've got is a NSNumber which is created in the AppDelegate and holds a numberWithBool:TRUE and a ViewController in which a comparison should be made.
My problem is, that the ViewController doesn't recognize that my NSNumber is set as 1. The debugger proves that the NSNumber is really set as 1 but nothing is happening.
if([appDelegate.gotUrl isEqualToNumber:[NSNumber numberWithBool:TRUE]])
{
    //will do nothing
}

Any solutions for my problem?
Thanks in advance
Comment: Try `if (appDelegate.gotUrl.boolValue) {...}` - does that work?
Comment: also note you can use `@YES` instead of `[NSNumber numberWithBool:YES]`.
Comment: Tried Product -> Clean ? I have tried numerous versions of this code you give and I can't make it fail. Either you are actually comparing a value that isn't set or is false (sets to false by default) or something is wrong which Clean would fix
Comment: Try checking with ...numberWithBool:FALSE] and see if that is triggered, then you know that this property is set to false.  When you set "gotUrl", is that variable a property or local variable ? When you set it, do you use self.gotUrl = TRUE or just "gotUrl = TRUE", there is a difference
Answer: if([appDelegate.gotUrl boolValue])
{
    // might do something
}


Why aren't 1 and -1 included in the graph of signum fuction?

Question: source : https://en.wikipedia.org/wiki/Sign_function#/media/File:Signum_function.svg
As you can see in the graph that 1 and -1 are open circles and aren't included. But the range of the signum function is {1,0,-1} so I'm unable to understand why 1 and -1 are open circles in the graph and whereas 0 isn't because the function is discontinuous at 0.
Comment: How would you draw the graph in such a way that the value at $0$ is $0$, but everywhere else it's either $-1$ or $1$?
Comment: Possibly because the Fourier series converges to 0 at 0.
Comment: @Dayton This question has nothing to do with Fourier series.
Comment: Review the definition of a function.
Answer: The function has to take one value at zero only, so you have to choose between $-1, 0, 1$ when defining it. Here $0$ is chosen


Erro 500 ao acessar página usando CheckSpelling no htaccess

Question: Tenho vários arquivos com tags de imagem, nessas imagens o nome do caminho tem letras maiúsculas e minúsculas, por exemplo:

Não é possível eu alterar o nome de todas as imagens, por que têm milhares, então usei a opção CheckSpelling do .htaccess só que se eu colocar no xampp essa opção, ocorre o seguinte erro:
Erro interno do Servidor!

O servidor encontrou um erro interno e não foi possível completar sua requisição. O servidor está sobrecarregado ou existe um erro em um script CGI.

Se você acredita ter encontrado um problema no servidor, por favor entre em contato com o webmaster.

Error 500

localhost
Apache/2.4.12 (Win32) OpenSSL/1.0.1m PHP/5.5.27

Não sei como proceder, segue o arquivo .htaccess:
RewriteEngine On
CheckSpelling On

Não sei como proceder, obrigado.
Comment: Boa tarde Furlan, coloque o conteudo do htaccess. LEIA: http://pt.stackoverflow.com/help/mcve - Entenda como uma critica construtiva. Assim que postar o conteudo do .htaccess eu prometo rentar responder
Comment: Obrigado por responder @GuilhermeNascimento , ja está adicionado a pergunta o código do .htaccess
Answer: O RewriteEngine On é usado pra mod_rewrite, mas não há nada escrito, ou seja ele parece não fazer nada, então remova.
Já o CheckSpelling On é provavel que esteja desabilitado, então você deve habilitar ele no arquivo httpd.conf, basta procurar um lugar semelhante a este:
LoadModule rewrite_module modules/mod_rewrite.so
LoadModule setenvif_module modules/mod_setenvif.so
LoadModule status_module modules/mod_status.so
LoadModule vhost_alias_module modules/mod_vhost_alias.so

E adicionar após eles isto:
LoadModule speling_module modules/mod_speling.so

Em seguida reinicie o Apache (o Xampp) e teste novamente.
Comment: Obrigado @Guilherme funcionou perfeitamente!


Teclado virtual em HTML5 e JS

Question: Olá,
Estou precisando de ajuda na construção de um teclado numérico virtual em HTML5 e JS, para um site mobile, porem o campo input numérico ao ser clicado não pode acionar o teclado padrão do dispositivo, como se o input não fosse um campo editável para o navegador e sim somente para o teclado virtual.
Desde já agradeço a atenção de todos.
Comment: @MoshMage, o teclado numérico não e o problema, o problema e quanto eu clico no 'input' o teclado do celular aparece automaticamente e é isso queria evitar, para que o usuário utilizasse o teclado que eu fiz e não o teclado padrão do celular.
Comment: Poste o código.
Comment: Porque é que não trocas o campo input por outro qualquer, como um botão, e quando clicado abre então esse teu teclado virutal (que, suponho que seja feito por botoes em vez de input)
Answer: Procurando "virtual keyboard javascript" no google encontrei isso:
https://mottie.github.io/Keyboard/

Teclado virtual em HTML5 e JS


Add new view controller and push on that in cocoa application

Question: I am new to OS X application. In iOS there is methods like :
1. self.window.rootViewController = self.viewController;
2. [self.window addSubview:self.viewController.view];

to add view controller in window or
3. DefaultViewController *objDefault = [[DefaultViewController alloc] initWithNibName:@"DefaultViewController" bundle:nil];
   [self.navigationController pushViewController:objDefault animated:TRUE];
4. DefaultViewController *objDefault = [[DefaultViewController alloc] initWithNibName:@"DefaultViewController" bundle:nil];
   [self presentViewController: objDefault animated:TRUE completion:nil];

to push on next view controller.
My question is that in OS X is there any method like above to add new view controller to window or push on next view controller..?
Answer: Cocoa and Cocoa-touch have a little different ways to change views on the window.
To change views you need to programmatically remove old subview and add new one.
- (void)addNewSubview:(NSView *)view // NSWindowController subclass implementation file
{
  [_subview removeFromSuperview];
  NSView *contentView = (NSView *)self.contentView;
  [contentView addSubview:view];
  _subview = view;
}

or simple [contentView replaceSubview:_subview with:view];
Since OS X 10.10 there's an opportunity to use storyboards something like in iOS.
UPD
To awake window from the application delegate class create your NSWindowController-subclass instance and show the window (it's mostly like in iOS' before-storyboards era).
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification
{
  CustomWindowController *controller = [[CustomWindowController alloc] initWithWindowNibName:@"CustomWindowController"];
  [controller showWindow:nil];
  [controller.window makeKeyAndOrderFront:nil];
}

Comment: I have subclass of NSViewController, and I want to add this one in `- (void)applicationDidFinishLaunching:(NSNotification *)aNotification`. Then How it can be achieved..?
Answer: If you are using storyboards and segues to show a new NSViewController, then you might need to close the old view controller. Here is how I do it:
- (void)prepareForSegue:(NSStoryboardSegue *)segue sender:(id)sender
{
    [self.view.window close];
}

Each view controller itself creates a window, so you need to close the old one before showing the new one.


How to count the number of checked Checkboxes with Rules?

Question: I have a Drupal Commerce site which uses user points (= coins) for paying.
I have a special case - the product, which the user should buy with his/her coins, needs some fields filled out by the user. So I used a content type for this case and when the user adds a new one, 10 coins will be reduced from the user's account - this works already fine.
Now I have also a taxonomy in this content type and the user can add terms to it, which are shown later in the form when the user fills it.
Problem :
I need to count how many checkboxes of the taxonomy terms are checked and multiply the costs with them. So if 3 of 5 are checked, then 10 coins * 3 = 30 coins will be the final price when the user adds a new content type.
Is this possible with Rules? I have no clue how to realize that
(I´m front-end developer and no PHP coder).
Comment: hi, thanks for your answer, was not able to test it yet because the project got postponed.
Comment: sorry, had to google how to accept an answer, i´m a totally stackexchange newbie
Comment: merci for the accept ... maybe you were looking for http://drupal.stackexchange.com/help/someone-answers ...?
Answer: Yes this is perfectly possible with Rules, and you don't need any PHP to get the job done. In your case, the crucial part of such rule is a Rules Action to perform a Loop. If you're not familiar with such loops, then I strongly recommend to have a look at the tutorial titled "Lists and loops".
In your case, you should use (at least) these Rules Actions:

"Add a variable" (say with a machine name like nr_of_checked_terms), with initial value "0".
Add a loop related to your taxonomy terms. After you do, you should iterate over each item in that list (= each taxonomy term). And for each iteration you should then perform a Rules Action to "Set a data value", whereas you actually increment the value of nr_of_checked_terms with "1".

After the loop finished, the value of nr_of_checked_terms will be the actual number of terms that were checked. Just add another Rules Action near the end to do your actual multiplication using nr_of_checked_terms as one of the available tokens.
Done
PS 1: Refer to my answer to "How to set multiple values to an unlimited Term Refence field with Rules" for some sample rules that are like a variation of your question here.
PS 2: I assume this is about D7 ...
Comment: hi, thanks a lot for your answer, yes, it was about D7


JasperReports, Documento Não Contém Paginas?

Question: Olá, sou novato com JasperReports e estou enfrentando um problema para conseguir gerar meu primeiro relatório (um DANFE), tudo que vi sobre o jasper até aqui envolvia banco de dados, como minha aplicação não usa banco ignorei isso e estou tentando passar os dados via HashMap, tudo aparenta estar ok, a aplicação funciona perfeitamente, mas quando o relatório vai abrir recebo uma mensagem dizendo que o documento não possui páginas, jás testei outros layouts JRXML que que encontrei por ai, nenhum abre, segue o código que carrega o jasper.
private void loader(){
    try{

        JasperReport jr = JasperCompileManager.compileReport("src/jasper/teste.jrxml");
        Map dados = new HashMap();
        dados.put("Emit_CNPJ", this.nfe.getEmitente().getCnpj());
        JasperPrint jp = JasperFillManager.fillReport(jr, dados);
        JasperViewer jv = new JasperViewer(jp, false);
        jv.setTitle("DANFE");
        jv.setVisible(true);

        debug.log("DANFE carregada com sucesso.");
    }catch(JRException ex){
        debug.log("Falha ao carregar JasperReports.");
        //Logger.getLogger(Visualizer.class.getName()).log(Level.SEVERE, null, ex);
    }
}

Comment: O seu arquivo teste.jrxml está com todos os parâmetros certinhos?
Answer: Os dados que vc quer passar pro jasper, estão em um banco de dados? Analisando seu código, eu tenho um exemplo sobre passar parametros pro jasper, porem estes dados estão em um banco de dados, saca só:
JasperReport jasperR;
JasperPrint jasperP;
JRResultSetDataSource jrRS;
Map parametros;

rs=stmt.executeQuery("Select * from tabela");
/* implementação da interface JRDataSource para DataSource ResultSet */
jrRS = new JRResultSetDataSource( rs );// no caso, o rs seria o resultado da query.

parametros = new HashMap();
jasperR = JasperCompileManager.compileReport("report1.jrxml");
jasperP = JasperFillManager.fillReport(jasperR, parametros, jrRS);

Na última linha, tem 3 parâmetros, o report do jasper, o hash map como segundo, e o result set como ultimo parâmetro.
Espero ter te ajudado.
Comment: Fiz exatamente como no exemplo do @Thiago e não deu certo.. continua aparecendo documento não contem páginas..
Answer: Olá, volto aqui para agradecer pelas respostas, felizmente já consegui resolver o problema, não sei se é correto mas por hora o relatório está sendo exibido, ao que tudo indica o jasper não exibe o relatório sem um "DataSource", por isso na linha:
JasperPrint jp = JasperFillManager.fillReport(jr, dados);

adicionei um BeanCollection passando um arrayList
... JasperFillManager.fillReport(jr, dados, new JRBeanCollectionDataSource(lista));

isso resolveu o problema.


CSS class auto suggestion in eclipse

Question: So far I have used netbeans, now I am planning to switch in eclipse , everything is fine but like in netbeans it doesn't provide me css class proposal. In netbeans if I use or write any css class , that class will be automatically appeared in css file as proposal even , in html/php file it shows class proposal from previously used class or class from framework like bootstrap , like the images below
for css file

for php file

But if I work in eclipse no css class or id proposal are showing . Like images below .
for php file in eclipse

for css file in eclipse

I am using eclipse mars  and WTP WebResources plugin is installed
Comment: I have the same exact problem. I tried both "Eclipse Neon for PHP" and "Eclipse Neon for JavaScript and Web Development". It refuses to show the CSS suggestions. Incredibly frustrating. If you figure it out, please shout it. Thank you.
Answer: Reinstall the Eclipse Web Toolkit Platform packages. You can do that either using the Eclipse Marketplace tool or Install New Software under the Help menu.
WTP Tools in Eclipse marketplace

Or you can install the Genuitec Webclipse packages which provides a more robust web development environment for front end developers.
https://www.genuitec.com/products/webclipse/
Comment: I'd say this is more of a question/comment to the original poster than an actual answer.

CSS class auto suggestion in eclipse


Does $1^i$ and $1^{\frac{0}{0}}$ also give $1$ again?

Question: This is the property of Real number $1$ that,
$1^n=1$ does this property only hold $\forall n \in \mathbb R$ or also $1^i=1$ and $1^{\frac{0}{0}}=1$
If it is; explain how?
I think that it should not give us $1$ again as we can't determine what is the square root of number $-1$ and similarly $\frac{0}{0}$ is indeterminate and so we can't proceed. May be I am wrong.
Comment: $1^i=\left(e^0\right)^i=e^{0\cdot i}=e^0=1$
Comment: But $\frac00$ isn't a number, so what would it even mean to talk about $1^\frac00$?
Comment: As for $1^i$: this answer to a related question says it all: http://math.stackexchange.com/a/3674/101420
Comment: My question involves "what is $1^{\frac{0}{0}}$" and the question you are talking about doesn't.
Comment: $\frac{0}{0}$ is indeterminate that is, we don't know that how many $0s$ are in $0$. Either one or many zeros or no zero. So I think that $1^{\frac{0}{0}}$ may or may not give us $1$. That confused me.
Answer: $1^i$ is defined as $e^{i \ln 1}$
$\ln 1$, though, it's not our real logarithm, but it's the complex one; the point is that is a multi-valued function; to be more precise,
$$\ln z = \ln_\mathbb R |z| + (\arg z + 2k\pi)i$$
Where with $\ln_\mathbb R$ I mean the usual real logarithm.
So $\ln 1 = \ln_\mathbb R 1 + (2k\pi)i = 2k\pi i$
Hence $$1^i = e^{i \ln 1} = e^{-2k\pi}$$
So $1^i$ it's not really a number, it's more like a set of numbers; all the numbers in the form $e^{-2k\pi}$, $k \in \mathbb Z$.
The value $k=0$ is special and it's sometimes called the principal value; choosing this value for $k$ clearly results in $1^i = 1$, but it's important to understand that $1^i$ is not a well-defined number.

Note that, as @Jonathan Y. points out, a similar argument also holds for $1^{3/5}$. And if one thinks about it also for $\sqrt 1$, which is not a number but the set $\pm 1$.
The point is that we can define without ambiguity $\sqrt 1$ (take the positive value) and $1^{3/5}$ (there is only one real root).
One could naively think that the same could be done with $1^i$; just define in some way a special value and work with that. The point is that it can't be done; there is no way to specify a value without ambiguity and carry on all the usual algebra rules. So we're stuck with this multi valued definition if we are in the complex plane; if we are on the real line, instead, it's possible to define $a^{b/c}$ as a single value.
P.S. The principal value I referred to earlier it's sometimes useful but problems arise if you define the complex logarithm as it's principal value. Once you start studying complex analysis and (for example) the residue theorem it should be clear why :-)
Comment: A similar argument could be made for, e.g., $1^{3/5}$, which (I think) is even more startling.
Comment: @JonathanY. Thanks! I've edited the answer to include it :)
Answer: $1^i$ is a multi-valued quantity $$e^{i\theta}=\cos\theta+i\sin\theta\implies e^{2n\pi i}=1\implies1^i=\color{RED}{e^{-2n\pi }}$$ for any integer $n.$
Answer: Maybe you would like to know that the exponentiation by complex number does not work very well. The previous answers are correct, but what if you think like this?
$$1^i=(i^4)^i=(i^i)^4=((e^{i\frac{\pi}{2}})^i)^4=(e^{-\frac{\pi}{2}})^4=e^{-2\pi} \neq 1$$
Where is our God now? You have to be very careful when you do exponentiation with complex numbers.


Getting file modification time on UNIX using utime in C

Question: I have been told by a professor that you can get a file's last modification time by using utime.h. However, the man page seem to cite that utime() only sets this value. How can I look up the last time a file was changed in C on a UNIX system?
Answer: This returns the file's mtime, the "time of last data modification". Note that Unix also has a concept ctime, the "time of last status change"  (see also ctime, atime, mtime).
<code>#include <sys/types.h>
#include <sys/stat.h>

time_t get_mtime(const char *path)
{
    struct stat statbuf;
    if (stat(path, &statbuf) == -1) {
        perror(path);
        exit(1);
    }
    return statbuf.st_mtime;
}
</code>
Comment: This was answered in 2010 but it's 2016 now and nanosecond resolution has been implemented since Linux kernel 2.5.48, POSIX.1-2008 and glibc 2.12. So using `statbuf.st_mtim` to get a `struct timespec` instead of using `statbuf.st_mtime` should work everwhere these days.
Comment: @AldySyahdeini `localtime(3)`
Answer: You can use the stat system call to get the last access and modification times.


Completeness of a metric with discrete topology

Question: Let $\mathbb{N}$ be a set of natural numbers. Define a metric $d$ as follows,
$$d(m,n)=\left |\frac{m-n}{mn} \right | \quad for \: all \: m,n \in \mathbb{N}.$$ With this metric, every singleton subset of $\mathbb{N}$ is an open set. Hence topology generated by this metric is a discrete topology. Every discrete metric space is a complete metric space. But here $\mathbb{N}$ is not a complete metric space, because $1,2,3, \dots$ is a Cauchy sequence in $(\mathbb{N},d)$, which is not convergent. I don't understand why this happened? The set $\mathbb{N}$ with discrete topology is complete with one metric while it is not complete with another metric generating the same topology.
Answer: $\{1,\frac 1 2 ,\frac  1 3,..\}$ has discrete topology w.r.t. the usual metric but this is not complete. A set with the discrete metric is complete but not every metric space with discrete topology is complete.
Comment: @ganesh Completeness is a 'metric property'. Topology alone does not give completeness.
Comment: Thanks. So, these are counterexamples for the statement "every metric space with discrete topology is complete".


How to correctly add meta tags to custom menu items?

Question: I want to be able to use the meta tag module for everything my site, but currently I have no idea how to add meta tags to custom pages. For example, I have this page:
function mymodule_menu()
{
    $items = array();
    $items['home'] = array(
      'title' => 'Home',
      'page callback' => 'mymodule_home_page',
      'access callback' => TRUE,
    );
    return $items;
}

function mymodule()
{
    $o = '';
    $o .= 'hello world';
    return $o;
}

Such a page doesn't get meta tags as it is a custom page. What is the best way to get meta tags on the page in this case? Or what is wrong with my strategy?
Answer: You can do this manually by using drupal_add_html_head(); in your menu's callback function
<?php

function mymodule_home_page() {

  $element = array(
    '#tag' => 'meta',
    '#attributes' => array(
      'name' => 'custom meta info',
      'content' => 'test content',
      'attributes' => 'D7',
    ),
  );
  drupal_add_html_head($element, 'Test');

  return 'hello';
}
?>

or some modules will allow you to add custom paths.


Random Walk with Drift: Why is the change in a trending variable also a function of a random variable when $E(\epsilon_t) = 0$?

Question: I came across Pearson's companion site of Murray, M. P. (2005). Econometrics: A modern introduction. Pearson Higher Education.
While skimming through the related lecture slides here http://wps.aw.com/wps/media/objects/2387/2445250/PPTs/ch18lectr26.ppt, there is something I don't get.
Slide #26-7 of the aformentioned powerpoint presentation correctly states that $E(v_t) = 0$. Given this assumption I do not understand why $E(Y_t) - E({Y_{t - 1}}) = \alpha + v_t$ as stated on slide #26-5: "The trending variable changes by a random amount each period". I think $v_t$ should drop out of the equation if the general assumption $E(v_t) = 0$ holds. Notice that slide #26-7 also states that $v_t$ is a random variable with $E(v_t) = 0$. So, if $E(v_t) = 0$ holds in general, why is $v_t$ still included in $E(Y_t) - E({Y_{t - 1}})$ above?
Comment: You are right. The correct formulation is on page 26-7.
Comment: @ChristophHanck: Thanks for your comment. 26-7 refers to the difference between successive periods, not beween the their expected values. Thus, am I right that the equation E(Y_t)−E(Y_t−1)=α+v_t is simply false?
Comment: Yes, if you take expectation on the left-hand side of the equation, you do so on the right-hand, too, and then $E(v_t)=0$ applies, as you correctly pointed out.
Comment: @ChristophHanck Thanks a million, that helps. To me it then appears that the actual difference betwen the expected values is E(Yt)−E(Yt−1) = α, which is confusing because it is pretty much in line with a deterministic trend. In other words, the book fails to show the difference between a deterministic and stochastic trend.
Comment: I now give a proper answer to your last question in the comments, see below.
Comment: @ChristophHanck Danke! ;) You answer is exactly what I suspected: The nonstationarity is what makes the difference between the deterministic and stochastic models. Sigh of relief…
Comment: Let us [continue this discussion in chat](http://chat.stackexchange.com/rooms/44044/discussion-between-denominator-and-christoph-hanck).
Answer: Let my give an answer to your last question in the comments:
We have the stochastic trend model $Y_t=\alpha+Y_{t-1}+v_t$ for which, as discussed in the comments,
$$
E(\Delta Y_t)=\alpha
$$
On the other hand, the deterministic trend model has $Y_t=\beta_0+\beta_1t+v_t$ and thus
$$
\Delta Y_t=\beta_0+\beta_1t+v_t-[\beta_0+\beta_1(t-1)+v_{t-1}]=\beta_1+\Delta v_t
$$
so that, indeed,
$$
E(\Delta Y_t)=\beta_1
$$
Hence, the two processes are indeed equivalent in terms of their expected drift.
They are not in terms of their variances, however. By recursive substitution (and assuming $Y_0=0$), you can write the stochastic trend model as
$$
Y_t=t\alpha+\sum_{s=1}^tv_s,
$$
which has variance
$$
Var(Y_t)=t\sigma^2_v
$$
whereas the deterministic trend process has variance
$$
Var(Y_t)=\sigma^2_v
$$
Playing around with the code
<code>alpha <- beta1 <- .1
beta0 <- 0
t <- 100
v <- rnorm(t)
Y.ST <- 1:t*alpha+cumsum(v)
Y.DT <- beta0 + beta1*1:t + v
plot(Y.ST, type="l", col="gold", lwd=2)
lines(Y.DT, col="purple", lwd=2)
</code>
will show differences between the two processes. If you pick a large value for the drift or a small standard deviation for the errors, the differences will tend to get blurred for moderate $t$, though.


function create with show project details by id in laravel

Question: Controller:
    public function create(Request $id)
{
    $data = OperationalPlan::findOrFail($id);
    $val = explode("|-|",$data->text);
    $nval = explode("|-|",$data->ntext);
    $neval = explode("|-|",$data->netext);
    $newval = explode("|-|",$data->newtext);
    $mnue1 = StrategicGoal::get();
    $mnue2 = Measurement::get();
    $mnue3 = tawagh::get();
    $mnue4 = detailed_target::get();
    $mnue5 = Management::get();
    $mnue6 = Department::get();
    $mnue7 = activety::where([['department', Auth::user()->department],['is_confirmed', 1],['is_deleted',0],])->get();

    return view('user.report.create' . $id , compact('mnue1', 'mnue2','mnue3', 'mnue4', 'mnue5', 'mnue6','mnue7',
    'val', 'nval', 'neval', 'newval', 'data'));
}

route:
  Route::get('/report/create/{id}','User\ReportController@create')->name('dashboard.report.create.id');

url :
id) }}" class="" title="View">

the message error is :
Property [text] does not exist on this collection instance.

can some one helps me please i tried to fix this but i do not got it.
Answer: Sure, remove the type-hint on $id. The 'id' being passed is NOT a Request:
public function create($id)

When you type-hinted that as Request, $id ends up being a Request object. When you pass that to findOrFail which will call find which will then call findMany, it will end up converting the Request to an array with toArray() since Request is Arrayable. This will end up returning a Collection because it thinks you are trying to find many records not a single record.
In short with what you had you ended up passing the array of inputs to find, not the 'id' you are looking for.
Comment: Thank you your answer helps me to find out the solution, I use find and also i use (Request $r) and defined a variable $id = $r->input('id'); .


How do I find which Java version is being used to execute my rules on Bluemix?

Question: I am executing my rules on the Business Rules service on Bluemix, and want to know which Java runtime version is used. How do I find this information?
Answer: This information is available if I enable tracing for the payload, for example by invoking it using https://brsv2-instanceID.domain/DecisionService/run.jsp?path=/ruleApp/1.0/ruleset/1.0&trace=true
(for example: https://brsv2-12345678.ng.bluemix.net/DecisionService/run.jsp?path=/myRuleApp/1.0/myRules/1.0&trace=true)
I made sure that infoSystemProperties was set to true for JSON.
The trace after execution of the request contains a "systemProperties" element/entry, which includes the Java information.
The answer How can I trace rules in the Business Rules service on Bluemix? has more information on tracing.


Fazendo Calculo do IMC não estou conseguindo só da o resultado 80

Question: #include <stdio.h>
#include <math.h>

int main()
{
    float peso,altura,imc;
    imc=0;
    printf("digite seu peso ?");
    scanf("%f",&peso);
    printf("digite sua altura? ");
    scanf("%f",&altura);
    imc= (peso/pow(altura,2 )); //usando a função pow
    printf(" IMC igual a  %10.2f ",imc);

    return 0;
}

e sem usar a função pow
#include <stdio.h>
#include <math.h>

int main()
{      float peso,altura,imc;
   imc=0;
    printf("digite seu peso ?");
    scanf("%f",&peso);
    printf("digite sua altura? ");
    scanf("%f",&altura);   // usando a função pow
    imc= (peso/altura*altura) ; // sem a função pow
    printf(" IMC igual a  %10.2f ",imc);

    return 0;
}

Comment: **Gabriel**, você pode [editar](https://pt.stackoverflow.com/posts/329878/edit) a pergunta e descrever o problema, caso necessite de ajuda sobre como utilizar a ferramenta, acesse a [help].
Answer: No primeiro teste não foi possivel reproduzir seu problema:

https://ideone.com/m4IVad

No segundo é erro básico de matemática.
Primeiro você divide peso pela altura, depos você multiplica pela altura:
     peso/altura*altura
// 1 ----^
// 2 -----------^

O resultado, adivinhe? Vai ser a altura1...
Veja a diferença com os parênteses no lugar apropriado:
imc = peso/(altura*altura);

https://ideone.com/LTEK5K

1. exceto diferenças de arredondamento que não vem ao caso neste exercício..


Proving Graphs Properties (common neighbors)

Question: I'm struggling with two different-but similar questions. I'm pretty new with the subject so will really appreciate explanation on how to approach these kind of question

Prove that in every 10 vertices graph with 28 edges there are 2 vertices with two different neighbors.
Prove that in any graph G with $|V|=n$ and $d(v)=\sqrt(n)$ $\forall v\in\ V$
there is a triangle or 2 vertices with two different neighbors.
Comment: Are there any precisions for 1 ?  Does it have to be connected ?  Because you can take $K_8$, the complete graph on 8 vertices, then add 2 isolated vertices (vertices with no edges incident to them).   This graph has 10 vertices, and no pair of vertices have different neighbors.
Comment: But the proof should be for any 10 vertices Graph with 28 edges, not only the complete graph
Comment: And I wrote the question as it's written in the book (translation from Hebrew)
Comment: Yes, but I didn't provide a proof - it's a counter-example to show that NOT every 10 vertices graphs have this property.  My guess is that is it assumed that the graph is connected.
Comment: okay, assuming it's connected- any suggestions?
Comment: I don't wanna bother you, but is "having two different neighbors" formally defined ?  Because from my understanding of it, 1. is false and 2. is (almost) trivial, so that's strange. My interpretation : say I have a graph on 4 vertices $a,b,c,d$ with $E(G) = \{ab, bc, cd, da\}$.  Then $a$ and $d$ are two vertices with two different neighbors (because $a$ has $b$, and $d$ has $c$).
Comment: That's my interpretation either. but how do I prove that in a graph with 10 vertices and 28 edges- there are always 2 vertices like the ones mentioned above?
Comment: And 3 might be trivial to you :) would appreciate an explanation :)
Comment: Edited answer to include the solution for the second problem. Note that a better (and stronger) version of the second problem reads: "Prove that in any graph $G$ with $|V|=n^2$ and minimum degree at least $n$ there is a triangle or 2 vertices with at least two common neighbours".
Answer: The title talks about "common neighbours", but the question itself is about "different neighbours".
This answer will convince you that "common neighbours" are meant.
We need a few lemma's. I'll just state them, they are easy to prove, let me know if you have trouble.
$G$ is our graph, $n$ is the vertex count, $e$ the edge count.
Lemma 1:
The average "sum of degrees" over pairs of different vertices is twice
the average degree (in formula: $\frac{\sum_{v\ne w}(d(v)+d(w)}{n}=\frac{4e}{n}$).
Lemma 2:
If we have vertices $v$ and $w$ with $d(v)+d(w)\geq n+2$ then $v$ and $w$ have at least two common neighbours.
Lemma 3:
If we have vertices $v$ and $w$ with $d(v)+d(w)\geq n$ and $G$ is triangle-free then
$v$ and $w$ have at least two common neighbours.
The first problem:
Lemma 1 tells us that the average "sum of degrees" is $\frac{4e}{n}>11$.
The pigeonhole principle now gives us a pair $v,w, v\ne w$ with $d(v)+d(w)\geq 12=n+2$,
so lemma 2 tells us that $v$ and $w$ have two common neighbours.
Note that the proof fails for $e=27$, which is strong evidence that "common neighbours"
is the proper choice to make.
The second problem is easier (or at least more common knowledge).
Note that "no two vertices with 2 common neighbours" is equivalent to "no $C_4$".
So we just need to show that a graph with girth 5 (no triangle $C_3$ and no $C_4$)
and minimum degree degree at least $n$ has more than $n^2$ vertices and this is a standard result:
let $v$ be an arbitrary vertex. $v$ has at least $n$ neighbours $w_1,\ldots,w_n$.
Each of this neighbours has itself has at least $n-1$ neighbours different from $v$. $w_i$ cannot
be a neighbour of $w_j$ (or we would have triangle $vw_iw_j$) and $w_i$ can $w_j$
cannot have a common neighbour $z$ (or we would have $C_4$ $vw_izw_j$).
So $G$ has at least $1+n+n(n-1)=n^2+1$ vertices.
Comment: Very nice !  Though it's still instructive to try to answer 1) as stated in the question !
Comment: @manuellafond:
The question as posed is rather unclear.
The most obvious interpretation leads to a question that is trivial and pointless.
The answer would be:
there are at least 2 vertices of degree at least 2, so there are two vertices with two different neighbours.


Spring Integration - Is it Possible for TCP Server to disconnect selective clients

Question: I am implementing Spring Integration (4.x Release) TCP server in my application. Where multiple clients will connect to my TCP server port. My applicaiton will start receiving multiple requests and there is one scenario where my TCP server should disconnect one of its TCP client keeping the conneciton alive with other clients.
I am able to get the openConnectionIds from server conneciton factory but not able to disconnect the selected client.
How to disconnect one of the TCP clients to TCP server ports.
Answer: There's a method on the connection factory that allows you to close the connection using its ID...
<code>/**
 * Close a connection with the specified connection id.
 * @param connectionId the connection id.
 * @return true if the connection was closed.
 */
public boolean closeConnection(String connectionId) {
</code>


Replacing switch statements when interfacing between templated and non-templated code

Question: The X:
A common pattern I'm seeing is that the underlying code for a function is templates, but for "reasons" the template code is not available at the upper layer (pick from aversion to templates in interface, the need for a shared library and not to expose implementation to customer, reading type settings at run time instead of compile time, etc.).
This often makes the following:
struct foo { virtual void foo() = 0;}
template <typename T> struct bar : public foo
{
    bar( /* Could be lots here */);
    virtual void foo() { /* Something complicated, but type specific */}
};

And then an initialize call:
foo* make_foo(int typed_param, /* More parameters */)
{
    switch(typed_param)
    {
        case 1: return new bar<int>(/* More parameters */);
        case 2: return new bar<float>(/* More parameters */);
        case 3: return new bar<double>(/* More parameters */);
        case 4: return new bar<uint8_t>(/* More parameters */);
        default: return NULL;
    }
}

This is annoying, repetitive, and error prone code.
So I says to myself, self says I, there has GOT to be a better way.
The Y:
I made this. Do you all have a better way?
////////////////////////////////////
//////Code to reuse all over the place
///
template <typename T, T VAL>
struct value_container
{
    static constexpr T value() {return VAL;}
};

template <typename J, J VAL, typename... Ts>
struct type_value_pair
{
    static constexpr J value() {return VAL;}

    template <class FOO>
    static auto do_things(const FOO& foo)->decltype(foo.template do_things<Ts...>()) const
    {
        foo.template do_things<Ts...>();
    }
};

template <typename T>
struct error_select
{
    T operator()() const { throw std::out_of_range("no match");}
};

template <typename T>
struct default_select
{
    T operator()() const { return T();}
};

template <typename S, typename... selectors>
struct type_selector
{
    template <typename K, class FOO, typename NOMATCH, typename J=decltype(S::do_things(FOO()))>
    static constexpr J select(const K& val, const FOO& foo=FOO(), const NOMATCH& op=NOMATCH())
    {
        return S::value()==val ? S::do_things(foo) : type_selector<selectors...>::template select<K, FOO, NOMATCH, J>(val, foo, op);
    }
};

template <typename S>
struct type_selector<S>
{
    template <typename K, class FOO, typename NOMATCH, typename J>
    static constexpr J select(const K& val, const FOO& foo=FOO(), const NOMATCH& op=NOMATCH())
    {
        return S::value()==val ? S::do_things(foo) : op();
    }
};

////////////////////////////////////
////// Specific implementation code
class base{public: virtual void foo() = 0;};

template <typename x>
struct derived : public base
{
    virtual void foo() {std::cout << "Ima " << typeid(x).name() << std::endl;}
};

struct my_op
{
    template<typename T>
    base* do_things() const
    {
        base* ret = new derived<T>();
        ret->foo();
        return ret;
    }
};

int main(int argc, char** argv)
{
    while (true)
    {
        std::cout << "Press a,b, or c" << std::endl;
        char key;
        std::cin >> key;

        base* value = type_selector<
            type_value_pair<char, 'a', int>,
            type_value_pair<char, 'b', long int>,
            type_value_pair<char, 'c', double> >::select(key, my_op(), default_select<base*>());

        std::cout << (void*)value << std::endl;
    }

    /* I am putting this in here for reference. It does the same
       thing, but the old way: */

    /*
        switch(key)
        {
            case 'a':
              {
                  base* ret = new derived<int>();
                  ret->foo();
                  value = ret;
                  break;
              }

            case 'b':
              {
                  base* ret = new derived<char>();
                  ret->foo();
                  value = ret;
                  break;
              }

            case 'c':
              {
                  base* ret = new derived<double>();
                  ret->foo();
                  value = ret;
                  break;
              }

            default:
                return NULL;
        }
    */
}

Problems I see with my implementation:

It is clear and readable as mud
Template parameters MUST be types, have to wrap values in types (template <typename T, T VAL> struct value_container { static constexpr T value() {return VAL;} };)
Currently no checking/forcing that the selectors are all type-value pairs.

And the only pros:

Removes code duplication.
If the case statement gets high/the contents of do_things gets high, then we can be a little shorter.

Has anyone do something similar or have a better way?
Comment: If all you're trying to do is replace the `switch` statement then you can use a `std::map` where `case_type` is whatever type you were switching on and `factoryFunction` is a `std::function` that returns a value of type `foo*`.
Comment: So, the biggest problem I see with your suggestion (well, ok, readability may be worse...) is that it only works for constant values of `typed_param`, since templates do not work with "runtime variables". (Edit: Unless the mud is so unclear, I don't understand how it works!)
Comment: @MatsPetersson I agree that it would be nice if there could be non-constant typed_params, but a switch-statement also requires "constant" typed_params for its case statements...in C++ the only way around that would elseifs. The "dynamic" part is only the input argument and whatever configurations of "foo" and "NOMATCH" are. edit: it also totally works, despite being ugly, so let me know if there is any specific questions on how it does!
Comment: I'm a little unclear what you're trying to accomplish here? The make_foo function in your original example is easily replaced with a template function that gets rid of the redundant boilerplate but you say the client code can't be exposed to templates? Then your new code does a bunch of other stuff and ends up requiring the client code to use templates... Can you be a bit clearer about what you're trying to do?
Comment: @YoungJohn hrm...and factory function would point towards a templated function, bar, to avoid the code duplication...that makes sense. Would make even more sense if there were templated lambdas.
Comment: @YoungJohn Can you check that my answer below is in line with what you were thinking? I like the idea!
Answer: You can always walk a type list indexed by type_param, as in:
struct foo
{
    virtual ~foo() = default;
    /* ... */
};

template<typename T>
struct bar : foo
{ /* ... */ };

template<typename TL>
struct foo_maker;

template<template<typename...> class TL, typename T, typename... Ts>
struct foo_maker<TL<T, Ts...>>
{
    template<typename... Us>
    std::unique_ptr<foo> operator()(int i, Us&&... us) const
    {
        return i == 1 ?
            std::unique_ptr<foo>(new bar<T>(std::forward<Us>(us)...)) :
            foo_maker<TL<Ts...>>()(i - 1, std::forward<Us>(us)...); }
};

template<template<typename...> class TL>
struct foo_maker<TL<>>
{
    template<typename... Us>
    std::unique_ptr<foo> operator()(int, Us&&...) const
    { return nullptr; }
};

template<typename...>
struct types;

template<typename... Us>
std::unique_ptr<foo> make_foo(int typed_param, Us&& us...)
{ return foo_maker<types<int, float, double, uint8_t>>()(typed_param, std::forward<Us>(us)...); };

Note:  this factory function is O(n) (although a clever compiler could make it O(1)), while the switch statement version is O(1).
Comment: I'm going to say that switch statements are also O(1) iff there is a clever compiler that'll translate it into a jump statement. A valid approach: while more specialized to a single implementation than mine, that isn't necessarily a bad thing.
Comment: (I'll still +1 as a creative solution, but I feel compelled to point out the functionality this method lacks). 1. It has the sames problems as my original post. 2. The typed_param MUST be an integral enumeration, else require a second lookup. 3. The /*more params*/ need to either be passed down the chain, it cannot be initialized into the parent (cannot do stuff in the constructor of foo_maker). 4. Cannot select collections of template initializes (what do you do if bar is `template  struct bar`?).
Comment: 3.  Edited my code to forward parameters.  4.  You can always walk two type lists, and is O(t + j).
Comment: Valid points, but it still hangs on to the same problems that my implementation had. YoungJohn's solution (translated below) can support value template arguments, and it is really obvious what you are doing, at the cost of the `std::bind` copy pasta.
Comment: Just had a thought, you could totally make this always O(1) by making the switch table yourself...
Answer: Just to expand YoungJohn's comment, it looks like this (I've included a single initialization of the operator, and it could be made simpler if there was no parameters, but if there are no parameters there is little reason to do this anyway :-P).
#include <functional>
#include <map>

////////////////////////////////////
//////specific impmenetation code
class base{public: virtual void foo() = 0;};

template <typename x>
struct derived : public base
{
    virtual void foo() {std::cout << "Ima " << typeid(x).name() << std::endl;}
};

struct my_op
{
    int some_param_; /// <shared parameter

    my_op(int some_param) : some_param_(some_param){} /// <constructor

    template<typename T>
    base* do_stuff() const
    {
        std::cout << "Use some parameter: " << some_param_ << std::endl;
        base* ret = new derived<T>();
        ret->foo();
        return ret;
    }
};

base* init_from_params(int some_param, char key)
{
    my_op op(some_param);
    using factoryFunction = std::function<base*()>;
    std::map<char, factoryFunction> mp
    {
        { 'a', std::bind(&my_op::do_stuff<int>, &op)},
        { 'b', std::bind(&my_op::do_stuff<long int>, &op)},
        { 'c', std::bind(&my_op::do_stuff<double>, &op)}
    } ;
    factoryFunction& f = mp[key];
    if (f)
    {
        return f();
    }
    return NULL;
}

int main(int argc, char** argv)
{
    volatile int parameters = 10;

    while (true)
    {
        std::cout << "Press a, b, or c" << std::endl;
        char key;
        std::cin >> key;

        base* value = init_from_params(parameters, key);

        std::cout << (void*)value << std::endl;
    }
}

Pros: so much shorter, so much more standard, so much less weird template stuff. It also doesn't require the templated arguments to all be types, we can select whatever we want to initialize the function.
Cons: In theory, it could have more overhead. In practice, I totally doubt that the overhead would ever matter.
I like it!
Comment: This is more or less what I was getting at. It seems a shame to have to construct the map from scratch every time init_from_params is called though, but if the map isn't created there then there is a question of ownership. Should the map be a member of base? As things are currently written probably not. But yes, this is essentially the approach I was getting at.
Comment: Ah, I see now, since the factory functions likely require parameters passed in you basically have to recreate the map each time.
Comment: @YoungJohn Exactly. Making map a (static) member base could avoid the multiple of the map (you could re-assign the settings if they need to change) but would introduce threading issues. Something that would be totally doable is to make a factory class that holds all the settings AND the map (basically make `init_from_params` a member function of `my_op` and replace `op` in that call with `this`). That class would still not be thread safe (with respect to settings changes), but you could make only one per thread and you'd be good to go. For large number of key-values, unordered may be faster.
Answer: template<class T>
foo* make_foo(int typed_param,/*more params*/)
{
    return new bar<T>(/*more params*/);
}

Comment: wrapping a template in a template directly only exposes another template. What we are looking for is something akin to mapping run-time variables to a template type, in order to select the template we will use at run time rather than compile time, and avoid code duplication.
Comment: @MadScienceDreams you are kind of mixing chalk and cheese there
Comment: Not really? templates can be a powerful tool to avoid reimplementing the same code for multiple types. A stupidly simple example would be demosaicing a bayer patterned image. You can write one template and get 8 bit, 16 bit, and 32 bit code all with one implementation. Problem is, you don't know what camera you are going to use at compile time: your template covers all cases, but needs to be initialized at compile time to be used. You need to select the template you'll used based on some camera parameter at run time. And thus the switch statement.


How to create a custom content-type with template for an "empty" page

Question: I want to display a Unity webplayer in a modal/overlay. I figured out a way to show a drupal page with the webplayer in the overlay, so I'm almost there. But that page then displays everything, including menus etc. The Context module allows me to strip most of it, but not everything. So it seems having an empty page to start with will be easiest.
What would be the best way to create a Drupal page that only shows the content and is otherwise empty? I have already created a custom content-type for the webplayer, so maybe there is a way to associate that with a custom template file that only prints the content? I'm also writing a module for this, so the solution can require changes that need to be implemented in code.
I'm not very familiar with theming, so I'm also interested what template file needs to be created or changed (page.tpl.php, node.tpl.php or something else altogether).
Comment: Please clarify what you mean by "only show content".  Do you want the header/footer? a blank screen?  Also "webplayer in a Drupal Overlay"  are you referring to an administrative overlay form?
Comment: I need a blank screen without headers, footers menus etc. The solution by karthik will work as I can then only output the needed javascript with the Unity object. I'm going to use Lightbox2 to display this.
Answer: By code, if you want a page that display's only content, here's how I would do it.
<code>function module_menu() {
$items['overlay/location']=array(
 'title' => 'Title of page',
 'page callback' => 'module_callback',
 );

return $items;
}

function module_callback() {
 echo 'show what ever!';
 //no return!
}
</code>
Take a look at hook_menu()
Comment: Indeed, I was making it more complicated then necessary. This will work fine, thanks. Still, if anyone knows how to tie a specific template.tpl.php to a content-type I'm interested ;-)


Erro no componente VueJs, conversor de moeda

Question: Olá, estou tentando criar um conversor de moeda com um componente, mas estou tento problemas
index.html
<!DOCTYPE html>

        <link rel="stylesheet" type="text/css" href="style.css"/>
        <meta charset="utf-8"/>

            <!DOCTYPE html>

                <meta charset="UTF-8">
                <title>Vue JS</title>

                <conversor></conversor>

index.js
 Vue.component('conversor', {
        props:{
            moedaA:{
                default:""
            },
            moedaB:{
                default:""
            },
        },
        template: `
{{moedaA}} Para {{moedaB}}

        <input type="text" v-model="moedaA_value" v-bind:placeholder="moedaA">
        <input type="button" value="Converter" v-on:click="converter">

{{moedaB_value}}
`,
    })
    new Vue({
        el: '#app',
        data: {
        },
    })

Erro:

Error compiling template:
Component template should contain exactly one root element. If you are
  using v-if on multiple elements, use v-else-if to chain them instead.
Comment: Coloca uma `` à volta de tudo o que está dentro do `template:`. Resolve o teu problema?
Comment: Tentei fazer isso mas sem solução :/
Answer: Como o erro já diz dentro de template deve haver exatamente um elemento pai.
Hoje você tem 4 elementos

{{moedaA}} Para {{moedaB}}

<input type="text" v-model="moedaA_value" v-bind:placeholder="moedaA">
<input type="button" value="Converter" v-on:click="converter">

{{moedaB_value}}

O correto seria:

{{moedaA}} Para {{moedaB}}

   <input type="text" v-model="moedaA_value" v-bind:placeholder="moedaA">
   <input type="button" value="Converter" v-on:click="converter">

{{moedaB_value}}

No seu código
Vue.component('conversor', {
        props:{
            moedaA:{
                default:""
            },
            moedaB:{
                default:""
            },
        },
        template: `

{{moedaA}} Para {{moedaB}}

        <input type="text" v-model="moedaA_value" v-bind:placeholder="moedaA">
        <input type="button" value="Converter" v-on:click="converter">

{{moedaB_value}}

`,
    })
    new Vue({
        el: '#app',
        data: {
        },
    })


Vscode autofilling for get and set information

Question: When using vscode, it helps me when writing get and set methods  and auto fills it in this format:
<code>     /**
     * @param strength the strength to set
     */
     public void setStrength(int strength) {
        this.strength = strength;
    }
</code>
However if I were writing this  I would do this:
<code>    /**
     * sets the strength variable
     */
    public void setStrength(int newStrength) {
        newStrength = strength;
    }
</code>
Which would be more correct? Also what does the comment mean in the first one?
Comment: Second snippet has a bug, because it's assigning to parameter variable, not to instance variable.
Answer: I don't believe there is a convention for parameter names in getters and setters. So technically they are both correct. Although, I have always used your first example even when I don't auto generate my methods and you will find a majority of open source Java code will use your first example.
Your comment is a javadoc. Build tools like Maven and Gradle offer the ability of compiling API documentation. IDE's (like VSCode) will also parse the javadoc and provide that to you dynamically. You can see this in action when you hover over method / class names.
I would become familiar with Java documentation, especially if someone else will look at your code. There are quite a few Java tags.


How to save a matrix whose every element is a cell containing a 17 column MATLAB table?

Question: Lets say I have data from a certain activity over 500 days. The duration of activity varies over those 500 days. And every day's activity is 17 columns long.
Everyday activity looks like this:

I created a (500 X 1) mat file of zeros called 'activity_database.mat' and then I tried to do this in MATLAB:
clear
load 'activity_database.mat'
for v=1:500
    ////////////////////////////
    DO SOMETHING TO GET A TABLE
    ///////////////////////////
    activity_data{v}=merged_table;
    save('activity_database.mat','activity_data')
end

Now, after running the code. When I try to load the activity_database.mat , I receive the following error:
Error using load
Unable to read MAT-file C:\Users\jackryan\activity_database.mat. File might be corrupt.

What am I doing wrong, here? Also, the database is 50000 elements actually, so I am expecting out of space error too (about 30 GB). Is there a way to store all this data in reasonable space complexity bounds?
Comment: How important is for the cumulated data to be in the same file?
Comment: @CST-Link  I already have the script which gives out the merged table for any day requested. But right now the goal is to create a database for all the activities across all the day. It's not that important, but will be helpful.
Answer: Instead of cumulating the entire data in a single file, you could actually save a file per day, in a specified order. Something like:
first_date = datenum(2012, 12, 20);
db_folder  = '//somewhere/over/the/rainbow/';
for v=1:500
        %// DO SOMETHING TO GET A TABLE
        mat_name = sprintf('activity_day_%s.mat', datestr(first_date+v-1,'yyyymmdd'));
        save(fullfile(db_folder,mat_name), 'merged_table');
end;

You should not have problems about over-sized .mat files, and you can load selectively the data depending on days.
Comment: Could you add code snippet to retrieve data from the db_folder, when needed?


How do I access nginx server logs from within Docker?

Question: I have Nginx routing requests from the browser to either the Express API or my react server, however, in the console I continue to get xhr requests that are just pending and then timeout with 502 bad gateway error which are generally caused by Nginx being unable to pass a request to "upstream", in this case my Express API and normally I would be able to check the /var/log/nginx/ files, but I am not sure how to do that when all this is happening within a Docker container.
I have tried this approach of docker logs <container name/id> command, but I get Error: No such container: <container-id>.
I obtained the container id from the last line after running docker-compose up --build and it says Successfully built <container-id>
I copied that id and ran docker logs <container-id> on a second panel in my iTerm.
I then did a docker ps and got this output:
CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS              PORTS                  NAMES
f37be54a9e60        complexly_api       "npm run dev"            43 minutes ago      Up 28 minutes                              complexly_api_1
9b87bc0aa343        complexly_nginx     "nginx -g 'daemon of…"   About an hour ago   Up 28 minutes       0.0.0.0:3050->80/tcp   complexly_nginx_1
1e30a05f8e28        complexly_worker    "npm run dev"            About an hour ago   Up 28 minutes                              complexly_worker_1
65611b5a6b05        complexly_client    "npm run start"          About an hour ago   Up 28 minutes                              complexly_client_1
9182b26fb402        redis:latest        "docker-entrypoint.s…"   About an hour ago   Up 28 minutes       6379/tcp               complexly_redis_1
8ca3596d8a50        postgres:latest     "docker-entrypoint.s…"   8 days ago          Up 28 minutes       5432/tcp               complexly_postgres_1

I believe I need to grab one of these container ids and do a docker logs with, but I am not sure.
Comment: Please show the exact commands you typed to lookup your container id and run the logs command.
Comment: Please copy and paste the exact commands you are running and their output, including the lookup of your container id. You are copying the wrong ID but I cannot see your screen to point you to the right one.
Comment: @BMitch, could I just do a `docker ps` and then grab the container id that belongs to nginx daemon? or whichever one is named nginx?
Answer: The issue appears to be that I was running docker logs on the wrong container.
By running docker ps I saw the different containers I had running and copied the container id of the one marked complexly_nginx and was able to get the logs I was looking for.


Who should I run slapindex as? Both root and openldap users seem unadvisable

Question: I am following these instructions to install OpenLDAP on Debian 6.0.
The instructions tell me to run slapindex as root, but it sounds like Debian does not like the idea:
WARNING!
Runnig as root!
There's a fair chance slapd will fail to start.
Check file permissions!

Google leads me to a discussion that suggests running slapindex as openldap. I find it strange as slapindex is not in the $PATH of openldap.
Which user should I run slapindex as?
If not root, why is slapindex in /usr/sbin?
Answer: You sure can use both root and openldap as user running slapindex, but if you do it as root, please don't forget to change the OpenLDAP data directory permissions back to openldap:openldap if you do so. For example,
chown -R openldap:openldap /var/lib/ldap/

Why slapindex is under /usr/sbin, I don't know. Perhaps because it is a very powerful and potentially dangerous tool which should be used those capable of being root, anyway.
Comment: Thanks for the comment about `/var/lib/ldap`. I accidentally ran `slapd` in debug mode as `root` and it stole all the file permissions away from the `openldap` user. A service restart failed due to `err 13` and told me to restore from backup. `chown` back to `openldap` for the files in `/var/lib/ldap` fixed me all up.
Comment: It's probably in /usr/sbin because it is an administrative tool that requires specific permissions (though not necessarily root, obviously) to run.  Displaying it in the hypothetical list of "user" commands, such as with tab completion in bash, would be silly.
Answer:
If not root, why is slapindex in /usr/sbin?

According to the FHS (Filesystem Hierarchy Standard) /usr/sbin are used for Non-essential system binaries, e.g., daemons for various network-services.
On CentOS, after executing slapindex as root you should change owner of the index in /var/lib/ldap to the ldap user, which is by default ldap. You could try to use su instead
# su - <ldap_user> -s /bin/bash /usr/sbin/slapindex


"You were not connected because a duplicate name exists on the network" Error on Server2003

Question: I have a Server2003 server which started to have the error in the subject:
System error 52 has occured
"You were not connected because a duplicate name exists on the network."
I get this error when I'm trying to access the server named "FileX" (server 2012) by it's A name record "store" such as "net view //store"
There is an A record on the DNS server "store" which points to the IP address of the FileX server (10.0.150.100).
This happens to be the only server 2003 server, so I can't replicate if this happens in all the servers or not.
"nbtstat -a store" returns "Host not fount" error.
net view //FileX does lists the files, no problems there.
I have tried the following:
Add NetBios name for the server: http://www.techrepublic.com/blog/the-enterprise-cloud/adding-multiple-netbios-names-for-windows-servers/ -> I made this on the FileX server, but did not reboot.
The suggestion provided by MS: http://support.microsoft.com/kb/914056 -> Tried it on the Server2003 machine, did not work.
I have tried editing the hosts file, disabling NetBIOS but haven't found a cure yet.
I'm not very familiar with netbios (too old for me) so I'm expecting some help.
Answer: Try creating a CNAME record to replace the A record. It's been a while since I last encountered this error but I believe this worked in conjunction with the kb914056 fix.
First in DNS create a CNAME record instead of a normal Host(A) record.
Launch your registry editor
Create a new DWORD key in the registry
On the server open regedit and navigate yo:
<code>HKEY_LOCAL_MACHINE\System\CurrentControlSet\Services\LanmanServer\Parameters
</code>
Create a new DWORD with the following details:
<code> Value name: DisableStrictNameChecking
 Data type: REG_DWORD
 Radix: Decimal
 Value: 1
</code>
Comment: I did what you've explained but it did not work. Thanks for the response.


Change spring boot snapshot/build version

Question: I have a requirement to change the build version in my spring boot application everytime I commit the code. But it should not be by changing the Pom.XML or application.properties file. Can someone please help how can this be achieved.
Comment: `But it should not be by changing the Pom.XML` that does not really makes sense... to make it clear everytime you build or everytime you change your project (means change in version control?)
Comment: I meant I don't want to modify Pom.xml with every build. I have got the solution now by using maven build number plugin.
Comment: Do you change the code or config in any way to trigger a new build? If yes that means a change in your project ...which should represented by changing a version (semver:?)...
Comment: Yes that's right. New version means change in the code. I just wanted to make it dynamic.
Answer: I have implemented this by using buildnumber maven plugin. It generates the build number automatically which get updated in builder.properties file.
So I don't have to change it manually in Pom.XML everytime.
Comment: Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer).


Total Number of Equivalence classes of R

Question: I was given the following question for homework:

Let P denote the set of all compound propositions involving the simple/atomic propositions p, q, and r and the
  logical connectives ∨, ∧, and ¬ (complementation). (Included in P are the tautology proposition true and the
  contradiction proposition false.) Define a binary relation R on P by:
  s R t if and only if s ≡ t,
  where ≡ denotes the logical equivalence in propositional logic.
How many equivalence classes of R are there? [ For every element p ∈ P, the equivalence class (of the
  equivalence relation R on P) containing p, denoted by [p]R, is the set {t ∈ P | t R p} — the set of all elements
  in P that are related to p under R. The index of an equivalence relation is the number of its equivalence
  classes. ]

Currently I'm completely stumped as we only talked about relations for around 45 minutes in class and I've never had formal teaching from a previous class (the same professor is in charge of this class as well as the Discrete Math class where he was suppose to teach this material).
From the notes I've taken, I gather that I'm supposed to be able to define the amount by putting a number into [p]R and seeing if it has a relation, and if so adding one to the total amount. So my best educated guess would be infinite since there are infinite possibilities for ≡.
Answer: No, the number of equivalence classes is finite, because there are only finitely many propositional variables, namely $p,q,r$. Any propositional formula in $P$ represents (or induces) a truth function — a function from $n$ tuples of truth values to truth values. The truth table of a formula defines this truth function. The formulas of $P$ define 3-ary truth functions.
Two formulas are equivalent iff their corresponding truth functions (truth tables) are the same. Furthermore, every possible truth table is represented by some formula: consider disjunctive normal form (DNF).
So, how many truth tables are there involving 3 variables? (Can you take it from here?)
Comment: I kind of glanced over the whole p,q,r and focused more on the bit of information in the brackets, thanks for clearing it up for me!
Comment: You're welcome, & thank you.
Answer: Hint: in this example, you can test to see if two propositions are equivalent by computing their truth tables.  If the final answers are identical (intermediate working being irrelevant), then they are equivalent; if the final answers are different, they are not.
So the question is in effect the same as asking: how many possible final answers are there for a truth table in three variables?
See if you can now answer the question.
Comment: @AustinMohr well... that's really part of counting *possible* truth tables - if it's not realisable then it's not possible.  I agree that there is work to be done here beyond just a naive counting argument.  I was only giving a hint, not a complete solution.
Comment: One might also want to demonstrate that every possible truth table is realizable by some proposition. That is, given a truth table $T$, show there is a proposition whose truth table is $T$.
Comment: Consider $ E(p)=\{p,\neg p, T, F\}.$ Show that if  $a , b \in  E(p)$  then $a\lor b$ and $a\land b$ are  equiv to members of $E(p).$ And that $a$ is equiv to a member of $E(p)$  iff  $\neg a$ is also. Now if $s$ is not equiv to a member of $E(p)$, take such an $s$ with the least number of symbols. Then $s$ is not $\neg t.$  If $s$ is $t\lor u,$  or  if $s$ is $t\land u$, then  $t$ and $u$ cannot both be equiv to members of $E(p)$ contrary to the minimal length of $s$ . So $s$ is atomic & not equal to $p$. Suppose $s=q$. Now consider what   $E(p,q)$ should be.


Inverting ARMA Processes

Question: I'm just a bit confused that when you convert an ARMA process to either a pure AR or MA representation then is it always an AR or MA infinite process that we obtain? For instance an ARMA(1,1), does it have an MA and AR infinite representation?
Answer: Lets restrict attention to $ARMA(1,1)$ processes for the moment. I.e., we consider a process
\begin{align}
y_t - ay_{t-1} = y_t(1-aL) = e_t(1-bL) = e_t - be_{t-1}
\end{align}
Where $e_t\overset{iid}{\sim}WN(0,\sigma^2)$ and $a,b \in \mathbb{R}$. Here, $WN$ means 'White noise', i.e. we leave the distribution unspecified, but the first two moments are assumed to exist.
Consider first the invertibility of the lag polynomial $(1-aL)$. What does invertibility mean? Simply that there exists a lag polynomial - say $A(L,a)$ - such that $(1-aL)A(L,a)=1$. Define now $A(L,a) := \sum_{i=0}^{\infty}a^iL^i$. Observe that
\begin{align}
(1-aL)A(L,a) &= (1-aL)(\sum_{i=0}^{\infty}a^iL^i) \\
(1-aL)A(L,a) &= (1-aL)(1+aL+a^2L^2 + \dots) \\
(1-aL)A(L,a) &= 1 + (aL-aL) + (a^2L^2 - a^2L^2) + \dots \\
(1-aL)A(L,a) &= 1
\end{align}
from which it follows that $A(L,a) = (1-aL)^{-1}$ (i.e., the inverse of $(1-aL)$, implying invertibility). Similarly, one can show that $A(L,b) = (1-bL)^{-1}$. More generally, for a first order lag polynomial $(1-\delta L)$, $A(L, \delta)$ will always be the inverse.
From this, you can infer that you may indeed write the above $ARMA(1,1)$ model either as $AR(\infty)$ representation ($y_t(1-aL)A(L,b) = e_t$) or as $MA(\infty)$ representation  ($y_t = e_t(1-bL)A(L,a)$).
Crucially, this was linked to the invertibility of any first order lag polynomial. for $ARMA(p,q)$, one cannot in general say that one could always write them in $AR(\infty)$ or $MA(\infty)$ representation. If you are interested in higher order $ARMA(p,q)$, Wold's Representation Theorem might be interesting for you: Roughly speaking, it says that any stationary process (which includes stationary $ARMA(p,q)$ processes) can be written in a $MA(\infty)$ form.
Answer: Any ARMA(p,q) process has an AR or MA infinite process, provided the stationary condition holds. The main purpose of this conversion is in theoretical studies. For example, it is much much easier to find the variance of an ARMA(p,q) process by a conversion to an MA($\infty$) process.

Inverting ARMA Processes