Probability Mass Function making the Truncated Normal Discrete

Question: I want to discretize the Truncated Normal to describe the spread in the Grades of students in a class sitting the same exam.
Let an arbitrary number of students sit the same exam. The grades are usually said to be normally distrubutted (they couldn't possibly be distributed with the truncated normal and much less by a simply normal because the grade are bound from both ends and are discrete).
The minimum grade is a parametre a (even negative grades are allowed)
The maximum grade is a parametre b
The minimum difference possible between two grades is a parametre c
x (measured in X axis) is the grade
y (measured in Y axis) is the probability of a student achieving X grade or the frequency that students in the class achieve grade X.
μ is a transformation of the mean, it is the mode if μ lies between a and b and is also the mean if μ lies halfway between a and b
σ is a transformation of the SD, it is the SD when $a\to-\infty\cap b\to\infty \cap c=0$
When $c=0$ we have a Truncated Normal
When $a\to-\infty\cap b\to\infty \cap c=0$ we have a Normal.
I want my distribution (f(x,μ,σ,a,b,c)) to meet some criteria
1 Being supported on the terms of an arithmetic progression. Both the initial and final terms and the common difference are parametres
2 Being unimodal in all cases but 1. Being bimodal in case the mode is equidistant from 2 values in the support.
3 Having probabilites strictly decreasing as X distances itself from the mode. The decrease in probability should be equal for x equally distant from the mode.
The change in the difference should first decrease and then increase after reaching a quasi-inflection point. The change in the difference should also be equal for x equally distant from the mean. I.e if the mode coincides with the midrange the distribution is symmetrical while if the mode is closer to one bound the distribution is symmetrical for all values closer than the nearest to the mode bound (short of like the Truncated Normal if you fold it at the mode all the values that are closer that the nearest bound coincide 1 to 1 and only what is further away does not coincide because there is nothing left for them to correspond to)
Hopefully the first 3 criteria are all compatible with each other.
4 If the above three criteria allow for it the distribution should belong to the Natural Exponential Family (better) or the Exponential Family (Plan B)
5 The distribution should be the Maximum entropy distribution that the above 4 criteria allow for (ignore criterion 4 if the first 3 make it impossible for the distribution to belong to the Exponential Family)
Such that the probability mass assigned to any point is proportional to the kernel of the normal distribution (leaving the mean and the standard error a parametre) calculated at that point.
E.g when a=0, b=25 and c=1
$f(0,\mu,\sigma, 0, 25, 1)\propto\mathrm{e}^{-\frac{{\mu}^2}{2{\sigma}^2}}$
$f(1,\mu,\sigma, 0, 25, 1)\propto\mathrm{e}^{-\frac{\left({\mu}-1\right)^2}{2{\sigma}^2}}$
$f(2,\mu,\sigma, 0, 25, 1)\propto\mathrm{e}^{-\frac{\left({\mu}-2\right)^2}{2{\sigma}^2}}$
$f(3,\mu,\sigma, 0, 25, 1)\propto\mathrm{e}^{-\frac{\left({\mu}-3\right)^2}{2{\sigma}^2}}$
.
.
.
$f(25,\mu,\sigma, 0, 25, 1)\propto\mathrm{e}^{-\frac{\left({\mu}-25\right)^2}{2{\sigma}^2}}$
of course
$\displaystyle \sum_{x=0}^{25}  f(x,\mu,\sigma, 0, 25, 1) = 1$
or more generally
$\displaystyle \sum_{x=a}^b  f(x,\mu,\sigma, a, b, c)=1$
What is the closed form solution (probably in terms of Theta functions)
Edit.
I am hoping the probability mass function I will get will be a conjugate prior (in the same probability family) that a posterior predictive distribution would be if we started with a discrete uniform prior (with a common difference c between each adjacent value in the support) where the random variable would be the individual students performance and each grade would be assigned the same frequency (if there are say 25 values in the support, 25 different grades possible, it would assign a probability of 0.04 for each grade) and the observations would be the individual performance of every student in the class (in the end we will have the performance of the class not simply their mean but an histogram). The posterior would be a distribution assigning a probability that a student randomly chosen scored X given that the class scored as the histogram shows.
I don't understand the difference between
$$P(X = x\vert \mu,\sigma,a,b,c) = \frac{e^{-\frac{(x-\mu)^2}{2\sigma^2}}}{\sum_{y \in \Omega} e^{-\frac{(y-\mu)^2}{2\sigma^2}}}$$
and
$$p_X(x) = \frac{\Phi \Big( \frac{x - \mu + 1/2}{\sigma} \Big) - \Phi \Big( \frac{x - \mu - 1/2}{\sigma} \Big)}{\Phi \Big( \frac{m - \mu + 1/2}{\sigma} \Big) - \Phi \Big( \frac{1/2 - \mu}{\sigma} \Big)}
\quad \quad \quad
\text{for } x=1,...,m,$$
Whuber said that they are not closed form solutions, because they involve an unevaluated sum. There is no closed form solution that doesn't involve Theta functions. I don't understand this either.
Comment: This question is confusing.  You repeatedly state you "hate approximations," but ironically you have yet to characterize the quantities you wish to compute!  All you have said explicitly is "I need a discrete distribution."  Could you characterize what you need in clear, mathematical terms so that people can know what might constitute an "approximation" and how to evaluate it? What do you mean by the "general problem" of which this might be one instance?
Comment: There is little justification in defining a pmf this way when compared with other functions from $\{0,...,y\}$ to $(0,1)$. The Normal density function is a density for a continuous variate and its values at a finite number of values such as the above integers cannot be interpreted as probabilities. In addition, most of the nice properties of a Normal distribution do not transfer to this new distribution.
Comment: In which sense an integer-Normal distribution is less of an approximation? more accurate? And what properties are you looking for in your model?
Comment: That helps clarify things, thank you.  However, you seem to be posing a very broad question: namely, how to construct parametric families of discrete distributions supported on a specified set (such as the integers from 0 to 25).  And of course you don't want to construct the family based on the data: that would make correct inference impossible.  On what basis, then, do you want to construct the distributional family??
Comment: @Xi'an The justification is simple I hate approximations. My data are bound both from below and above and much more significantly are discrete. I don't want a distribution which is easy to work with I want an acurate distribution (or the closest possible to that) even if I end up with something hard to work with. What other distributions f(μ,σ,x,z,y) are there (which are both discrete, and bounded from both sides). What properties do those distributions have that my constructed distributtion would lack?
Comment: @Xi'an The properties I am looking for in my distribution would be having a discrete support, being bound both from above and below, being unimodal (or at worst bi-modal in case the mean is exactly in the mid-range between two points in the support), having probabilities strictly decreasing as X distances itself from the mode, being symmetrical if the mean coincides with the midrange (in this case with y=25 if the mean is 12.5). Hopefully the difference in probability would first decrease as we got more distant from the mean and then start increasing back when reaching a quasiinflextion point.
Comment: @Xi'an Hopefully it would also belong to the Exponential Family or better yet to the Natural Exponential Family. Furthermore it would be the Maximum Entropy Distribution out of the available ones (Meeting all the aforementioned criteria minus the impossible ;due to an inherent incompatibility of the other criteria and not due to maximum entropy, ones to meet). The data are sets of 25 answers to Multiple Choice exam questions. Others use Normal or Truncated Normal but in my opinion both are a poor fit for the data.
Comment: @whuber I don't want to compute quantities (with my question). I want to find the best fit for my data and construct a distribution.
Comment: Could you explain the sense in which "find the best fit" and "construct a distribution" differ?  And then what an "approximation" might mean?
Comment: @whuber There isn't probably a difference. I meant find the best fit in concreto and contruct a distribution in abstracto. The data best fits a single family of distributions. From the specific case a single distribution (the parametres would be estimated from the sample) I would like to abductively construct a distribution (analytically-parametrically) to use to all similar data. An approximation is any deviation from the facts motivated by ease to manipulate data. An example would be using a continuous distribution to describe data which are a priori knowingly discrete.
Comment: @whuber Another approximation would be using a distribution with an unbound support  for data which are a priori known to be bound. The is no negative height and many datasets are by construction discrete. When designing a multiple choice test a question is either Correct or Wrong there is no such thing as a half-right
Comment: @whuber I would like to contstruct my distribution to fit my needed criteria. Based (loosely) on goodness of fit and descriptive accuracy. My question is how to construct a specific family of functions meeting these criteria.
Comment: @whuber The properties I am looking for in my distribution would be having a discrete support, being bound both from above and below, being unimodal (or at worst bi-modal in case the mean is exactly in the mid-range between two points in the support), having probabilities strictly decreasing as X distances itself from the mode, being symmetrical if the mean coincides with the midrange (in this case with y=25 if the mean is 12.5). Hopefully the difference in probability would first decrease as we got more distant from the mean and then start increasing back when reaching a quasiinflextion point
Comment: @whuber Hopefully it would also belong to the Exponential Family or better yet to the Natural Exponential Family. Furthermore it would be the Maximum Entropy Distribution out of the available ones (Meeting all the aforementioned criteria minus the impossible ;due to an inherent incompatibility of the other criteria and not due to maximum entropy, ones to meet). The data are sets of 25 answers to Multiple Choice exam questions. Others use Normal or Truncated Normal but in my opinion both are a poor fit for the data.
Comment: @whuber The difference in probability and the change in the difference would be equal for points equally distant from the mean. Unless of course the mean is closer to one bound which would make any such difference&change in difference disappear and the equal difference and equal change for probability would only hold for points that are as close to the mean as the nearest bound an example of a continuous(sadly) distribution would be the truncated normal. In case μ = (a + b) /2 it is symmetric while for all other μ the function is quasi-symmetric.
Comment: @whuber Folding the distribution at μ all the points to the nearest bound coincide with the respective points (as distant as the nearest bound). And also the first derivative is also kind of symmetrical the first derivative is maximised at μ while the rest is the additive inverse of the symmetrical. Last but not least the second derivative is also symmetrical in the true sense.
Comment: That information will be helpful to everyone thinking about your question, so consider putting it into the question itself.
Comment: @whuber How do you suggest I word myself when adding such information? Could you please suggest an edit adding this information? Also there is more information in the replies to the answer.
Comment: @whuber I tried but ended up with a word of text. I really don't know what information to keep.
Comment: @whuber I tried rewording the entire question.
Comment: @whuber Isn't the question now clear and unambiguous?
Comment: @whuber Please check my wording in the original question once more. I edited it to restrict it to grades.
Comment: Thank you, George.  But what is your question?  You state you want to discretize a Normal distribution and then you do just that.  What is left to say?
Comment: @whuber I want the closed form solution. Tyrel Stokes gave me a closed form solution (It is somewhat too specific with a=0 and c=1) and I don't know whether it meets the criteria I intended for it to meet.
Comment: He did not give you a closed form solution, because it involves an unevaluated sum.  There is no closed form solution that doesn't involve Theta functions.
Comment: It would be more natural to try a beta distribution, and or other distributions that have support on the finite range from a to b. It is unclear to me whether you are looking for a [discrete distribution with finite support](https://en.wikipedia.org/wiki/List_of_probability_distributions#With_finite_support) or a [continuous distribution with support on a bounded interval](https://en.wikipedia.org/wiki/List_of_probability_distributions#With_finite_support). However, a left and right truncated normal distribution is certainly not the first thing that comes to mind, ...
Comment: cont... and, I have having a difficult time imaging how such a thing would be physical.
Answer: The other answer here uses the normal density values at the exact points.  Another similar method would be to take the normal probabilities across intervals centred on those points.  In the latter case, taking the support to be $X = 1,...,m$ you get:
$$p_X(x) = \frac{\Phi \Big( \frac{x - \mu + 1/2}{\sigma} \Big) - \Phi \Big( \frac{x - \mu - 1/2}{\sigma} \Big)}{\Phi \Big( \frac{m - \mu + 1/2}{\sigma} \Big) - \Phi \Big( \frac{1/2 - \mu}{\sigma} \Big)}
\quad \quad \quad
\text{for } x=1,...,m,$$
where $\Phi$ is the CDF of the standard normal distribution.  You can then adjust to an arbitrary arithmetic progression by taking the appropriate linear transformation.  This has the first three properties you stipulated in your question.
Comment: @Xi'an you are right, silly mistake. I was erroneously thinking of the categorical distribution, which is in the exponential family, where the parameters are $p_1, p_2, p_3, \cdots, p_n$, and thought that would capture any other discrete distribution. But, then the parameterization is entirely changed.
Comment: Can you please answer which of the 2 has a higher entropy and which has a higher variance (σ is just a scale parametre it is a transformation of the standard error)?
Comment: I don't know which has the higher entropy or variance.
Comment: What does it mean to "take the normal probabilities"? Does this pmf belong to either the natural exponential family or the exponential family? Is the entropy maxed out given the constraints? If we calculated the bayesian posterior given a discrete uniform distribution (with constant c) and normally distributed data would we end up with a posterior of this family; would this pmf be a conjugate prior to the posterior calculated with a discrete unifrom and normally distributed data? How much of a difference would it make to use this pmf as a prior rather than a discrete uniform (with constant c)?
Comment: @SextusEmpiricus Does it belong to the Natural Exponential family too?
Comment: @George I don't believe it does. Neither does the truncated normal distribution (if you do not fix $\sigma, a, b$ and $c$). The motivation/advantage of the distribution here would be that the cumulative distribution is relatively simple to express, it is exactly the same as the continuous truncated normal distribution.
Comment: What is the difference between $$p_X(x) = \frac{\Phi \Big( \frac{x - \mu + 1/2}{\sigma} \Big) - \Phi \Big( \frac{x - \mu - 1/2}{\sigma} \Big)}{\Phi \Big( \frac{m - \mu + 1/2}{\sigma} \Big) - \Phi \Big( \frac{1/2 - \mu}{\sigma} \Big)}
\quad \quad \quad
\text{for } x=1,...,m,e$$ and $$P(X = x\vert \mu,\sigma,a=0,b,c=1) = \frac{e^{-\frac{(x-\mu)^2}{2\sigma^2}}}{\sum_{y \in \Omega} e^{-\frac{(y-\mu)^2}{2\sigma^2}}}$$ are they the same distribution just differently formulated?
Comment: What justifies the different method? What is the difference (for the better)? Does $$p_X(x) = \frac{\Phi \Big( \frac{x - \mu + c/2}{\sigma} \Big) - \Phi \Big( \frac{x - \mu - c/2}{\sigma} \Big)}{\Phi \Big( \frac{b - \mu + c/2}{\sigma} \Big) - \Phi \Big( \frac{a+c/2 - \mu}{\sigma} \Big)}
\quad \quad \quad
\text{for } x=a,a+c,a+2c,...b-c,b,$$ have a greater entropy than $$P(X = x\vert \mu,\sigma,a,b,c) = \frac{e^{-\frac{(x-\mu)^2}{2\sigma^2}}}{\sum_{y \in \Omega} e^{-\frac{(y-\mu)^2}{2\sigma^2}}}$$ Where $\Omega = \lbrace a,a+c,a+2c,\dots b-c,c \rbrace$ all the values in the support?
Answer: When you use the values of the normal density then you get automatically the first four conditions satisfied
$$P(X = x\vert \mu,\sigma,a,b,c) = \frac{e^{-\frac{(x-\mu)^2}{2\sigma^2}}}{\sum_{y \in \Omega} e^{-\frac{(y-\mu)^2}{2\sigma^2}}}$$
where $\Omega = \lbrace a,a+c,a+2c,\dots b-c,c \rbrace$ all the values in the support.

Maximum entropy
The fifth condition, maximum entropy, is also fulfilled since the maximum entropy distribution with constraints $\sum_{\forall x} x p(x) = \mu$ and $\sum_{\forall x} x^2 p(x) = \text{var}$ must be of the form $$P(X=x) = ce^{\lambda_1 x + \lambda_2 x^2}$$ which is like the distribution above (e.g. see that with $\lambda_1 = \mu/\sigma^2$ and $\lambda_2 = -1/(2\sigma^2)$ you get the above).

We can also prove it explicitly by considering the Kullback-Leiber divergence or Gibbs inequality with another distribution $f(x)$, and our distribution $g(x)$
$$\begin{array}{}
- \sum_{\forall x} f(x)\log f(x) &\leq& - \sum_{\forall x} f(x)\log g(x) \\
&\leq& - \sum_{\forall x} f(x)\log \left(ce^{\lambda_1 x + \lambda_2 x^2} \right)\\
&\leq & - \sum_{\forall x} f(x)\left(\log c + \lambda_1 x + \lambda_2 x^2 \right)\\
&\leq & - \sum_{\forall x} g(x)\left(\log c + \lambda_1 x + \lambda_2 x^2 \right) \\
&\leq& - \sum_{\forall x} g(x)\log g(x)
\end{array}$$
This second last step where we switch from $f(x)$ to $g(x)$ is because of the constraints
$$\begin{array}{}
\sum_{\forall x} f(x) &=& \sum_{\forall x} g(x) &=& 1 \\
\sum_{\forall x} xf(x) &=& \sum_{\forall x} xg(x) &=& \mu \\
\sum_{\forall x} x^2f(x) &=& \sum_{\forall x} x^2g(x) &=& \text{var}
\end{array}$$
with these constraints we can rewrite
$$\sum_{\forall x} f(x)\left(\log c + \lambda_1 x + \lambda_2 x^2 \right) = \sum_{\forall x} g(x)\left(\log c + \lambda_1 x + \lambda_2 x^2 \right)$$
So we must have that the entropy of $f(x)$ must be smaller than the entropy of $g(x)$.
Comment: @GeorgeNtoulos  "use the values of the normal density": it means that we make the PMF of the discrete distribution equal to the PDF of the continuous distribution, with only a multiplicative constant as difference.
Comment: Indeed my distribution is similar to Tyrel Stokes' solution. The only difference is that the parameters $a,b,c$ are incorporated and I have shown (intuitively) that the distribution is the maximum entropy distribution. The distribution by Ben is different, but approximately it is very close because with small steps (relative to $\sigma$) you get that $$\Phi \Big( \frac{x - \mu + 1/2}{\sigma} \Big) - \Phi \Big( \frac{x - \mu - 1/2}{\sigma} \Big) \approx \phi \Big( \frac{x - \mu}{\sigma}\Big)/\sigma $$
Comment: What is the likelihood function of the observations (and what do you observe?) based on which you update the prior into the posterior?
Comment: Can you please answer which of the 2 has a higher entropy and which has a higher variance (σ is just a scale parametre it is a transformation of the standard error)?
Comment: @GeorgeNtoulos which of the 2 what? This question is four months old and there are a lot of comments. I do not know what you are referring to.
Comment: One distribution is $$P(X = x\vert \mu,\sigma,a,b,c) = \frac{\Phi \Big( \frac{x - \mu + c/2}{\sigma} \Big) - \Phi \Big( \frac{x - \mu - c/2}{\sigma} \Big)}{\Phi \Big( \frac{b - \mu + c/2}{\sigma} \Big) - \Phi \Big( \frac{a+c/2 - \mu}{\sigma} \Big)}\quad\text{for}\quad x=\lbrace a,a+c,a+2c,...b-c,b\rbrace$$ and the second is $$P(X = x\vert \mu,\sigma,a,b,c) = \frac{e^{-\frac{(x-\mu)^2}{2\sigma^2}}}{\sum_{y \in \Omega} e^{-\frac{(y-\mu)^2}{2\sigma^2}}} \quad \quad \text {where } \quad \Omega = \lbrace a,a+c,a+2c,\dots b-c,b \rbrace$$ which one has a higher entropy and which one greater variance?
Comment: @George Ntoulos It depends on the parameters but when the distributions have the same mean, variance and domain $\Omega$ then the second distribution has the higher entropy because it is the maximum entropy distribution for a given mean, variance and domain.
Comment: Then is there any reason to use the probabilities across intervals centred on some points instead of using the value of the density at those exact points? Is there any advantage to the different approach (using probabilities as a base instead of the density). Otherwise the second one (density-based) looks more elegant too it is not simply a matter of higher entropy. But is the variance the same tranformation of σ in both distributions when the other parametres (a, b, c, μ) are equal considering c is quitte large and a and b are finite?
Comment: about your second point: The variance and also the mean do not need to be the same given the parameters are equal (and it might actually be very difficult to find cases where they are the same although they should be close to each other). To find expressions to compute particular values of $\mu$ and $\sigma$ for a given mean and variance is not easy and there is probably no closed-form expression. However you can easily obtain values by fitting the distribution.
Comment: about your first point: an argument for the first distribution with probabilities computed across intervals is that for the points in $\Omega$ it has the same CDF as the continuous truncated distribution. This might be a desirable property for some.
Comment: The question regarding conjugate priors was: Let's say we believe (wrongly/mistakenly) that the scores of students in a test are uniformly distributed on $\lbrace a,a+c,a+2c,...b-c,b\rbrace$ so the prior $p(\theta)$ is that uniform while the observations have a likelihood $p(x|\theta)$ that is a normal distribution with unkown mean and unkown variance (we could estimate the mean and the variance but let's allow them to stay as parametres) and the normalizing factor is calculated as usual. Will the resulting posterior $p(\theta|x)$ belong to some of the above distribution families?
Comment: What are $\theta$ and $x$ in this story about conjugate priors?
Comment: I am basically asking for some calculus of distributions. I want to know the result of $p(\theta|x) = \frac{p(x|\theta)}{p(x)}p(\theta)$ when $p(\theta)$ is a discrete uniform (over the terms of an arithmetic sequence) and $p(x|\theta)$ is a regular normal (with the mean and the standard error left as parametres) and the normalizing factor accordingly calculated. Hopefully the resulting posterior would be the density-based dicrete version of the normal. My desired discrete version is a conjugate prior to the result of this calculus of distributions-based posterior (same family)
Comment: x are the individual scores of students in the class while θ is a parametre I don't even understand what means (genally) in a likelihood function. I never understood θ in my statistics classes. Not even on my Bayesian Statistics class (that is why a barely passed) Bayesian Statistics. What does θ generally mean on a likelihood function?
Comment: Maybe θ are the observed individial students' grades while x might be the general (observed and unobserved) students' grades. I am not sure what θ is in general.
Comment: if the likelihood is $$p(x|\theta) \propto e^{-a(x-\theta)^2}$$ and the prior is $$p(\theta) \propto e^{-b(\theta-\mu)^2}$$ then the posterior is proportional to the product $$p(\theta| x) \propto e^{-a(x-\theta)^2}e^{-b(\theta-\mu)^2} = e^{-a(x-\theta)^2-b(\theta-\mu)^2} = e^{-c(d-\theta)^2}$$ where you need to make the exact computation for $c$ and $d$ but you will know for sure that it is of this form because the addition of two polynomials is another polynomial of the same order as the highest order in the addition. So yes, the pdf in this answer is a conjugate prior distribution.
Comment: There are 2 calculi of distributions in my question. One where the likelihood is $p(x|\theta)=\dfrac{\mathrm{e}^{-\frac{\left(x-{\mu}\right)^2}{2{\sigma}^2}}}{\sqrt{2}\sqrt{{\pi}}{\sigma}}$ and the prior is $p(\theta)=U \lbrace a,a+c,a+2c,...b-c,b\rbrace$ and the posterior $p(\theta|x)$ is unkown (let's say f(x)) (it is the result of the calculus of distributions. And the other question (requiring a second calculus) is if that posterior resulting from the calculus before will be a conjugate prior to a posterior calculated from it (f(x) and a regular normal as the likelihood distribution.
Comment: What is θ and what does it generally mean on a likelihood function? Can we do Bayesian Statistics when there is no parametre of interest (we are not interested in the mean or the variance but only on the individual scores). We observe individual scores and we want to predict unobserved individual scores. What is θ and what role does it play? Can we calculate a posterior in such situation? How? What difference does it make in the algebra we must do whether we calculate a posterior predictive distribution or some posterior of some other parametre? Isn't it the same formula we must apply?
Comment: What does it mean to "use the values of the normal density"? Does this pmf belong to the natural exponential family or just the exponential family? If we calculated the bayesian posterior given a discrete uniform distribution (with constant c between values in the support) and normally distributed data would we end up with a posterior of this family? Would this pmf be a conjugate prior to the posterior calculated with a discrete unifrom (with constant c) and normally distributed data? How much of a difference would it make to use this pmf as a prior rather than a discrete uniform (with c)?
Comment: The pmf belongs to a two-parameter exponential family (or five-parameters if you include $a,b$ and $c$). When you fix the variance then it will also belong to the natural exponential family.
Comment: @GeorgeNtoulos It is not clear to me what you are asking for with the Bayesian computations.
Comment: In what family does the posterior belong to when the prior is a discrete uniform (with a common difference c between each pair of adjacent values of the support) and the data is from a normal distribution (with unknown mean and variance)? Lets say the posterior is from X family. Does $$P(X = x\vert \mu,\sigma,a,b,c) = \frac{e^{-\frac{(x-\mu)^2}{2\sigma^2}}}{\sum_{y \in \Omega} e^{-\frac{(y-\mu)^2}{2\sigma^2}}}$$ belong to X family? Is $$P(X = x\vert \mu,\sigma,a,b,c) = \frac{e^{-\frac{(x-\mu)^2}{2\sigma^2}}}{\sum_{y \in \Omega} e^{-\frac{(y-\mu)^2}{2\sigma^2}}}$$ a conjugate prior to X?
Comment: @GeorgeNtoulos "the data is from a normal distribution"? What sort of data and which parameters of that normal distribution has the uniform distribution as prior?
Comment: I like your answer more than the one Tyrel Stokes (I liked his too I just prefer yours) gave me but I am seeing that $$f_X(X=x;\mu, \sigma) = \frac{exp(-\frac{(\mu -x)^2}{2\sigma^2})}{\sum_{y=0}^Texp(-\frac{(\mu -y)^2}{2\sigma^2})}$$ is just a special case of $$P(X = x\vert \mu,\sigma,a,b,c) = \frac{e^{-\frac{(x-\mu)^2}{2\sigma^2}}}{\sum_{y \in \Omega} e^{-\frac{(y-\mu)^2}{2\sigma^2}}}$$ with a=0 and c=1 I am not seeing any other difference but  Whuber said that  There is no closed form solution that doesn't involve Theta functions.
Comment: What is the difference between $$p_X(x) = \frac{\Phi \Big( \frac{x - \mu + 1/2}{\sigma} \Big) - \Phi \Big( \frac{x - \mu - 1/2}{\sigma} \Big)}{\Phi \Big( \frac{m - \mu + 1/2}{\sigma} \Big) - \Phi \Big( \frac{1/2 - \mu}{\sigma} \Big)}
\quad \quad \quad
\text{for } x=1,...,m,e$$ and $$P(X = x\vert \mu,\sigma,a=0,b,c=1) = \frac{e^{-\frac{(x-\mu)^2}{2\sigma^2}}}{\sum_{y \in \Omega} e^{-\frac{(y-\mu)^2}{2\sigma^2}}}$$ are they the same distribution just differently formulated?
Comment: The uniform distribution would be a distribution of the grades of each student when the grades are between 0 and 100 (or 25) with no decimal then the prior would assume (believe or rather show the belief) that the grades are uniformly distributed with each grade having equal probability (0.04 or 0.01) and the data would be drawn from a normal when μ is the mean performance of the class. Intuitevely the resulting posterior should be of the same family as $$P(X = x\vert \mu,\sigma,a,b,c) = \frac{e^{-\frac{(x-\mu)^2}{2\sigma^2}}}{\sum_{y \in \Omega} e^{-\frac{(y-\mu)^2}{2\sigma^2}}}$$
Comment: @GeorgeNtoulos I still do not follow your Bayesian problem and which variable is being estimated based on what sort of data. Maybe you should put it in the question or create a new question.
Comment: The data points would be the grades of each student. In the end it will be the number of students that achieved each grade. (1 was achieved by 1 student, 2 was achieved by Z and so on)
Comment: No specific variable is estimated the posterior is calculated as an end in itself. It contains all the information available. Posterior calculated=Problem solved. I am just asking if such a Posterior (calculated from a discrete uniform and normal data) has $$P(X = x\vert \mu,\sigma,a,b,c) = \frac{e^{-\frac{(x-\mu)^2}{2\sigma^2}}}{\sum_{y \in \Omega} e^{-\frac{(y-\mu)^2}{2\sigma^2}}}$$ as a conjugate prior. I am asking if instead of using a dicrete unform as a prior we used the "discretisized" normal if the prior and the posterior would belong to the same family.
Comment: The posterior is a probability distribution for a particular parameter. Which parameter?
Comment: https://en.wikipedia.org/wiki/Posterior_probability#Definition https://en.wikipedia.org/wiki/Posterior_probability#Example https://en.wikipedia.org/wiki/Posterior_probability#Calculation The posterior would be the posterior probability distribution of the individual grades. It would be the conditional probability (conditioned on the wholle classes' performce) of a single individual grade/performance. Given that the class performed in the observed way it would be the probability that if we picked a random student they received X grade. I am not sure I would call it a parametre.
Comment: The mean of the posterior (the posterior would be a belief incorporating the evidence the classes' performance) would be the arithmetic mean of the students performance and the standard deviation would be estimated likewise. It would be a posterior for X (individual performance) neither for the Mean nor for μ (a transformation of the mean).
Comment: The likelihood function is a normal distribution and you observe the individual grades of each student in the class.
Comment: @GeorgeNtoulos but how does this likelihood function depend on X which is the parameter for which you describe the posterior. Say we have $$P(X|\theta)_{posterior} \propto P(\theta|X)P(X)_{prior}$$ It is not clear how you see $P(\theta|X)$, what are the $\theta$ and what is the likelihood function for the $\theta$? We need some observation $\theta$ distributed according to a distribution parameterized by $X$.
Comment: I did not understand the question. X is the individual performance of each student and θ is the performance (the whole distribution not just the mean) of the whole class. So the posterior would be the conditional probability of a random student having performed X (having received X grade) and the Likelihood would be the (joint) conditional probability of the class having performed (a distribution of the grades not just the mean) given on each student having performed $X_i$ (I guess it would be an histogram with X being the Grade and Y being the Frequency)
Comment: @GeorgeNtoulos maybe you mean the [posterior predictive distribution](https://en.m.wikipedia.org/wiki/Posterior_predictive_distribution)? It is best at this moment to write it as a question because I do not follow your logic viewing a distribution of $X$ as a posterior distribution. The Bayes rule is $$P(X|\theta)_{posterior} \propto P(\theta|X)P(X)_{prior}$$ and I do not see how your descriptions match this. The posterior $P(X|\theta)$ relates to the distribution of a parameter $X$ as function of an observation $\theta$ where these observations can be described by a likelihood $P(\theta|X)$.
Comment: So if you see a distribution of $X$ as a 'posterior distribution', then the $X$ must be a parameter in the distribution of your observations.
Comment: I am not very confident I have grasped the concept of a parametre of a probability distribution. I want my posterior to be exactly that a posterior predictive distribution. Predicting the probability that a random student will have grade X given that/conditioned on the class having performed as the Histrogram/Likelihood shows. The observations are the number of students having achieved grade X (or the frequency that grade X was achieved in the Class). If my observations are the frequency that grade X was achieved in Class is grade X a parametre it is measured in X ayis and is the main variable
Comment: @make it a question that makes it easier to follow and answer
Comment: @It is not a question. Surely not a separate/distinct one. So I added the information to this question here.
Comment: If we relaxed the restrictions of specified mean and specified variance (you said that the distribution is the maximum entropy distribution for a given mean, variance and domain) and only kept the domain fixed and as for the mean and variance only required a dependence on any location and scale parametres (we only want our distribution do be a function of location a scale parametres without specific mean and variance being given) what would be the maximum entropy distribution?
Comment: I don't want to fix anything. I want my maximum entropy distribution to be a function of these unspecified parametres. The entropy of this distribution for the same domain  $P(X = x\vert \mu,\sigma,a,b,c) = \frac{e^{-\frac{(x-\mu)^2}{2\sigma^2}}}{\sum_{y \in \Omega} e^{-\frac{(y-\mu)^2}{2\sigma^2}}}$  is lower than the entropy of this one $P(X = x\vert \mu,\sigma,a,b,c) = \frac{2^{-\frac{(x-\mu)^2}{2\sigma^2}}}{\sum_{y \in \Omega} 2^{-\frac{(y-\mu)^2}{2\sigma^2}}}$ And it gets higher the closer the base of the exponentials gets to 1 (but then the parametres don't matter).
Comment: @GeorgeNtoulos If you don't fix anything, then the uniform distribution has the highest entropy. If you want something else then you need to add constraints like the requirement that the distribution has a particular mean or variance.
Comment: $P(X = x\vert \mu,\sigma,a,b,c) = \frac{z^{-\frac{(x-\mu)^2}{2\sigma^2}}}{\sum_{y \in \Omega} z^{-\frac{(y-\mu)^2}{2\sigma^2}}}$ has a greater entropy for the same σ, μ,and domain. σ Is just a scale parametre (a transformation of the standard error) not the standad error itself. So as z approaches 1 the variance also gets larger even thought the scale parametre was named σ (the 2 σs are interpreted differently they are different transformations of standart error)
Comment: But the uniform distribution doesn't have location and scale parametres at all (neither specified nor unspecified). $P(X = x\vert \mu,\sigma,a,b,c) = \frac{z^{-\frac{(x-\mu)^2}{2\sigma^2}}}{\sum_{y \in \Omega} z^{-\frac{(y-\mu)^2}{2\sigma^2}}}$ has a greater entropy for the same σ, μ,and domain. σ Is just a scale parametre (a transformation of the standard error) not the standad error itself. So as z approaches 1 the variance also gets larger even thought the scale parametre was named σ (the 2 σs are interpreted differently they are different transformations of standart error)
Comment: I would like to set z=1 but then I don't think the scale and location parametres matter any more. And if I can't set z=1 then it can be made arbitrarily closer to 1. There is always a number between 2 numbers. I don't want to lose my location and scale parametres (they can be different transformations of the mean and the variance no problem with the interpretation). I don't know what can I use for my likelihood (I want to make the least possible unwarranted assumptions)
Comment: *"But the uniform distribution doesn't have location and scale parametres at all "* Yes, but you wanted to have the maximum entropy distribution or not?
Comment: The maximum entropy distribution does not care but I do. Also I don't care about specific values of parametres. The specified mean is less worrisome than the specified variance althought I would like to lose both. I want constrants that are differently formulated. I only want my maximum entropy distribution to be a function of location and scale parametres without constraining it to specified values. You said and I quote "maximum entropy distribution for a given mean, variance and domain." and I want to loosen the restrictions of given mean and variance without losing my parametres.
Comment: I don't want to have the maximum entropy out of all possible distributions. I want given domain but not given mean and/or variance (I just want a distributions which are a function of those). e.g $P(X = x\vert \mu,\sigma,a,b,c) = \frac{z^{-\frac{(x-\mu)^2}{2\sigma^2}}}{\sum_{y \in \Omega} z^{-\frac{(y-\mu)^2}{2\sigma^2}}}$ as z approaches 1 the distribution becomes a uniform distribution (at z=1 I lose location and scale parametres). For the same values of the parametres the domain stays the same but the variance increases and the entropy increases too.
Comment: If you want a maximum entropy distribution that is parametric distribution then you need to impose a restriction on the probability distribution, like variance or mean. This doesn't mean that those variance and mean need to be fixed, they can be parameters that are allowed to vary. But for a given variance, given mean and given range, you will have a discrete variation of the normal distribution with given values for location and scale parameters.
Comment: I didn't understand your comment. Please use as an example $P(X = x\vert \mu,\sigma,a,b,c) = \frac{z^{-\frac{(x-\mu)^2}{2\sigma^2}}}{\sum_{y \in \Omega} z^{-\frac{(y-\mu)^2}{2\sigma^2}}}$ as z approaches 1 the variance increases and so does the entropy. Given the same μ,σ,a,b, and c the variance (and the entropy) gets higher the closer z gets to 1. I just don't want to set z=1 because then I get a uniform and lose my location and scale parametres (they no longer have any interpretation or significance) and I am in a double bind because I can get arbitrarily close to 1. Is there an alternative?
Comment: *"I don't want to have the maximum entropy out of all possible distributions"* if you don't want this then you need to specify how you want to reduce the possible distributions. Just saying that the distribution needs to have parameters doesn't do it.
Comment: I just can't formulate mathematically the restrictions I want to impose. The restrictions are given domain but not given (emphasis on given) mean and variance. In the example I used above the distribution is a distribution over location and scale parametres. But there is a different relation with the variance each time (σ is not the same transformation of variance for all z). I find it difficult to express it using natural language (formulating it mathematically is even more difficult).
Comment: For the same values of a,b,c,μ,σ the variance is higher and the entropy is also higher as z gets arbitrarily close to 1.  The relation of the parametres and the variance is different as z varies. When z is 1 there is no relation at all. I understand what given in our context of maximum entropy means. I understand that it does not mean the mean and variance are completely fixed. But when z in my example varies the relation of σ and variance also changes. What is the maximum entropy distribution for given mean (in our context of maximum entropy distributions) and given domain (but not variance)?
Comment: Theoretical I want to ask what stays given when z changes (consider it a fixed hyperparametre). z=e doesn't satisfy me I can do much better. neither does z=2. In the end nothing satisfies me because I can always get closer to 1 but never set z=1 because otherwise my μ and σ would lose their significance. I want a distribution with these two parametres still being significant but given μ and σ (not the exact mean and variance) the entropy should be the maximum possible.
Comment: The exponential function is a single parametre family.
Comment: $\frac{1.0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001^{-\frac{(x-μ)^2}{2σ^2}}}{\sum_{y\inΩ}1.0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001^{-\frac{(y-μ)^2}{2σ^2}}}$ is a 2 parametre family.
Comment: I don't understand why "Just saying that the distribution needs to have parameters doesn't do it."
Comment: What exactly happens when z diminishes from (1,e] and the rest of the parametres remain the same? Somehow the entropy increases without the distribution losing μ and σ. Probably mean and variance stop being "given" considering that when z=e the distribution already is "maximum entropy distribution for a given mean, variance and domain."
Comment: Z is not a scale parametre it is a fixed hyperparametre it controls the family in much the same way A, B and C do. And now I am confused. If base e already is a maximum entropy for given domain, mean and variance how can base 2, base 1.5, base ->1 also be a maximum entropy for given domain, mean and variance? When one changes z it also changes mean and variance. Aren't the restrictions different when z is different so that the distribution is a maximum entropy distribution? Otherwise only 1 of them would be the maximum entropy distribution
Comment: But z is fixed (it is an assumption of the model or otherwise known for certain) while σ is estimated (being a tranformation of the standard error). Z is fixed in much the same way a,b, c are fixed. I am not certain what you mean with a change in parametrization. I control z (I can set it to any value I like) while I don't control σ (I am estimating it). I am making dreaded assumptions to calculate my likelyhood the specific value of z would be one of them (under my absolute control exactly like a,b,c). Please explain what you meant with change in parametrization.
Comment: I appreciate the values differ in a different way when all else is equal (excluding z) and when all else is equal (excluding σ). I also didn't capture what was meant with fit σ and μ with z=2. Could I use $\frac{z^{-\frac{(x-μ)^v}{2σ^w}}}{\sum_{y\inΩ}z^{-\frac{(y-μ)^v}{2σ^w}}}$ to calculate/define my likelihood are more than 2 parametres warranted? I am interested in a posterior predictive distribution (and maybe a posterior distribution for the mean and variance) I would use this distribution (the observations are known to be positively correlated) for the likelihood and a uniform for a prior
Answer: The most natural way would be as follows:
Let $X$ have support $0,1,...T$, where $T \in \{2,3,...,\}$ (i.e T can be taken as the limit to $\infty$, since the infinite sum can be bounded by the integral over the kernel of a gaussian pdf, but it will be intractable to work with in practice).
$$f_X(X=x;\mu, \sigma) = \frac{exp(-\frac{(\mu -x)^2}{2\sigma^2})}{\sum_{y=0}^Texp(-\frac{(\mu -y)^2}{2\sigma^2})}$$
This is a special case of the softmax function ($\frac{exp(z_i)}{\sum_{i=1}^Nexp(z_i)})$, which is commonly used to map the reals to the interval $(0,1)$ with the property that the elements sum to 1. There are many choice models which take this form, such as the multinomial logit, with $T < \infty$.
I agree with @Xi'an, however, that defining a pmf this way is unlikely to be justified. It is hard to imagine a principled construction of what this would represent and as Xi'an stated, the properties of a gaussian that make it nice to work with are not inherited by this new model.
Comment: The justification is simple I hate approximations. My data are bound both from below and above and much more significantly are discrete. I don't want a distribution which is easy to work with I want an acurate distribution (or the closest possible to that) even if I end up with something hard to work with. What other distributions f(μ,σ,x,z,y) are there (which are both discrete, and bounded from both sides). What properties do those distributions have that my constructed distributtion would lack?
Comment: reading the other comments, are you modelling the responses to each question i for data set j? Or the number of correct responses in each data set j?
Comment: Most probably the second. There are i students (and i exams) that each received the same 25 questions (different each year). The results are positively dependent (students who know/believe that they will do well tend to sit the exams more often, so on years with better teaching and/or a smarter cohort the sample is larger and the mean is larger too because of self-choice students themselves choose to sit the exam or not). I consider each year a different population (different students unless some failed and choose to retake it and different 25 question).
Comment: I want to infer 2 things a) how good was the performance of the specific student (my metric is [Their score / (The mean of all other students + The standard error of all other students)] and I take the weighted harmonic mean of the "Standardized" score between all their subjects. b I want to make inference on the Teaching that year. the mean might have dropped either because the test makers gave difficult questions or because the teachers taught poorly that year (or the cohort were stupid).
Comment: You could use a binomial model, where p_i is the probability of success for each class. If you wanted to try and separate the effects of teaching and the effect of the cohort it will be tricky. The two main approaches would be to find covariates with sufficient information to control for the strength of the class (maybe mark from previous year or gpa generally) and model p_i as an inverse logit which is a function of a parameter for the class and then the covariate information. The other typical route would be to model the selection process itself and use a weighted estimator.
Comment: But the data are not binary. They are not Pass/Fail. It is about how(quantity/magnitude) well that class performed on average on each subject (the teacher might be bad or used poor teaching methods that year, the test might have be difficult, the class might have been stupid).
Comment: each student can be modelled as from a binomial still. For each question, they either get the question right or wrong. If we suppose that conditional on $p_i$, the probability of a student in class i answering the question correctly, then each response within a student is independent we get a binomial with n=25 for each student. Now as mentioned before we model $p_i = logit^{-1}(\mu_i + X_i\beta)$. i.e, we model the probability within each class as being related to $u_i$ a parameter that helps set the class average and some covariates about the class $X_i$, like say grades in other classes.
Comment: Then you can back out the means for each class after the fact. This model does not assume that students pass or fail.
Comment: Again, to make the causal claims you would like it will still be tricky.
Comment: Binomial with known trials (here n =25) is exponential family as per some of your requirements above also.
Comment: and it also deals with concerns about being discrete over 0 to 25, and if it is not clear, the mean for each class will be $25*p_i = 25*logit^{−1}(\mu_i + X_i\beta))$. Using your estimates (which can be handled easily in any glm package, you can get estimates of the class means and then variance in a similar and construct your measure for how well each student did. The binomial can also be see as maximum entropy defined with respect to the mean or over suitable sets. https://cpb-us-w2.wpmucdn.com/u.osu.edu/dist/7/36891/files/2017/07/ech4-18a6gg9.pdf
Comment: I am not interested in each individual student. x_i is the number of Correct Answers student i got. X_i are certainly not independent they might not be linearly correlated but there is a strong positive dependence (the students are self-selected not randomized the teacher's transmissivity, the quality of the teacher's method, the difficulty of the test affect all of them, the students who know they will do well will sit the exam, usually a better teacher implies more confident students).
Comment: What I am trying to say is whether they got the specific question right or wrong is not important. I am not trying to model Bernouli Trials.
Comment: Let us [continue this discussion in chat](https://chat.stackexchange.com/rooms/117219/discussion-between-tyrel-stokes-and-george-ntoulos).
Comment: I tried rewording the entire question.
Comment: Isn't the question now clear and unambiguous?
Comment: For me, my answer to your question is still the same and you didn't like it. To me, it makes more sense to model the data generating process directly and then compute quantities of interest after. In general, condition 1 will be hard to satisfy and may be extremely difficult in a way that makes sense with the data generating process. If you don't like that, then I would suggest looking at non-parametric estimators of your quantities of interest, however as I said before that won't fix your problem with controlling for the strength of the class without additional covariates and modelling.
Comment: But maybe someone else will come along with a different solution, who knows. Good luck!
Comment: I loved your answer. What made you thing that I didn't like it? You were the only person that gave me what I asked for. A distribution. I don't understand your suggestions to. 1. "model the data generating process directly and then compute quantities of interest after" and 2. "looking at non-parametric estimators of your quantities of interest, however as I said before that won't fix your problem with controlling for the strength of the class without additional covariates and modelling". What do you mean?
Comment: Could you pleast explain 1. what made you feel that I didn't like your question, 2. what do "model the data generating process directly and then compute quantities of interest after" and "looking at non-parametric estimators of your quantities of interest, however as I said before that won't fix your problem with controlling for the strength of the class without additional covariates and modelling" mean?
Comment: Just to make sure you understood my question. I don't want to make an inference on the classes' performance but I want to describe the observed classes' performance instead. I don't want inferential statistics but descriptive statistics. You could say the description is an end in itself. And that was all the question was asking about. I want this distibution to describe the performance. Probably the distribution I am asking for would be a conjugate prior to a posterior generated from a discrete uniform (with constant intervals) prior and normal or truncated normal data.


variables declared inside for loop which is inside a function - global or local(function)?

Question: suppose, if a for loop is inside a function, and I declare a variable inside for loop, will that variable be global variable or local variable confined to that function in which the for loop is present?
Answer: For the most part, loops do not have their own scope, so the variable's scope will be the scope of wherever the for loop lives. With that in mind, if the for loop is within a function, it will have local scope. One exception would be using let x = something in Javascript. This would release the memory at the end of the loops iteration.
Comment: Thanks for your response, robcarney. if I place the below for loop --> for(var i=0; i<5;i++) inside a function and then console.log(i) outside the function, it still displays i=0. Doesn't that mean that the variable i is accessible outside the function making it a global variable?
Answer: Your question depends on a lot of factors i.e. programming language and the way you are declaring or using a variable.
For example in js:-
var y = 5;
function foo() {
    var x = 2;
    z = 5;
}

var x here is a local variable i.e. it cannot be used anywhere other than in the function foo.
var y on the other hand can be used globally as it is declared in the global scope
var z is not declared but it has been used to assign a value to it, so in javascript such a variable is considered to be declared in the global scope. So, it can be used outside the function foo


How to get more info on this PDO MySql error with Zend

Question: In my PHP script I run an update statement as follows:
$this->_db->update('names', $data, $this->_db->quoteInto('id = ?', $obj->id));

The db handle is a Zend_Db_Adapter_Abstract instance (of the PDO MySql variety).
The problem is that the update is failing and I can't seem to get more info on the error.
The error occurs within a try/catch block.  When I catch the error, I run:
$db->getProfiler()->getLastQueryProfile();

And the output is:
2012-11-14T22:20:02+11:00 INFO (6): Zend_Db_Profiler_Query Object
(
    [_query:protected] => begin
    [_queryType:protected] => 64
    [_startedMicrotime:protected] => 1352892002.6064
    [_endedMicrotime:protected] => 1352892002.6066
    [_boundParams:protected] => Array
        (
        )

I know it says no parameters are bound, but I really don't think that's the case.  I think that somehow 'last query' is not what I think it is.
Secondly, when I catch the error I also run:
$db->getConnection()->errorInfo();

And the output is:
2012-11-14T22:20:02+11:00 INFO (6): Array
(
    [0] => 00000
    [1] =>
    [2] =>
)

Obviously this is not very helpful.
Any ideas?  How can I get more info on the error?
Thanks!
Answer: You can force PDO to throw exceptions with all the info:
<?php

$this->_db->->getConnection()->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

try {
    $this->_db->update('names', $data, $this->_db->quoteInto('id = ?', $obj->id));
}
catch (Exception $ex) {
    print_r($ex);
}


.click() affect only one element with class

Question: I've got the list of news, with short and full text, and a title of the news article. Clicking on it expands full view and vise versa. Yet clicking on first article also expands all other articles. How do I only affect the one I clicked?
Here's the example:
$(document).ready(function () {
    $('.news-expand').click(function () {
        $(".news-content-short").toggle();
        $(".news-content-full").toggle();
        $('.news-date').toggleClass('active-date');
        $('.news-expand').toggleClass('active');
    });
});

Answer: You need to act on only the items in the section you clicked. The code for that would be like:
$(document)
    .ready(function () {
    $('.news-expand')
        .click(function () {
        var par = $(this).parents('.main-news-holder');
        par.find(".news-content-short").toggle();
        par.find(".news-content-full").toggle();
        par.find('.news-date').toggleClass('active-date');
        par.find('.news-expand').toggleClass('active');
        return false;
    });
});

Check this demo: http://jsbin.com/ikijap/1/edit
Comment: Actually, You're better off using closest, instead of parents. Else you're using a function that was intended to do more than you're using it for.
Comment: .click(function (e) {
e.preventDefault();
Answer: You're problem is not that your click event is called based on class, but that in your click event you're acting on every item in the class.
Instead, use this
For more details on the click event, see JQuery's API
Answer: This is because you are always working on all items of the set. So e.g. $(".news-content-short").toggle(); toggles all items with the according class and not only the one you want.
The following should work:
$('.news-expand').click(function () {
      $parent = $(this).parents(".main-news-holder");
      $parent.find(".news-content-short,.news-content-short").toggle().end()
             .find('.news-date').toggleClass('active-date').end()
             .find('.news-expand').toggleClass('active');
});

Your example working
Answer: $(document)
    .ready(function () {
    $('.news-expand').click(function () {
        var parent = $(this).closest('.main-news-holder');
        $(this).toggleClass('active');
        parent.find(".news-content-short").toggle();
        parent.find(".news-content-full").toggle();
        parent.find('.news-date').toggleClass('active-date');
    });
});

Comment: actually, you have to go `$(this).parent().parent().parent()` ^^
Answer: You will need to get to the parent div and after that you can hide/show the correct divs.
Check the jsbin demo here: http://jsbin.com/irihax/14/
$(document)
    .ready(function () {
    $('.news-expand')
        .click(function () {
          var mainDiv = $(this).parent().parent().parent();
        mainDiv.find(".news-content-short").toggle();
        mainDiv.find(".news-content-full").toggle();
        mainDiv.find('.news-date').toggleClass('active-date');
        mainDiv.find('.news-expand').toggleClass('active');
    });

});

Comment: Using the parents function provided by @techfoobar is better.
Answer: By rearrange the html code,
<!DOCTYPE html>

        <meta charset=utf-8 />
        <title>JS Bin</title>

1 sep

Show more

short short short short short

text text text text text text text text text text text text text text
                            text text text text text text text text text text text text text text text
                            text text text text text text text text text text text text text text text
                            text text text text text text text text text text text text text text text
                            text text text text text text text text text text text text text text text
                            text text text text text text

2 sep

Show more

short short short short short

text text text text text text text text text text text text text text
                            text text text text text text text text text text text text text text text
                            text text text text text text text text text text text text text text text
                            text text text text text text text text text text text text text text text
                            text text text text text text text text text text text text text text text
                            text text text text text text

Hope this will help.


IPC::Open2 output to already open file handle as per doc example

Question: The documented example in perldoc IPC::Open2 (read from parent STDIN and write to already open handle) is  a simplified version of what I'm trying to achieve. Namely, parent writes a preamble to a output file, then a subprocess writes its output directly to the same file.
I've made a simple child script which reads input lines and prints to STDERR and STDOUT. The STDOUT being the the 'already open handle' from the parent.
#!/usr/bin/env perl
##parent.pl
use IPC::Open2;

# read from parent STDIN and write to already open handle
open my $file, '>', 'outfile.txt' or die "open failed: $!";
my $pid = open2($file, "<&STDIN", "./child.pl");

# reap zombie and retrieve exit status
waitpid( $pid, 0 );
my $child_exit_status = $? >> 8;

#!/usr/bin/env perl
##child.pl

while(<STDIN>){
    print STDOUT "STDOUT: ",$_;
    print STDERR "STDERR: ", $_;
}
print STDERR "END OF CHILD\n";

An  example run of parent.pl:
Hello
^D
STDERR: Hello
STDERR: END OF CHILD

However, I don't see the expected "STDOUT: Hello" in the output file 'outfile.txt'
Is there some additional setup I've missed to get this example to work?
Answer: open my $file, '>', 'outfile.txt' or die "open failed: $!";
my $pid = open2($file, "<&STDIN", "./child.pl");

This will create a new pipe, and overwrite the $file variable with a handle refering to the read end of the pipe, closing the old file handle in the process ;-)
In order to pass an existing file handle to open2 or open3, you want to use the >&FILEHANDLE format, but I wasn't able to figure out any way to do that when FILEHANDLE is a local variable, as your my $file.
But the undocumented >&NUM or >&=NUM forms (where NUM is a file descriptor number) just work:
open my $file, '>', 'outfile.txt' or die "open failed: $!";
my $pid = open2('>&'.fileno($file), '<&STDIN', './child.pl');

Example:
$ perl -MIPC::Open2 -e '
   open my $f, ">foo";
   open2(">&".fileno($f), "<&STDIN", "echo bar")
'; cat foo
bar

Comment: This is `IPC:Open2`. Plain `open` also supports `open my $f, '>file'; open my $g, '>&', $f` nicely, which `IPC::Open2` apparently does not ;-)
Comment: Thanks for the tip here, solved my problem.  Much easier than the manual fd duplications I was doing to get it to work!


Does a guide for installation of drupal Cartaro distribution exist?

Question: I have been trying to install the Cartaro distribution of drupal on windows that makes drupal
a complete geo-stack. I have been unable to find complete documentation for the same and the
installation fails to detect postgis installed on the computer as well as there is some confusion about the terminology for geoserver.
Answer: Have a look at Cartaro's Getting Started guide. Especially see the quoted commands to set up permissions for PostGIS properly.
Additionally, there have been changes to the error reporting of Cartaro in July which should result in more precise error messages in case something is wrong with PostGIS.
Please report any bugs in Cartaro using its bug tracker on the Drupal site so that is does not get overlooked. We'd be happy to see a report there regarding the GeoServer terminology along with a more verbose description.


Boundedness of a sublevel set of a convex function

Question: Let $f : \mathbf R^n \to \mathbf R$ be a convex function with $f(0)=0$ and $\displaystyle\lim_{t\to\infty}f(tx)=\infty$ for any $x\in\mathbf R-\{0\}$. Is $$A:=\{x \mid f(x)\le 1 \}$$ bounded?

I was thinking about projecting $A$ onto the unit spherical surface, but did not know how to proceed.
Comment: From Rockafellar's "Convex Analysis", Theorem 8.4: "*A non-empty closed convex set $C$ in $\mathbb{R}^n$ is bounded if and only if its recession cone $0^+C$ consists of the zero vector alone*".
Comment: @copper.hat: Thank you for pointing out this is a classical result.
Answer: We already know that $A$ is convex as the sub-level sets of a convex function are convex.  If $A$ is unbounded, then for every $x\in A$, there is some nonzero vector $h_{x}$ such that $x+th_{x}\in A$ for all $t\geq 0$. Since $f(0)=0$, we can find $v:=h_{0}$ so $th_{0}\in A$ for all $t\geq 0$. Thus, $f(th_{0})\leq 1$ for all $t\geq 0$. This contradicts that $\lim_{t\to\infty} f(th_{0}) = \infty$.
Comment: Just a comment, as shown in the link, it's  important that $A$ is closed.
Comment: @Balgani: It is sufficient in this case to have $0 \in \operatorname{ri} A$, and since $0 \in A^\circ$ that is satisfied.
Comment: +1. Nice answer. I hope you do not mind me accepting mathcounterexample.net's answer as the proof of his for the existence of ray is simpler than the accepted answer of the linked question.
Answer: $A$ is indeed bounded
We can prove it by contradiction, using the result that for finite dimensional real vector spaces an unbounded convex subset contains a ray. See my website for the proof.
$A$ being a level set of $f$ is convex and not empty as $0 \in A$. $0$ is even an interior point of $A$ as $f$ is continuous. According to the result above, $A$ contains a ray $[0, \infty v )$ with $v \in A$. By definition of $A$, the value of $f$ on this ray is less or equal to $1$. In contradiction with the hypothesis $\displaystyle\lim_{t\to\infty}f(tv)=\infty$.
Comment: How does this differ from the answer below?
Comment: @copper.hat: I suppose the difference is that the proof here of "an unbounded closed convex subset of a finite dimensional real vector space contains a ray" is simpler than the accepted answer in the linked question in the answer of Wraith1995.


Accessing XAML (WPF) elements in F#

Question: I'm trying to create a reactive application in F# using WPF and I have encountered some problems with accessing XAML elements from the code.
In the XAML-file I have created a grid containing 16 columns and rows each:
        <StackPanel Name="cellStackPanel">
        <Grid Name="cellGrid" Height="500" Width="500" Margin="10,10,10,10" Background="#CCCCCC">
            <Grid.Resources>

            </Grid.Resources>
            <Grid.RowDefinitions>
                <RowDefinition Height="*" />
                <RowDefinition Height="*" />
                <RowDefinition Height="*" />
                <RowDefinition Height="*" />
                <RowDefinition Height="*" />
                <RowDefinition Height="*" />
                <RowDefinition Height="*" />
                <RowDefinition Height="*" />
                <RowDefinition Height="*" />
                <RowDefinition Height="*" />
                <RowDefinition Height="*" />
                <RowDefinition Height="*" />
                <RowDefinition Height="*" />
                <RowDefinition Height="*" />
                <RowDefinition Height="*" />
                <RowDefinition Height="*" />
            </Grid.RowDefinitions>
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="*" />
                <ColumnDefinition Width="*" />
                <ColumnDefinition Width="*" />
                <ColumnDefinition Width="*" />
                <ColumnDefinition Width="*" />
                <ColumnDefinition Width="*" />
                <ColumnDefinition Width="*" />
                <ColumnDefinition Width="*" />
                <ColumnDefinition Width="*" />
                <ColumnDefinition Width="*" />
                <ColumnDefinition Width="*" />
                <ColumnDefinition Width="*" />
                <ColumnDefinition Width="*" />
                <ColumnDefinition Width="*" />
                <ColumnDefinition Width="*" />
                <ColumnDefinition Width="*" />
            </Grid.ColumnDefinitions>
        </Grid>
    </StackPanel>

In F#, I traverse through the grid and programatically initialize every cell into ToggleButtons:
    let initCell (x,y) (grid : Grid) =
        let cell = ToggleButton()
        Grid.SetColumn(cell, x)
        Grid.SetRow(cell, y)
        ignore (grid.Children.Add(cell))

Now I want to create an observable (to wait for in a recursive asynchronous loop) for clicking any of my ToggleButtons. I can access the grid element itself within the code but my problem is that I don't know how to access its child elements that I've created programatically. I was thinking of a, perhaps rudimentary, solution which is to catch the click event from the entire grid, and at the same time get the mouse coordinates to calculate which cell was clicked. But that is probably not a good way to do this.
I hope my question is understandable, otherwise, let me know.
Comment: Why don't you use FsXAML + FSharp.ViewModule?
Comment: You should start by looking into the MVVM pattern, to put it very very briefly, the idea is that you have a fairly strict separation of the code responsible for layout (XAML), UI logic and business logic.  It operates through data binding and results in you almost never needing to programmatically address UI elements.
Comment: I wrote the answer, if it's not quite what you wanted, I will edit it.
Comment: Great. If ever you decide to use FsXAML or FSharp.ViewModule, then just do the ping in the chat - http://chat.stackoverflow.com/rooms/51909/f - I will be glad to help
Comment: you can loop `grid.Children` when necessary and retrive ToggleButtons
Comment: also: it is possible to create RowDefinitions and ColumnDefinitions in loop. Or just use `UniformGrid Columns="16" Rows="16"` instead of `Grid`
Comment: @ASh You are right, I guess I could loop through the Children UIElementCollection. But I'm not sure how to get their click events to merge them all together into one single observable. Could you provide an example of how to do this? Observable.merge only takes two sources, and I do not want to build a lengthy nested merge with hundreds of rows.
Comment: @FoggyFinder I'm not really familiar with FsXAML and FSharp.ViewModule. Would you like to tell me briefly how it solves my problem? Thanks in advance.
Comment: @Filip Lagerholm , Sorry for the wait. Yes, it will be much easier. I don't quite understand what you want to get in the end. If you write more I can write an example.
Comment: please do not ignore me. If my answer is not what you need just write about it.
Comment: @FoggyFinder Thanks for your response and for taking the time to help. I have not had the opportunity to test your solution yet. I managed, before you wrote, to get around my problem by using my second solution.
Comment: @FoggyFinder Instead of defining columns and rows manually and then loop through each cell to initiate buttons, I just observe the mouseDown event for the UI element, extract the mouse cursor position, and finally calculate the corresponding grid coordinates. It actually turned out very concise and dynamic. Conceptually, however, I believe that your solution can work. Unless someone else with similar problems find this thread and does it before, I hope to be able to take a closer look at what you are proposing.
Answer: As I said in the comment easier to use FsXAML + FSharp.ViewModule.
I don't quite understand what you want to, so a simple example:
 <Grid>
        <ListBox
            ItemsSource="{Binding Cells}"
            HorizontalContentAlignment="Stretch"
            VerticalContentAlignment="Stretch">
            <ListBox.ItemsPanel>
                <ItemsPanelTemplate>
                    <UniformGrid Rows="{Binding N}" Columns="{Binding N}"/>
                </ItemsPanelTemplate>
            </ListBox.ItemsPanel>
            <ListBox.ItemTemplate>
                <DataTemplate>
                    <ToggleButton Content="{Binding Text}"
                                  IsChecked="{Binding IsChecked}"
                                  Command="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ListBox}},
                                                    Path=DataContext.ClickCommand}"
                                  CommandParameter="{Binding RelativeSource={RelativeSource Self},Path=DataContext}"
                                  >

                        <ToggleButton.Style>

                        </ToggleButton.Style>
                    </ToggleButton>
                </DataTemplate>
            </ListBox.ItemTemplate>
            <ListBox.ItemContainerStyle>

            </ListBox.ItemContainerStyle>
        </ListBox>
    </Grid>

You can use ItemsControl instead of ListBox, but configuring it will take some time =)
.fs:
type State = {mutable IsChecked:bool; Text:string}

type MainViewModel() as self =
    inherit ViewModelBase()

    let n = 16
    let data = [1..n*n] |> List.map(fun i -> {IsChecked = false; Text = string i})

    let click (state:obj) =
        let st = (state :?> State)
        MessageBox.Show(sprintf "%s %b" st.Text st.IsChecked ) |> ignore

    let clickcommand =  self.Factory.CommandSyncParam(click)

    member __.ClickCommand = clickcommand
    member __.Cells = data
    member __.N = n

Thus, you can do anything with your object in the function click.
P.S. I allowed myself to change a little your ToggleButton style to the picture was more clearer.
Answer: I'm not a big fan of 3rd party solutions as an answer.  If I understand your question, you are trying to access an element that was specified in your XAML.  This can be easily done by converting your XAML to a string type then using:
let xamlBytes = Encoding.UTF8.GetBytes(xamlString)
let xamlStream = new MemoryStream(xamlBytes)
let xamlRoot = XamlReader.Load(xamlStream)
let rootElement = xamlRoot :?> FrameworkElement
let elementYouNeed = rootElement.FindName("nameOfElementYouNeed") :?> TypeOfElementYouNeed

Your case might be slightly different but this is the general idea.

Accessing XAML (WPF) elements in F#


Multi-Head attention layers - what is a warpper multi-head layer in Keras?

Question: I am new to attention mechanisms and I want to learn more about it by doing some practical examples. I came across a Keras implementation for multi-head attention found it in this website Pypi keras multi-head. I found two different ways to implement it in Keras.

One way is to use a multi-head attention as a keras wrapper layer with either LSTM or CNN.
This is a snippet of implementating multi-head as a wrapper layer with LSTM in Keras. This example is taken from this website keras multi-head"

import keras
from keras_multi_head import MultiHead

model = keras.models.Sequential()
model.add(keras.layers.Embedding(input_dim=100, output_dim=20, name='Embedding'))
model.add(MultiHead(keras.layers.LSTM(units=64), layer_num=3, name='Multi-LSTMs'))
model.add(keras.layers.Flatten(name='Flatten'))
model.add(keras.layers.Dense(units=4, activation='softmax', name='Dense'))
model.build()
model.summary()

The other way is to use it separately as a stand-alone layer.
This is a snippet of the second implementation for multi-head as stand-alone laye, also taken from keras multi-head"

import keras
from keras_multi_head import MultiHeadAttention

input_layer = keras.layers.Input( shape=(2, 3), name='Input',)
att_layer = MultiHeadAttention( head_num=3, name='Multi-Head',)(input_layer)
model = keras.models.Model(inputs=input_layer, outputs=att_layer)
model.compile( optimizer='adam', loss='mse', metrics={},)

I have been trying to find some documents that explain this but I have not found yet.
Update:
What I have found was that the second implementation (MultiHeadAttention) is more like the Transformer paper "Attention All You Need". However, I am still struggling to understand the first implementation which is the wrapper layer.
Does the first one (as a wrapper layer) would combine the output of multi-head with LSTM?.
I was wondering if someone could explain the idea behind them, especially, the wrapper layer.
Comment: Have you try this https://www.tensorflow.org/api_docs/python/tf/keras/layers/MultiHeadAttention
Comment: No. I haven't try it.
Answer: I understand your confusion. From my experience, what the Multihead (this wrapper) does is that it duplicates (or parallelize) layers to form a kind of multichannel architecture, and each channel can be used to extract different features from the input.
For instance, each channel can have a different configuration, which is later concatenated to make an inference. So, the MultiHead can be used to wrap conventional architectures to form multihead-CNN, multihead-LSTM etc.
Note that the attention layer is different. You may stack attention layers to form a new architecture. You may also parallelize the attention layer (MultiHeadAttention) and configure each layer as explained above. See here for different implementation of the attention layer.
Comment: Do you know if there is any similar resource for pytorch? With same examples for multihead-lstm...


splitting selecting rows from a table based on page number of table ASP net SQL

Question: I thought how to get more performance to show data from a table with thousands of rows and that i could split a select in parts.
For example, I have a Repeater in ASP NET and only shows 10 rows at the time. I want to select only 10 rows from the table, on next page it selects the next 10 rows and so on.
the problem is that I can't find anything to give me a head on on this problem and I was hoping someone with knowledge of this could refer me to some good start ups, thank you.
Comment: Possible duplicate of [Implement paging (skip / take) functionality with this query](https://stackoverflow.com/questions/13220743/implement-paging-skip-take-functionality-with-this-query)
Comment: Check how OFFSET and FETCH work.
Answer: Try this Sample Sql script
first it select only 10 rows from the table, on next page it selects the next 10 rows and so on.
<code>DECLARE @i_PageIndex INT=1,-- change page index 1 and 2 .. you we get the exact difference
        @i_PageSize INT=10

SELECT COUNT(1) OVER() AS recordCnt,
       ROW_NUMBER()OVER(ORDER BY TABLE_NAME) AS Seq,
       *
FROM INFORMATION_SCHEMA.COLUMNS
ORDER BY ROW_NUMBER()OVER(ORDER BY TABLE_NAME)
OFFSET(COALESCE(@i_PageIndex, 1) - 1) * @i_PageSize ROWS FETCH NEXT @i_PageSize ROWS ONLY
</code>
Comment: This seems to do what i need. Thanks


Advection-style first order nonlinear PDE system

Question: Given functions $a(t,x,y) > 0, d(t,x) >0$ and constants $b,c > 0$, I would like to find the three functions $u(t,x),v(t,x) , w(t,x,y)$ that solve the system:
\begin{align}
u_t - u_x &= -\left(\int_0^x a(t,x,y)\mathrm{d}y+b\right) u(t,x) + c v(t,x) + w_y(t,x,0) + d(t,x)\\
v_t - v_x &= b u(t,x) - c v(t,x) + b \int_0^x w(t,x,y) \mathrm{d} y\\
w_t - w_x - w_y &= a(t,x,y) u(t,x)  - b w(t,x,y),
\end{align}
and satisfy $u(t,0)=v(t,0)=w(t,x,0) = 0$.
Interpretation : the state of a job allocating platform

$u,w,v$ - is the number of workers $u$noccupied, $w$orking or on a sick lea$v$e.
$x$ - is the remaining duration of the working contract, by the end of which a worker leaves the system
$y$ - is the remaining duration of a job assignment
$a(t,x,y)$ - is the probability of being assigned a job of duration $y$ at date $t$
$d(t,x)$ - is the number of new workers joining the platform at date $t$ for the duration $x$
$b,c$ - is the chance of falling ill and that of recovering.

Once a job assignment is over ($y=0$), the busy worker joins the ranks of the unoccupied (the $w_y(t,x,0)$ term in the $u$-equation). Once the contract is over ($x=0$) the worker leaves the platform.
I kind of found the solution to a linear 1st order PDE system in the Andrei D. Polyanin's bestiary, but am absolutely at loss about what to do with the $w_y(t,x,0)$ and $\int w \mathrm{d}y $ terms.
Although not exactly a model of a physics phenomenon, this system looks like something that the physicists are most likely to be familiar with.
I would be immensely grateful for the solution and/or all the pointers to the sources treating this kind of problems (lectures, keywords, etc.).
Update
Noticing that for every worker the date of retirement, $T_x$,  and for every job the date of expiry, $T_y$, are constants, I can use the substitution $x = T_x - t$ and $y = T_y - t$ to transform equations 2 and 3 into ODEs, solve them and reverse the substitution to obtain $w,v$ in terms of $u$:
\begin{align*}
w(t,x,y) & = \int_0^t \int_{s}^{y+s} \mathrm{e}^{-b s} a_y(t-s,x+s,\xi) u(t-s,x+s) \mathrm{d}\xi \mathrm{d} s \\
v(t,x) & = b \int_0^t \int_{s}^{x + s} \mathrm{e}^{-cs} u_x(t-s,\xi) + W_x(t-s,\xi) \mathrm{d} \xi \mathrm{d} s.
\end{align*}
where
\begin{equation*}
    W(t,x) := \int_0^x w(t,x,y) \mathrm{d} y,
\end{equation*}
is the total size of the busy group across all job durations.
Plugging these expressions into the first equation one gets the following PDE in $u$:
\begin{align}
u_t =& u_x - \left(\int_0^x a\mathrm{d}y +b \right) u \\
     & + cb \int_0^t \int_{s}^{x + s} \mathrm{e}^{-cs} u_x(t-s,\xi)\mathrm{d} \xi \mathrm{d} s \\
     & + cb \int_0^t \int_{s}^{x + s} \mathrm{e}^{-cs} W_x(t-s,\xi) \mathrm{d} \xi \mathrm{d} s \\
     & + \int_0^t \mathrm{e}^{-bs} a_y(t-s,x+s,0) u(t-s, x+s) \mathrm{d}\xi \\
     & + d(t,x).
\end{align}
Comment: @Emilio I went through every question in the cited Meta posts, and I find it unfair to put my post in the same basket. I honestly started from an actual problem, formalized it and brought it to the people who solve problems about the real world. Think of Feynman's rotating plate. Or that "share of visible surface" question, you so gloriously answered. How is that one about pure physics? It reeks of (analytical) geometry
Comment: @Vadim You're welcome to litigate the scope of mathematical physics as it is understood on this site, and the topicality of questions on the "broader applicability" of physics methods to non-physics questions, on Meta. As of this writing the consensus is very clear (and documented e.g. [here](//physics.meta.stackexchange.com/q/5713), [here](//physics.meta.stackexchange.com/q/7140) and [here](//physics.meta.stackexchange.com/q/164)). If you think it should change, by all means argue for it -- **in Meta** where the debate will be visible.
Comment: The question as asked belongs on the maths site. Cross-posting in this way is not appropriate -- the question needs to be explicitly edited to address each site you post it on, and saying "this is a mathematical problem that physicists might be familiar with" (note: physicists, not physicians) is not sufficient tailoring nor sufficient grounds to be on-topic here. (Questions need to be *about* physics, not just have a tangential connection.) Moreover, if you do cross-post, you need to clearly label this on every copy.
Comment: My apologies, Emilio, I am sorry to have broken the rules, but it turns out the math site is a swamp, whereas here I got a useful comment 10 min after posting.
Could you please point me to the instructions on how to cross post properly without recasting the model as one of a physics phenomenon? I am not fluent in physics since highschool, I'm an economist.

The "physicians" joke is very funny :)
Comment: @ Konstantin I'm sure the "physicians" joke is funny the first couple of times, but it's worth considering your audience before using it.
Comment: The general cross-posting guidelines are [here](https://meta.stackexchange.com/questions/64068). If you're looking for the guidelines regarding how to post here a question that is not about physics without putting in any work to make it about physics, then, as you should be able to guess, there aren't any. If MSE doesn't provide answers, then the standard methods of bringing attention to a question apply. Regarding the answer you got here, there's nothing physics- nor physicist-specific about it. This thread belongs on MSE.
Comment: @EmilioPisanty the value of physics is that it is applicable well beyond studying "physical phenomena". Physicists are in great demand due to the ability of creating models for a wide range of phenomena. The question clearly belongs to the domain of "mathematical physics".
Comment: @Vadim As e.g. Wikipedia describes it, mathematical physics refers to "the development of mathematical methods for application to problems in physics". This question does nothing of the sort. There's nothing wrong with this question, but it is simply not about physics. The question of whether this site should be open to questions that are not about physics, (being instead about math that could benefit from the eyes of a physicist) has been litigated multiple times on Meta. If you or Konstantin feel it should be revisited, then it should be -- on Meta.
Comment: @EmilioPisanty while wikipedia is a useful source, it is not an authority, as the articles are often written by people with limited knowledge. Specifically, in the FSU countries "mathematical physics" refers to methods of solving PDEs - books and university courses are named this way. Same can be said about non-linear theory (aka "theory of oscillations"). Finally, your answer does not address my main argument about broader applicability of our methods.
Answer: I think this is a nice example of a system of equations solvable by the Laplace transform (I suppose that we are interested only in $x,y>0$ here):
$$
\bar{u}(p,t)=\int_0^{+\infty}dx u(x,t)e^{-px}, etc.
$$
This should reduce it to a system of linear ordinary differential equations in respect to time, which can be solved. Then one uses the Laplace transform table to try to obtain the solution in $(x,t)$ variables.
Update.
Another rather general approach that works particularly well for the first order PDEs is the method if characteristics (see the section "Two-dimensional theory" here).
Comment: You transform it in respect to both $x$ and $y$. Obviously, you have two different laplace variables (e.g., $p$ for $x$, and $s$ for $y$)
Comment: Thanks for your interest? I could totally do that if I had a single locational variable, but what should I do with the $w(t,x,y)$ equation?
Comment: So, I have two complex arguments in the transformed system? Ok, I had a hunch but didn't dare to proceed
Comment: It may make things more clear, if you denote these variables as $p_x, p_y$ - then it looks analogous, e.g., to solving a wave equation is several dimensions.
Comment: I don't know what to do with the LTs of $w_y(t,x,0)$ and $\int_0^x w(t,x,y) d y$. $a(y)$ also looks innocent only in this special case, if I allow it to depend on $t,x$ I get convolutions in LT equations.
Comment: @Konstantin if you post more details about how you approach it, I will try to help. Note also the additional suggestion that I added to my answer.
Comment: Let us [continue this discussion in chat](https://chat.stackexchange.com/rooms/116975/discussion-between-konstantin-and-vadim).


Multiple powershell scripts crashing at the same time using timer

Question: I have 3 independent powershell scripts all called separately that all do very similar things.  A timer is setup in each to check CVS files every 5 minutes and display the results as an icon in the task bar in Windows.  They query different CSV files but the layout is similar as below:
<code>//setup my variables
$poll_timer = New-Object System.Timers.Timer($poll_interval * 1000 * 60)
$poll_timer.Start()

function check_CSV{
    query the CSV
    $Icon.Icon = $whichImage
...
}
$poll = {
    check_CSV
}
Register-ObjectEvent $poll_timer -EventName Elapsed -Action $poll
</code>
All works well and they run all day.  However, 2 or 3 times a week, they crash so the polling stops.  What I find weird though is that all 3 crash and stop polling.  Powershell still works if I run a different script, but these 3, which are all called independently, all crash at the same time.
I have put $ErrorActionPreference = "silentlycontinue" at the top and it doesn't seem to make any difference.  I can't see why they crash, it just occasionally seems to hang whilst running the checking of the CSV.
Thanks in advance.
Comment: Is your code using try catch `try{$poll = {
    check_CSV
}}catch{}`
Comment: No.  But I can do!
Comment: I would add some logging to confirm each step, but I suspect that the CSV files are inaccessible so now and then (e.g. because they being exported from ?Excel?). JPBlanc suggestion might indeed resolve such issue but your `SilentlyContinue` might also cause that you dealing with invalid data (empty or from a previous poll)...
Comment: if you are simply checking for a file ... have you tried using the built in method for handling that? [*grin*] this .... FileSystemWatcher Class (System.IO) | Microsoft Docs — https://learn.microsoft.com/en-us/dotnet/api/system.io.filesystemwatcher?view=netframework-4.7.2 ///// it can watch for a file using standard system resources and you won't have the PoSh instances running all the time since it can be used as a task trigger.
Comment: @JPBlanc Assigning a variable a scriptblock will never cause an exception.. the try/catch should wrap around the command call instead.
Comment: @ TheIncorrigible1 my mistake I just want to catch the check_CSV exception `$poll = {
   try{ check_CSV}catch{# Put the log}
} `
Answer: In the end, I believe it was due to the independent Powershell scripts using the same Timer names.  So I used for example:
<code>Register-ObjectEvent $poll_timer_script1 -EventName Elapsed -Action $poll_script1
Register-ObjectEvent $poll_timer_script2 -EventName Elapsed -Action $poll_script2
</code>
I do not fully understand why this would help as they are separate scripts in separate files called independently but after a couple of weeks, I've not had a crash which would almost certainly have happened by now.


Como retornar o array de anos usando react-select

Question: Estou usando o react-select para fazer um select no projeto React.
Eu preciso retornar os últimos 5 anos.
E depois popular o options={} do Select.
Só que ele tá pegando apenas o ultimo ano, no caso o 2020, mas não tá trazendo a lista inteira, que seria: 2020,2019,2018,2017,2016
  const getOptions = () => {
    const years = [];

    for (let i = 0; i < 5; i++) {
      years.push(new Date().getFullYear() - i);
    }

    for (let valor of years) {
      console.log(valor);
      const anos = [
        {
          value: valor,
          label: valor
        }
      ];

      console.log("years", years);
      console.log("anos", anos);
      return anos;
    }
  };

Select:
 <Select
        placeholder="Ano"
        value={props.values.ano}
        onChange={selectedOption => {
          handleChange("ano")(selectedOption);
        }}
        isSearchable={true}
        options={getOptions()}
        styles={customStyles}
        name="ano"
        isLoading={false}
        loadingMessage={() => "Carregando os ano"}
        noOptionsMessage={() => "Não tem ano"}
      />

Ele carrega apenas:
Answer: Acho que você se confundiu
como seu código atribui um valor, ao inves de incrementar o array, é natural que aconteça isso
repare:
for (let valor of years) {
  const anos = [
    {
     value: valor,
     label: valor
    }
  ];
  return anos;
 }

o correto seria você incrementar com push resultando num codigo assim:
anos.push({
  value: valor,
  label: valor
 })

defina let anos antes do for, e implemente o push em anos, dentro do for de years.
assim como a const years foi definido antes do for.
const years = [];

for (let i = 0; i < 5; i++) {
  years.push(new Date().getFullYear() - i);
}

o retorno da função getOptions deve ficar fora do for assim terminando as atribuições e depois retornando o array.
 let anos = [];
 for (let valor of years) {
  anos.push({
     value: valor,
     label: valor
    })
 }
 return anos;

Uma dica use let ao inves de const. A const se refere a constante ou seja não muda, mas let define uma variavel dentro de um escopo que pode ser mudada durante a execussão do mesmo.
Answer: Você também pode optar por uma solução um pouco mais declarativa, sem a necessidade de usar uma solução imperativa. Não há nada de errado com o for, mas ele foge um pouco dos padrões "imutáveis" que o React prega.
Então, você pode fazer também algo como:

function getOptions(ammount = 5) {
  return Array.from({ length: ammount })
    .map((_, index) => new Date().getFullYear() - index);
}

console.log(getOptions());

Basicamente, estamos criando uma lista com 5 elementos e mapeando cada elemento desse array para um ano em específico. Para isso, fazemos uma subtração do ano atual menos o índice do elemento, então, teremos:

Primeira iteração, índice zero: 2020 - 0 -> 2020;
Segunda iteração, índice um: 2020 - 1 -> 2019;
Terceira iteração, índice dois: 2020 - 2 -> 2018;
Quarta iteração, índice três: 2020 - 1 -> 2017;
Quinta iteração, índice quatro: 2020 - 4 -> 2016.
Comment: Gostei da forma que você fez, principalmente a explicação de imperativo e declarativo.


How to control the memory usage of a swap partiotion?

Question: Thats pretty much the quesiton: how can I control the memory usage of each swap partiotion, say /etc/sa5?
Answer: I don't get it, memory usage of swap partition? It depends on the anonymous memory which is moved to swap during memory reclaim.
You can set priority on the swap partition however. Also, did you mention /etc/sa5 correctly. If I am not wrong, I haven't seen any such file.
Comment: If your swap file is in /etc you need to update the unix version you are using ;)
Comment: Exactly my thought.


Test score bigger than Train score in Linear Regression

Question: I'm new to ML and I'm trying to create a linear regression model. My data consist of 100 samples with 4 features each. This is my humble code
<code>X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=80)

reg = LinearRegression()
reg.fit(X_train, y_train)
score_test = reg.score(X_test, y_test)
score_train = reg.score(X_train, y_train)
print("Train Score is :", score_train)
print("Test Score is :", score_test)
</code>
The problem is that the score in Test set (0.97) is way bigger than the score in Train set (0.71). How we can explain this?
Thank you in advance :)
Answer: Have you perhaps misinterpreted what "score" is meant to be doing? From the sci kit learn website:

.score( ) Returns the coefficient of determination R^2 of the prediction

It is not looking at the accuracy measure of your regression, but the R^2 value of your regression fit of your linear regression on your training data set. It doesn't make sense to use it again on the testing data (that's not how R^2 is supposed to work).
Comment: But shouldn't the R^2 score in the train set be bigger than R^2 score in the test set??
Comment: Please refer to this anawer. I think it may help in your understanding https://stats.stackexchange.com/a/320519/117574
Comment: Also imagine if your test set were two data points, and these two points completely lie on your model regression line by chance. It would have an R^2 value of 1.
Comment: Also if you are happy with my answer please dont forget to mark it as accepted by using the tick :)


Difference between heteroscedasticity and ARCH effects?

Question: What is the difference between heteroscedasticity and ARCH effects?
For example in R you can do a Breusch-Pagan Test to test for heteroscedasticity, and a Lagrange Multiplier (LM) test for autoregressive conditional heteroscedasticity (ARCH) effects. Do these tests not test for the exact same thing?
Answer: There are different forms of heteroskedasticity and ARCH is one of them.
In a cross-sectional setting, conditional heteroskedasticity usually means that $\text{Var}(\varepsilon_i|X_i)=\sigma_i^2=\sigma^2(X_i)$ where $\varepsilon_i$ is the error term of observation $i$ and $X_i$ is the vector of regressor values for observation $i$. Thus, the conditional variance is a function of the regressors.
Example: $\text{Var}(\varepsilon_i|X_i)=c|X_{1i}|$ for some positive constant $c$.
ARCH is a specific kind of conditional heteroskedasticity that applies only to time series data (or data that has a time series dimension). As is clear from the title, it is autoregressive. Here, $\text{Var}(\varepsilon_t|I_{t-1})=\sigma_t^2=\sigma^2(I_{t-1})$ where $\varepsilon_t$ is the error term of the time period $t$ and $I_{t-1}$ is the information available at time $t-1$, e.g. the set of historical values of the dependent variable: $I_{t-1}=\{y_{t-1},y_{t-2},\dots,y_1,y_0\}$.
Example: the popular GARCH(1,1) model has $\text{Var}(\varepsilon_t|I_{t-1})=\sigma_t^2=\omega+\alpha_1\varepsilon_{t-1}^2+\beta_1\sigma_{t-1}^2$.
Note that in the case of ARCH, the conditional variance does not vary with the regressors. (You could have a combination of ARCH patterns and variance dependence on regressors, but this would not be a pure ARCH any longer.)
The tests you are referring to do not test the same thing. Breusch-Pagan tests for the first kind of heteroskedasticity, while ARCH-LM tests for the second kind (ARCH).
Comment: Wow, thanks for the great answer!
Comment: @user553480, you are welcome!