counter on each images in view

Question: I have a view that display 8 images(which links to their particular node) uploaded by the all users, now i want to display a counter which counts total number of times that image or that image link have been visited/viewed.
Please help me.
I think ..Its like if you on the left of this Question answer section on this site they have mentioned three things
1.Asked Today
2.Viewed 4 times(or total no. of times viewed )
3.etc
my requirement is second.
Thanks
Comment: I got the answer by using view content statistics, no need of any module..

Thanks
Answer: Sounds like Node view count module would be suitable, especially as it integrates with views.

counter on each images in view


Evaluate the limit(0/0) case

Question: evaluate the limit using L'hop
$$\lim_{t\to0}\frac{1}{2t}\int_{x-t}^{x+t}vf'(v)dv $$
how to apply fundamental theorm in this case?
Answer: Let
$$F(t)=\int_{x-t}^{x+t}vf'(v)dv$$
so
$$F'(t)=(x+t)f'(x+t)+(x-t)f'(x-t)$$
hence by l'Hospital's rule we have
$$\lim_{t\to0}\frac{1}{2t}\int_{x-t}^{x+t}vf'(v)dv=\lim_{t\to0}\frac{F'(t)}{2}=xf'(x) $$
assuming that $f'$ is continuous at $x$.

Evaluate the limit(0/0) case


Xalan DLL missing

Question: I'm trying to compile a sample visual C++ 2008 project to test Xalan-C++ library. When I try to compile the project, it gives an error saying "xalan-c_1_11d.dll is missing". When I checked the the library files there were no .DLL files at all, only static libraries. Is there any way for me to resolve this issue without having to compile Xalan-C++ library myself? Thanks in advance.
Answer: You should change the linking model to static instead of dynamic. In VC++ there is an option of library linking which has Single threaded static, single threaded dll, multi threaded static and multi threaded dll. you need to change that.
also there must be a lib file that the linker would use to link the function calls from your dll. you can instruct the compiler using the following syntax:
<code>#pragma comment(lib, "mylib.lib")
</code>
this will link the lib file to your program. Also the ending of name in "d" myxxxd.lib mentions that compiler is looking for the debug version. try to change the build from debug to release to see if that helps

Xalan DLL missing


How are note durations named in the British system?

Question: This looks like a dupe of Why are notes named the way they are? but it isn't. I want to know about rhythm.
I understand that in the international (British) system, a breve is what we Americans call a double whole note.
Semibreve is a whole note, 4 beats in common time.
Minim is a half note.
Crochet is a quarter note, 1 beat in common time.
Quaver is an eighth note.
Once I get below quaver, I get lost. Is it hemi? semi? demi? And what is the logic for choosing which to use?
Comment: Semiquaver, then demisemiquaver, then hemidemisemiquaver, then semihemidemisemiquaver, then demisemihemidemisemiquaver... You can see the progression, I'm sure: always adding 'semi", then "demi", then "hemi" to the front of the word.
Comment: In informal speech, 16th and 32nd notes are often just called "semis" and "demis". There isn't much need for the names shorter than 32nds. The names "semiquaver" and "semibreve" follow the same pattern for "half a quaver", and "half a breve".
Comment: I've seen 64th notes in the wild on several occasions, including *Pictures at an Exhibition*. This is one area where I feel the American naming system is easier and more sensible, in contrast to weights and measures.
Answer: It's kind of a strange story.  In an early form of notation there were two kinds of notes, long and short.  "Longa" means "long" and "breve" means short.
So the longest note you are ever likely to see in modern music (twice as long as the longest note you usually see) is a "short".
At some point someone needed a shorter note than the short, thus the "half short", or semi-breve.
That wasn't short enough, so the smallest possible, or minimal, note was invented: the minim.
Which still wasn't short enough.  A note was invented that looked like a small hook, thus "crotchet". The next smaller note could be used to represent a quavery sound, and after that they just went with every synonym for "half" they could find.
It's like money inflation, but in reverse.  Notation deflation.  There was a time when you could buy a good meal for a penny and sing four breves in one second.  Now a semi-breve is enough for a full second at MM crotchet=120 and a penny won't buy you half a biscuit.
Postscript:
I decided to look for evidence of my assertions, so I got out the Oxford English Dictionary which gives dated examples of early use of words.  You can't count on it for the very earliest use of a word but it is helpful.
"Maxima", "longa", "breve" and "minim" (longest, long, short, shortest) seem to have appeared around the same time, with a citation of "minim" and "maxima" from 1440 and "longa" and "breve" from 1460.  Also "crotchet" appears in 1440 defined as "semiminima".  That would appear to indicate that at the same time they defined the shortest note, they also defined a shorter one!
"Semibreve" appears in 1594; "quaver" in 1570 and "semiquaver" in 1576.  I don't know what the relation of breve and minim was in 1460; perhaps the minim was half of the breve and later became one quarter of the breve.  An expert in early music notation can clear this up for us.
In 1706, someone named Phillips defines "demisemiquaver" as "The least note in music."  By this time of course Bach was using as many beams as he needed so there was no such thing as a "least" note; any note could be split in two.
The OED defines "hemidemisemiquaver" as an example in the entry for "hemi-" but does not give any citation.
Comment: The OED does only give English examples, being interested in when a word crossed over from French or Latin or German into English, not when it first appeared in the original language.  "Maxima" and "minim" no doubt have a long history in Latin, probably going back to the earliest mensural notation.  "Crotchet" and "quaver" sound English to me.
Comment: [Wikipedia](https://en.wikipedia.org/wiki/Mensural_notation#Note_values) seems to agree with your first version, only that semibrevis is older than minima. This notes are said to be used in 13th century. Maybe the Oxford dictionary writes only about usage in English. Wikipedia source is probably Apel, Willi (1962). Die Notation der polyphonen Musik, 900–1600. Leipzig: Breitkopf & Härtel. [=Apel 1961, in German.], but I am not sure whether It covers the whole section or only the last paragraph.
Comment: +1.Don't know if this is all true, but love the rhetoric (if that's the correct word!)
Comment: Great information Mark. I am familiar with the history of long notes and rhythmic inflation, but it adds a lot of context to the discussion. +1
Comment: As Bartek and Mark noted, the OED only gives examples of English usage; the usage of semibreve goes to the 13th c. in France and minim (originally semibrevis minima -- or the smallest possible semibreve) appears in the early 14th c. The semiminim appears not much later (Karen Cook just wrote a diss. on it). In English usage (Morley 1597) "Large" replaces Maxima. At that time there was not a filled/hollowed note distinction, so the semiminim or "quarter" really did have a hook ("crotchet"); after the note colors changed (c. 1420-50) the hook got passed to the next smaller note.
Comment: The hook does, however, still appear for quarter notes in the form of the old style ("French") quarter rest (an eighth rest facing the opposite direction).
Answer: Wikipedia has a very good breakdown of how notes are named. Here's a snippet of just the names of the ones that are different:

American Name                  British Name

double note                 |   breve
whole note                  |   semibreve
half note                   |   minim
quarter note                |   crotchet
eighth note                 |   quaver
sixteenth note              |   semiquaver
thirty-second note          |   demisemiquaver
sixty-fourth note           |   hemidemisemiquaver
hundred twenty-eighth note  |   semihemidemisemiquaver

As you can see in the British naming scheme, the quaver is the smallest unit. The prefixes semi, demi, and hemi all just mean half and they all are applied in that order when referring to something smaller. Which is why you see the notes above in the following order. There is no "official" British name for a 256th notes, but based on the naming pattern to that point, you could call it a demisemihemidemisemiquaver. Although this pattern gets wordy very fast, you could name much smaller notes also using this system.
Comment: It appears that "semi" was all there was for more than a hundred years until someone added "demi", and I don't know how many years went by before "hemi" appeared.  See the citations in my long answer.  If my language knowledge is correct, "semi" is Latin, "demi" is French and "hemi" is Greek.  Examples:  semicircle, demitasse, hemisphere.
Comment: Quaver is the shortest note with a unique name.  Then we get into half-quavers, quarter-quavers....
Comment: Makes sense. Any reason for the semi, demi, hemi order? I didn't see one in the wiki pages.
Comment: @Josiah as far as I know, it's historic in nature and that's just the way it is. There's a little more info at the bottom of the wiki page: https://en.wikipedia.org/wiki/Note_value#Origins_of_the_names
Comment: Ironic - the smaller the note duration, the longer the name...     Why do you say 'quaver is the smallest unit'?


Restricting Kerberos Credential Cache to session

Question: Currently we are using a very bad access model to our servers.
Every person logs in via ssh to the same unix user. We have several keytabs which are used by everyone and normally the same keytab is used. However sometimes someone needs to use one of the other keytabs. But the kinit overwrites the ticket cache to the new principal.
Therefore I would like to know if it is possible to make a kinit that is only valid in the current session and does not affect the other sessions of the same unix user?
Thanks for your help!
Answer:
Every person logs in via ssh to the same unix user.

You probably should resolve that. (shared accounts makes individuals unaccountable.)

Kerberos credential are cached in /tmp by default, but I don't know off-hand if that path is hard-coded or derived from the $TMPDIR environment.
So anything that creates a private TMPDIR per session (and cleans that up after termination of the session) ought to work for you.
I think you might be able to handle that though PAM:

libpam-tmpdir is one approach, that sets a per-session $TMP & $TMPDIR but that won't work on a applications that don't honour the environment and directly go to /tmp/.
or the pam_namespace  PAM module that sets up a private namespace for a session with polyinstantiated directories. A polyinstantiated directory provides a different instance of itself based on user name, or when using SELinux, user name, security context or both.
Comment: Thank you very much, i will test your solutions. However, I am not able to install any packages, so let's hope they are already installed. (I also hate the login policy, but there is no way I can change that)
Answer: Yes, this is a bad model and should be changed. Not only are you having everyone use the same user, but it sounds like you're using keytabs like unprotected ssh private keys. For the latter issue please look at man .k5login for gssapi ssh.
Until then you can throw something like this in a bash profile:
export KRB5CCNAME=FILE:/tmp/krb5cc_$(id -u)_$(base64 /dev/urandom | head -c 10)
That should give every session it's own krb5 credential cache.


Finding the value of an integral containing $(\ln x)^2$ in the denominator

Question: While reviewing (as an instructor/test editor) a second semester calculus exam, I came across the following problem:

Find the volume of the solid created by revolving around the $x$-axis the area under the curve $$y = \frac{1}{x\ln x}$$ to the right of the vertical line $x=e$.

This involves calculating the integral $$\pi \int_{e}^{\infty}\frac{1}{x^2(\ln x)^2}dx. $$
As far as I can see, this integral is well beyond an undergraduate calculus course. The best even I can do with it is to say the integral converges (comparison test with the relevant integral of $\frac{1}{x^2}$.)
Am I missing a way to solve this integral?
Comment: this integral can not expressed in the known elementary functions
Comment: I don't see any way to avoid some exponential integral function. $\pi  \left(\text{Ei}(-1)+\frac{1}{e}\right)\approx 0.466512$
Comment: Does it come out better if you use the cylindrical shells method insted of the disks method?
Comment: Shells present the difficulty of having to express the height of each shell in terms of $y$. You have to solve $y=1/(x\ln x)$ for an expression in terms of $y$.
Comment: Are you sure it's not $\dfrac1{\sqrt x~\ln x}$ ?
Comment: Yes. Unfortunately there is no square root. The test was written by a graduate assistant for a freshman course and the department put me in charge of reviewing the test after it was submitted. But I just wanted to make sure I was not missing something obvious.
Answer: We have the integral $I$ given by
$$I=\pi\int_e^{\infty} \frac{1}{x^2(\log x)^2}\,dx$$
Enforce the substitution $x\to e^x$.  Then we have
$$I=\pi\int_1^{\infty} \frac{e^{-x}}{x^2}\,dx$$
Now, integration by parts reveals
$$\begin{align}
I&=\pi\left(-\left.\frac{e^{-x}}{x}\right|_{1}^{\infty}-\int_1^{\infty} \frac{e^{-x}}{x}\,dx\right)\\\\
&=\pi\left(e^{-1}-\int_1^{\infty}\frac{e^{-x}}{x}\,dx\right)\\\\
&=\pi/e+\pi \,\text{Ei}(-1)
\end{align}$$
where $\text{Ei}(x)$ is the Exponential Integral
$$\text{Ei}(x)=-\int_{-x}^{\infty}\frac{e^{-t}}{t}\,dt$$


Proving $\sum\limits_{k=0}^n \sum\limits_{j=0}^{n-k} \frac{(k-1)^2}{k!} \frac{(-1)^j}{j!} =1$ without character theory

Question:
Let $n \geq 2$ be an integer. I would like to prove the following identity in an easy way:
  $$\sum\limits_{k=0}^n \left( \frac{(k-1)^2}{k!} \sum\limits_{j=0}^{n-k} \frac{(-1)^j}{j!} \right)=1$$

You can see on WolframAlpha, for $n=3$, that this holds.

Here is nice proof I've found. However it seems to be awfully sophisticated...
Consider the representation $S_n \to \text{GL}(V)$ where $V=\text{span}_{\Bbb C}(e_1-e_2, \dots, e_1-e_n)$ and $\sigma \cdot (e_1-e_i) := e_{\sigma(1)}- e_{\sigma(i)}\,$.
It is well-known that this is an irrep: we can show that if $0\neq u \in V$, then $\text{span}_{\Bbb C}(\{\sigma \cdot u \mid \sigma \in S_n\}) = V$.
In particular, the scalar product of character is
$\langle \chi_{V}, \chi_V \rangle=1$.
But $\chi_V = \chi_{S_n} - \chi_1$ where $\chi_{S_n} $ is the permutation character of $S_n$ and $\chi_{1}$ the trivial character.
$\newcommand{\supp}{\text{supp}}$
Therefore, if $\supp(\sigma)$ denotes the support of a permutation $\sigma$, we have:
$$ \begin{align}
\langle \chi_{V}, \chi_V \rangle &=
\frac{1}{n!} \sum\limits_{\sigma \in S_n} |\chi_{S_n}(\sigma)-1|^2\\&=
\frac{1}{n!} \sum\limits_{\sigma \in S_n}
\left|\text{card}(\{1, \dots, n\} \setminus \supp(\sigma)) \;-\; 1\right|^2\\&=
\frac{1}{n!} \sum\limits_{m=0}^n\; \sum\limits_{\substack{\sigma \in S_n\\ |\supp(\sigma)|=m}}
\left|n-m \;-\; 1\right|^2\\&\stackrel{(*)}{=}
\frac{1}{n!} \sum\limits_{m=0}^n (n-m- 1)^2 {n \choose m} m! \sum\limits_{j=0}^m  \frac{(-1)^j}{j!} \\&=
\sum\limits_{m=0}^n (n-m- 1)^2\frac{1}{(n-m)!} \sum\limits_{j=0}^m  \frac{(-1)^j}{j!} \\&=
\sum\limits_{k=0}^n \left( \frac{(k-1)^2}{k!} \sum\limits_{j=0}^{n-k} \frac{(-1)^j}{j!} \right)=1
 \end{align} $$
The equality $(*)$ holds because to choose $\sigma \in S_n$ has a support of cardinality $m$, I choose $m$ numbers out of $n$, and then I have $m!\sum\limits_{j=0}^{m} \frac{(-1)^j}{j!}$ derangements of these $m$ elements.

The following posts are close to my identity, but different: (1), (2). This one only proves $\sum\limits_{k=0}^n \left( \frac{1}{k!} \sum\limits_{j=0}^{n-k} \frac{(-1)^j}{j!} \right)=1$.
In all cases, I would like to see some easy proofs of my identity.
Thank you for your comments!
Answer: We may start from:
$$ \sum_{k\geq 0} \frac{(k-1)^2}{k!}x^k = (1-x+x^2)\,e^{x}\tag{1} $$
$$ \sum_{k\geq 0}\left(\sum_{j=0}^{k}\frac{(-1)^j}{j!}\right) x^k = \frac{e^{-x}}{1-x}\tag{2} $$
then notice that the original sum is just the coefficient of $x^n$ in the product between the RHSs of $(1)$ and $(2)$, i.e.

$$ [x^n]\left(\frac{1-x+x^2}{1-x}\right)=[x^n]\left(-x+\color{red}{\frac{1}{1-x}}\right)\tag{3}$$

Now the claim is pretty trivial: the original sum equals $1$ for every $n\in\mathbb{N}$, except for $n=1$ where it equals zero.
Comment: @Watson: it is just a consequence of a simple lemma. If $$f(x)=\sum_{n\geq 0}a_n x^n,$$ then: $$ \sum_{n\geq 0}\left(\sum_{k=0}^{n}a_k\right)x^n = \frac{f(x)}{1-x}.$$ Just multiply both sides of the last equation by $(1-x)$ and rearrange.
Comment: @Watson You can also establish (2) by interchanging the order of summation, then recognizing a geometric series.
Comment: Thank you! Do you have a reference for (2)?
Answer: Another method is induction.
$f(n):=\sum\limits_{k=0}^n \left( \frac{(k-1)^2}{k!} \sum\limits_{j=0}^{n-k} \frac{(-1)^j}{j!} \right)$
It's easy to calculate $f(n+1)-f(n)=0$ for $n\ge 2$:
$f(0)=1$, $f(1)=0$, $f(2)=1$
$$f(n+1)-f(n)=
\sum\limits_{k=0}^{n+1}\frac{(k-1)^2(-1)^{n+1-k}}{k!(n+1-k)!}=\\\sum\limits_{k=2}^{n+1}\frac{k(k-1)(-1)^{n+1-k}}{k!(n+1-k)!} - \sum\limits_{k=1}^{n+1}\frac{k(-1)^{n+1-k}}{k!(n+1-k)!}  +\sum\limits_{k=0}^{n+1}\frac{(-1)^{n+1-k}}{k!(n+1-k)!}=\\
\frac{0^{n-1}}{(n-1)!}-\frac{0^n}{n!}+\frac{0^{n+1}}{(n+1)!}=0$$
for $n\ge 2$
Comment: It's fairly easy, but it does require showing that $\sum_{k=0}^{n}{n\choose k}(k-1)^2(-1)^{k} = 0$. Adding how to do this would improve the answer.
Comment: I was only providing you with a suggestion on how to improve the answer. I don't control (or care) how people vote here.
Comment: @Winther: It's false to downvote. The result above is only a consequence of the binominal formula which can be provided.
Comment: @user90369: thank you for your idea! If you add a bit more detail to your answer, as suggested by Winther, I will upvote your post.
Comment: @Winther: Sorry, I thought wrong.
Comment: @Watson: I will continue one day later.
Answer: $\newcommand{\angles}[1]{\left\langle\,{#1}\,\right\rangle}
 \newcommand{\braces}[1]{\left\lbrace\,{#1}\,\right\rbrace}
 \newcommand{\bracks}[1]{\left\lbrack\,{#1}\,\right\rbrack}
 \newcommand{\dd}{\mathrm{d}}
 \newcommand{\ds}[1]{\displaystyle{#1}}
 \newcommand{\expo}[1]{\,\mathrm{e}^{#1}\,}
 \newcommand{\half}{{1 \over 2}}
 \newcommand{\ic}{\mathrm{i}}
 \newcommand{\iff}{\Leftrightarrow}
 \newcommand{\imp}{\Longrightarrow}
 \newcommand{\ol}[1]{\overline{#1}}
 \newcommand{\pars}[1]{\left(\,{#1}\,\right)}
 \newcommand{\partiald}[3][]{\frac{\partial^{#1} #2}{\partial #3^{#1}}}
 \newcommand{\root}[2][]{\,\sqrt[#1]{\,{#2}\,}\,}
 \newcommand{\totald}[3][]{\frac{\mathrm{d}^{#1} #2}{\mathrm{d} #3^{#1}}}
 \newcommand{\verts}[1]{\left\vert\,{#1}\,\right\vert}$

$\ds{\sum_{k = 0}^{n}\bracks{{\pars{k - 1}^{2} \over k!}
\sum_{j = 0}^{n - k}{\pars{-1}^{j} \over j!}} = 1:\,?}$

Lets $\ds{a_{k} \equiv {\pars{k - 1}^{2} \over k!}\,,\ b_{j} \equiv {\pars{-1}^{j} \over j!}\ \mbox{such that}\
\sum_{k = 0}^{n}{\pars{k - 1}^{2} \over k!}
\sum_{j = 0}^{n - k}{\pars{-1}^{j} \over j!} =
\sum_{k = 0}^{n}a_{k}\sum_{j = 0}^{n - k}b_{j}}$.

Then, we'll compare the sums for upper limits of $\ds{n}$ and $\ds{n + 1}$:
\begin{align}
\sum_{k = 0}^{n + 1}a_{k}\sum_{j = 0}^{n + 1 - k}b_{j} & =
\sum_{k = 0}^{n}a_{k}\sum_{j = 0}^{n + 1 - k}b_{j} +
a_{n + 1}\sum_{j = 0}^{0}b_{j} =
\sum_{k = 0}^{n}a_{k}\pars{\sum_{j = 0}^{n - k}b_{j} + b_{n + 1 - k}} +
a_{n + 1}
\\[3mm] & =
\sum_{k = 0}^{n}a_{k}\sum_{j = 0}^{n - k}b_{j} +
\sum_{k = 0}^{n}a_{k}b_{n + 1 -k} + a_{n + 1} =
\sum_{k = 0}^{n}a_{k}\sum_{j = 0}^{n - k}b_{j} +
\sum_{k = 0}^{n + 1}a_{k}b_{n + 1 - k}
\end{align}

which leads to
\begin{equation}
\sum_{k = 0}^{n + 1}a_{k}\sum_{j = 0}^{n + 1 - k}b_{j} -
\sum_{k = 0}^{n}a_{k}\sum_{j = 0}^{n - k}b_{j} =
\sum_{k = 0}^{n + 1}a_{k}b_{n + 1 - k}\tag{1}
\end{equation}

In the following step, we'll show that the difference between the sums for the upper limits of $\ds{n + 1}$ and $\ds{n}$ $\pars{~\mbox{the RHS of}\ \pars{1}~}$
vanishes out. Namely,
\begin{align}
\sum_{k = 0}^{n + 1}a_{k}b_{n + 1 -k} & =
\sum_{k = 0}^{n + 1}{\pars{k - 1}^{2} \over k!}\,
{\pars{-1}^{n + 1 - k} \over \pars{n + 1 - k}!} =
{\pars{-1}^{n} \over \pars{n + 1}!}
\sum_{k = 0}^{n +1}{n + 1 \choose k}\pars{k - 1}^{2}\pars{-1}^{k - 1}
\\[3mm] & =
{\pars{-1}^{n} \over \pars{n + 1}!}\,
\lim_{x\ \to\ -1}\pars{x\,\partiald{}{x}}^{2}\
\sum_{k = 0}^{n +1}{n + 1 \choose k}x^{k - 1}
\\[3mm] & =
{\pars{-1}^{n} \over \pars{n + 1}!}\, \underbrace{%
\lim_{x\ \to\ -1}\pars{x\,\partiald{}{x}}^{2}
\bracks{\pars{1 + x}^{n + 1} \over x}}_{\ds{=\ 0}}
= 0
\end{align}

The RHS $\pars{1}$ vanishes out which show that the sum is independent of $\ds{n}$ and it has the value of $\ds{\ \large\color{#f00}{1}}$.
Comment: Thank you very much Felix! (BTW, I think your last sentence can be removed.)
Comment: @Watson Done ==> Removed. Thanks.
Comment: Why are we supposed to believe that $$\lim_{x\ \to\ -1}\left(x\,\frac{\partial}{\partial x}\right)^{2}
\left[\frac{(1 + x)^{n + 1}}{x}\right]=\lim_{x\ \to\ 0}\left(x\,\frac{\partial}{\partial x}\right)^{2}
\left[\frac{x^{n + 1}}{1-x}\right]\ ?$$
Comment: @Did You are right. Thanks. I forgot that there are multiplicative prefactors $x$ 's in $x\,{\partial \over \partial x}$ which must be changed. I just removed that line.
Comment: Now, why $$\lim_{x\ \to\ -1}\left(x\,\frac{\partial}{\partial x}\right)^{2} \left[\frac{(1 + x)^{n + 1}}{x}\right]=0\ ?$$


How to display view in all available languages?

Question: I need to set up a view that lists content in all available languages despite user's current language. I tried creating content translation relationships to all languages and setting fields to use these relationships, but it doesn't work. It only shows fields with the user's current language. How do I get it to list all fields in all languages?
Comment: Welcome to Drupal Answers! The purpose of the language is exactly to show the content in the language the user prefers. I don't see the purpose of showing the content of all the fields in all the possible languages.
Comment: The purpose is not to show anything to users. I'm outputting the view as XML and I need to have all languages shown in the output.
Answer: You could try to do this with the field language setting in view.
I would try to set this to language neutral.
I have not tested this myself, just my 2 cents ;-)
Look to screenshots for clarification
Comment: Already tried it. Does not work.


Avoid escape double quotes in bash when read from file

Question: I have following file content:
1:"z:\raws\data\fractal\todo_1.*"
2:"z:\raws\data\fractal\todo_2.*"
3:"z:\raws\data\fractal\todo_3.*"
...

reading content as array, I do with cat
args=($(cat file.txt))

Then I want to pass arguments to an executable like:
./path/to/executable ${args[@]}
But somehow will become:
./path/to/executable 1:\"z:\raws\data\fractal\todo_1.*\" 2:\"z:\raws\data\fractal\todo_2.*\"
There's a way to remove \" and leave as " instead ?
like outout:
./path/to/executable 1:"z:\raws\data\fractal\todo_1.*" 2:"z:\raws\data\fractal\todo_2.*"
Comment: Don't use `bash` to process this file; use a language with a CSV parser (most such parsers don't really care what character is used as a delimiter, and let you specify comma, tab, *colon*, whatever is actually used by the file).
Comment: Are these received in your executable as `\\"`? Because perhaps it's just escaping them for `bash` to correctly call the command?
Comment: [edit] your question to tell us hw you know that `./path/to/executable ${args[@]}` somehow will become `./path/to/executable 1:\"z:\raws\data\fractal\todo_1.*\" 2:\"z:\raws\data\fractal\todo_2.*\"`. I suspect you're misinterpreting the output of something and that is actually not what's happening. Change `./path/to/executable ${args[@]}` to `printf '%s\n' "${args[@]}"` to see if the values in `args[]` are really having their double quotes escaped when passed to the command or not then [edit] your question to show us that output.
Comment: You could use `tr` for removing all the quotes, while reading the file (see the section titled _Process substitution_ in the bash man-page). But will this be sufficient? According to your posting, you also have as prefix a number, followed by a colon. Shouldn't this be removed as well?
Answer: $ cat tst.sh
#!/usr/bin/env bash

readarray -t args < file.txt

printf '%s\n' "${args[@]}"

$ ./tst.sh
1:"z:\raws\data\fractal\todo_1.*"
2:"z:\raws\data\fractal\todo_2.*"
3:"z:\raws\data\fractal\todo_3.*"

Replace printf '%s\n' with ./path/to/executable for whatever command you want to pass the args[] content to.


VSCode Focus Active Editor Group when explorer is Focused Not Working

Question: In VSCode 1.64.1 on Windows, I'm trying to create some conditional shortcuts for focusing.
When the file explorer is not focused I would like ctrl+0 to focus the active editor group. When the active editor group is focused, I would like ctrl+0 to focus the explorer. I tried the following, but it only partially works.
Currently, hitting ctrl+0 will focus the explorer, but hitting ctrl+0 again when the explorer is focused does not focus the active editor group as desired:
//keybindings.json
  {
    "key": "ctrl+0",
    "command": "workbench.action.focusActiveEditorGroup",
    "when": "!editorTextFocus"
  },
  {
    "key": "ctrl+0",
    "command": "workbench.action.focusSideBar",
    "when": "!explorerFocus"
  }

Answer: I don't see a explorerFocus context key.  The below does work:
{
  "key": "ctrl+0",
  "command": "workbench.action.focusActiveEditorGroup",
  "when": "!editorTextFocus"
},
{
  "key": "ctrl+0",
  "command": "workbench.action.focusSideBar",
  "when": "!filesExplorerFocus"                  // change here
}

Apparently when you use a non-existent context key that when clause is not evaluated at all - as if it wasn't there.  And since evaluation of the keybindings is from the bottom of the file up - first one from bottom wins - your focusActiveEditorGroup command will never be seen.


Java and Scala ClassNotFoundException after upgrading to IntelliJ 14

Question: I recently upgraded to IntelliJ 14, then added Scala support.
My main files stopped running.  For example the GUI file, which has no errors and is a totally self contained hello world style for testing this error:
Exception in thread "main" java.lang.ClassNotFoundException: GUI

It makes no sense and I'm pretty frustrated that the IntelliJ devs are slacking in not auto-detecting a solution to this.  I have tried everything to fix it.  From settings, compilers, to making the project from scratch.
I only had a bit of luck when making it from scratch, but as soon as I started to add my other files (files that were not even being used!) it starts with the error.
It seems that any files outside of the original project module (when creating a new project to test fix) will not run giving ClassNotFoundException.
This may be related to my other question: https://stackoverflow.com/questions/27516673/cannot-run-file-located-out-of-main-module-intellij-14-java-scala
Comment: Where is that error coming from?  Is it your own GUI file?
Comment: Its a skeleton FX hello world that has no other project deps, and no errors.  Works in main module, but not if it is in any other.
Answer: Sample View of the problem

I had the same problem and was able to fix it by right clicking the directory my class was in, and clicking Mark as sources root. This should make your class discoverable and able to run.
Solution
Comment: Thanks @Michael, it saved my day.
Comment: It was already marked as source - but un-marking it and re-marking it did the trick :-)
Answer: Turns out that Make, No Error Check does not work the same for scala as it does for Java.
Errors in the scala files will cause an ambiguous error message on run, with no clear link to the error.
Fixing the scala files fixes the error.
Answer: In my case, the solution was at the JDK and java level.
When I set JDK 14 this error occurred.
So when I work with a scala project, I set java 8 everywhere in the project(module) settings and in the configuration of the main method.

In project(module) settings section: Project, Modules, SDK's

In main method settings: JRE


Error in installing angular-bootstrap-affix using bower

Question: I am using this command to install mgcrea's angular-bootstrap-affix using bower :
bower install angular-bootstrap-affix --save

But it is showing the following error:

ECMDERR Failed to execute
"git ls-remote --tags --heads git://github.com/mgcrea/angular-bootstrap-affix.git",
exit code of #128

Can anybody let me know how I can resolve this error?
Answer: I think that the repository mentioned above no longer exists.
You can use this fork here: https://github.com/passy/angular-bootstrap-affix.git
Use "angular-bootstrap-affix": "https://github.com/passy/angular-bootstrap-affix.git" in bower.json
Or create your own fork from it and give that URL.


NGINX: add_header for GET not working

Question: The following (simplified) NGINX config results in OPTIONS calls correctly getting the Access-Control-Allow-Origin header headers in return, but GET not:
location / {
    if ($request_method = OPTIONS ) {
        add_header 'Access-Control-Allow-Origin' '$http_origin' always;
        return 204;
    }
    add_header 'Access-Control-Allow-Origin' '$http_origin' always;
    try_files $uri @proxy_to_app;
}

location @proxy_to_app {
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header Host $http_host;
    proxy_redirect off;
    proxy_pass http://app_server;
}

I've tried every combination in the location block, but nothing works, the only solution I could think of that works is moving the this line into the location @proxy_to_app section:
    add_header 'Access-Control-Allow-Origin' '$http_origin' always;

It's like that proxy_to_app block is removing the added headers again.
Comment: Put `add_header` to `location @proxy_to_app`
Answer: As Alexey Ten stated, I moved add_header into location @proxy_to_app

NGINX: add_header for GET not working


How to judge if a supervised machine learning model is overfitting or not?

Question: Can anyone tell me how to judge if a supervised machine learning model is overfitting or not? If I don't have an external validation dataset, I want to know if I can use ROC of 10 fold cross validation to explain overfitting. If I have an external validation dataset, what should I do next?
Answer: In short: by validating your model. The main reason of validation is to assert no overfit occurs and to estimate generalized model performance.
Overfit
First let us look at what overfitting actually is.
Models are normally trained to fit a dataset by minimizing some loss function on
a training set. There is however a limit where minimizing this training error will
no longer benefit the models true performance, but only minimize the error on the
specific set of data. This essentially means that the model has been too tightly
fitted to the specific data points in the training set, trying to model patterns in the data originating from noise. This concept is called overfit. An example of overfit is displayed below where you see the training set in black and a larger set from the actual population in the background. In this figure you can see that the blue model is too tightly fitted to the training set, modeling the underlying noise.

In order to judge if a model is overfitted or not, we need to estimate the generalized error (or performance) that the model will have on future data and compare it to our performance on the training set. Estimating this error can be done in several different ways.
Dataset split
The most straightforward approach to estimating the generalized performance is to
partition the dataset into three parts, a training set, a validation set and a test set.
The training set is used for training the model to fit the data, the validation set is
used to measure differences in performance between models in order to select the
best one and the test set to assert that the model selection process does not overfit to the first two sets.
To estimate the amount of overfit simply evaluate your metrics of interest on the test set as a last step and compare it to your performance on the training set. You mention ROC but in my opinion you should also look at other metrics such as for example brier score or a calibration plot to ensure model performance. This is of course depending on your problem. There are a lot of metrics but this is besides the point here.
This method is very common and respected but it puts a big demand on availability of data. If your dataset is too small you will most probably lose a lot of performance and your results will be biased on the split.
Cross-validation
One way to get around wasting a large part of the data to validation and test is to
use cross-validation (CV) which estimates the generalized performance using the same data as is used to train the model. The idea behind cross-validation is to split the dataset up into a certain number of subsets, and then use each of these subsets as held out test sets in turn while using the rest of the data to train the model. Averaging the metric over all the folds will give you an estimate of the model performance. The final model is then generally trained using all data.
However, the CV estimate is not unbiased. But the more folds you use the smaller the bias but then you get larger variance instead.
As in the dataset split we get an estimate of the model performance and to estimate the overfit you simply compare the metrics from your CV with the ones acquired from evaluating the metrics on your training set.
Bootstrap
The idea behind bootstrap is similar to CV but instead of splitting the dataset into parts we introduce randomness in the training by drawing
training sets from the whole dataset repeatedly with replacement and performing
the full training phase on each of these bootstrap samples.
The simplest form of bootstrap validation simply evaluates the metrics on the samples not found in the training set (i.e. the ones left out) and average over all repeats.
This method will give you an estimate of model performance which in most cases are less biased than CV. Again, comparing it with your training set performance and you get the overfit.
There are ways to improve the bootstrap validation. The .632+ method is known to give better, more robust estimates of the generalized model performance, taking overfit into account. (If you're interested the original article is a good read: Improvements on Cross-Validation: The 632+ Bootstrap Method)
I hope this answers your question. If you are interested in model validation I recommend reading the part on validation in the book The elements of statistical learning: data mining, inference and prediction which is freely available online.
Comment: Note that your terminology of validating vs. testing is not followed in all fields. E.g. in my field (analytical chemistry) *validation* is a procedure that should prove that the model works well (and measure how well it works). It is done with the *final* model, no further changes are allowed afterwards (or, if you do so, you need to validate again with independent data). So I'd call your validation set an "inner test set" or "optimization test set". The "outer" test data does *not prevent* overfitting, but it may be used to measure the extent of overfitting.
Comment: Ok, I don't have experience in your field. Thanks for the clarification. It is probably the same in other fields as well. I simply used the terminology used in the book I linked to in the end. I hope it is not too confusing.
Answer: Here's how you can estimate the extent of overfitting:

Get an internal error estimate. Either resubstitutio (= predict training data), or if you do an inner cross "validation" to optimize hyperparameters, also that measure would be of interest.
Get an independent test set error estimate. Usually, resampling (iterated cross validation or out-of-bootstrap* is recommended. But you need to be careful that no data leaks occur. I.e. the resampling loop must recalculate all steps that have calculations spanning more than one case. That includes pre-processing steps such as centering, scaling, etc. Also, make sure you split at the highest level if you have a "hierarchical" (also known as "clustered) data structure such as repeated measurements of e.g. the same patient (=> resample patients).
Then compare how much better the "inner" error estimate looks than the independent one.

Here's an example:

Trefferrate = hit rate (% correct classified), Variablenzahl = number of variables (= model complexity)
Symbols: . resubstitution, + internal leave-one-out estimate of hyperparameter optimizer, o outer cross validation independent at patient level
This works with ROC, or performance measures such as Brier's score, sensitivity, specificity, ...
* I don't recommend  .632 or .632+ bootstrap here: they already mix in resubstitution error: you can anyways calculate them later from your resubstitution and out-of-bootstap estimates.
Answer: The overfitting is simply the direct consequence of considering the statistical parameters, and therefore the results obtained, as a useful information without checking that them was not obtained in a random way. Therefore, in order to estimate the presence of overfitting we have to use the algorithm on a database equivalent to the real one but with randomly generated values, repeating this operation many times we can estimate the probability of obtaining equal or better results in a random way. If this probability is high, we are most likely in an overfitting situation. For example, the probability that a fourth-degree polynomial has a correlation of 1 with 5 random points on a plane is 100%, so this correlation is useless and we are in an overfitting situation.


"Marca d'água" com CSS

Question: Cenário teste
Tenho um input em um , em que o fundo do  tem cor:

td {
  padding: 2em;
  background-color: yellow;
}

      <input type="number"/>

Dúvida

Gostaria de saber, como posso criar uma "marca d'água" com o CSS nesse fundo do , para que eu possa utilizá-lo incluindo pela class (no exemplo, classe "marcado").

Exemplo de possíveis resultados esperados
Comment: Tem coisas que é melhor com imagens, eu sei que tem as dicas com CSS puro, mas tem coisas que se for falar dos problemas ou da complexidade daria duas páginas de texto, então vou me limitar a isso, background-image e SVG casariam bem para resolver o seu caso ;)
Answer: Aqui tem um exemplo, é 100% com CSS e tudo feito com background, repare que mesmo se um input for maior o canto não deforma. E vc pode controlar facilmente o tamanho da marca pelo background-size

.marcado {
  padding: 2em;
  background-image:
  linear-gradient(135deg, transparent 0%, transparent 50%, red 50%, red 55%, transparent 55%, transparent 60%, red 60%),
  linear-gradient(yellow, yellow);
    /*controla o tamanho do chanfro vermelho aqui*/
  background-size: 40px 40px, 100% 100%;
  background-position: right bottom;
  background-repeat: no-repeat;
}

      <input type="number"/>

      <input type="number" style="width: 400px;" />

Answer: Você pode fazer isso com HTML e CSS utilizando o elemento before
E então utilizar uma classe como "-active" para mostrar ou esconder o mesmo

table td {
  padding: 2em;
  background-color: #ff0;
  position: relative;
  overflow: hidden
}

table td:before {
  content: "";
  position: absolute;
  width: 60px;
  height: 60px;
  background-color: red;
  right: -30px;
  bottom: -30px;
  transform: rotate(45deg)
}
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css">

      <input type="number"/>

Comment: Cara uma dica, não precisa publicar 2 resposta, apenas edite a outra antiga e inclua o snippet do código nela
Comment: Primerira vez respondendo aqui heheheh
Valeu amigo
Comment: Já fica a dica rss
Comment: Willyan, mas se eu fizer dessa forma, todas ficaram com a marca, não é? você adicionou direto no `td`, eu queria que fosse uma classe, assim eu adiciono só em alguns...

"Marca d'água" com CSS


Where ZFS configuration is saved?

Question: I have a simple setup:

Ubuntu 13.04 on internal  USB thumbdrive
4xSATA drive in raidz spool with some volumes /tank/vol1, /tank/vol2

Where does zfs store its' configuration data - is it on member drives of zpool?
What would happen if USB thumbdrive dies and I need to reinstall it and access data on zpool?
Answer: The configuration is stored in the member drives.
There is also a zpool.cache file in /etc/zfs or /boot that has a copy of the configuration so that the kernel mounts zfs filesystems that it had previously known about. A zfs volume will not automatically be mounted at startup until it's imported (which adds it to the cache file).
Comment: Not really, no... If your thumbdrive dies you can just import the zpool on another computer.
Comment: Thank you!Does it makes sense to backup cache file?
Answer: ZFS Configuration is stored on the member drives of the zpool, yes.
Sounds like you'd lose your Ubuntu system, but it's not clear what's on the thumbdrive.

Where ZFS configuration is saved?


Compartilhar LocalStorage com browsers

Question: Existe alguma forma de compartilhar localstorage com vários browsers?
Por exemplo, eu defino localStorage.setItem("lang", "pt"); no Chrome, porém, gostaria que esse valor ficasse disponível no Firefox e outros navegadores que dêem suporte a LocalStorage.
OBJETIVO:
Meu objetivo com isso é fazer uma forma do meu sistema entender a língua que o cliente escolher e que eu salvei no localstorage e recuperar em outros momentos, em outros navegadores.
Existe alguma forma?
Comment: Se fosse possivel, seria uma falha de segurança bem grave.
Comment: vou editar a pergunta pra ver se surge alguma sugestão bacana...
Answer: Não é possível, pois o localStorage é uma implementação de uma especificação do  HTML5, cada navegador implementa da forma que quer e também a localização desses dados muda de um navegador para o outro.
O que pode ser feito é você salvar essa informações no servidor e "setar" os valores no localStorage de cada navegador que o usuário acessar.
Referência: html5 Local Storage Across Different Browsers

Compartilhar LocalStorage com browsers


Drupal 8: Best practice to get nid in form_submit

Question: I can get nid from within form_submit by using one of those snipet:
<code>$form_state->getFormObject()->getEntity()->id()
</code>
or
<code>\Drupal::routeMatch()->getParameter('node')->id()
</code>
If feel this is a little bit overkilling... what is the best way?
Comment: Welcome to Drupal Answers :) Could you expand on what you mean by "overkilling"? What would the method that you want to be able to use look like? Your first example looks absolutely perfect, what specifically do you find to be overkill about it?
Comment: I was thinking that the number of the function call was high to just get the nid. But I am happy by your answer: I asked this question to be sure that I don't miss something (more simple). Thanks again!
Answer: You're looking for <code>$node = $form_state->getFormObject()->getEntity()</code>.
Oh, saw that you actually mentioned that. This is the correct way to do it.


Como configurar o driver pdo_mysql no Laravel 6

Question:
LaravelDoctrine\ORM\Exceptions\DriverNotFound  : Driver [pdo_mysql] not supported.

Meu arquivo de configuração database.php está da seguinte forma:
<code>        'mysql' => [
            'driver' => 'pdo_mysql',
            'url' => env('DATABASE_URL'),
            'host' => env('DB_HOST', '127.0.0.1'),
            'port' => env('DB_PORT', '3306'),
            'database' => env('DB_DATABASE', 'forge'),
            'username' => env('DB_USERNAME', 'forge'),
            'password' => env('DB_PASSWORD', ''),
            'unix_socket' => env('DB_SOCKET', ''),
            'charset' => 'utf8',
            'collation' => 'utf8_unicode_ci',
            'prefix' => '',
            'prefix_indexes' => true,
            'strict' => true,
            'engine' => null,
            'options' => extension_loaded('pdo_mysql') ? array_filter([
                PDO::MYSQL_ATTR_SSL_CA => env('MYSQL_ATTR_SSL_CA'),
            ]) : [],
        ],
</code>
Answer: Boa tarde, Bruno! Tudo bem?
Utilizo o pdo em um dos meus projetos e não precisei fazer essa configuração no database.php
Provavelmente essa configuração deve ser feita no apache. Chegou a verificar se o driver está sendo carregado?
Se ainda não fez, você pode verificar criando um phpinfo() no seu servidor. Se tiver configurado certinho, deve mostrar la
Comment: Bom dia Thiago, agradeço sua ajuda, deu certo aqui. Vlw
Comment: Boa, Bruno!
Que bom que solucionou.


How to read the field collection data

Question: I have a field collection with name as 'TELEPHONE NUMBERS AND DETAILS' and the machine key as 'field_telephone_numbers'.
When I use node_load getting the output as
[field_orgs_number_details] => Array

(

[und] => Array

(
    [0] => Array

    (
        [value] => Number 2
        [format] =>
        [safe_value] => Number 2
    )

)

)

[field_orgs_telephone_number] => Array

(

[und] => Array

(
    [0] => Array
    (
        [value] => 123456
        [format] =>
        [safe_value] => 123456
    )

)

)

How to read the data 'Number 2' and '123456' into a array.
Updated:
 [1] => Array

   (

   [entity] => Array

      (

        [field_collection_item] => Array

            (
            [15994] => Array
                (
                [field_orgs_number_details] => Array
                    (
                    [#object] => FieldCollectionItemEntity Object
                       (
                         [field_orgs_number_details] => Array
                             (
                                [und] => Array
                                    (
                                        [0] => Array
                                            (
                                            [value] => Number 3
                                            [format] =>
                                            [safe_value] => Number 3
                                            )
                                    )
                            )

                        [field_orgs_telephone_number] => Array
                            (
                            [und] => Array
                                (
                                [0] => Array
                                  (
                                [value] => 333333333333
                                [format] =>
                                [safe_value] => 333333333333
                                )
                            )
                        )

                    [rdf_mapping] => Array
                        (
                        )

                [entity_view_prepared] => 1
                    )
                )
            )
        )
    )
)

 When i use

 $data = render($content['field_telephone_numbers']);

 Getting output as

  Telephone
  123456  - Number 2

Answer: consider you have called like this $content = node_load(1);
then you can get the values like below
$content['field_orgs_number_details']['und'][0]['value']

Similarly you can do the same for getting the telephone numbers
Comment: getting empty results.
Comment: check the parent array of 'field_orgs_number_details ' and append that name in front of this field. I have given only based on your output. i am sure there will be parent array for this field.
Comment: I have updated the total output. Please check it and let me know.
Comment: try like this $orgs = entity_load('field_collection_item', array($content->field_orgs_number_details['und'][0]['value'])); this will give you value "Number 2". Try similarly for telephone
Comment: Good....you can share the code, so that it might be helpful to others...
Answer: place the following hook in your template.php
function rows_from_field_collection(&$vars, $field_name, $field_array)    {
    $vars['rows'] = array();
    foreach($vars['element']['#items'] as $key => $item) {
        $entity_id = $item['value'];
        $entity = field_collection_item_load($entity_id);
        $wrapper = entity_metadata_wrapper('field_collection_item', $entity);
        $row = array();
        foreach($field_array as $field){
          //$row[$field] = $wrapper->$field;
          $row[$field] = $wrapper->$field->value();
          //$row[$field] = $entity->$field->value();
         }
        $row['field_collection_id'] = $item['value'];
        $vars['rows'][] = $row;
    }
}

and use
<?php print render($content['node_field_name']); ?>

How to read the field collection data


Como saber se uma janela JDialog esta aberta ou fechada?

Question: Queria saber, como eu posso saber se uma tela, no meu caso um JDialog está aberto. Existe algum evento ou maneira de saber isto?
Obs: Eu vou utilizar essa "informação" como parâmetro em uma condição, por exemplo, se tela fechada faça tal coisa.
import java.awt.event.ActionEvent;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;

public class FecharTela extends JFrame {

    private JButton botao = new JButton("+");
    private DialogX x = new DialogX();

    public FecharTela() {
        setTitle("Teste");
        add(montaTela());
        setSize(500, 400);
        setLocationRelativeTo(null);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
    }

    private JComponent montaTela() {
        JPanel jpMontaTela = new JPanel();
        jpMontaTela.add(botao);

        botao.addActionListener((ActionEvent e) -> {

            x.setVisible(true);
        });

        return jpMontaTela;
    }

    public static void main(String[] args) {
        FecharTela ft = new FecharTela();
        ft.setVisible(true);
    }
}

class DialogX extends JDialog {

    public DialogX() {
        setSize(300, 300);
        setLocationRelativeTo(null);
        add(new JLabel("Erro no campo .."));
    }
}

Answer: Você pode utilizar os métodos isVisible() e/ou isDisplayable() herdados da classe Component  para checar se a janela já foi aberta ou não.


Singular value and eigen-decomposition of a square symmetric matrix should be identical, but differ in sign

Question: As far as I know, singular value decomposition (SVD) and eigendecomposition give the same result for symmetric square matrices. But when I check the results in R, that's not what I see. Please see below R code (I set the random seed for reproducibility purposes):
set.seed(111)
X = matrix(rnorm(50), nrow=5, ncol=10)
prinden = svd(X %*% t(X))
prineden = eigen(X %*% t(X))

> prinden$u
       [,1]       [,2]        [,3]       [,4]        [,5]
[1,] -0.3812420  0.1714440  0.89298930 -0.1352677  0.09764363
[2,] -0.3086450 -0.1785482  0.05935694  0.9181008 -0.16256214
[3,]  0.2125363  0.8719446 -0.06555398  0.3011303  0.31553776
[4,] -0.6109540  0.4041138 -0.30752420 -0.2079534 -0.57062372
[5,] -0.5839147 -0.1230124 -0.31650973 -0.0697814  0.73407341

> prineden$vectors
       [,1]       [,2]        [,3]       [,4]        [,5]
[1,] -0.3812420 -0.1714440  0.89298930 -0.1352677  0.09764363
[2,] -0.3086450  0.1785482  0.05935694  0.9181008 -0.16256214
[3,]  0.2125363 -0.8719446 -0.06555398  0.3011303  0.31553776
[4,] -0.6109540 -0.4041138 -0.30752420 -0.2079534 -0.57062372
[5,] -0.5839147  0.1230124 -0.31650973 -0.0697814  0.73407341

The 2nd columns of prinden$u and prineden$vectors are negative of each other, while other columns are the same. How come is this possible? What am I missing?
Comment: Sign does not matter. It depends on the specific implementation of the function. If you negate the second column the results are identical. So these are actually two equivalent decomposition outputs.
Comment: This is very closely related to http://stats.stackexchange.com/questions/88880.
Comment: The sign difference is well explained in [this math answer](https://math.stackexchange.com/a/2704268/874001).
Answer: Also, if your square matrix is indefinite (and thus has negative eigenvalues), the SVD won't capture that since it always returns nonnegative singular values.
Answer: The decomposition is not unique.
First of all, any reflection is a proper decomposition, too.
Secondly, if you have identical eigenvalues, any rotation within these axes is a proper decomposition, too.
In particular, any identity ("eye") + rotation matrix is a decomposition of any other identity ("eye") or rotation matrix (because any vector is a unit vector of them).
Such solutions do arise in practise when you use e.g. power iterations to find only the first few eigenvectors (numerically, not analytically, obviously. Reality isn't exact.)
Comment: I don't think "eye matrix" is a mathematical term. You are probably referring to the `eye()` function in Matlab, but what it returns is called an *identity* matrix.
Comment: `eye` matrix may be less ambiguous. Identity can happen on so many levels. Personally I would have preferred the term identity, but have the impression some people find `eye` more understandable for stats users.


Does JMP aggregate data in graph-building?

Question: I am using JMP to find a relationship between drought index values and yearly corn yields for a 30 year period.  I have drought data for seven different indeces and each index ranges from -6 (severe drought) to +6 (extremely high precipitation).
The drought data contains monthly drought index values for March-September for every year from 1981 to 2011.  The corn yield data contains one number (bushels/acre) for every year from 1981 to 2011.  I built two side-by-side graphs in JMP, with one showing corn yield data over the 30 year period and the other showing drought data from one particular index over the same time period.  Both are smooth curves and visually line up and seem to have a relationship.
My problem is that I have no idea how JMP is processing the drought data. There are eight separate drought index values per year, every year, for each drought index, and only one value per year for the corn yield data. I assumed that JMP was smoothing out the drought curve by taking an average of the eight index values for every year, then using that number in the graph construction but I haven't been able to find any literature that can tell me this for certain.
Comment: Can you post the graphs and/or give more specifics on how you made them (eg did you use the graph builder or were they generated with a different JMP module)?
Comment: ![enter image description here](http://i.stack.imgur.com/ob1NB.jpg) Thank you for your answer. I simply dragged the variables I was interested in onto their appropriate areas in the graph builder in JMP 9. I did not use the Smoother element. Do you think the cubic spline explanation would be applied automatically?
Answer: Just to make sure I understand you, I think you're plotting the index value by the year value, and there are several index values per year value. And you're in Graph Builder using the Smoother element. Here's a quick mock-up:

Actually in my mock-up, I also have the Points element turned on to emphasize the multiple Y values by X.
From the JMP 11 doc:

The smoother is a cubic spline with a default lambda of 0.05 and
  standardized X values. You can change the value of lambda using the
  slider. You can obtain the same spline in the Bivariate platform...

Cubic splines are technically only defined for data sets with unique X values. In case of duplicate Xs, JMP first takes the weighted mean of the corresponding Y values. Use the Freq drop zone in Graph Builder if you want to control the weighting, otherwise each Y is weighted equally.


Try Catch Finally nested behaviour with exception

Question: So I was wondering about the behaviour of a nested try-catch-finally blocks.
What I mean is, what if inside the first finally block, we have another try-catch-finally blocks and a exception happens in the inner finally block??
Is the exception going to be propagated? And is it going to be caught somewhere?
Where should I catch the exception? In the inner finally block or if it's propagated should I catch it from the upper code?
Example:
static bool Func()
{
    try
    {}
    catch
    {}
    finally
    {
        try
        {}
        catch
        {}
        finally
        {
           throw new ApplicationException();
        }
    }
}

Comment: No I'm asking about an exception in the inner finally block @BenReich
Comment: And no, @Anirudh, I'm asking about a nested one.
Comment: the inner finally block's exception would propagate out of the containing finally block and would be handled at the higher level..So excetion thrown in inner finally block would go outward until it finds a specific catch block at higher  level or it would throw the exception if none is found
Comment: You could easily write code and test your hypothesis any way you want. This question is rightfully closed, there are plenty of resources on this site and elsewhere that describe the behavior, and you can test to discover and confirm those behaviors as well. Do more research.
Comment: as i said for your given example there's no catch block for that exception and so it would not be catch'ed..remember all other outer finally block would not be executed further..
Comment: So or I put a try with a catch inside for the exception or I put a try for all the code and the catch under
Answer: Depends. You can handle the exception in your inner exception, but if you don't want to handle it, you can just THROW it so the outer Try Catch will 'receive' the exception.
See here for more detailed example :
Comment: How is the outer Try Cartch going to read the exception if the exception happens in a finally??


Possible encoding issue between PS and C++

Question: I have a C++ program written using Qt that I'm using as a front end to create AD accounts. Essentially I launch an elevated process that executes PowerShell commands within an elevated PowerShell session. I can create the accounts fine but when I attempt to pull membership from a pre-existing user to copy it over to the new one it fails. I need to understand why it's failing and resolve the issue, any help is greatly appreciated. It fails with the following error:
Get-ADUser : Cannot validate argument on parameter 'Identity'. The argument is null. Provide a valid value for the
argument, and then try running the command again.
At line:2 char:28
+ "}); $groups = (Get-ADUser $tmpusr -Properties MemberOf).MemberOf; $u ...
+                            ~~~~~~~
    + CategoryInfo          : InvalidData: (:) [Get-ADUser], ParameterBindingValidationException
    + FullyQualifiedErrorId : ParameterArgumentValidationError,Microsoft.ActiveDirectory.Management.Commands.GetADUser

The $tmpusr variable is just the value of duser.template_user which is pulled from a QComboBox and is deffinetly not null because it outputs correctly and shows the selected template account. In C++ it's just data added to a struct member:
duser.set_groups_command = "$tmpusr = (Get-ADUser -Filter {Name -like " "\"" + duser.template_user + "\"" "}); "
                           "$groups = (Get-ADUser $tmpusr -Properties MemberOf).MemberOf; "
                           "$usr = " "\"" + duser.sam_name + "\"" + "; "
                           "Foreach ($group in $groups) {Add-ADGroupMember -Identity (Get-ADGroup $group).name -Members $usr} ";

If I strip the C++ and run the same command within PowerShell it executes fine:
$tmpusr = (Get-ADUser -Filter {Name -like "Example User"}); $groups = (Get-ADUser $tmpusr -Properties MemberOf).MemberOf; $usr = "TestUser"; Foreach ($group in $groups) {Add-ADGroupMember -Identity (Get-ADGroup $group).name -Members $usr}

The purpose of the command is to determine which groups "Example User" belongs to and then to add "TestUser" to the same groups. Again, creating the user works fine. That is done with:
duser.complete_command = p + "New-ADUser -Name " + "\"" + duser.employe_name +"\"" + " -GivenName " + "\"" + duser.given_name + "\""
                + " -Surname " + "\"" + duser.surname + "\"" + " -AccountPassword $sec " + " -UserPrincipalName " + "\"" + duser.userpname + "\""
                " -DisplayName " + "\"" + duser.display_name + "\"" + " -EmailAddress " + "\"" + duser.email_address + "\"" + " -SamAccountName " +
                "\"" + duser.sam_name + "\"" + " -Enabled " + duser.is_enabled;

You'll note the existence of "p" which is another QString created earlier on to convert to a secure string. The only other component is the function that elevates and executes:
 void MainWindow::elevate_and_execute(QString param)
 {
     QProcess *process = new QProcess();
     QStringList params = QStringList();
     params = QStringList({"-Command", QString("Start-Process -Verb runAs powershell; "), param});
     process->startDetached("powershell", params);
     process->waitForFinished();
     process->terminate();

 }

Comment: It looks like to me that there are extra double quotes before some of your slashes?  Could you try a slimmer version of the same statement and see what happens?  `"$tmpusr = Get-ADUser -Filter \"Name -like '" + duser.template_user + "'\";"` which should essentially be the same as `$tmpusr = Get-ADUser -Filter "Name -like 'Example User'";`
Comment: @suroh Yes, but you are doing it like `"... " "\""` instead of `"... \""`.
Comment: The adittional quotes are just inteded to escape a single double quote where needed. so "\"" is really just " but there certainly are other ways of achieving this. I'll try the slimmed down version and see what happens, thank you!
Comment: I guess you are just missing some `+`s   `"... " "\""` should be `"... " + "\""`
Comment: Gotcha, yeah sorry I guess I had a little stroke there. Thank you both for pointing that out. I'm sorry for the delayed response, I tried the reduction but am having the same error in the same place. I'l lreview more thoroughly in case I've missed something else. Could the be an issue in how the commands are chained?
Answer: I was able to resolve the issue. I found that when I pulled the so called template user from the QComboBox it contained a carriage return. I had written the logs to a text file and found it was pushing it to the next line; so the $tmpusr was broken. I was able to resolve the issue by modifying the duser.template_user variable when it's initially filled by stripping that "\r" out with remove(QChar('\r'))


Adding a website URL to a Profile Field

Question: Adding a users' website link (URL) to a field.
Can somebody please clarify the best approach to this using Profile2 as I cannot seem to find any option for "URL" type in any field. Maybe I'm having a blond moment or just cannot see the wood for the trees, but to save us hours searching online, can somebody advise on the simplest and most obvious solution to users being able to enter their 'website' link (ie: to link to an external URL such as a homesite such as a bandname.com, mybusiness.com).
I am also using Field Collection but presume any created filed type will be similar in setup.
I would envisage the user being able to add such a URL into their profile detial post registration in a similar way to the user DB on drupal.org (ala "Mywebsite").
Thank you.
Comment: did you tried http://drupal.org/project/link?
Comment: Thank you Mohammad, I've replied to Clive below, but a verbatim answer to you also for your response.
Answer: There's no native URL field type in Drupal 7 but the Link module provides one with lots of features

With this module links can be added easily to any content types and profiles and include advanced validating and different ways of storing internal or external links and URLs.

Profile2 profiles are entities so adding a link field to one will be an easy task through the UI.
Comment: Thank you Clive, looks like Link Module will be the one, (seems I missed that in my drupal.org search) I shall look into it now. Much appreciated.
Comment: Excellent! For those who require to add a "Users" external website URL with a User Profile, this is the module. Hopefully this will be included in any future D8 core (-:
Answer: You can also achieve that using the URL field module. I've used this module in one of my project. You can also add Optional title field to the URL.
Image from the module page.

You can also achieve that without using any contributed module.
Add textarea field (instead of text filed) and set Text processing  as Filtered text in the field settings. Make sure to select  Convert URLs into links option in Text Formats.
That's it. The entered URL will be appeared as link at output.
Comment: Thanks very much for your tip, I will checkout the Module to see if I can reuse it in my future projects, I'll let you know how I get on and feedback where appropriate. (-:

Adding a website URL to a Profile Field


Filtrar por data no Mysql

Question: Tenho uma tabela onde é armazenado a data de cadastro no formato DATE(). O cadastro vem desde 2013 e pega todos os dias e meses até dezembro de 2017:
2013-01-01
2013-01-02
2013-01-03
......

2017-12-01
2017-12-02
2017-12-03

Gostaria de filtrar da seguinte forma:
Janeiro 2013
.....
Aqui listasse todos os registros dos dias 01 a 31 de janeiro de 2013
....
e assim por diante até dezembro 2017.
No mysql tentei dessa forma:
SELECT MONTH(DataCadastro) AS MesCadastro, YEAR(DataCadastro) AS AnoCadastro FROM `tabela` GROUP BY MesCadastro;

Só que ele retorna dessa forma:

E quando tento agrupar o ano:

Preciso só da query, pois vou usar o PHP para a listagem.
Answer: use um where e o comando between para filtrar entre um intervalo de valores
SELECT MONTH(DataCadastro) AS MesCadastro, YEAR(DataCadastro) AS AnoCadastro

FROM tabela where DataCadastro between '01.01.2013' and '31.01.2013'

GROUP BY MesCadastro;

Comment: Olá Gabriel. Certo, mas como eu aplicaria para a minha solução? Pois estou precisando criar esse filtro para  poder fazer do jeito que mencionei no post.
Comment: SELECT MONTH(DataCadastro) AS MesCadastro, YEAR(DataCadastro) AS AnoCadastro FROM `tabela` where DataCadastro between '01.01.2013' and '31.01.2013' GROUP BY MesCadastro;
Answer: Infelizmente acredito que não exista uma forma de trazer os resultados como você deseja, mas você pode usar o group_concat() para agrupar os meses com um separador e explodir a string no php, que você disse que usará para listagem:
SELECT group_concat(MONTH(DataCadastro) separator ',') as MesesCadastro , YEAR(DataCadastro) AS AnoCadastro  FROM tabela where DataCadastro between '01.01.2013' and '31.01.2013' GROUP BY MesCadastro;

No php ficaria:
$lista[$result['AnoCadastro']] = explode(',', $result['MesesCadastro'] );
//resultado esperado -> $lista['2018'] => [1,2,3...]

outra opção é trazer os dados normalmente sem agrupar e fazer um loop com php para agrupa-los:
$anos = [];
$foreach($result as $res){
   if(!isset($anos[ $res['AnoCadastro'] ])){
       $anos[ $res['AnoCadastro'] ] = [$res['MesCadastro']];
   }else{
       $anos[ $res['AnoCadastro'] ][]= $res['MesCadastro'];
   }
}

https://dev.mysql.com/doc/refman/5.6/en/group-by-functions.html#function_group-concat
http://php.net/manual/pt_BR/function.explode.php

Filtrar por data no Mysql


How to find out a^b^c^… mod m

Question: I would like to calculate:
abcd... mod m
I know when a is coprime to m then we can easily find out the answer using  Euler's totient function. But I wish to know the ideas when a is not coprime to m.
Thanks In Advance !!!
Answer: Use Chinese Remainder Theorem. We have
$$\begin{cases}m=\gcd(a,m)\cdot m_1\\a=\gcd(a,m)\cdot a_1\\ m_1,a_1\in\mathbb Z\end{cases}$$
$$\begin{cases}a^{b^{c^{d^\ldots}}}\equiv 0\pmod {\gcd(a,m)}\\
a^{b^{c^{d^\ldots}}}\equiv a^{b^{c^{d^\ldots}}\mod {\phi(m_1)}}\equiv r \pmod{m_1}, r\neq 0\end{cases}$$
$$a^{b^{c^{d^\ldots}}}\equiv r\cdot\gcd(a,m)\cdot\left(\frac{1}{\gcd(a,m)}\mod {m_1}\right)\pmod {m}$$

You can find more information on the Chinese Remainder Theorem (abbreviated as CRT) here and anywhere else, just google it.
Here are two ways of solving a system of $2$ linear congruences that have coprime moduli.
The first one uses the Bezout's Lemma and the Extended Euclidean Algorithm.
They are similar in the way that the $1$st one finds modular multiplicative inverses with the help of the Extended Euclidean Algorithm. We have $\frac{1}{n}\equiv y\pmod m$ and $\frac{1}{m}\equiv x\pmod n$.
$$\begin{cases}a\equiv r_m\pmod m\\a\equiv r_n\pmod n\\\gcd(m,n)=1\\mx+ny=1\\a,r_m,r_n,x,y,m,n\in\mathbb Z\end{cases}\implies r_n(mx)+r_m(ny)\equiv \text{answer}\pmod {mn}$$
$$\begin{cases}a\equiv r_m\pmod m, \frac{1}{n}\equiv n''\pmod {m}\\
a\equiv r_n\pmod n, \frac{1}{m}\equiv m''\pmod n\\\gcd(m,n)=1\\a,r_m,r_n,n'',m'',m,n\in\mathbb Z\end{cases}\implies r_mnn''+r_nmm''\equiv \text{answer}\pmod {mn}$$
Comment: Bro How to find out the value of r is 2nd expression .
Comment: @monsterspy well, you said it yourself that everything is simple when $\gcd(a,m)=1$.
Comment: I think r(mod k) is equivalent to r % k !!!!!!! @mathh
Comment: @monsterspy Yes, that is how the $\mod{}$ function is defined.
Comment: Okay thanks alot Bro. .
Comment: Would you please explain this with one example , then It will be easy for me to grasp the concepts . .!!
Comment: @monsterspy first, do you know what modular multiplicative inverses are? $\frac{1}{h}\equiv g\pmod{t}$, where $hg\equiv 1\pmod t$.
Comment: No Bro. . I know only Modular Inverse . .
Comment: Modular multiplicative inverse is what you have in mind. Inverses can be multiplicative and additive, and what you have in mind is multiplicative. Additive inverse of $j$ is just $-j$.
Comment: Okay Bro . . :-)
Comment: I've updated the answer with a description of the Chinese Remainder Theorem. Still haven't added any examples, though. You can add in some numbers and see why all the facts are true yourself.
Comment: Okay, Now I got it too. . thanks for giving your specious time to help me . . @mathh

How to find out a^b^c^… mod m


AD FS 3.0 Event ID 364 while creating MFA (and SSO)

Question: I have an clean installation of AD FS 3.0 installed on windows server 2012. I am trying to create MFA on my internal network using this Codeplex.
AD FS Management > Authentication Policies

Multi-factor locations: Intranet
Selected Multi factor Authentication Extension (name from codeplex)

When I go to my adfs site (https://adfs.xx.com/adfs/ls/IdpInitiatedSignon.aspx) and login with valid credentials, I get the following error:
On site

Activity ID: 00000000-0000-0000-3d00-0080000000e9
Error time: Mon, 01    Feb 2016 09:04:18 GMT
Cookie: enabled
User agent string: Mozilla/5.0    (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko)    Chrome/48.0.2564.97
  Safari/537.36

On server (Event viewer > Appl. and Serv. Logs > AD FS > Admin)

Level: Error, Source: AD FS, Event ID: 364, Task Category: None
.
Encountered error during federation passive request.
Additional Data
Protocol Name:  Saml
Relying Party:  http://adfs.xx.com/adfs/services/trust
Exception details:  System.FormatException: Input string was not in a
  correct format.    at
  System.Text.StringBuilder.AppendFormat(IFormatProvider provider,
  String format, Object[] args)    at
  System.String.Format(IFormatProvider provider, String format, Object[]
  args)    at
  Neos.IdentityServer.MultiFactor.AuthenticationProvider.IsAvailableForUser(Claim
  identityClaim, IAuthenticationContext context)    at
  Microsoft.IdentityServer.Web.Authentication.External.ExternalAuthenticationHandler.IsAvailableForUser(Claim
  identityClaim, IAuthenticationContext authContext)    at
  Microsoft.IdentityServer.Web.Authentication.External.ExternalAuthenticationHandler.ProcessContext(ProtocolContext
  context, IAuthenticationContext authContext, IAccountStoreUserData
  userData)    at
  Microsoft.IdentityServer.Web.Authentication.External.ExternalAuthenticationHandler.Process(ProtocolContext
  context)    at
  Microsoft.IdentityServer.Web.Authentication.AuthenticationOptionsHandler.Process(ProtocolContext
  context)    at
  Microsoft.IdentityServer.Web.PassiveProtocolListener.OnGetContext(WrappedHttpListenerContext
  context)

I have tried to fix the problem by checking the SSL certificates; they are all correct installed. There are no ping errors. I've also checked the code from the project and there are also no faults to see.
Does anyone know about this error or give me an push into the right direction? Any help much appreciated!
[Update 1]
The loglevel is level 2; an basic error.
[Update 2]
See the Codeplex Issues.
[Update 3]
New version available with fixed bugs. The errormessages are fixed.
Answer: The Microsoft TechNet reference for ADFS 2.0 states the following for Event 364:

This event can be caused by anything that is incorrect in the passive request. It can occur during single sign-on (SSO) or logout for both SAML and WS-Federation scenarios.

https://technet.microsoft.com/en-us/library/adfs2-troubleshooting-fedpassive-request-failures(v=ws.10).
I realize you're using a newer version of ADFS but I couldn't find an updated reference in the 2012 R2 documentation. However, the description isn't all that helpful anyway.
References from some other sources usually point to certificate issues (revocation checking, missing certificate in chain) or a time skew.
http://www.gfi.com/blog/how-to-resolve-adfs-issues-with-event-id-364/
I know you said the certificates were installed correctly but you may want to double check that you can complete the revocation check and the chain validates. The easiest way to do this would be to open the certificate on the server from the Certificates snap-in and make sure there are no errors are warnings on the General and Certification Path tabs.
I've had time skew issues bite me in other authentication scenarios so definitely make sure all of your clocks match up as well.
Another thread I ran into mentioned an issue with SPNs. I know when I setup an ADFS 2012 R2 environment I ran into a problem with the SPN registration because my server's FQDN was the same as my intended Federation Service name (adfs.domain.com) so it was unable to register the SPN for ADFS. I fixed this by changing the hostname to something else and manually registering the SPNs. Unfortunately, I don't remember if this issue caused an event 364 though.
One thing I am curious about that you didn't mention if you had tried is whether or not you tested authentication to ADFS without the MFA extension. The extension name showing up in the exception stack seems to indicate it is part of the issue but that test could help you rule out issues with other aspects of your ADFS deployment.
Finally, if none of the above seems to help I would recheck the extension documentation to make sure that you didn't miss any steps in the setup. Hope that helps!
Comment: Hi @learley, I've checked all your solutions there were some faults anyway, +1 for that. But unfortunately I got still the error..
Comment: Were you able to test your ADFS configuration without the MFA extension? If not, you may want to run the uninstall steps provided in the documentation (https://adfsmfa.codeplex.com/documentation) and then attempt to authenticate to the ADFS site. This could at least help us determine if it is an issue specific to the extension or something else in your environment.
Comment: Adfs works fine without this extention. I have also installed another extension and that was working fine as 2nd factor.
Answer: I faced this issue in Windows Server 2016 and it turned out to be fairly basic in my setup. The issue is that the page was not enabled. When I attempted to signon, I received an the error 364.
The link to the answer for my issue is, https://blogs.technet.microsoft.com/rmilne/2017/06/20/how-to-enable-idpinitiatedsignon-page-in-ad-fs-2016/
Set-AdfsProperties –EnableIdpInitiatedSignonPage $True

Answer: I had the same issue in Windows Server 2016. It turned out, that the MFA Provider defined available LCIDs (languages) for en-US only but my browser did not send en or en-US as an accepted language.
Setting en-US as an accepted language in the browser helped temporary.
But because I have written the MFA provider myself, I defined at least CultureInfo.InvariantCulture.LCID as one of the AvailableLcids in my IAuthenticationAdapterMetadata implementation. This solved the problem.


AngularJS document.write() won't work in partial

Question: I want to include the current year in the copy-write notice in the footer of AngularJS app I'm building with:

The problem is when I try to add it in a partial that has been added to document with ng-include it won't work:

It works when I add it directly to index.html.  What is the best way to achieve this in AngularJS?
Do I need to turn the footer into a directive and add a controller for this?
Answer: You need to set a scope variable in your footer's controller. e.g. $scope.year = new Date().getFullYear(); then you can use it in your HTML like this: {{year}}.
It need not be a directive. You can also use ng-controller="footerCtrl" etc. as an HTML property for your footer to point to the controller you want to use for your footer.
Comment: Wanted to also mention that technically your copyright date will at some point be legally incorrect, if you say launch your site this month and make no improvements when January rolls around, you'll see 2017 instead of the correct value of 2016.
Comment: I thought it was normal practice to display the current year i.e date of latest revision which is the current year for most maintained websites.  http://updateyourfooter.com
Comment: If you're working on a website with constantly changing daily content (user-generated etc.) where the ownership of the content is with the site's owners, then it'd make sense to have the copyright update. e.g. (C) 2012-2016, XYZ Inc. All rights reserved. (2016 would auto-change to 2017.) If it's content that is rarely updated and only via published releases, such as a static site you write for a client, it shouldn't auto-change to be a date later than the creation of the last content.


Is the range of a bounded linear functional closed?

Question: Let $X$ be an inner product space and $f$ be a bounded linear functional $f: X \rightarrow \mathbb{C}$. Is $ran f$ a closed subspace of $X$?
I have found that $ker f$ is a closed subspace of $X$, but have no idea for the range of $f$.
Any hint will be most appreciated.
Comment: You're implying the range of a linear functional on $X$ is a subspace of $X$, nonsense.
Comment: @user444628: I think you want the range of $f$ to be a closed subspace of $\mathbb{R}?$
Comment: @user444628: You might need to see Closed Graph Theorem.
Comment: @Idonknow  Oh thank you so much. So what is an example of a functional whose range is not a subspace?
Comment: I think you mean bounded linear operator rather than bounded linear functional.
Comment: @jgon I mean a bounded linear functional.
Comment: @user444628 I'm very confused by what you're asking then, so I'll ask my question again without using words that could be confused. Do you mean that $f : X\to X$, or $f : X\to \Bbb{K}$ where $\Bbb{K}$ is the field you're working over. If it's indeed the latter, you should understand our confusion.
Comment: @jgon Oh so sorry for me making the mistake. I mean a bounded linear functional from X to \mathbb{C}.
Comment: Then the range is either 0 or $\Bbb{C}$, which are certainly closed subspaces of $\Bbb{C}$.
Answer: The range of a (complex) linear functional is indeed a subspace and has dimension over C of either 0 or 1 .If 0 then the range of f is (0) ,if 1 then the range of f is C .in both cases closed in C


Where to find structure of objects that I can access in PHP snippets added to different parts of UI?

Question: In views I can add PHP snippets for custom validation or when I want to provide default value for contextual filter. It is telling me that I can use $view or $argument - but where is documentation of these objects? Where can I read what are my possibilities in these areas (or how check this, by using debugger for example)?
Answer: You can install the devel module and use the dpm function to check it out.
You can check the whole list of devel functions at http://ratatosk.net/drupal/tutorials/debugging-drupal.html
Comment: I installed devel module, and put this code to (PHP custom code) action in Rules: "dpm($site);" yet when action happens - it doesn't show anything, so I still doesn't know what in $site variable is at the moment of execution :/ .
Comment: did you try print dpm($site);
Comment: Yes, it still doesn't work. I tried drupal_set_message() to be sure that action triggers and it works. Tried also "kpr($site);" without effect :/ .
Comment: I don't know why but after installing Drupal again it now works. Thanks!


How do I hook the stock status message to the product page?

Question: I have a Commerce Demo site that uses the off canvas flyout cart and I am using the Commerce Simple Stock module to stop items being sold if they are out of stock.
The module changes the stock number and prevents the item being loaded to the cart if already purchased. It sends user/status messages and removes the add to cart button using commerce_simple_stock_form_commerce_order_item_add_to_cart_form_alter().
This hook doesn't work for the Commerce Demo form.
The theme hook for the Add to cart button in Commerce Demo is commerce_cart_flyout_add_to_cart_button().
The stock status messages show on the admin pages but not on the product page itself.
How do I hook the stock status message from the module to the product page?
Comment: What do you mean by "hook the stock status message from the module to the product page"?  It's not clear to me what the goal is.
Comment: Do you see any system messages on your product page? I.e. is the issue really that no system messages appear on those pages?
Comment: @sonfd The system messages are showing up when you go to the admin panel but not on the actual product page itself. It is as though the template for the product is not picking up the system message
Comment: @PatrickKenny the template that is showing the product  (which includes the add to cart button) is not showing the system message that the stock level is at 0. This system message is showing on other parts of the site but not the page I want it to.
Answer: System Messages are printed to the page via a block (Block: Messages, Category: System).

If the messages block isn't aren't appearing on a particular page:

Check to make sure the block is added to a region in the active theme for the page in question.
Check to make sure any visibility settings for the block are configured correctly for the target audience
Make sure that your theme actually renders the region that you added the block to.

If you're still not seeing the messages block:

Create a static custom block (something that should always appear) and place it in the region.
Test with the block added to a region you know is rendering, i.e. the main content region.
Inspect the source html of the page to make sure the html is actually missing and isn't just being hidden by css.
Enable twig_debug and verify that the page is built with the templates you think it is. Check each template (Page, Region, Block, potentially others, but it would likely be one of these that's the issue) and make sure the template is properly rendering what it needs to.


Maximum Internet Bandwidth per User

Question: My question pertains to network bandwidth outside our local LAN.
We have a 10Mbps internet connection provided by our ISP.  We need to setup a wireless connection and the plan is to add a 54Mbps wireless router to our 10Mbps LAN. Approximately 30 pax/users will connect into this wireless router.
What is maximum speed each user can get if they are all using or browsing the internet at the same time?  For example, if each one is downloading a 10MB web portal applet over the internet in the morning when first logging on.
Comment: The maximum speed they can get is 10Mbps.
Answer: Raw straight answer? About 24 seconds for a 1MB file per user. But 10Mbps divided by 30 concurrent users for web browsing is going to be extremely tight. Ignoring for a moment that WiFi will bring it's own congestion issues the resulting performance is going to hugely depend on the type of internet traffic consumed.
If it is streaming HD video for all, it's going to be a disaster to chop that into usable chunks. Traditionally the first port of call for low bandwidth was to implement an internet caching services. Personally I've experience of Squid proxy and it's very good. The main issue is it will struggle with TLS/SSL traffic nor streaming traffic, so whilst it can have a fantastic savings for downloads, that doesn't make up a lot of modern internet traffic.
In order to make the traffic usable you'll probably need to restrict some types of traffic such as youtube. If your router allows it, I would recommend setting some sort of QoS (Quality of Service) to ensure that important traffic is given a higher priority than trvial traffic.
Try and host your own content where possible to save internet transit via local servers for typical files. Have a look at Self-Hosted/Hybrid alternatives to typical cloud systems and storage.
Another strategy is to utilise your bandwidth at night time when it would otherwise not be in use by scheduling tasks to happen outside of normal hours that aren't time critical.
Answer: Your question is not that easy to answer.  As gsmitheidw pointed out, 10mb divided by 30 would get you in the ball park, but you have to consider other overhead such as people checking email, or other network congestion.
If your users really need to be downloading 10mb files once per day or periodically, I would seriously consider upgrading your internet connection.  I assume that the 30ish users do not make up the entirety of your network.  Even if it is just half of your network, 60 connections sharing a 10mb pipe has got to be painful.
Also, consider an 802.11ac wireless router.  The 802.11g router you have is built on technology that is more than 10 years old.  You should be planning for the future, not just trying to satisfy current needs.  You will be forever be playing catch-up.  Doing it right the first time will save you and your company many headaches in the immediate and long term future.
The short answer:  consider upgrading your internet as well as a faster wireless router for as many users as you are supporting.

Maximum Internet Bandwidth per User


hide certain category from single post

Question: I need to limit number of categories display in a single post on wordpress using this script
    function swift_list_cats($num){
$temp=get_the_category();
$count=count($temp);// Getting the total number of categories the post is filed in.
for($i=0;$i<$num&&$i<$count;$i++){
//Formatting our output.
$cat_string.='cat_ID ).'">'.$temp[$i]->cat_name.'';
if($i!=$num-1&&$i+1<$count)
//Adding a ',' if it's not the last category.
//You can add your own separator here.
$cat_string.=' | ';
}
echo $cat_string;
}

But I also need to hide some categories. How would I do that?
Answer: Simple answer is to return a new count not based on the length of your array so
for($i=0;$i<$num&&$i<$count;$i++){

becomes:
for($i=0;$i<10;$i++){

or use $temp = array_slice(get_the_category(), //ofset 0, //length 10);
Array slice info can be seen here.
If you need to hide some values, this would be far easier to do by adding a hidden column to your database and select values WHERE hidden = 0. However to address your question.You need to know which values you want to hide. Store these in an array and do the following.
        function swift_list_cats($num){

    $hiddenArray = [12, 105];

    //change offset and limit to what you desire removing the slashes and labels

    $temp = array_slice(get_the_category(),  0,  10);
        $count=count($temp);

    $cat_string = '';

    for($i=0;$i<$num&&$i<$count;$i++){

        if(in_array($temp[i]->cat_ID, $hiddenArray)){
              continue;
        }

        $cat_string.='cat_ID ).'">'.$temp[$i]->cat_name.'';

        if($i!=$num-1&&$i+1<$count)

            $cat_string.=' | ';
    }
    echo $cat_string;
}

$hiddenArray is the array you populate with your category IDs that you want hidden
Comment: how to use it? i ned for example hide ctagory 12 and 105
Comment: Parse error: syntax error, unexpected ';', expecting ',' or ')' in C:\xampp\apps\wordpress
Comment: recopy code please. $cat_string needed to be set first. If there's any issues now, the issue is bigger than this code.
Comment: now there is no error but category in single post was not hide :(
Comment: contact me via my email on my profile and i can investigate further.
Comment: add_filter( 'get_the_categories', 'remove_category_link' );

function remove_category_link( $categories ) {

    if ( is_admin() )
        return $categories;

    $remove = array();

    foreach ( $categories as $category ) {

    if ( $category->name == "category name" ) continue;
    $remove[] = $category;
    }
    return $remove;
}    solved usign this thanks :9

hide certain category from single post


Space the score notes evenly

Question: Is there a way in LilyPond to space the score notes evenly?

In the sample image made with LilyPond 2.22.01 the notes are not equally spaced.
Edit
The idea is to get all the notes to be spaced equally regardless of their note value.
Comment: The notes are not _supposed_ to be evenly spaced because they represent different durations.  Spacing them evenly would be confusing and would make the music harder to read.
Comment: Yeah unless you're trying to teach something about engraving and note spacing or otherwise doing something unusual, do not space notes evenly. If you want someone to actually perform what you're engraving, even note spacing will make it much harder for them. Elaine Gould codified a lot of note spacing best practices in her book *Behind Bars*. Well worth a read for anyone writing any kind of score for performance or recording.
Comment: @ToddWilcox good point.  You _do_ want the notes to be evenly spaced if you want to make an "avoid this practice" example.
Comment: I'm really curious about the use case: why would you ever want to do this?
Comment: @Creynders look here: https://music.stackexchange.com/q/117971/81941
Answer:
You can tell LilyPond to space the notes strictly based on their note values, with the command below (I think this is what you are looking for):
\override Score.SpacingSpanner.strict-note-spacing = ##t
(see changing-horizontal-spacing)

You might think that this will make the music easier to read, as the notes will be on some evenly spaced (invisible) time grid.  And that might be true is some cases, but it usually is a waste of horizontal space. Besides, the time information is already represented by the note symbols (beams, dots, etc.).

Updated Answer
After reading your comments, what you want is the notes to be be evenly spaced regardless of their note values.
In this case what you want to set, is the shortest duration to get a unit space:
\override Score.SpacingSpanner.shortest-duration-space = #16
(see spacing-spanner-interface)

Note
This also provides a score that is harder to read than the default spacing provided by LilyPond's typesetting algorithm.  This complicated algorithm is one of the reasons that makes it such a good engraving program.
Comment: @Mahanidhi And, just to reiterate what's in the comments above... performers rely on the "default" spacing, in which longer notes get more space, as a visual cue to the rhythm. Equal spacing would be harder to read.
Comment: it partially works in the sense that little changes. From the guide I did not understand if it is possible to give a value to spacing.
Comment: @Mahanidhi Try setting the shortest duration value _as well_ (as per the example at the top of the page linked), e.g. :
`\override Score.SpacingSpanner.base-shortest-duration = #(ly:make-moment 1/16)`.

Or are you wanting to get all the notes to be spaced equally regardless of their note value?
Comment: Yes the idea is to get all the notes to be spaced equally regardless of their note value

Space the score notes evenly


How do I translate this SQL code into classic ASP/VB code

Question: I need to modify some code of an existing classic ASP web application created by my predecessor.
The current code:
sql = "SELECT * FROM (SELECT substr(trim(WURK_SUMMARY.WORK_ORD_NO),-4,4) LF, LREQ.PROCESS_CENTER, WURK_SUMMARY.WORK_ORD_NO As ORDER_NO, WURK_SUMMARY.ORIG_DT, WURK_SUMMARY.PART_DESC, WURK_SUMMARY.ROUT_PART_DESC, WURK_SUMMARY.BASE_TRAK_ID, WURK_SUMMARY.ROUT_PART_NO, WURK_SUMMARY.COMBINE_NO, "

sql = sql & "WURK_SUMMARY.WO_STATUS_DESC, WURK_SUMMARY.REQD_DT, WURK_SUMMARY.ACT_START_DT, WURK_SUMMARY.RLSE_DT, WURK_SUMMARY.CLOSE_DT, WURK_SUMMARY.ACT_CMPL_DT, WURK_SUMMARY.LOAD_HOURS, WURK_SUMMARY.ACTUAL_HOURS, "

sql = sql & "ROW_NUMBER() OVER (PARTITION BY WURK_SUMMARY.WORK_ORD_NO ORDER BY WURK_SUMMARY.WORK_ORD_NO) AS RowNUMBR FROM WURK_SUMMARY JOIN LREQ ON WURK_SUMMARY.WORK_ORD_NO=LREQ.ORDER_NO WHERE "

    if use_work_ord_no=true then
    sql = sql & "WURK_SUMMARY.WORK_ORD_NO LIKE '"&mln&"-%' "
    else
    sql = sql & "WURK_SUMMARY.COMBINE_NO='"&mln&"' "
    end if

    sql = sql & "AND LREQ.PROCESS_CENTER='"&process_center&"' "

Sql Code to add to above code:
AND LREQ.SEQ_NO =
        (SELECT MIN(LREQ2B.SEQ_NO)
            FROM LREQ AS LREQ2B
            WHERE LREQ.ORDER_NO = LREQ2B.ORDER_NO
            AND LREQ.TRAK_ID = LREQ2B.TRAK_ID)

Comment: Can you just concatenate it to the rest of the concatenated mess? Also, VB.NET is not asp-classic.
Comment: As @the_lotus suggests, just add the following line `sql = sql & "AND LREQ.SEQ_NO = (SELECT MIN(LREQ2B.SEQ_NO)  FROM LREQ AS LREQ2B WHERE LREQ.ORDER_NO = LREQ2B.ORDER_NO AND LREQ.TRAK_ID = LREQ2B.TRAK_ID)"`
Answer: here's a cleaned up crack at it:
sql = "SELECT * FROM (SELECT substr(trim(WURK_SUMMARY.WORK_ORD_NO),-4,4) LF, LREQ.PROCESS_CENTER, WURK_SUMMARY.WORK_ORD_NO As ORDER_NO, WURK_SUMMARY.ORIG_DT, WURK_SUMMARY.PART_DESC, WURK_SUMMARY.ROUT_PART_DESC, WURK_SUMMARY.BASE_TRAK_ID, WURK_SUMMARY.ROUT_PART_NO, WURK_SUMMARY.COMBINE_NO, " _
& "WURK_SUMMARY.WO_STATUS_DESC, WURK_SUMMARY.REQD_DT, WURK_SUMMARY.ACT_START_DT, WURK_SUMMARY.RLSE_DT, WURK_SUMMARY.CLOSE_DT, WURK_SUMMARY.ACT_CMPL_DT, WURK_SUMMARY.LOAD_HOURS, WURK_SUMMARY.ACTUAL_HOURS, " _
& "ROW_NUMBER() OVER (PARTITION BY WURK_SUMMARY.WORK_ORD_NO ORDER BY WURK_SUMMARY.WORK_ORD_NO) AS RowNUMBR FROM WURK_SUMMARY JOIN LREQ ON WURK_SUMMARY.WORK_ORD_NO=LREQ.ORDER_NO WHERE "

if use_work_ord_no=true then
    sql = sql & "WURK_SUMMARY.WORK_ORD_NO LIKE '"&mln&"-%' "
else
    sql = sql & "WURK_SUMMARY.COMBINE_NO='"&mln&"' "
end if

sql = sql & "AND LREQ.PROCESS_CENTER='"&process_center&"' " _
& "AND LREQ.SEQ_NO = " _
& " (SELECT MIN(LREQ2B.SEQ_NO) " _
& "     FROM LREQ AS LREQ2B " _
& "     WHERE LREQ.ORDER_NO = LREQ2B.ORDER_NO " _
& "        AND LREQ.TRAK_ID = LREQ2B.TRAK_ID) "


console output formatting

Question: Are there any conventions for formatting console output from a command line app for readability and consistency?  For instance, do you indent sub-information, when do you print a blank line, if ever, how should you accent important statements.
I've found  output can quickly degenerate into a chaotic blur.  I'm interested in hearing about what other people do.
Update: Really this is for embedded software which spits debug status out a terminal, but it's pretty much like a console app, and I figured everyone would be more familiar with that.  Thanks so far.
Answer: I'd differentiate two kinds of programs:
Do you print information that might be used by a script (i.e. it should be parseable)? Then define a pretty strict format and use only that (for example fixed field separators).
Do you print information that need not be parsed by a script (or is there an alternative script-parseable format already)? Then write what comes natural:
My suggestions:

write it so that you would like to read it
indent sub-information 2 or 4 spaces, definitely not more
separate blocks of information by one empty line at most
respect the COLUMN environment variable (and possible ROWS if it applies to your output).
Answer: If this is for a *nix environment, then I'd recommend reading Basics of Unix Philosophy. It's not specific to output but there are some good guidelines for command line programs in general.

Expect the output of every program to become the input to another, as yet unknown, program. Don't clutter output with extraneous information. Avoid stringently columnar or binary input formats. Don't insist on interactive input.

console output formatting


Login And Pay With Amazon Automatic Integration Guide

Question: I have been working with Login And Pay With Amazon Automatic Integration Guide. Amazon has provided a document for the same:   http://docs.developer.amazonservices.com/en_US/pay_with_amazon_automatic_payments/APAGuide_GettingStarted.html
But the problem is - document is for US marketplace and I am implementing for UK. Now when I implement the same, it returns the error:
<code>"Unknown client ID".</code>
Can anyone please help me in the same. I have been working on this from past 3 days, and it comes out like a mess to me.
Answer: You should be following the UK guide. http://docs.developer.amazonservices.com/en_UK/apa_guide/APAGuide_GettingStarted.html