How is the kurtosis of a distribution related to the geometry of the density function?

Question: The kurtosis is to measure the peakedness and flatness of a distribution. The density function of the distribution, if it exists, can be viewed as a curve, and has geometric features (such as curvature, convexity, ...) related  to its shape.
So I wonder whether the kurtosis of a distribution is related to some geometric features of the density function, which can explain the geometric meaning of kurtosis?
Comment: Please give sources as precise URLs (not just "from the web"). Although at least one of these sources should not be used, knowing precisely what to avoid can also be useful information.
Comment: http://www.signalfinancialgroup.com/images/Kurtosis.jpg and http://mvpprograms.com/help/images/KurtosisPict.jpg
Comment: I am asking for some relation in formula to some geometric quantity  of the density curve, not just the vague meaning I pointed out in my post. Or it is fine to just have some explanation of why kurtosis has the geometric meaning
Comment: @Peter That is far from the truth.  One can modify the geometry of the graph of the PDF almost arbitrarily without changing any specified (finite number of its) moments.
Comment: The closely related question at http://stats.stackexchange.com/questions/25010/identity-of-moment-generating-functions suggests what the right answer to this question should be.
Comment: @whuber while I agree and thank you for that example, I also wonder whether it doesn't says more about the remarkable property of that particular family of pdf than it does about kurtosis in general.
Comment: @user603 That's a good thing to wonder. However, the statement is not about this particular family: it just happens that for the lognormal distribution one can produce an explicit representation of a class of alternative PDFs with the same moments. It *is* special that *all* of the moments are the same, but perturbing most distributions in a way that fixes a finite number of their moments is not hard.  (It's hard for certain discrete distributions, such as the Bernoulli, but they don't have PDFs.)
Answer: The moments of a continuous distribution, and functions of them like the kurtosis, tell you extremely little about the graph of its density function.
Consider, for instance, the following graphs.

Each of these is the graph of a non-negative function integrating to $1$: they are all PDFs.  Moreover, they all have exactly the same moments--every last infinite number of them.  Thus they share a common kurtosis (which happens to equal $-3+3 e^2+2 e^3+e^4$.)
The formulas for these functions are
$$f_{k,s}(x) = \frac{1}{\sqrt{2\pi}x} \exp\left(-\frac{1}{2}(\log(x))^2\right)\left(1 + s\sin(2 k \pi \log(x))\right)$$
for $x \gt 0,$ $-1\le s\le 1,$ and $k\in\mathbb{Z}.$
The figure displays values of $s$ at the left and values of $k$ across the top.  The left-hand column shows the PDF for the standard lognormal distribution.
Exercise 6.21 in Kendall's Advanced Theory of Statistics (Stuart & Ord, 5th edition) asks the reader to show that these all have the same moments.
One can similarly modify any pdf to create another pdf of radically different shape but with the same second and fourth central moments (say), which therefore would have the same kurtosis. From this example alone it should be abundantly clear that kurtosis is not an easily interpretable or intuitive measure of symmetry, unimodality, bimodality, convexity, or any other familiar geometric characterization of a curve.
Functions of moments, therefore (and kurtosis as a special case) do not describe geometric properties of the graph of the pdf.  This intuitively makes sense: because a pdf represents probability by means of area, we can almost freely shift probability density around from one location to another, radically changing the appearance of the pdf, while fixing any finite number of pre-specified moments.
Comment: "From this example alone it should be abundantly clear... any other familiar geometric characterization of a curve." I understand what you mean, but there is ground for reasonable divergence in the interpretation here. Another interpretation is that of Darlington, who shows how starting from a symmetric distribution, moving some mass at specific points increases/decrease the kurtosis (again, not a contradiction of your example, just a more 'positive'  understanding).
Comment: @user603 I don't disagree, but I think that the "positive" approach overlooks the very special assumptions that are implicitly made in order for it to work at all. One could also begin with the graph of an extremely asymmetric PDF whose skewness is zero (they are not hard to construct).  Thus that positive approach merely describes what happens to certain very special PDFs when the mass is moved around.  Although that can be quite useful for intuition, it seems to have no logical bearing on the present question.
Comment: I agree for the skewness (and for your answer in general). But the kurtosis, as a function, has a minimum. That makes things slightly more interesting.
Comment: @user603 Thank you; that's an insightful distinction.  I don't think it changes any of the present conclusions in important ways but it certainly helps the intuition and points to an important difference between even and odd moments.
Answer: [NB this was written in response to another question on site; the answers were merged to the present question. This is why this answer seems to respond to a differently worded question. However much of the post should be relevant here.]
Kurtosis doesn't really measure the shape of distributions. Within some distribution families perhaps, you can say it describes the shape, but more generally kurtosis doesn't tell you terribly much about the actual shape. Shape is impacted by many things, including things unrelated to kurtosis.
If one does image searches for kurtosis, quite a few images like this one show up:

which instead seem to be showing changing variance, rather than increasing kurtosis. For comparison, here's three normal densities I just drew (using R) with different standard deviations:

As you can see, it looks almost identical to the previous picture. These all have exactly the same kurtosis. By contrast, here's an example that is probably nearer to what the diagram was aiming for

The green curve is both more peaked and heavier tailed (though this display isn't well suited to seeing how much heavier the tail actually is). The blue curve is less peaked and has very light tails (indeed it has no tails at all beyond $\sqrt{6}$ standard deviations from the mean).
This is usually what people mean when they talk about kurtosis indicating the shape of the density. However, kurtosis can be subtle -- it doesn't have to work like that.
For example, at a given variance higher kurtosis can actually occur with a lower peak.
One must also beware the temptation (and in quite a few books it's openly stated) that zero excess kurtosis implies normality. There are distributions with excess kurtosis 0 that are nothing like normal. Here's an example:

Indeed, that also illustrates the previous point. I could readily construct a similar-looking distribution with higher kurtosis than the normal but which is still zero at the center - a complete absence of peak.
There are a number of posts on site that describe kurtosis further. One example is here.
Comment: Some authors write of kurtosis as peakedness and some write of it as tail weight, but the skeptical interpretation that kurtosis is whatever kurtosis measures is the only totally safe story. Numerical examples given by Irving Kaplansky (1945) alone suffice to show that kurtosis bears neither interpretation unequivocally. (Kaplansky's paper is one of a few that he wrote in the mid-1940s on probability and statistics. He is much better known as a distinguished algebraist.) Full reference and more within http://www.stata-journal.com/sjpdf.html?articlenum=st0204
Comment: Don't trust any pictures in this territory unless they are computer-drawn and matched by a calculation of kurtosis. It's horribly common **still** that authors sketch something by hand and/or give it to graphic design people who don't understand the mathematical essentials and don't get that specification from authors. (Conversely, strong statisticians can be, and often are, poor at graphic design.) A first and crucial qualitative test of such pictures is that the total area under each **must** be identical; that's not true to my eye of the blue and brown curves, for a start.
Comment: There are books and papers claiming that kurtosis is peakedness, so my first clause remains correct as well as supportable as a statement on what is in the literature. What's more crucial is how one regards Kaplansky's examples and arguments.
Comment: @Glen_b The pictures are not from the book. The book does not give illustrations. I used the goolge picture search for these illustrations.
Comment: It is such a nicely illustrated explanation that I had no doubt it would remain intelligible after the merge, despite the embedded quotations.  This experience does suggest that the practice of quoting parts of a question be limited, and hints at the merits of searching for duplicate questions before answering (something [I have been found guilty of not doing,](http://meta.stats.stackexchange.com/questions/2450/sending-a-private-message-to-another-user#comment6696_2450) too).
Comment: But I did not say it? The book says it?
Comment: I know that. I never said you said it. How would you suggest I respond to blatantly incorrect statements that you ask about? Just pretend they're not wrong?
Comment: Argh? But.....? And I also put a second picture in it, because you say it is misleading, but the second picture is more or less the same. So the pictures DO show different kurtosis....or not....?
Comment: Damn, I (statistician) got screwed in this simple topic.
Comment: I'm trying to add to my answer. I've been looking for additional resources (other posts) to explain why the claims are false. I suggest you don't waste further time on that particular resource.
Comment: Ok thanks, but if you google for kurtosis pictures most of the pictures are like that, so the pictures DO show changes in the kurtosis correctly....?
Comment: Nick, your "Some authors write of kurtosis as peakedness and some write of it as tail weight, but the skeptical interpretation that kurtosis is whatever kurtosis measures is the only totally safe story," is not supportable. Kurtosis measures nothing about the peak, and it does measure tailweight; see the theorems in my TAS article supporting the "tail" interpretation. "Counterexamples" to the "tail" interpretation are based on silly measures of  what it means to be "more heavy tailed," using irrelevant notions of density crossings. Practically, tails concerns outliers, not density crossings.
Comment: Yes, "peakedness" is in the literature. But the concepts are not mathematically connected; counterexamples abound. The description must be abandoned. Pearson started it wrongly in 1905, and Fisher parroted Pearson in all editions of his famous book through 1964. No one wanted to argue with those giants. Then Balanda and Macgillivray equivocated, stating incorrectly that it measures movement from shoulders to tail and center *without proof* in 1986 or so. DeCarlo kept it going with an incorrect first sentence in his 1997 abstract (never supported in his paper!) Someone had to end the nonsense.
Answer: For symmetric distributions (that is those for which the even centred moments are meaningful) kurtosis measures a geometric feature of the underlying pdf.
It is not true that kurtosis measures (or is in general related) to
the peakedness of a distribution. Rather, kurtosis measure
how far the underlying distribution is from being symmetric and
 bimodal (algebraically, a perfectly symmetric and bimodal
distribution will have a kurtosis of 1, which is the smallest possible value the kurtosis can have)[0].
In a nutshell[1], if you define:
$$k=E(x-\mu)^4/\sigma^4$$
with $E(X)=\mu,V(X)=\sigma^2$, then
$$k=V(Z^2)+1\ge1$$
for $Z=(X-\mu)/\sigma$.
This implies that $k$ can be seen as a measure
of dispersion of $Z^2$ around its expectation 1.
In other words, if you have a geometrical interpretation
of the variance and the expectation, than that of
the kurtosis follows.
[0] R. B. Darlington (1970). Is Kurtosis Really "Peakedness?".
The American Statistician , Vol. 24, No. 2.
[1] J. J. A. Moors (1986).The Meaning of Kurtosis: Darlington Reexamined.
The American Statistician, Volume 40, Issue 4.
Comment: Everywhere you write "bimodal" do you perhaps mean "unimodal"?
Comment: Yes, these examples work for symmetric distributions. An explicit one could be constructed from the pseudo-lognormal families: take one of those (infinitely modal) pdfs $f$ with a mean of $\mu$ and define a new pdf as $g(x) = (f(x)+f(2\mu-x))/2.$ By mixing in a small amount of $g$ with a minimum-kurtosis distribution you find that there are distributions with infinitely many modes whose kurtosis is arbitrarily close to the minimum value of $1$. Thus, at least, kurtosis says nothing whatsoever about bimodality. Since it does not, precisely what geometric property of the pdf is it describing?
Comment: let us [continue this discussion in chat](http://chat.stackexchange.com/rooms/12824/discussion-between-whuber-and-user603)
Comment: Kurtosis does not indicate bimodality, except in the extreme case where it is near its minimum, where it indicates something similar to the two-point equiprobable distribution. You can have bimodal distributions with every possible value of kurtosis.  See https://www.ncbi.nlm.nih.gov/pmc/articles/PMC4321753/ for examples.
Comment: Yes; see the paper I linked. The first sentence of DeCarlo's abstract is absolutely wrong. If you don't want to read my paper, here is the math: take any symmetric bimodal distribution and mix it with a much wider symmetric distribution having the same median as the bimodal. The mixture is symmetric and bimodal for small $p$. By tweaking the wider distribution and the mixing $p$, you can make the kurtosis range to infinity. And you can get kurtosis as small as you want by using .5N(-1,v) + .5N(1,v), letting $v \rightarrow 0$.  Symmetric and bimodal pdfs are easy to construct for all kurtosis.
Comment: @PeterWestfall: I have now read your paper and find it very clear and informative. As you guessed, I will need to edit my answer in light of the arguments presented therein. I will try to do so this week.
Comment: @whuber: I have just seen your last answer to this in the chat. The chat is closed now (for inactivity). But I think your result (if correct) contradicts the  Darlington paper since (If i understand it correctly) your result implies that the minimizer to the kurtosis (at symmetric distribution) is not unique.
Comment: @whuber: no. See [0] "the smaller the khurtosis, the greater the bimodality". A bimodal distribution where the modes are at $\mu\pm\sigma$ will have kurtosis of 1.
Comment: I guess I don't follow, because kurtosis has no essential relationship to bimodality or modes in general. Indeed, for any bimodal PDF of given kurtosis there are other PDFs with the same kurtosis having arbitrary numbers of modes, so kurtosis cannot possibly be interpreted as saying anything about modes.
Comment: The second equation in my post shows what shape (and it is unique) a pdf should have to attain the lowest possible kurtosis. Then, it is wholly legitimate to interpret kurtosis as a measure of departure from that shape.
Comment: Yes, I have been reflecting on your earlier comments and now this latest one clarifies your logic (+1). Thank you for your patience in explaining it. However, it still is not clear to me how this fact would translate to a statement about *geometric characterizations of the pdf.* The problem is that the unique minimum-kurtosis distributional shape has no pdf and any distribution with a pdf can be perturbed, without changing its kurtosis, into one whose pdf has awful geometric properties. E.g., for any kurtosis greater than the minimum of $1$ there exists a pdf with infinitely many modes.
Comment: @whuber: But are these examples for symmetric distributions? I take it as given that centred even moments can note satisfyingly describe features of the shape of non symmetric pdf's. I've edited my answer to make this point explicit.
Comment: @whuber: *arbitrarily close to 1*? Presumably the rate of contamination of the sample by draws from $g(x)$ is bounded by $1/n$? In other word the contamination by draws from $g(x)$, as soon as it will produce that third mode, will affect the kurtosis. Likewise, I don't see how the assymptotic kurtosis of that contaminated distribution (which is not the same as that of the individual component distributions) can be taken *arbitrarily close to 1*.
Comment: @Peter: but can you have symmetric *and* bimodal distributions with every possible values of kurtosis?
Answer: A different kind of answer: We can illustrate kurtosis geometrically, using ideas from http://www.quantdec.com/envstats/notes/class_06/properties.htm: graphical moments.
Start with the definition of kurtosis:
$$ \DeclareMathOperator{\E}{\mathbb{E}}
  k = \E \left(  \frac{X-\mu}{\sigma} \right)^4 =\int \left(\frac{x-\mu}{\sigma}\right)^4 f(x) \; dx
$$
where $f$ is the density of $X$, $\mu, \sigma^2$ respectively expectation and variance. The nonnegative function under the integral sign integrates to the kurtosis, and gives contribution to kurtosis from around $x$. We can call it the kurtosis density, and plotting it shows the kurtosis graphically. (Note that in this post we are not using the excess kurtosis $k_e=k-3$ at all).
In the following I will show a plot of graphical kurtosis for some symmetric distributions, all centered at zero and scaled to have variance 1.

Note the virtual absence of contribution to the kurtosis from the center, showing that kurtosis does not have much to do with "peakedness".
Comment: Exactly right. The areas under the curves you show from -1 to +1 are between 0 and 1 for all distributions, and are between 0 and 0.5 for all continuous distributions for which the density of $Z^2$ is decreasing on the [0,1] range. Those two theorems are proven in my paper https://www.ncbi.nlm.nih.gov/pmc/articles/PMC4321753/ . A third theorem proven therein is that, for any sequence of distributions for which kurtosis tends to infinity, the ratio of the area under the range from $-b$ to $+b$ to kurtosis tends to zero, for every fixed $b$.
Answer: Kurtosis is not related to the geometry of the distribution at all, at least not in the central portion of the distribution. In the central portion of the distribution (within the $\mu \pm \sigma$ range) the geometry can show an infinite peak, a flat peak, or bimodal peaks, both in cases where the kurtosis is infinite, and in cases where the kurtosis is less than that of the normal distribution. Kurtosis measures tail behavior (outliers) only. See https://www.ncbi.nlm.nih.gov/pmc/articles/PMC4321753/
Edit 11/23/2018:  Since writing this post, I have developed some geometrical perspectives on kurtosis. One is that excess kurtosis can indeed be visualized geometrically in terms of deviations from the expected 45 degree line in the tails of the normal quantile-quantile plot; see
Does this Q-Q plot indicates leptokurtic or platykurtic distribution?
Another (perhaps more physical than geometrical) interpretation of kurtosis is that kurtosis can be visualized as the point of balance of the distribution $p_V(v)$, where $V = \{(X - \mu)/\sigma \}^4$. Note that (non-excess) kurtosis of $X$ is equal to $E(V)$. Thus, the distribution of $V$ balances at the kurtosis of $X$.
Another result that shows that geometry in the $\mu \pm \sigma$ range is nearly irrelevant to kurtosis is given as follows. Consider the pdf of any RV $X$ having finite fourth moment. (Thus the result applies to all empirical distributions.) Replace the mass (or geometry) within the $\mu \pm \sigma$ range arbitrarily to get a new distribution, but keep the mean and standard deviation of the resulting distribution equal to $\mu$ and $\sigma$ of the original $X$. Then the maximum difference in kurtosis for all such replacements is $\le 0.25$. On the other hand, if you replace the mass outside the $\mu \pm \sigma$ range, keeping the center mass as well as $\mu$, $\sigma$ fixed, the difference in kurtosis is unbounded for all such replacements.
Comment: Rather than just continuing to refer people to a paper in most of your posts, would you mind summarizing the arguments here? See the help [here](http://stats.stackexchange.com/help/how-to-answer) under "always provide context for links", in particular where it says "always quote the important part". It's not necessarily to literally quote it where the argument is extensive, but at least a summary of the argument is needed. You just make a couple of sweeping statements and then link to a paper. The statement that kurtosis *measures* tail behavior is (absent context) misleading (demonstrably so)
Comment: ... but it's impossible to disagree with arguments you don't present here, and perhaps arrive at a more nuanced conclusion.
Comment: My arguments are clearly laid out here: https://en.wikipedia.org/wiki/Talk:Kurtosis#Why_kurtosis_should_not_be_interpreted_as_.22peakedness.22   Comments welcome! BTW, kurtosis *IS* a measure of tail weight, just not the same as others that have been considered. It measures tail weight via E(Z^4), which is a measure of tail weight since the values |Z|<1 contribute so little to it. By the same logic, E(Z^n), for higher even powers n, are also tail weight measures.


Finding the missing entry in determinant

Question: We have,
$\begin{vmatrix}
a^2+2a & 2a+1 & 1 \\
2a+1 & x & 1\\
3 & 3 & 1
\end{vmatrix}=(a-1)^3$ I am asked to prove $x=a+2$ by using properties of determinants.
I've no idea how to solve it. Though tried to add or substract one column or row with others. No combinations had worked.
Answer: $$\begin{vmatrix}
a^2+2a & 2a+1 & 1 \\
2a+1 & x & 1\\
3 & 3 & 1
\end{vmatrix}\underbrace{=}_{C_1-3C_3, C_2-3C_3} \begin{vmatrix}
a^2+2a-3 & 2a-2 & 1 \\
2a-2 & x-3 & 1\\
0 & 0 & 1
\end{vmatrix}=\begin{vmatrix}
a^2+2a-3 & 2a-2 \\
2a-2 & x-3\\
\end{vmatrix}$$
$$=(x-3)(a^2+2a-3)-4(a-1)^2=(a-1)^3 \iff x-3=\frac{(a-1)^3+4(a-1)^2}{a^2+2a-3}=a-1,$$ from where $x=a+2.$
Comment: We could also apply the operation $R_1 - \frac 12 (a + 3)R_2$ followed by a row-switch in order to bring the original matrix to upper-triangular form.


apache2: apr_sockaddr_info_get() failed for

Question: After upgrade apache, restarting apache2 service give me that error
Starting web server: apache2AH00557: apache2: apr_sockaddr_info_get() failed for debian

What I did is:
Edit /etc/hosts file and add
127.0.0.1 debian

After that error disapear. Did I do all right?
Answer: ServerName should be set to a name that your server can resolve to an IP address. It is also good if your web servers clients can also resolve that address but not vital.
Your work around is acceptable as long as you are not using the name for name based virtual hosts or expecting apache to generate redirect url's.
The best solution is to have a real world DNS name that both you and people accessing the host can look up.


Looking for ways to create UML model from Java source

Question: What is the best way to document Java sources in UML? I know class diagrams, package diagrams and object diagram. What else should be documented? And is there any recommendation for a tool to support documentation?
Comment: I removed `relation diagram` from your question since there is no such diagram. Go for @xmojmr's answer. I guess GenMyModel is also worth a try.
Comment: I don't understand your question. "UML from java code" does mean what? Use Java to create UML (diagrams)?
Comment: sorry for my english, i want make diagrams from java code,
what any diagrams can i make from java code, i need guide reference for my work.
Comment: So you're trying to reverse engineer your Java code to get an UML model out of it?
Comment: oh thanks for revision.
yes, i think there is a best way.
Answer: Use an UML modeling tool with some kind of code reverse engineering support so that it can create some basic diagrams automatically from your existing code.
Creation of the rest requires manual work and some imagination and some thinking on your side. There's no magic tool. That would be your task/work/effort.
To find out what might the "UML beside classes..." browse through

uml-diagrams.org: UML Diagrams Examples
camunda.org: BPMN Examples, Patterns and Best Practises
Comment: no, i need make it manually, i want to know what any diagrams can i make from java code, and rules making for each of these diagram.
Comment: @uwong15 the `uml-diagrams.org` online book is probably the easiest `UML` book one can read and at the same time the most complete and up-to-date. To document your `Java` application, how does the code look ("structure diagrams") what does the code do ("behavior diagrams") and why ("use case diagram") **you can use all** of the available `UML` diagrams. For each diagram type the book contains examples, explaining chapter, drawing reference chapter and sometimes some discussion and historical background. After you know what's possible with pencil & paper, get a good `UML` modeling tool...
Comment: @newbie I can somehow imagine what kind of `Java` code is hidden behind this [class diagram example](http://www.uml-diagrams.org/java-7-concurrent-uml-class-diagram-example.html?context=cls-examples) and this [sequence diagram example](http://www.uml-diagrams.org/examples/spring-hibernate-transaction-sequence-diagram-example.html?context=seq-examples). Both were drawn using  "Microsoft Visio and UML 2.2 stencils" (not very rigorous/helpful `UML` tool). Pick an `UML` tool and read it's tutorials. It's probably the best I can advise you without seeing the real `*.java` code
Comment: @newbie in order to see how exactly should your manual result look like, you can use a tool like [ObjectAid UML Explorer for Eclipse](http://www.objectaid.com/), feed it with your `*.java` files, see what the tool draws and do the same (or similar) thing manually. There are about 20 [different types of  UML diagrams](http://www.uml-diagrams.org/uml-25-diagrams.html) and all of them can describe your real `*.java` code. Just start drawing and if you hit some concrete drawing obstacle related to some concrete piece of code then open another question
Comment: i have e-book in here [link](http://www.csd.uoc.gr/~hy252/references/UML_for_Java_Programmers-Book.pdf). i need more references to support my project please.
Comment: i not seem any examples that uml maked from java source, or may i cannot find it.
can u help me ???
Comment: @newbie which UML modeling tool do you use? Which Java IDE do you use? which OS do you use as your development platform?
Comment: i'm not using a tool, i want to make UML diagram manually. i wish i have complete tutorial how to make it.
Comment: very thanks for your help, it's little help for me.
but my part is to analyze real `*.java` and convert it to UML diagram manually.
sorry for my english.
Comment: @newbie I don't understand what kind of references or support you need for your project, neither what is your project about, how large etc. **I did start** with `UML` drawing for real by downloading evaluation version of `Sparx Systems Enterprise Architect`, loading my existing code into it using the [Source Code Reverse Engineering](http://www.sparxsystems.com/enterprise_architect_user_guide/12.0/software_engineering/reverseengineersourcecode.html) feature, reading it's tutorial example model and starting to draw something useful around my own code base. Then my employer purchased a license
Comment: so, i need examples java code, then create UML diagram from that codes.
Comment: @newbie yes, it is one way how to learn things practically. If you have some code already. In order to learn it from the other end, playing with trial version of the [Astah UML modeling tool](http://astah.net/) can be also  useful and their paper [Modeling in the Agile Age](http://cdn.astah.net/resources/modeling-in-the-agile-age.pdf) may explain a few things to you as the book you have linked above is some 12 years old. **start**-somehow-anyhow
Answer: From Java code, you can get the class diagram including relationships (relation diagram does not exist). Object diagram is for describing runtime instances.
If you have your Java code in a Git repository, you can get the corresponding UML model online using the GenMyModel reverse engineering feature (get started, documentation).


userscript - Add item to right-click menu

Question: I am writing a userscript for Greasemonkey and want to add an item to right click context menu. If I'm not mistaken, this function is called window.addEventListener("contextmenu", ...).
Can you give me example of this?
Comment: I'm not sure why an incorrect answer was voted up. The guy asking already said he's using GM, which is an extension with the ability to do this. It is not a new feature, but has been a staple of it's functionality for several years. Please see [here](http://stackoverflow.com/a/24145259/1307905) for an example of code with this functionality using GreaseMonkey
Comment: [**Related**](https://stackoverflow.com/questions/42800590/tampermonkey-right-click-menu) not sure if duplicate... What's your take, @Brock? . . . I can move my answer here.
Comment: @brasofilo, not a duplicate.  GM and TM are radically different in this respect.  ... Also, not sure if this question meets today's standards...
Answer: Following script was copied from http://userscripts-mirror.org/scripts/review/151097:

Important warning! This copy is unchanged and untested.  There might be security issues with userscripts.  GM is very powerful and if used on the wrong page the safety of your computer may be at risk.

/*
    Google Image Search Context Menu
    Add 'Search by Image' in browser context menu when you
    right click on image to search Google with that image.
    Copyright (C) 2012 LouCypher

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program. If not, see <http://www.gnu.org/licenses/>
*/

// ==UserScript==
// @name            Google Image Search Context Menu
// @namespace       http://userscripts.org/users/12
// @description     Add 'Search by Image' in browser context menu when you right click on image to search Google with that image.
// @version         1.2
// @author          LouCypher
// @license         GPL
// @resource        license https://raw.github.com/LouCypher/userscripts/master/licenses/GPL/LICENSE.txt
// @updateURL       https://userscripts.org/scripts/source/151097.meta.js
// @include         *
// @exclude         file://*
// @grant           GM_openInTab
// ==/UserScript==

if (!("contextMenu" in document.documentElement &&
      "HTMLMenuItemElement" in window)) return;

var body = document.body;
body.addEventListener("contextmenu", initMenu, false);

var menu = body.appendChild(document.createElement("menu"));
menu.outerHTML = '<menu id="userscript-search-by-image" type="context">\
                    <menuitem label="Search Google with this image"\
                              icon="data:image/png;base64,\
iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAABHNCSVQICAgIfAhkiAAAAAlwSFlz\
AAAK6wAACusBgosNWgAAABx0RVh0U29mdHdhcmUAQWRvYmUgRmlyZXdvcmtzIENTNXG14zYAAAEl\
SURBVDiNY/z//z8DJYCRkIKsthv/kRX9Z2BgmFalARdiIcaGKZXqcH5O+01U+ay2G3MYGBiSiXUm\
mofnsBDSjEUTMkiBe2Eq1JnZ7TcZBHhZGNythBl0lLkZODmYGX7++sdw/sZnhl3H3zF8+voHwwsY\
FkR5ijNICLMzTF31hOHnr38MHGxMDJlhMgwv3vxkWL7jJYpaJmzu0lTigWtmYGBg+PHrH8P0VU8Y\
tJV5MNRiNYCfmxmuGQZ+/PrHwMmOqRyrAX///WfgYEOV4mBjwjAUpwHHL31iyA6XgRvCwcbEkBUm\
w3DuxmcMtVgDkYONicHLVoTBSJOXgYONieHHz38Ml+98Ydh88DXDtx//CBtACmBiYGCYS4H+OYyU\
5kasgUgKAADN8WLFzlj9rgAAAABJRU5ErkJggg=="></menuitem>\
                  </menu>';

document.querySelector("#userscript-search-by-image menuitem")
        .addEventListener("click", searchImage, false);

function initMenu(aEvent) {
  // Executed when user right click on web page body
  // aEvent.target is the element you right click on
  var node = aEvent.target;
  var item = document.querySelector("#userscript-search-by-image menuitem");
  if (node.localName == "img") {
    body.setAttribute("contextmenu", "userscript-search-by-image");
    item.setAttribute("imageURL", node.src);
  } else {
    body.removeAttribute("contextmenu");
    item.removeAttribute("imageURL");
  }
}

function addParamsToForm(aForm, aKey, aValue) {
  var hiddenField = document.createElement("input");
  hiddenField.setAttribute("type", "hidden");
  hiddenField.setAttribute("name", aKey);
  hiddenField.setAttribute("value", aValue);
  aForm.appendChild(hiddenField);
}

function searchImage(aEvent) {
  // Executed when user click on menuitem
  // aEvent.target is the <menuitem> element
  var imageURL = aEvent.target.getAttribute("imageURL");
  if (imageURL.indexOf("data:") == 0) {
    var base64Offset = imageURL.indexOf(",");
    if (base64Offset != -1) {
      var inlineImage = imageURL.substring(base64Offset + 1)
                                 .replace(/\+/g, "-")
                                 .replace(/\//g, "_")
                                 .replace(/\./g, "=");

      var form = document.createElement("form");
      form.setAttribute("method", "POST");
      form.setAttribute("action", "//www.google.com/searchbyimage/upload");
      form.setAttribute("enctype", "multipart/form-data");
      form.setAttribute("target", "_blank");
      addParamsToForm(form, "image_content", inlineImage);
      addParamsToForm(form, "filename", "");
      addParamsToForm(form, "image_url", "");
      body.appendChild(form);
      form.submit();
    }
  } else {
    GM_openInTab("https://www.google.com/searchbyimage?image_url=" +
                 encodeURIComponent(imageURL));
  }
}

Comment: I've been using a userscript based on similar code but it has sadly stopped working since upgrading from Firefox ESR 78 to ESR 91, I believe because `menu` is no longer supported as per https://caniuse.com/menu
Answer: Unfortunately the <menu>+<menuitem> solution no longer works since Firefox 85 (and never worked in other browsers I believe) see here and here.
Below is an example of how to add an item to the right-click menu (tested in Tampermonkey & Firefox 91) although sadly it shows up under a 'Tampermonkey' sub-menu rather than as a top-level item in its own right.
The key part is @run-at context-menu
// ==UserScript==
// @name        Name of context menu item
// @include     *
// @version     0.1
// @grant       GM_openInTab
// @run-at      context-menu
// ==/UserScript==

(function() {
    'use strict';

    // If you want to do something based on the selected text
    var selectedText = window.getSelection().toString();

    // Construct your destination URL
    var url = ...

    // Open in new, foreground tab
    GM_openInTab(url, false);
})();


Pygame Mouse Event Position Issue

Question: I want to obtain coordinates of mouse position at the time when the mouse button is pressed. I'm using the following code to try to achieve that:
for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
        elif event.type == pygame.MOUSEBUTTONDOWN:
            mouse_pos = event.pos

My problem is when I move the mouse just after clicking, event.pos gives me the new cursor position instead of the coordinates of where I actually clicked. How do I set mouse_pos to the actual coordinates of the click?
Comment: If you use `mouse_pos = event.pos`, `mouse_pos` will contain the actual coordinates of the click. Maybe you overwrite it elsewhere in your code?
Comment: Is move mouse just after clicking different then dragging in your context
Comment: @udhy Yes, I release the mouse button and then move.
Comment: @sloth No, I didn't find it overwritten elsewhere in the code.
Comment: Try making a small program and run this code, does this still gives an error.
Answer: Although this thread was asked 4 months ago if your still looking for the answer here it is...
In your loop you are using the wrong command to get the mouse position. Instead of using this...
mouse_pos = event.pos

Use this...
mouse_pos = pygame.mouse.get_pos()

This command will grab the current mouse location when called, and return it as a tuple like this (x,y).
I hope this helps you with your issue.
Comment: `event.pos` is the mouse position.

Pygame Mouse Event Position Issue


How do i call an activity after a sms has been received by application?

Question: I am using BroadcastReceiver class for receiving the sms. My main class code is:
package org.apache.sms;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.SmsMessage;

public class SMSApp extends BroadcastReceiver
{
@Override
public void onReceive(Context context, Intent intent)
{
    //---get the SMS message passed in---
    Bundle bundle = intent.getExtras();
    SmsMessage[] msgs = null;
    String str = "";
    if (bundle != null)
    {
        //---retrieve the SMS message received---
        Object[] pdus = (Object[]) bundle.get("pdus");
        msgs = new SmsMessage[pdus.length];
        for (int i=0; i<msgs.length; i++){
            msgs[i] = SmsMessage.createFromPdu((byte[])pdus[i]);
            str += "SMS from " + msgs[i].getOriginatingAddress();
            str += " :";
            str += msgs[i].getMessageBody().toString();
            str += "\n";
        }
        //---display the new SMS message---
        Toast.makeText(context, str, Toast.LENGTH_SHORT).show();
        /*
        Intent i = new Intent(context,Second.class);
        i.putExtra("msg",str);
        i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(i);
        */

    }
    this.abortBroadcast();
}

}
manifest file is:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="org.apache.sms" android:versionCode="1"
android:versionName="1.0.0">
<uses-sdk android:minSdkVersion="8" />
<application android:icon="@drawable/icon" android:label="@string/app_name">
    <receiver android:name=".SMSApp">
        <intent-filter android:priority="100">
            <action android:name="android.provider.Telephony.SMS_RECEIVED" />
        </intent-filter>
    </receiver>

</application>
<uses-permission android:name="android.permission.RECEIVE_SMS">
</uses-permission>
</manifest>

Right now my application displays the message in a pop up.
But i want to display the second screen when my application receive the sms. For this i have added following code after Toast.makeText method :
 Intent i = new Intent(context,Second.class);
        i.putExtra("msg",str);
        i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(i);

After adding following code nothing is happening. No error only message comes in notification bar.
Comment: can u post your updated code?
Comment: thank saurabh for replying i have added my updated code
Answer: Maybe you should add 'Second' Activity in manifest file?
Comment: Thanks pixel & jn0101 it was due to the activity tag (second) that was missing in manifest file. Added
 tag and it resolved the issue.


onPlay (or onClick?) Trigger Full Screen Video on iPad

Question: Using the following HTML and JavaScript, I've been trying to trigger fullscreen video on the iPad. This works if there is only one video, but because there are numerous videos on the same page, only the first one works. I don't know how to separate out the videos so that they will all work properly. I've tried changing the IDs, and still, it doesn't work. Any advice would be greatly appreciated!
HTML:
<video id="test1" width="100%" height="200px" poster="http://www.example.com/wp-content/uploads/2013/12/example.png">
<source src="http://video.example.com/example.mp4" type="video/mp4">
</video>
<button id="test2">Play Video</button>

JavaScript:

Answer: Without looking at the page that contains multiple videos, it's hard to know for sure. But it sounds like you may be using the #test1 and #test2 IDs in your HTML more than once, in which case document.getElementById('test1') would only return the first matching element on the page. Check out the result of what's being console'd out here: http://jsfiddle.net/tjnicolaides/q7Pyh/
Try using document.getElementsByTagName or document.getElementsByClassName and looping through the results to add your event listeners to each video on the page. Here's an example: http://jsfiddle.net/tjnicolaides/NDYkU/
var videos = document.getElementsByTagName('video'),
    play_buttons = document.getElementsByClassName('play_button'),
    time;

for(var i=0; i< videos.length; i++) {
    // add event listeners and stuff here
}

for(var i=0; i < play_buttons.length; i++) {
    // add event listeners and stuff here
}


Como trabalhar com release no git?

Question: O recurso release do GitHub é um recurso da plataforma ou do próprio Git? Pergunto isso pois não vi este recurso no Bitbucket.
Comment: Não é a resposta para a sua pergunta, mas é uma leitura interessante sobre lançamentos de versão usando Git/Gitflow. Nesta resposta eu discorri um tanto sobre os recursos do Git mesmo para evolução da versão e da prática adotada onde trabalho: https://pt.stackoverflow.com/a/275914/64969
Comment: É da plataforma.
Answer: O recurso release é da plataforma, algo mais alto nível, mas conceitualmente ele se aplica no Git atráves da criação de tags, que são versões estáveis disponibilizadas para os usuários utilizarem. Dessa forma, o que o github chama de release nada mais é do que um recurso da plataforma para disponibilizar tags do Git.

Referências:
https://stackoverflow.com/questions/18506508/whats-the-difference-between-tag-and-release
Comment: Complementando, outras plataformas tem soluções semelhantes a essa do GitHub. No GitLab (e acho que no BitBucket também, mas faz muito tempo que não uso), existe uma seção de tags. Nela, você pode colocar uma espécie de notas de lançamento para cada tag individualmente. Tem uma função muito semelhante à release do GitHub, talvez apenas não tenha a disponibilidade de download de compilados.

Como trabalhar com release no git?


Troubleshooting linux server reboots?

Question: I have a Linux server I've just set up, debian squeeze, 2.6.32-5-amd64, and over the past week it's rebooted three times, twice in one day. There was no power outage that I am aware of (and it's running on a UPS), and there are no errors in syslog, besides a few to-be-expected ones on bootup to do with clearing out entries in the ext4 journal due to the unclean shutdown.
What steps can I take to determine the cause of the reboots? Is there a way to get it to hang instead of rebooting, so I can copy stack traces or something off the screen? Any way to increase debug messages, or get it to dump things to disk, or something?
Answer: That may be some hardware problem; the most common are failed RAM and overheating. You could install mbmon to monitor motherboard and CPU temperature; and runmemtest86+ to check your RAM and CPU cache.
Comment: mbmon gives "No Hardware Monitor found" but after upgrading my kernel, lm-sensors gives CPU core temperature now, which seems reasonable (average around 35 C, goes up to 55C if I run a benchmark on all cores). Will try memtest when I figure out how to run it on a remote server.
Comment: You can't run it directly on a remote server, but there's a linux equivalent you may run without rebooting (though it's not as thorough): memtester.
Answer: There is a chance it is a 'kernel panic' and a kernel 'oops' message is sent to the console before the reboot. The kernel can be configured to reboot on 'panic' or to stay on. Check:
cat /proc/sys/kernel/panic

If it is non-zero try putting 0 there (you can do it directly writting to the file, via /etc/sysctl.conf which is usually parsed on boot, or using the sysctl utility), this should stop rebooting. If it is already 0, then the reboots are not caused by kernel panics.
Comment: It's 0...so must be something else then. Thanks for the tip.
Answer: Check the output of last.  Look for reboot.  Try to correlate that with who was logged in if anyone and who has superuser privileges.  If it is not a user, you may have power/heat issues or some type of kernel panic causing issues.  Try to rule those out one by one.
Comment: Nobody else but me logging in (double checked the IP even from last). It's on an UPS, so I don't think it's a power issue, unless the server power supply is failing. I don't think it's heat issues, at least the server is not heavily loaded, and the current temperature is quite low (CPU at 36C), I'll start logging the temperature though.
Comment: Is there a way to get it to dump the kernel panic to disk or to screen? I'm worried that it's just rebooting and not saving the error messages anywhere. Is there a 'debug mode' or something I can enable?
Comment: A kernel panic is very unlikely - hardware trouble such as an overheating processor or memory errors is much more likely.
Comment: how to verify that? I have the same problem but I need to convince my provider that something is hardware? Too much reboot may be a software issue.

Troubleshooting linux server reboots?


Using views with a custom table/schema

Question: I need to set up some views that will pull some data from a custom table I created.  Some views will need to pull content the regular way and from my custom table (where I may query for a particular nid, etc.).
How do I do this, or where is a good place to research?
Comment: This article seems to be pretty on point: http://mydons.com/how-to-expose-custom-module-table-to-views-in-drupal/
Comment: That looks like it may be what I'm looking for.  Thanks!
Answer: Your module needs to implement hook_views_data().
The example given in the hook documentation is for a table defined from the following SQL.
CREATE TABLE example_table (
  nid INT(11) NOT NULL,
  plain_text_field VARCHAR(32,
  numeric_field INT(11),
  boolean_field INT(1),
  timestamp_field INT(8),
  PRIMARY KEY(nid)
);

function mymodule_views_data() {
  $data['example_table']['table']['group'] = t('Example table');

  $data['example_table']['table']['base'] = array(
    'field' => 'nid',
    'title' => t('Example table'),
    'help' => t('Example table contains example content and can be related to nodes.'),
    'weight' => -10,
  );

  $data['example_table']['table']['join'] = array(
    'node' => array(
      'left_field' => 'nid',
      'field' => 'nid',
    ),
  );

  $data['example_table']['nid'] = array(
    'title' => t('Example content'),
    'help' => t('Some example content that references a node.'),
    'relationship' => array(
      'base' => 'node',
      'base field' => 'nid', // The name of the field on the joined table.
      // 'field' => 'nid' -- see hook_views_data_alter(); not needed here.
      'handler' => 'views_handler_relationship',
      'label' => t('Example node'),
    ),
  );

  $data['example_table']['plain_text_field'] = array(
    'title' => t('Plain text field'),
    'help' => t('Just a plain text field.'),
    'field' => array(
      'handler' => 'views_handler_field',
      'click sortable' => TRUE,
    ),
    'sort' => array(
      'handler' => 'views_handler_sort',
    ),
    'filter' => array(
      'handler' => 'views_handler_filter_string',
    ),
    'argument' => array(
      'handler' => 'views_handler_argument_string',
    ),
  );

  $data['example_table']['numeric_field'] = array(
    'title' => t('Numeric field'),
    'help' => t('Just a numeric field.'),
    'field' => array(
      'handler' => 'views_handler_field_numeric',
      'click sortable' => TRUE,
    ),
    'filter' => array(
      'handler' => 'views_handler_filter_numeric',
    ),
    'sort' => array(
      'handler' => 'views_handler_sort',
    ),
  );

  $data['example_table']['boolean_field'] = array(
    'title' => t('Boolean field'),
    'help' => t('Just an on/off field.'),
    'field' => array(
      'handler' => 'views_handler_field_boolean',
      'click sortable' => TRUE,
    ),
    'filter' => array(
      'handler' => 'views_handler_filter_boolean_operator',
      'label' => t('Published'),
      'type' => 'yes-no',
      'use equal' => TRUE,
    ),
    'sort' => array(
      'handler' => 'views_handler_sort',
    ),
  );

  $data['example_table']['timestamp_field'] = array(
    'title' => t('Timestamp field'),
    'help' => t('Just a timestamp field.'),
    'field' => array(
      'handler' => 'views_handler_field_date',
      'click sortable' => TRUE,
    ),
    'sort' => array(
      'handler' => 'views_handler_sort_date',
    ),
    'filter' => array(
      'handler' => 'views_handler_filter_date',
    ),
  );

  return $data;
}

Comment: This has been an excellent help. However, one of my fields is multivalue, and so I think it must be set up differently -- but how?
Comment: The difference is in the handlers you need to use, and what you use instead of "yes-no"; I cannot tell you which handlers are for a multi-value field, though. Probably it is better as question, if nobody asked it already.
Answer: I think it would probably be worth investigating the Data module. This is very powerful, since it allows you to declare a non-Drupal table to Drupal such that it becomes visible in Views as a data source (like "Content", "Taxonomy", etc). You can also declare joins between the non-Drupal table and Drupal entities (so for example if you can stock a nid in your non-Drupal table, then you can declare a join on the nid with any node).
There is also a submodule which allows you to declare your non-Drupal table as an entity, but so far I've not tried that.

Using views with a custom table/schema


Can't set @model to class in dynamic loaded dll

Question: I'm working on a MVC project where we dynamically load dll's. In these dll's are other MVC projects (we call them modules). We do this so we can support a plug-and-play for the modules, update them without publishing the whole project.
We have multiple simple modules that work, now I'm facing a problem with a new module I'm developing.
In all the view of the module we define the model like @model dynamic. But because I want to use @Html.TextBoxFor() that´s not allowed else it results in

An expression tree may not contain a dynamic operation

So I thought, no problem I'll just change to @model ModuleNameSpace.ClassName But now the whole view can´t be loaded anymore... exception says:

The view found at '~/PATH_TO_VIEW_FILE' was not created.

With @model dynamic the view is working and when I create a seperate project it's also working with @model ModuleNameSpace.ClassName. So it seems to be a problem because we add the assembly dynamical?
Modules are loaded like this:
System.Reflection.AssemblyName name = System.Reflection.AssemblyName.GetAssemblyName(module.FullName);
            System.Reflection.Assembly assembly = System.Reflection.Assembly.Load(name);

Answer: I've found a solution to my problem. The problem was that the model didn't find the class in the assembly. I don't know exactly why but I've found a way to solve it.
You're able to set a function for the case an assembly is not found. Because I trust the source and this is an internal application I can set full trust in the web config. In the resolve method I point to the dll's where the module is in and then the class is found and it works!
Global.asax:
 protected void Application_Start()
  {
             AppDomain currentDomain = AppDomain.CurrentDomain;

             currentDomain.AssemblyResolve += new ResolveEventHandler(CurrentDomain_AssemblyResolve);

 }

 static Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs args)
 {
             var pluginsFolder = GetPluginFolder()
         return (from f in pluginsFolder.GetFiles("*.dll", SearchOption.AllDirectories)
                     let assemblyName = AssemblyName.GetAssemblyName(f.FullName)
                     where assemblyName.FullName == args.Name || assemblyName.FullName.Split(',')[0] == args.Name
                     select Assembly.LoadFile(f.FullName)).FirstOrDefault();
 }

Thanks to shawazza


How to make a sequence element-wise clustering with a RNN (preferable in Keras)

Question: Non-Keras contributions are also welcome since the question is very concrete already.
Imagine I have a sequence $S_i = s_0, s_1, ..., s_n$, where $s_k$ is the k-th element that represents an element of the sequence $S_i$. Now I want to cluster these sequence elements if they are "similar" (this similitude will be trained with training data).
Here is the structure of a training sample $x_i$ with len=6:
$x_i = s_0, s_1, s_2, s_3, s_4, s_5$
$y_i = y_0, y_1, y_2, y_3, y_4, y_5$
Where $s_k$ are vectors (300 dimensional vectors of Real values) and $y_i$ is the cluster where that vector pertains (e.g. 1).
Here is a possible example of the labels for this sample:
$y_i = 0, 0, 1, 0, 1, 2$
Meaning that:

The elements 0, 1 and 3 of the sequence are related (therefore put in the same cluster)
Elements 2 and 4 are also related, and
Element 5 is put alone in another cluster.

I have 3 questions:

How would this prediction be represented? As far as I know, I should return_sequences=True in the LSTM layer so for each input sequence, I have an output sequence, but I do not know what should I do with that output.
What would my loss function be like? I guess it would be some kind of clustering metric like V-Measure Score, that gives an error wrt an input label of clusters, but I am not sure what would be the approach to implement a loss like this.
What would the final layer of my network be like? Since given a sequence element, my prediction would have to be either to put the sequence element in a new cluster or some cluster where a prior sequence element has been put into, I am not sure how to model this.

Thanks in advance.
Answer: I have found that this problem can simply be solved by encoding the input properly and targeting the correspondent sequences (also properly encoded).
Answering my own three questions:
First of all, this is not a clustering problem since we have the labels for each sequence element. This is a supervised sequence labelling problem.

How would this prediction be represented? As far as I know, I should
  return_sequences=True in the LSTM layer so for each input sequence, I
  have an output sequence, but I do not know what should I do with that
  output.

Since you want to classify each sequence element, you should add a TimeDistributed Dense layer in order to make that Dense layer give a different output for each timestep. If the activation of that dense is the softmax function, then you have set up your network properly for a sequence labelling problem.

What would my loss function be like? I guess it would be some kind of
  clustering metric like V-Measure Score, that gives an error wrt an
  input label of clusters, but I am not sure what would be the approach
  to implement a loss like this.

V-Measure is to compare different clustering results of data and say how similar they are. Since here you are using it only to see if your model fits well, your inputs to the V-Measure would be (y_true, y_pred). Instead of doing that, your loss function can perfectly be the categorical crossentropy between your y_true and your y_pred, since you have the labels.

What would the final layer of my network be like? Since given a
  sequence element, my prediction would have to be either to put the
  sequence element in a new cluster or some cluster where a prior
  sequence element has been put into, I am not sure how to model this.

The output would be the TimeDistributed Dense with softmax activation we have seen before. The network itself will have learned if the input element should be put in a different class or not depending on the problem it has been trained to solve.
Here is a full example that solves my problem:
import keras
import random

letters = 'abc'

w_len = len(letters)

seq_len = 15
num_seqs = 1000

seqs = []

for i in range(num_seqs):
    s = ''
    for j in range(seq_len):
        s += random.choice(letters)
    seqs.append(s)

from keras.preprocessing.text import Tokenizer
tokenizer = Tokenizer(char_level=True, oov_token=None)
tokenizer.fit_on_texts(seqs)
seqs_keras = tokenizer.texts_to_sequences(seqs)

from keras import backend as K
import tensorflow as tf
with tf.Session() as sess:
    seqs_keras_oh = K.one_hot(seqs_keras, w_len+1).eval()

def label_sample(x):
    y = []
    seen_idx = 0
    d = {}
    for i in range(len(x)):
        if (x[i] not in d):
        d[x[i]] = seen_idx
        seen_idx += 1

        y.append(d[x[i]])

    return y

y = [label_sample(x) for x in seqs_keras]

with tf.Session() as sess:
    y_oh = K.one_hot(y, w_len+1).eval()

from keras.layers import LSTM, Input, TimeDistributed, Dense
from keras.models import Model

encoded_length = seqs_keras_oh.shape[2]

l_in = Input(shape=(seq_len, w_len+1))
l_lstm = LSTM(16, return_sequences=True)(l_in)
l_out = TimeDistributed(Dense(encoded_length, activation='softmax'))(l_lstm)

model = Model(inputs=l_in, outputs=l_out)

model.compile(
        optimizer='rmsprop',
        loss='categorical_crossentropy',
        metrics=['accuracy']
    )

model.fit(x=seqs_keras_oh, y=y_oh, batch_size=8, epochs=1000, validation_split=0.2)

After some epochs:
800/800 [==============================] - 1s 1ms/step - loss: 0.0195 - acc: 0.9988 - val_loss: 0.0180 - val_acc: 1.0000
Epoch 71/1000

Comment: @whuber I have edited my own answer and added the answers to the questions.
Comment: You asked three questions: could you explain how this post responds to them?


hook_libraries_info() doesn't work

Question: I have a custom almost empty module where I'm tring to insert a js file using hook_libraries_info(). But when I load the home I don't see my script inserted. It works when I use a simple drupal_add_js.
What I'm doing wrong? I've seen other examples like masonry and nivo-slider and those are similar. Do I need to init somehow? I'm new at module development, so probably is something simple.
DETAILS
Libraries module is enabled:
-  Libraries    7.x-2.1
The location of the library folder is this:
- sites/all/libraries/test/test.js
test.module
<?php
//drupal_add_js('sites/all/libraries/test/test.js'); when uncommented it works

/**
 * Implements hook_libraries_info().
 */
function test_libraries_info() {  // it never works
  $libraries['test'] = array(
    'name' => 'Test',
    'vendor url' => 'http://www.example.com/',
    'download url' => 'http://www.example.com/',
    'files' => array(
      'js' => array(
        'test.js',
      ),
    ),

  );
  return $libraries;
}

Answer: hook_libraries_info(), documented in libraries.api.php, is just a hook that informs the Libraries API module of any existing external library. Its purpose is not loading those libraries when a Drupal page is shown; for that, the module needs to call libraries_load() (defined in libraries.module) when necessary.
libraries_load_files() is the function that actually load in the page the CSS and Javascript files, respectively with drupal_add_css() and drupal_add_js().
  // Load both the JavaScript and the CSS files.
  // The parameters for drupal_add_js() and drupal_add_css() require special
  // handling.
  // @see drupal_process_attached()
  foreach (array('js', 'css') as $type) {
    if (!empty($library['files'][$type])) {
      foreach ($library['files'][$type] as $data => $options) {
        // If the value is not an array, it's a filename and passed as first
        // (and only) argument.
        if (!is_array($options)) {
          $data = $options;
          $options = array();
        }
        // In some cases, the first parameter ($data) is an array. Arrays can't
        // be passed as keys in PHP, so we have to get $data from the value
        // array.
        if (is_numeric($data)) {
          $data = $options['data'];
          unset($options['data']);
        }
        // Prepend the library path to the file name.
        $data = "$path/$data";
        // Apply the default group if the group isn't explicitly given.
        if (!isset($options['group'])) {
          $options['group'] = ($type == 'js') ? JS_DEFAULT : CSS_DEFAULT;
        }
        call_user_func('drupal_add_' . $type, $data, $options);
        $count++;
      }
    }
  }

Answer: You are missing the version part which is necessary:
version arguments' => array(
      'file' => 'readme.txt',
      // Best practice: Document the actual version strings for later reference.
      // 1.x: Version 1.0
      'pattern' => '/Version (\d+)/',
      'lines' => 5,
    ),

http://drupalcontrib.org/api/drupal/contributions!libraries!libraries.api.php/function/hook_libraries_info/7
Comment: The link the dead

hook_libraries_info() doesn't work


A simple infinite limit question with logs

Question: $$f(n)= 3n \log\log n$$
and   $$g(n)=n (\log n)^6 + 8n^2$$ and I try to find
$$\lim_{n \rightarrow \infty} \frac{f(n)}{g(n)}$$
Comment: You mean $f(n)=3n\log\log n$ and $g(n)=n(\log n)^6 + 8n^2$?
Comment: @MPW Yes, I don't know how to write this porerly. Sorry about that.
Comment: No problem, just specifically wondered if the 6 was iteration or exponent.
Answer: Hint:
$$\frac{n\log\log n}{n\log^6n+8n^2}\le\frac{n\log n}{8n^2}\le\frac{1}{n^{1/2}}$$
Comment: Thank you firstly. Then can we say it goes to 0 ?
Comment: @EminÇiftçi Indeed, using for example the squeeze theorem.
Comment: Oh, okey I see now clearly. Thank you again.
Answer: Well, $g(n)\sim_\infty 8n^2$, hence
$$\frac{f(n)}{g(n)}\sim_\infty\frac{3n \log\log n}{8n^2}=\frac38\frac{\log\log n}{n}\to 0,$$
 as $\log\log n\in o(\log n)\in o(n)$.


Isomorphism of two field extensions

Question: Let $\alpha$ and $\beta$ be algebraic elements of an extension $L$ of $K$. Is it always true that if they have the same minimum polyomial then $K(\alpha)$ is isomorphic to $K(\beta)$?
I think it is true, it follows pretty much straightforward out of the definition of miminum polynomial. My question is: are there exceptions? If not, how can you prove it?
And also: does it work the other way round, meaning if two extensions are isomorphic then they  always contain such a minimum polynomial?
Answer: Hint (not really a hint as it pretty much gives you the answer): If $f(x)$ is the minimum polynomial of $\alpha, \beta$ then both $K(\alpha), K(\beta)$ are isomorphic to $K[x]/(f(x))$.
If your isomorphism fixes $K$ (i.e. acts as identity on $K$) then they have the same minimal polynomial.
Comment: Cheers, now that I see it it is very clear.
Answer: The last part of the question is not clear. First, extensions do not contain polynomials. Second, if you are asking, given that $K(\alpha)$ and $K(\beta)$ are isomorphic as extensions of $K$, is it true that $\alpha$ and $\beta$ have the same minimum polynomial, then certainly the answer is no. E.g., ${\bf Q}(\root4\of2)$ and ${\bf Q}(i\root4\of2+17)$ are isomorphic extensions of the rationals, but $\root4\of2$ and $i\root4\of2+17$ don't have the same minimum polynomial. But perhaps what you are asking is, given that $K(\alpha)$ and $K(\beta)$ are isomorphic as extensions of $K$, is there an element $\gamma$ such that $K(\beta)=K(\gamma)$ and $\alpha$ and $\gamma$ have the same minimum polynomial, then Rankeya's answer applies; take $\gamma$ to be the image of $\alpha$ under the isomorphism.

Isomorphism of two field extensions


How to enable MySQL logging?

Question: I am running MySQL 5.0.45 on OS X 10.6.1 and I cannot get MySQL to log anything. I am debugging an application and need to see all queries and errors.
I added to the etc/my.cnf:
[mysqld]
bind-address = 127.0.0.1
log = /var/log/mysqld.log
log-error = /var/log/mysqld.error.log

I used sudo to create two log files, set permissions to 644, then restarted MySQL.
I referred to Where is my mysql log on OS X? in order to troubleshoot.
Running:
ps auxww|grep [m]ysqld

Returns:
_mysql      71   0.0  0.8   646996  15996   ??  S     7:31PM   0:01.10 /usr/local/mysql/libexec/mysqld --basedir=/usr/local/mysql --datadir=/usr/local/mysql/var --pid-file=/usr/local/mysql/var/Macintosh-41.local.pid
_mysql      46   0.0  0.0   600336    744   ??  Ss    7:30PM   0:00.03 /bin/sh /usr/local/mysql/bin/mysqld_safe

And running:
$(ps auxww|sed -n '/sed -n/d;/mysqld /{s/.* \([^ ]*mysqld\) .*/\1/;p;}') --verbose --help|grep '^log'

Returns:
log                               /var/log/mysqld.log
log-bin                           (No default value)
log-bin-index                     (No default value)
log-bin-trust-function-creators   FALSE
log-bin-trust-routine-creators    FALSE
log-error                         /var/log/mysqld.error.log
log-isam                          myisam.log
log-queries-not-using-indexes     FALSE
log-short-format                  FALSE
log-slave-updates                 FALSE
log-slow-admin-statements         FALSE
log-slow-queries                  (No default value)
log-tc                            tc.log
log-tc-size                       24576
log-update                        (No default value)
log-warnings                      1

Running:
mysql> show variables like '%log%';

Returns:
+---------------------------------+---------------------------+
| Variable_name                   | Value                     |
+---------------------------------+---------------------------+
| back_log                        | 50                        |
| binlog_cache_size               | 32768                     |
| expire_logs_days                | 0                         |
| innodb_flush_log_at_trx_commit  | 1                         |
| innodb_locks_unsafe_for_binlog  | OFF                       |
| innodb_log_arch_dir             |                           |
| innodb_log_archive              | OFF                       |
| innodb_log_buffer_size          | 1048576                   |
| innodb_log_file_size            | 5242880                   |
| innodb_log_files_in_group       | 2                         |
| innodb_log_group_home_dir       | ./                        |
| innodb_mirrored_log_groups      | 1                         |
| log                             | ON                        |
| log_bin                         | OFF                       |
| log_bin_trust_function_creators | OFF                       |
| log_error                       | /var/log/mysqld.error.log |
| log_queries_not_using_indexes   | OFF                       |
| log_slave_updates               | OFF                       |
| log_slow_queries                | OFF                       |
| log_warnings                    | 1                         |
| max_binlog_cache_size           | 4294967295                |
| max_binlog_size                 | 1073741824                |
| max_relay_log_size              | 0                         |
| relay_log_purge                 | ON                        |
| relay_log_space_limit           | 0                         |
| sync_binlog                     | 0                         |
+---------------------------------+---------------------------+
26 rows in set (0.00 sec)

Any help on how I can get MySQL to log?
Answer: Even though you used chmod 644, make sure mysql is the owner of the logs.
touch /var/log/mysql.log
chown mysql:mysql /var/log/mysql.log
touch /var/log/mysql.error.log
chown mysql:mysql /var/log/mysql.error.log

Next, restart mysqld.
Then, log into mysql and run:
mysql> show variables like '%log%';

Look at the values for general_log, general_log_file, log, log_error, etc.
Switch them on as needed and run mysqladmin flushlogs as needed.
Comment: Now logging. Must have been the ownership oversight. Although, see my edited question for results of "show variables like '%log%'" query. MySQL is logging to /var/log/mysql.log, so why doesn't it show?
Answer: To enable the log files, you need to make sure that one or more of the following directives are in the [mysqld] section of your mysql server's main configuration file (/etc/my.cnf on mine):
[mysqld]
log-bin
log
log-error
log-slow-queries

The logs will be created, by default, in the same data directory that holds the database subdirectories themselves (typically /var/lib/mysql) and the log file names default to the hostname  followed by a suffix that matches the directive names above (eg. -bin, -slow-queries, etc).
To keep your logs in a different path, or using different filenames, specify the base name following the log= directive, and any path and filename you like e.g.:
[mysqld]
log-bin=/var/log/mysql-bin.log
general-log=/var/log/mysql.log
log-error=/var/log/mysql-error.log
slow-query-log=/var/log/mysql-slowquery.log

You need to restart mysqld for these changes to take effect.
Comment: Great answer, but `log` and `log-slow-queries` are deprecated. Use [`general-log`](https://dev.mysql.com/doc/refman/8.0/en/query-log.html) and [`slow-query-log`](https://dev.mysql.com/doc/refman/8.0/en/slow-query-log.html) instead.
Answer: The previous answers were out dated. You can look the configuration file in /etc/my.cnf or on windows ./mysql/my.ini.
In the [mysqld] section add
log_bin
general_log
log_error

The documentation for windows states that the logs get stored in ProgramData/MySQL/MySQL Server 5.6/. Ignore it because it's a lie.
In addition the recommended log option is depreciated and results in the error
ambiguous option '--log' (log-bin, log_slave_updates)

being logged in ./mysql/data/host.err and the daemon silently dying. The correct setting is general-log.
Also log-slow-queries is not valid and caused the error
C:\mysql\bin\mysqld.exe: unknown option '--log-slow-queries'

So be certain to stay away from that also.
Comment: Thank you! I could not start the server with the `log=` option and could for the life of me figure out why.  Finally someone with an answer. `general-log`
Comment: `log-slow-queries` has been deprecated. [Use `slow-query-log`](https://dev.mysql.com/doc/refman/8.0/en/slow-query-log.html) instead.
Answer: Try different log settings in my.cnf. In my case I needed:
general_log = on

general_log_file=/var/log/mysql/mysql.log

Comment: I also needed this instruction for WAMP, where I used

`general_log = on`
`general-log-file="c:/wamp/logs/mysql_general.log"`
Answer: Enter mysql command line with super privileges and perform:

SET GLOBAL general_log_file = '/var/log/mysql/mysql.log';

In my case, it didn't matter if I had this variable already set with the same value! Also, I changed the permissions and the owner of the file as mentioned in the other posts.
Answer: edit my.conf

general_log=1
log_error=/var/logs/mysql/error.log
general_log_file=/var/logs/mysql/mysql.log

How to enable MySQL logging?


drag and drop system overlapping dropped divs element

Question: try dropping the grey boxes inside any column if you drop too many inside on column, the boxes will end up overlapping with eachother. How can I do a validation to stop this from happening? I want each box to be underneath eachother with a X px gap from eachother.
Below is not the entire code for those boxes. if you would like to see the full source code please use the website.

function dragInfo(event) {
    event.dataTransfer.setData("Info", event.target.id);
}

function allowDrop(event) {
    event.preventDefault();
}

function drop(event) {
    event.preventDefault();
    var data = event.dataTransfer.getData("Info");
    event.target.appendChild(document.getElementById(data));
    console.log(data);
}

function drag_drop(event) {
    event.preventDefault();
}
.columnContent {
    padding-top: 5px;
    width: 129px;
    height: auto;
    text-align: center;
    margin: 3px;
    border-radius: 20px;
    flex-direction: column;
}

.dropBox {
    display: inline-block;
    position: relative;
    height: 140px;
    width: 120px;
    border: 2px dashed;
    background-color: lightgray;
    cursor: move;
    box-sizing: border-box;
    z-index: 1;
}

Customer's order

Drag file here

                <p1 id="pdfInfo"></p1>

            <input id="txt1" placeholder="Customer's code" style="visibility: hidden">

            <input id="txt2" placeholder="Customer's size" style="visibility: hidden">

            <input id="txt3" placeholder="Customer's DD" style="visibility: hidden">

            <button id="btn" style="visibility: hidden">Save</button>

Planned

Answer: I changed the HTML code to this:

Planned

Passing this as the second parameter to the drop function.
Then change the JavaScript to the following:
function drop(event, el) {
    event.preventDefault();
    var data = event.dataTransfer.getData("Info");
    el.appendChild(document.getElementById(data));
    console.log(data);
}

Adding the option for an element as the second parameter. Then use the passed element as the element to be appended.

Full snippet below

function dragInfo(event) {
    event.dataTransfer.setData("Info", event.target.id);
}

function allowDrop(event) {
    event.preventDefault();
}

function drop(event, el) {
    event.preventDefault();
    var data = event.dataTransfer.getData("Info");
    el.appendChild(document.getElementById(data));
    console.log(data);
}

function drag_drop(event) {
    event.preventDefault();
}
.columnContent {
    padding-top: 5px;
    width: 129px;
    height: auto;
    text-align: center;
    margin: 3px;
    border-radius: 20px;
    flex-direction: column;
}

.dropBox {
    display: inline-block;
    position: relative;
    height: 140px;
    width: 120px;
    border: 2px dashed;
    background-color: lightgray;
    cursor: move;
    box-sizing: border-box;
    z-index: 1;
}

Customer's order

Drag file here

                <p1 id="pdfInfo"></p1>

            <input id="txt1" placeholder="Customer's code" style="visibility: hidden">

            <input id="txt2" placeholder="Customer's size" style="visibility: hidden">

            <input id="txt3" placeholder="Customer's DD" style="visibility: hidden">

            <button id="btn" style="visibility: hidden">Save</button>

Planned

Comment: Thank you that did fix the problem!
Comment: what is "this" passing?
Comment: you need to pass the current scope, for that u need to pass 'this'
Comment: Im getting a new error now which I think its involving passing the parameter this. dropping many boxes to the column will eventually cause one of the column to transform into dragable child. Have a look! http://2much.online/ drop several boxes around and you shall get an error where you can drag and drop one of the columns as you try to drag the box the column will come with it.


$\int_0^\tau5\cos^4(\theta)+3\cos^2(\theta)+1\mathrm{d}\theta$

Question: Problem:

$$\int_0^{\tau}\sqrt2\cos^4(\theta)+3\cos^2(\theta)+7\mathrm{d}\theta\quad$$

Current strategy:

Replace $\cos^{2}(\theta)$ with $\frac{1}{2}\left(1+\cos(2\theta)\right)$
$$\begin{align}\int_0^\tau\sqrt2\frac{1}{2}&\left(1+\cos(2\theta)\right)^2(\theta)+3\frac{1}{2}\left(1+\cos(2\theta)\right)+7\mathrm{d}\theta =\\&=
\int_0^\tau\sqrt2\frac{1}{2}\left(1+2\cos(\theta)+\cos^2(\theta)\right)+3\frac{1}{2}\left(1+\cos(2\theta)\right)+7\mathrm{d}\theta\\&=
\int_0^\tau\sqrt2\frac{1}{2}\left(1+2\cos(\theta)+\frac{1}{2}\left(1+\cos(4\theta)\right)\right)+3\frac{1}{2}\left(1+\cos(2\theta)\right)+7\mathrm{d}\theta \end{align}$$
  Is there a better strategy?
Comment: You can also use $\cos(x)^4=\cos(x)^2(1-\sin(x)^2)=\cos(x)^2-\cos(x)^2\sin(x)^2$. Then use $1/2\sin(2x)=\cos(x)\sin(x)$
Comment: use eulers identity/formula to replace trig functions by exponentials.
Answer: These integrals may be dispatched rapidly if you use average values. If we let $\langle f(x)\rangle$ denote the average value of $f(x)$, then since they only differ in phase, $$\langle\cos^2\theta\rangle=\langle\sin^2\theta\rangle=\frac{\langle\cos^2\theta\rangle+\langle\sin^2\theta\rangle}2=\frac{\langle\cos^2\theta+\sin^2\theta\rangle}2=\frac{\langle1\rangle}2=\frac12$$
We may use @MrYouMath's hint above to arrive at
$$\begin{align}\langle\cos^4\theta\rangle & =\langle\cos^2\theta(1-\sin^2\theta)\rangle=\langle\cos^2\theta-\frac14\sin^22\theta\rangle\\
 & =\langle\cos^2\theta\rangle-\frac14\langle\sin^22\theta\rangle=\frac12-\frac14\cdot\frac12=\frac38\end{align}$$
Then over an integral number of periods, the trig functions take on their average values, so we can use
$$\int_a^bf(x)dx=(b-a)\langle f(x)\rangle$$
So the beauty of it is
$$\begin{align}\int_0^{2\pi}\left(\sqrt2\cos^4\theta+3\cos^2\theta+7\right)d\theta & =2\pi\left(\sqrt2\langle\cos^4\theta\rangle+3\langle\cos^2\theta\rangle+7\langle1\rangle\right)\\
 & =2\pi\left(\sqrt2\cdot\frac38+3\cdot\frac12+7\cdot1\right)\\
 & =\frac{\pi}4(68+3\sqrt2)\end{align}$$
Just like that!
Comment: Indeed, why not use that one integrates over a period to simplify everything... +1.
Answer: use that $$\cos(x)^4=\frac{1}{8} (4 \cos (2 x)+\cos (4 x)+3)$$
and
$$\cos(x)^2=\frac{1}{2} (\cos (2 x)+1)$$
Answer: HINT:
$$\int_0^{2\pi}\left(\sqrt{2}\cos^4(\theta)+3\cos^2(\theta)+7\right)\space\text{d}\theta=$$
$$\sqrt{2}\int_0^{2\pi}\cos^4(\theta)\space\text{d}\theta+3\int_0^{2\pi}\cos^2(\theta)\space\text{d}\theta+7\int_0^{2\pi}1\space\text{d}\theta=$$
$$\sqrt{2}\int_0^{2\pi}\cos^4(\theta)\space\text{d}\theta+3\int_0^{2\pi}\cos^2(\theta)\space\text{d}\theta+7\left[\theta\right]_{0}^{2\pi}=$$

Use:
$$\cos^2(x)=\frac{1}{2}+\frac{\cos(2x)}{2}$$

$$\sqrt{2}\int_0^{2\pi}\cos^4(\theta)\space\text{d}\theta+3\int_0^{2\pi}\left[\frac{1}{2}+\frac{\cos(2x)}{2}\right]\space\text{d}\theta+7\left[\theta\right]_{0}^{2\pi}=$$
$$\sqrt{2}\int_0^{2\pi}\cos^4(\theta)\space\text{d}\theta+3\left[\frac{1}{2}\int_0^{2\pi}1\space\text{d}\theta+\frac{1}{2}\int_0^{2\pi}\cos(2x)\space\text{d}\theta\right]+7\left[\theta\right]_{0}^{2\pi}=$$
$$\sqrt{2}\int_0^{2\pi}\cos^4(\theta)\space\text{d}\theta+3\left[\frac{1}{2}\left[\theta\right]_{0}^{2\pi}+\frac{1}{2}\int_0^{2\pi}\cos(2x)\space\text{d}\theta\right]+7\left[\theta\right]_{0}^{2\pi}=$$

Substitute $u=2\theta$ and $\text{d}u=2\space\text{d}\theta$.
This gives a new lower bound $u=2\cdot0=0$ and upper bound $u=2\cdot2\pi=4\pi$:

$$\sqrt{2}\int_0^{2\pi}\cos^4(\theta)\space\text{d}\theta+3\left[\frac{1}{2}\left[\theta\right]_{0}^{2\pi}+\frac{1}{4}\int_0^{4\pi}\cos(u)\space\text{d}u\right]+7\left[\theta\right]_{0}^{2\pi}=$$
$$\sqrt{2}\int_0^{2\pi}\cos^4(\theta)\space\text{d}\theta+3\left[\frac{1}{2}\left[\theta\right]_{0}^{2\pi}+\frac{1}{4}\left[\sin(u)\right]_{0}^{4\pi}\right]+7\left[\theta\right]_{0}^{2\pi}=$$

For $\cos^4(\theta)$ use the reduction formula:
$$\int\cos^m(x)\space\text{d}x=\frac{\sin(x)\cos^{m-1}(x)}{m}+\frac{m-1}{m}\int\cos^{m-2}(x)\space\text{d}x$$

$$\sqrt{2}\int_0^{2\pi}\cos^4(\theta)\space\text{d}\theta+17\pi$$


Set read status for a group chat using Firebase

Question: I am trying to make a chat application containing individual chat between users and group chat using Firebase. And I would like to make a read status for each message, Now the problem is, consider a group chat have a node
> groupId---->
>         --->messageId
>                  -->userId
>                  -->messageType
>                  -->text

My implimentation is like if a user sending a message to a group that will be added under group id with message id node and who are all listening to the group will get that child message now I want to keep a status for who are all read the message. I can handle it by keeping a local status, But if the user logging from another device how can I handle that?
Comment: You have to make a boolean under messageID Node, that keeps the record of Read status
Comment: If group having more members its not possible right?
Comment: I am also implementing the same functionality in my app. I have implemented single user chat but i am facing issues in group chat. Could you sent me the database schema of your app?
Answer: If you want to track whether a user had read each message, you'll need to store that in your database:
read_messages_per_user
  <userId>
    <messageId>: true

This may become a lot of data over time. So a more efficient (but less specific) variant is to store the last message that the user read.
last_read_messageId_per_user
  <userId>: <messageId>


Computing KL divergence between uniform and multivariate Gaussian

Question: Another post has addressed the fact that KL divergence is defined between a uniform distribution and a Gaussian distribution $$D_{\text{KL}}(\mathcal{U}(x) \parallel \mathcal{N}(x \mid \mu, \Sigma)) = \int \mathcal{U}(x) \log\frac{\mathcal{U}(x)}{\mathcal{N}(x \mid \mu, \Sigma)} dx$$
essentially because the Gaussian in the denominator has infinite support, and so will have non-zero density over the support of the uniform distribution - we don't have any numerical problems in theory. This post provides a closed-form solution for computing the KL divergence between two multivariate Gaussians. I am hoping to find a similar solution for the case I describe above, between a uniform and a multivariate Gaussian.
Does a closed-form solution exist for arbitrary dimensions? If not that, what about in the 2-D case? If none of the above, how would I go about estimating this quantity aside from a pure sampling-based approximation?
Answer: It depends what the support of the uniform distribution looks like. But if you assume that it is supported on an axis-aligned rectangle $[a,b]\times [c,d]$ then it works out simply. Letting $u={\frac 1 {(b-a)(d-c)}}$, we have
\begin{eqnarray*}
&&\int_{[a,b]\times [c,d]} u\left(\log(u)+{\frac 1 2}(x-\mu)^tC^{-1}(x-\mu)+{\frac 1 2}\log |C|+{\frac {1} {2}}\log 2\pi\right)dx\\
& = &\log(u)+{\frac 1 2}\log |C|+{\frac {1} {2}}\log 2\pi+{\frac 1 2}u\int_{[a,b]\times [c,d]}(x-\mu)^tC^{-1}(x-\mu)dx
\end{eqnarray*}
Now, for simplicitly I'll take $\mu=0$ (although this is actually no loss of generality, because you can compensate for this by translating the bounds of the rectangle). Let $C^{-1}_{ij}$ denote the entries of $C^{-1}$. Tye integral is
\begin{eqnarray*}
&&\int_{[a,b]\times [c,d]}x_1^2C^{-1}_{11}+2x_1x_2C^{-1}_{12}+x_2^2C^{-1}_{22}dx_1dx_2\\
& = & \int_{c}^d {\frac {x_1^3C^{-1}_{11}}{3}}+x_1^2x_2C^{-1}_{12}|_{x_1=a}^b +(b-a)x_2^2C^{-1}_{22}dx_2\\
& = &\int_{c}^d {\frac {(b^3-a^3)C^{-1}_{11}}{3}}+(b^2-a^2)x_2C^{-1}_{12} +(b-a)x_2^2C^{-1}_{22}dx_2\\
& = & {\frac {(d-c)(b^3-a^3)C^{-1}_{11}}{3}}+{\frac 1 2}(d^2-c^2)(b^2-a^2)C^{-1}_{12}+{\frac {(b-a)(d^3-c^3)C^{-1}_{22}}{3}}
\end{eqnarray*}
In higher dimensions, you have to evaluate integrals like $\int_{\prod_i [a_i,b_i]} x_px_qC^{-1}_{ab} \prod_i dx_i$. In case $p=q$, the integral is $\prod_{i\neq p}(b_i-a_i)C^{-1}_{pp}(b_p^3-a_p^3)/3$, while if $p\neq q$ it is $\prod_{i\neq p,q}(b_i-a_i)C^{-1}_{pq}(b_p^2-a_p^2)(b_q^2-a_q^2)/4$. So in arbtirary dimensions you get the formula
$$\int_{\prod_i [a_i,b_i]}x^tC^{-1}xdx=\sum_p\prod_{i\neq p}(b_i-a_i)C^{-1}_{pp}(b_p^3-a_p^3)/3+ \sum_{p\neq q}\prod_{i\neq p,q}(b_i-a_i)C^{-1}_{pq}(b_p^2-a_p^2)(b_q^2-a_q^2)/4$$


How to properly set signal volume when sampling

Question: When sampling from a turntable into my sampler trough a mixer I'm not sure how to best set the signal volume in order to get the best quality recording.
My signal path is:
turntable -> mixer channel phono input -> mixer amp output to sampler
I can control:

the channel's input gain
the mixer's output volume
the sampler's input gain

I have level monitoring both on my mixer and on my sampler so I'm able to see if the sound is clipping.
How should I best balance the 3 controls?
Comment: I think you're missing a component. "mixer channel phono input"…  Is this just a regular 'line in' you'd expect to plug a CD, mp3 player etc into? That's just not going to work for a record deck. You need an RIAA preamplifier, otherwise everything is just going to sound tinny & scratchy. Nothing you do with levels is going to recover that, unless you have an RIAA emulator plugin in your signal chain, which is still going to need more careful level-matching than your existing setup.
Answer: Most modern audio electronics are designed to be linear. That means that ideally, it shouldn't matter how much signal level you have: the output level simply scales along with the input level, with no change in the signal quality.
In practice, that's never quite true. The most prominent factors are:

If you get over the clipping threshold, it... well, clips. In linear circuits based on operational amplifiers, this is a pretty yes-or-no situation, sounds very harsh, and is widely considered just wrong, so in your situation you should probably ensure clipping never happens.In other applications, clipping is just part of the sound and can be desirable to drive a bit "hot". In particular valve-based circuitry clips in a smooth way that enrichens the harmonics and compresses the signal, particularly desired for electric guitar. But for a turntable, any desired soft-clipping would presumably be already on the record – so even if using a tube preamp, significantly overdriving it would probably be counterproductive, unless you deliberately want to distort something.

Every piece of circuitry introduces some amount of noise (both Johnson-Nyquist white noise and various kinds of hum- or buzz interference). This is largely independent of the signal level, so it's typically best to keep the signal as high as possible in each stage of the signal chain, so you can turn the final output down and thereby reduce how much of the noise is audible in the end.

For these reasons, the standard practice is to turn the gain of each part of a signal chain up as high as possible so it just barely doesn't clip even at the loudest inputs. This can be achieved by putting in a loud input, turning up the gain until it just starts clipping, then turning down again by something like 3 dB to 9 dB. The more you take it down again, the more sure you can be that it really won't clip in action, but you will also pick up some more noise – though in your application that should hardly matter because a vinyl disc already has quite a high noise level that you can't possibly avoid no matter what gain settings you use.
Output levels, on devices that have controls for that, should generally be set to a reasonably high level too – either 100%, or to a 0 dB setting, or as high as the next device in the chain can handle without having to turn the gain knob extremely low (which could be problematic because it might get very sensitive to small variations and possibly unbalance the stereo).


Calculate number of events in a clinical trial design

Question: Suppose I have 1000 patients enrolled in a trial (assuming 1:1 randomization to Treatment and Control arms), and my objective is to estimate the number of events (e.g., overall survival) needed to have a test of power at least 0.8 under the assumption of alpha=0.05. I wonder if there are formulas there to use, and/or R package that performs such power/sample size analyses. Thank you!
Comment: This approach is a bit backward from standard practice. Usually the size of the study is the result of power calculations based on event probabilities, estimated treatment effects, and the participant accrual pattern. Here one is starting already with a sample size of 1000. What is the purpose of the proposed calculation, if the sample size is already known?
Comment: You also need to take the estimated effect of the treatment into consideration.
Answer: There are ways of calculating this, but not implemented in R as far as I know. A good read would be Therenay & Grambsch's book (the reference for the survival package), chapter 3.3 "Sample size". If you don't have access to this book, it references the following 3 papers:

D. A. Schoenfeld. Sample-size formula for the proportional-hazards
regression model. Biometries, 39:499-503, 1983.
D. Schoenfeld. The asymptotic properties of nonparametrie tests for
comparing survival distributions. Biometrika, 68:316-319, 1981.
D. Berstein and S. W. Lagakos. SampIe size and power determination
for stratified clinical trials. J Stat. Comput. Simul., 8:65-73, 1978.
Comment: The R `Hmisc` package's `cpower` and `spower` functions help a bit.


How to set counting amount in a slider using input type=number?

Question: I have a slider that I am using the following code for
<form>
emails:

<input type="range" id="item1" min="0" max="100" value="0" />
0

  Total is: $0
</form>

Here's the fiddle: https://jsfiddle.net/j2bh9stu/1/
What I am trying to figure out is to how to set up the slider to show a price of $2 everytime the slider passes the 10,000 mark on a 1mil scale. Right now I have it outputting $2 for every single number, while I need it to output $2 if the slider is between 0-10k, $4 if its between 10,001 and 20k, ect.
Answer: I've forked your fiddle and modified the js a bit: https://jsfiddle.net/tfqym7cp/2/
main change is here, in the showTotal function:
// it's always a good idea to give readable names to variables
let emailCount = $(this).val();
// fist, compute the number of units you want to charge
let units = Math.floor(emailCount/1e4) + 1;
// then it becomes easy to compute the total price
total += parseInt(units * prices[myid]);

Cheers!


Generally covariant Klein-Gordon equation

Question: Consider a 4-dimensional smooth manifold $M$ on which there is a Lorentzian metric $g_{ab}$ and a function $\phi$ satisfying the following two equations (in abstract index notation):
\begin{equation}
g^{ab}\nabla_{a}\nabla_{b}\phi - m^{2}\phi = 0,
\qquad
R_{abcd} = 0.
\end{equation}
I've been told that the covariance group of these equations is $\mathrm{Diff}(M)$, but I am having a hard time seeing it for myself.  From what I understand, this means that for any $\psi \in \mathrm{Diff}(M)$, $\psi^{*}\phi$ (and $\psi^{*}g_{ab}$?) is a solution of these equations just if $\phi$ (and $g_{ab}$?) is.  It's straightforward that $\psi^{*}R_{abcd} = 0$, but I am having a hard time showing that $\psi^{*}(g^{ab}\nabla_{a}\nabla_{b}\phi) = g^{ab}\nabla_{a}\nabla_{b}(\psi^{*}\phi)$.  Is this true?  If so, how would I go about showing that?
Comment: As I understand "covariance", just the **form** of the equation has to be preserved while the quantities are recalculated with respect to the choice of coordinates. Mathematicians call this "naturality" :-)
Comment: And one more thing: the diffeomorphisms correspond to the changes of coordinates.
Answer: The answer given by @YuriVyatkin is the right answer to my question, but I thought I'd write out more fully how it answers my question.
Usual statements of general covariance are something like "the form of the equations is the same in every frame" or "the diffeomorphism group is the covariance group of the theory."  While I'm sure these are true, they are too imprecise for me to understand (or involve terms like "form" that I can't find the mathematical definition of), which is why I wanted some mathematical statement that corresponds to what they mean.  Sometimes physicists will say that if you have a tensor equation, then you automatically have general covariance.  I could accept that as a definition of general covariance, but it wasn't clear to me how that's related to the other two characterizations.  I've settled on something that I find satisfying, which boils down to the naturality of the pullback.
The basic statement of general covariance that seems right to me is from Anderson's Principles of Relativity Physics, which in a slightly modernized form is something like:
A group $G$ is a covariance group of a theory if

There is a faithful representation $\rho$ of $G$ on the state space of the theory, and
If $\langle O_{1}, O_{2}, \dots \rangle$ is a solution of the equations of the theory (where $O_{i}$ are some quantities), then for all $g \in G$, $\langle \rho(g)O_{1}, \rho(g)O_{2}, \dots \rangle$ is a solution as well.

So consider a massive scalar Klein-Gordon field on flat spacetime:
$$
g^{ab}\nabla_{a}\nabla_{b}\phi - m^{2}\phi = 0, \qquad
R_{abcd} = 0.
$$
The state space of the theory is pairs $\langle g_{ab}, \phi \rangle$ of a
Lorentzian metric and a scalar field, and there is a faithful representation of $\mathrm{Diff}(M)$ on these pairs given by
$$
\rho(\psi)\colon \langle g_{ab}, \phi \rangle \mapsto \langle (\psi^{-1})^{*}g_{ab}, (\psi^{-1})^{*}\phi \rangle
$$
for each $\psi \in \mathrm{Diff}(M)$.  We're allowed to pull back $g_{ab}$
    because we're only concerned with diffeos.  (And actually, we can get rid
    of the inverses by noting that what we're really doing is pushing both
    things forward.  But I'll stick with talking in terms of pullbacks.)  The
    result of applying $\rho(\psi)$ is a pair of a Lorentzian metric and a
    scalar field, so we're still in the state space of the theory, and since
    the pushforward is linear, it really is a representation.  Faithfulness is
    also pretty direct.  So now we just need to show that $\langle \psi^{*}g_{ab}, \psi^{*}\phi \rangle$ is a solution to the equations for all $\psi^{-1} \in \mathrm{Diff}(M)$.
This is what was really hanging me up, since I wasn't sure how to see this.  I now realize that part of my problem was the fact that $\nabla_{a}$ was involved, and I didn't know how pullbacks interacted with it.  So consider a simpler theory for a moment, of the form
$$
G_{ab} = 8\pi T_{ab}
$$
To show that $\langle \psi^{*}G_{ab}, \psi^{*}T_{ab} \rangle$ is a solution is straightforward:
$$
(\psi^{*}G)_{ab} - 8\pi(\psi^{*}T)_{ab}
=
\psi^{*}(G_{ab} - 8\pi T_{ab})
=
\psi^{*}0
=
0
$$
which follows directly from the linearity and naturality of the pullback with respect to all the tensor operations (scalar multiplication, tensor addition, etc.).  This example makes it clear why tensor equations are key: since the pullback is natural, you'll always be able to bring it all outside the equation, and the right side will always vanish.  So if you have a tensor equation, then you get diffeomorphism covariance for free.
Okay, back to the Klein-Gordon equation.  The tensor equations involve 5 doodads ($g_{ab}$, $\nabla_{a}$, $\phi$, $m$, and $R_{abcd}$), but only two show up in the state pairs.  Which is fine, since $\nabla_{a}$ is assumed to be the Levi-Civita covariant derivative, so it and $R_{abcd}$ are determined by $g_{ab}$.  And since $m^{2}$ is just a constant function, it's invariant under the pullback.  Since the pullback of the Levi-Civita connection is the Levi-Civita connection, and the pullback of a flat metric is a flat metric, the second equation is automatically satisfied, and for the first we have
$$
(\psi^{*}g)^{ab}(\psi^{*}\nabla)_{a}(\psi^{*}\nabla)_{b}(\psi^{*}\phi)
-
(\psi^{*}m^{2})(\psi^{*}\phi)
=
\psi^{*}(g^{ab}\nabla_{a}\nabla_{b}\phi - m^{2}\phi)
=
\psi^{*}0
=
0.
$$
So there you go, $\langle \psi^{*}g_{ab}, \psi^{*}\phi\rangle$ is really a solution.  I think the biggest problem I was having was seeing what the importance of the pullback was.  It's the reason that tensor equations give us general covariance, but I've never seen someone make this connection explicit.  I think it's also what people mean when they talk about the "form" of the equations being preserved under coordinate transformations.  I still am not totally sure what "form" means here, but it's not really important, since I can just translate that to naturality when I hear it.
Also, just to quickly answer the last question from my post:  it's not true in
general that
$
g^{ab}\nabla_{a}\nabla_{b}(\psi^{*}\phi) =
g^{ab}\nabla_{a}\nabla_{b}\phi
$.
Two ways to see this:  the way that I first realized it is that
$\nabla_{a}\nabla_{b}\phi = {\star}\, d\star d\phi$, and the pullback only
commutes (up to a sign) with the Hodge star when $\psi$ is an isometry.  Since
there are two stars, any pullback by an isometry will satisfy
$
g^{ab}\nabla_{a}\nabla_{b}(\psi^{*}\phi) =
g^{ab}\nabla_{a}\nabla_{b}\phi
$.
Alternatively, note that since $\nabla_{a}$ is determined by $g_{ab}$, this
equation is just the demand that $(\psi^{*}g)_{ab} = g_{ab}$; i.e., that $\psi$
is an isometry.
Comment: +1. Thank you for posting this! I've been always curious how the physicists think about this matters )))
Comment: I don't know if this will help, but one can think of a gauge theory as a map $F:X\to Y$, with a gauge group $\mathcal{G}$ acting on the configuration spaces $X$ and $Y$ so $F$ is $\mathcal{G}$-equivariant. In this case, it looks like $X = Y = C^\infty(M)$ and $F = \tr\operatorname{Hess} - m^2$. Clearly $\operatorname{Diff}(M)$ acts on $C^\infty(M)$ by pullback, so it suffices to see that $F$ is $\mathcal{G}$-equivariant. This is where the naturality argument comes in, allowing you to argue that trace and the Hessian are tensor quantities, hence diffeomorphism-equivariant.
Comment: @Neal, that helps a whole lot.  I think it's the last piece of what was originally puzzling me.  Thanks!
Comment: @JohnDougherty You're welcome! By the way, I forgot the curvature equation. Let $A$ be the Levi-Civita connection 1-form, with curvature $R(A)$. Then $X = C^\infty\oplus\Omega^1$, $Y = C^\infty\oplus\Omega^2$ and $F = (\operatorname{tr}\operatorname{Hess} - m^2)\oplus R(A)$.
Answer: Wouldn't it better to have $\psi^{*}(g^{ab}\nabla_{a}\nabla_{b}\phi) = (\psi^{*}g)^{ab}(\psi^{*}\nabla)_{a}(\psi^{*}\nabla)_{b}(\psi^{*}\phi)$?
Then this is just the naturality of the metric and the connection.
Comment: This would certainly be easier to show, since as you say, it is just an instance of naturality.  The claim I'm trying to precisify, though, is "a representation of Diff(M) will take solutions of this equation to other solutions."  It's not clear to me whether this means that f o g will be a solution for g in Diff(M) if f is, or whether it just means that the pullback of tensors is defined as you say.
Comment: Sorry, I don't have much time now to expand my answer, so unless other people did this, I would advise you to take a look at the discussion [here](http://physics.stackexchange.com/questions/27008/from-manifold-to-manifold) that I find very relevant.
Comment: I'm still confused, but I'm having a hard time saying exactly why.  I think your answer is the right one to my question, and I'm just mixed up over something else, so I'm accepting your answer.
Comment: Thanks @John for accepting the answer. Just in case I'll remind you that there is no rush to accept until you are fully satisfied. We collaborate here, and other people may be interested in the details. If you have some thoughts you could consider adding your own answer here as well.