When do posteriors converge to a point mass?

Question: What are the necessary conditions for a model's posterior to converge to a point mass in the limit of infinite observations? What is an example that breaks this convergence result?
Off the top of my head, I think misspecified models or nonidentifiable models would break these convergence guarantees, but how do I go about formalizing this?
Edit: for those who voted to close this because the question is ambiguous, please comment below for how I can resolve your concern.
Comment: Be more specific which posterior's convergence
Comment: hi @develarist thanks for pointing out that my question is ambiguous, but what do you mean by "which posterior's convergence"? I am asking in general, when the posterior distribution of a statistical model converges in distribution to a point mass. Maybe my questions were misleading due to the inconsistent of pluralization? I've revised the question with that in mind.
Answer: Adding three points to  the answer by  @SextusEmpiricus:
First, Doob's Theorem says that the posterior (under correct model specification) converges to the truth except on a set of parameters $\theta$ with prior probability zero. In a finite-dimensional setting you would typically have a prior that puts some mass everywhere, so that a  set with prior probability zero also has Lebesgue measure zero.
Second, finite-dimensional misspecified models will typically also have (frequentist) posterior convergence to a point mass, at the $\theta_0$ which minimises the Kullback-Leibler divergence to the data-generating model.  The arguments for this are analogous to the arguments for convergence of misspecified MLEs to the 'least false' model, and can be done along the lines of @SextusEmpiricus's answer.
Third, this is all much more complicated for infinite-dimensional parameters, partly because sets of prior probability 1 can be  quite small in infinite-dimensional spaces. For any specified $\epsilon>0$, a  probability distribution places at least $1-\epsilon$ of its mass on some compact set $K_\epsilon$. In, eg, Hilbert or Banach spaces a compact set can't contain any open ball.
In  infinite-dimensional problems:

Doob's Theorem is still true, but it's less useful.
Whether or not the posterior converges to a point depends on how big (flexible, overfitting,..) the model is
It's quite possible for a correctly specified model to have a prior converging to the wrong point mass. In fact, Freedman gave a reasonable-looking problem for which this is typical. So prior choice is more tricky than it is in finite-dimensional problems.
Comment: "In, eg, Hilbert or Banach spaces a compact set can't contain any open ball..."---that depends on the topology. Closed balls are weak-* compact in Banach spaces. In Freedman's example, the parameter space is the positive part of unit ball of $l^1$, but the topology considered is the weak-* topology (equivalently, topology of weak convergence), not the Banach space topology. In particular, the parameter space itself is compact. It seems that the weak-* topology is the natural one for this context in general.
Comment: Yes, you can define a different topology to make any set you like compact. There's still a valid problem that big spaces are big, completely separate from the Freedman problem.
Comment: What would be an example of a Bayesian problem, where the parameter space---subset of a Banach space (say)---is considered with the norm topology? If the normal means model, where the parameter lies in the Hilbert space $l^2$, has been considered from the Bayesian perspective (?), I guess that would be one example.
Comment: When I look up Doob's Theorem and follow the link to Wikipedia, then I get to https://en.wikipedia.org/wiki/Doob%27s_martingale_convergence_theorems which is not the typical easy reading wiki article. Do you know of another good introductory reference?
Comment: If the prior does not contain the true parameter or is a false model, than the convergence can be to a multi modal distribution. A set of several points that minimize the divergence. https://stats.stackexchange.com/questions/468227/bayesian-inference-with-false-models-to-what-does-it-converge/ (I know, you wrote typical, here is just an example how it can fail to go to a point mass)
Answer: Convergence of the posterior due to convergence of the likelihood
One way to look at 'convergence' is in a frequentist way, for increasing sample size the posterior will, with increasing probability, be high for the true parameter and low for the false parameter.
For this we can use the Bayes factor
$$\frac{P(\theta_1\vert x)}{P(\theta_0\vert x)} = \frac{P(x \vert \theta_1)}{P(x \vert \theta_0)}  \frac{P(\theta_1)}{P(\theta_0)} $$
where $\theta_0$ is the true parameter value and $\theta_1$ is any other alternative value. (maybe it is a bit strange to speak about the true parameter in a Bayesian context, but maybe the same is true for speaking about converging of the posterior, which is maybe more like a frequentist property of the posterior)
Assume that the likelihood ratio ${P(x \vert \theta_1)}/{P(x \vert \theta_0)}$ will converge to 0 in probability for all values $\theta_1$ that do not have a likelihood function that is the same as the likelihood function for the true parameter value $\theta_0$. (we will show that later)
So if ${P(x \vert \theta_1)}/{P(x \vert \theta_0)}$ converges, and if $P(\theta_0)$ is nonzero, then you will have that ${P(\theta_1\vert x)}/{P(\theta_0\vert x)}$ converges. And this implies that $P(x \vert \theta)$ converges to / concentrates in the point $\theta_0$.

What are the necessary conditions for a model's posterior to converge to a point mass in the limit of infinite observations?

So you need two conditions:

The likelihood function of two different parameters must be different.

$P(\theta)$ is non-zero for the correct $\theta$. (you can argue similarly for densities $f(\theta)$ as prior)
Intuitive: If your prior gives zero density/probability to the true $\theta$ then the posterior will never give a non-zero density/probability to the true $\theta$, no matter how large sample you take.

Convergence of the likelihood ratio to zero
The likelihood ratio of a sample of size $n$ converges to zero (when $\theta_1$ is not the true parameter).
$$ \frac{P(x_1, x_2, \dots , x_n \vert \theta_1)}{P(x_1, x_2, \dots , x_n \vert \theta_0)} \quad  \xrightarrow{P} \quad 0$$
or for the negative log-likelihood ratio
$$-\Lambda_{\theta_1,n} = - \log \left( \frac{P(x_1, x_2, \dots , x_n \vert \theta_1)}{P(x_1, x_2, \dots , x_n \vert \theta_0)} \right) \quad  \xrightarrow{P} \quad \infty$$
We can show this by using the law of large numbers (and we need to assume that the measurements are independent).
If we assume that the measurements are independent then we can view the log-likelihood for a sample of size $n$ as the sum of the values of the log-likelihood for single measurements
$$\Lambda_{\theta_1,n} = \log \left( \frac{P(x_1, x_2, \dots , x_n \vert \theta_1)}{P(x_1, x_2, \dots , x_n \vert \theta_0)} \right) = \log \left( \prod_{i=1}^n \frac{P(x_i \vert \theta_1)}{P(x_i \vert \theta_0)}   \right) = \sum_{i=1}^n \log \left( \frac{P(x_i \vert \theta_1)}{P(x_i \vert \theta_0)}   \right)$$
Note that the expectation value of the negative log-likelihood
$$E\left[- \log \left( \frac{P_{x \vert \theta_1}(x \vert \theta_1)}{P_{x \vert \theta_0}(x \vert \theta_0)} \right)\right] = -\sum_{ x \in \chi} P_{x \vert \theta_0}(x \vert \theta_0) \log \left( \frac{P_{x \vert \theta_1}(x \vert \theta_1)}{P_{x \vert \theta_0}(x \vert \theta_0)} \right) \geq 0$$
resembles the Kullback-Leibler divergence, which is positive as can be shown by Gibbs' inequality, and equality to zero occurs iff $P(x \vert \theta_1) = P(x \vert \theta_0)$:
So if this expectation is positive then by the law of large numbers, $-{\Lambda_{\theta_1,n}}/{n}$ convergences to some positive constant $c$
$$\lim_{n \to \infty} P\left( \left| -\frac{\Lambda_{\theta_1,n}}{n}-c \right| > \epsilon  \right) = 0$$
which implies that $-{\Lambda_{\theta_1,n}}$ will converge to infinity. For any $K>0$
$$\lim_{n \to \infty} P\left( {-\Lambda_{\theta_1,n}}  < K \right) = 0$$
Comment: Arguing via CLT is not really necessary (and may require unnecessarily strong moment assumptions, as you noted).
For convenience, define $\Lambda$ instead via the reciprocal of the likelihood ratio. Then, by LLN, $\frac{\Lambda}{n}$ converges in probability to the KL divergence, which is strictly positive. So $\Lambda \rightarrow \infty$ in probability, which would prove the convergence claim when the parameter space has two elements.
Comment: Thanks for your answer. I like this approach and justification; i'll leave this unanswered for a few more days.
Comment: @Michael, I was thinking of using the law of large numbers. But it is $\Lambda/n$ that converges and not $\Lambda$.
Comment: "But it is Λ/n that converges and not Λ..."---yes, that is all that is needed (for this argument, in the case of two-element parameter space). The general argument uses the fact that the posterior densities form a martingale, which imposes no rate whatsoever (Doob's martingale convergence theorem). This suggests that an argument that insists on a $\sqrt{n}$-rate---such as one that relies on the CLT---is not likely to work in general. (Asymptotic normality also extraneous here.)
Comment: @Michael you are right. The convergence of the likelihood can be shown by LLN. For some reason I had mixed up my mind. All we need is that the probability of the log-likelihood being above some number can be made as small we want. I thought that the scaling from $\Lambda/n$ to $\Lambda$ was mixing this up, but it doesn't matter at all.
Comment: The case of parameter space with finite cardinality also follows immediately from what you have there---convergence in probability is uniform over any finite set. A counter-example under misspecification also follows: If true model is $\theta^* \notin \{\theta_0, \theta_1\}$, then posterior converges to $(\frac{e^{-D_0}p_0}{e^{-D_0}p_0 + e^{-D_1}(1-p_0)}, \frac{e^{-D_1}(1-p_0)}{e^{-D_0}p_0 + e^{-D_1}(1-p_0)})$, where $D_i$ is KL divergence between $\theta^*$ and $\theta_i$. The posterior is not a point mass if the prior $(p_0, 1-p_0)$ is not point mass. Nice illustration for this special case.
Comment: This seems like a *sufficient* condition for the posterior to converge to a point mass, but *not a necessary one*. Suppose the prior $p(\theta)$ is itself a point mass (i.e. "I know the value of $\theta$ for sure and no amount of evidence can change that") then the posterior would be a point mass as well, which demonstrates that convergence of the likelihood is not necessary.
Comment: @ericperkerson That's right. Actually I was not trying to show how/when/why the prior converges at all to a point (aiming at necessary conditions), but instead how/when/why the prior converges to the 'true value' (and aiming to sufficient conditions). I also see this convergence of the likelihood not as a condition, but instead as the mechanism of interest and as the intuition behind the convergence. The posterior is the prior multiplied with the support, and it is the latter that converges. Sure, the prior might be a point mass to start with.
Answer: The necessary and sufficient condition that the posterior converges to the point mass at the true parameter is that the model is correctly specified and identified,
for any prior whose support contains the true parameter.
(Convergence here means that, under the law determined by $\theta$, for every neighborhood $U$ of $\theta$, the measure $\mu_n(U)$ of $U$ under posterior $\mu_n$ converges almost surely to $1$.)
Below is a simple argument for the case of finite parameter spaces, say $\{\theta_0, \theta_1\}$.
(The argument can be extended to the general case.
The general statement is that consistency holds except on a set of prior measure zero. The assumption that the parameter space is finite avoids measure-theoretic considerations.
The general statement comes with the usual caveat for almost-everywhere statements---one cannot say whether it holds for a given $\theta$.)
Necessity
Suppose the posterior is consistent at $\theta_0$. Then it's immediate that the model must be identified.
Otherwise, the likelihood ratio process
$$
\prod_{k = 1}^n \frac{p(x_k|\theta_1)}{p(x_k|\theta_0)}, \, n = 1, 2, \cdots
$$
equals $1$ almost surely and the posterior is equal to the prior for all $n$, almost surely.
Sufficiency
Now suppose the posterior is consistent. This implies that the likelihood ratio process converges to zero almost surely.
Two things to notice here:

Under the law determined by $\theta_0$, the likelihood ratio process
$$
M_n = \prod_{k = 1}^n \frac{p(x_k|\theta_1)}{p(x_k|\theta_0)} \equiv \prod_{k = 1}^n X_k.
$$
is a nonnegative martingale, and, by the consistency assumption, $M_n \stackrel{a.s.}{\rightarrow} M_{\infty} \equiv 0$.

$p(x|\theta_1)$ is equal to $p(x|\theta_0)$ $dx$-almost everywhere with respect to reference measure $dx$ if and only if
$\rho = \int \sqrt{ p(x|\theta_1) p(x|\theta_0)} dx = 1$. In general, $0 \leq \rho \leq 1$.

Define
$$
N_n = \prod_{k = 1}^n \frac{ X_k^{\frac12} }{\rho}= \frac{1}{\rho^n} \prod_{k = 1}^n X_k^{\frac12},
$$ which is also a nonnegative martingale.
Now suppose model is not identified, i.e. $\rho  = 1$.
Then $(N_n)$ is uniformly bounded in $L^1$ (because $E[N_n^2] = 1$ for all $n$).
By Doob's $L^2$ inequality,
$$
E[\, \sup_n M_n\, ] \leq 4 \sup_n E[\, N_n^2 \,] < \infty.
$$
This implies that $(X_n)$ is a uniformly integrable martingale. By Doob's convergence theorem for UI martingale, $M_n = E[M_{\infty}|M_k, k \leq n] = 0$, which is impossible---$\prod_{k=1}^n p(x_k|\theta_1)$ cannot be zero almost surely if $\rho = 1$.
Comments on Sufficiency
Couple comments on the sufficiency part:

The coefficient $\rho$ was first considered by Kakutani (1948), who used it to prove the consistency of the LR test, among other things.

For finite parameter space, sufficiency can also be shown via the KL-divergence argument in the answer of @SextusEmpiricus (although I don't believe that argument
extends to the general setting; the martingale property seems more primitive).
In the case of finite parameter space, both arguments make use of convexity (via the $\log$ and $\sqrt{\cdot}$ functions respectively.)

Infinite Dimensional Parameter Space
The set of priors whose support contains the true parameter can be "very small", when the parameter space is infinite dimensional.
In the example of Freedman (1965), mentioned by @ThomasLumley,
the parameter space $\Theta$ is the set of all probability measures on $\mathbb{N}$, i.e.
$$
\Theta = \{ (p_i)_{i \geq 1}: \; p_i \geq 0 \; \forall i, \mbox{ and } \sum_i p_i = 1\} \subset l^1(\mathbb{N}),
$$
and given the weak-* topology induced by the pairing between $l^{\infty}$ and $l^1$.
The set of priors is the set of probability measures on $\Theta$, given the topology of weak convergence.
Freedman showed that the (true parameter, prior)-pairs which are consistent is "small" with respect to the product topology.


Set up IIS as forward proxy for HTTPS requests

Question: Is it possible to set up IIS as a forward proxy for HTTPS requests?
My use case is this: I have some process running locally on the IIS machine which is able to make HTTP calls, but not HTTPS calls. I would like to set up IIS so that I can send a HTTP request to it (on localhost) and IIS would then forward the request as a HTTPS request to the real URL (using some sort of mapping based on the original URL).
Like this:
myprogram on server1 <-> http <-> IIS on server1 <-> https <-> server2

Is this possible?  This link (http://www.iis.net/learn/extensions/configuring-application-request-routing-(arr)/creating-a-forward-proxy-using-application-request-routing) says "Note that ARR processes only HTTP traffic, not other protocols. ARR does not support the HTTP CONNECT verb, and as a result, does not support forwarding HTTPS traffic." but maybe there are other ways of achieving this on IIS?
Comment: I have the same question..
Answer: This is actually quite easy and a case for SSL offloading.

Install Application Request Routing (ARR) and URL Rewrite with the Web Plattform Installer, restart your IIS Manager.
Now you should see a Server Farms entry in the IIS manager tree. If you have Server 1 with the IP 192.168.1.1 as HTTP and Server 2 with the IP 192.168.1.2 as exposed HTTPS Endpoint , you just setup a Server Farm, add Server 1 to it (by IP or local DNS name, Server 2 must be able to resolve the name of Server 1). Do not add Server 2 to the webfarm. It will ask you to allow automatic creation of a Rewrite Rule to properly forward the requests.*
Create a standard website which has the SSL Binding to Server 2 (potentially with an SNI hostname, if you have more than one site hosting on the IIS).
Then, click on the Server itself (in IIS Manager) and go into the "URL Rewrite" Module. There you will find the new Rewrite Module called something like ARR_[ServerFarm]_Loadbalance. Double click on the rule, and under Conditions, add {HTTPS} (Input) which matches the pattern on (Pattern).

Under Action, you select Action Type Route to Server Farm and set your Action Properties to Scheme: http://, Server farm: [YourServerFarmName] and leave the path untouched. You can then also tick Stop processing of subsequent rules if that is not ticked already.
*NOTE: If you have already other websites running on this server (possibly with SNI), you should also add another condition in the rewrite rule to only forward to the server farm, if the corresponding URL is queried. The condition is {HTTP_HOST} matches the pattern yoururl.com.
Hope that helps.
Comment: With the Web Platform Installer now completely removed by Microsoft, you must download and install the IIS plugins directly:

https://www.iis.net/downloads/microsoft/url-rewrite
and
https://www.iis.net/downloads/microsoft/application-request-routing


If A represents area of ellipse $3x^2+4xy +3y^2=1$ then the value of $\frac{3\sqrt{3}}{\pi}A = ?$

Question: If A represents area of ellipse $3x^2+4xy +3y^2=1$ then the value of $\frac{3\sqrt{3}}{\pi}A = ?$
My approach :
Since area of ellipse is $\pi ab$ where a is semi major axis and b is semi minor axis.
Let $(rcos\theta , r sin\theta)$ be any point of the ellipse. Since this ellipse has its centre at (0,0).
Therefore the given ellipse passes through $(rcos\theta, rsin\theta)$
Equation of the ellipse $3x^2+4xy +3y^2=1$ can be written as $3r^2cos^2\theta +4r^2sin\theta cos\theta +3r^2sin^2\theta =1$
$\Rightarrow 3r^2 +r^2 sin2\theta =1$
$\Rightarrow r^2= \frac{1}{3+sin2\theta}$
Please suggest whether this is right way of approaching , and please suggest further. Thanks
Comment: $4\sin\theta\cos\theta=2\sin2\theta.$
Answer: HINT:
As the area is one of the invariants in the Rotation of axes, use this method to eliminate $xy$ to find the values of $a,b$ in the new coordinate Axes
Answer: You could use the following fact: If an ellipse is defined implicitly by
$$\alpha x^2+\beta xy+\gamma y^2=1$$
then its area is given by the following formula
$$A=\frac{2\pi}{\sqrt{4\alpha\gamma-\beta^2}}$$
You could also use the rotation of axis to transform the implicit expression into the traditional formula of the ellipse i.e.
$$\frac{x^2}{a^2}+\frac{y^2}{b^2}=1$$
Then $A=\pi a b$ would be the area of the ellipse.
Answer: In general you would need to diagonalize the quadratic form part. But, as you observed, polar coordinates work wonders this time.

$\sin2\theta$ takes all the values in the range $[-1,1]$
Therefore $3+2\sin2\theta$ takes all the values in the range $[1,5]$.
Therefore $r^2$ takes all the values in the range _______________
Therefore $r$ takes all the values in the range _______________
Therefore the semi-axes are _______ and ________

You fill in the blanks!
Comment: The reason why polar coordinates work ($\Leftrightarrow$ that $2\theta$ appears) is that this time the axes are tilted by 45 degrees. Everything fits as $\sin2\theta$ attains it maximum at $\theta=\pi/4$.


footer to stay in view and content scroll behinds?

Question: How can I make it so item2 blue box is always visible at the bottom of the page and any content would scroll behind this?
JSFiddle with added content

.container {
  height: 100vh;
}

.item1 {
  background-color: pink;
  height: 80%;
}

.item2 {
  background-color: cyan;
  height: 20%;
  position: sticky;
  bottom: 0;
}

Comment: Remove **height: 80%** for item1
Answer: It looks like the property of .flex-container is doing the issue. Usually if you want to have a div or footer on bottom you allign it with position: absolute; and bottom: 0; while your parent div gets position: relative;.
This way your footer will be always on the bottom of the screen, all you need to do is to give the last ellement of your css some margin-bottom based on the height of your footer. This way you should not cover any content.
Read this it will help you.


Problem on Finding the speed using Intertia

Question:
I did the first part (using parallel axis theorem) and showed that intertia.

The problem is in the second part, I know that $C=I\frac{d^2\theta}{dt^2}$ , where C is the moment. So in this case it will be moment about A.
So it's like I don't know how to find the velocity at C, I don't know how to do this part. Any help is very much appreciated.
Answer: Let's start with the simplest version of this problem. Suppose we take a massless rigid rod, attach a weight to one end, and run an axis through the other end. In that case the center of gravity is just at the end of the rod. Thus if the rod starts off horizontal and is released, the initial acceleration is just that of gravity ($g$) since the gravitational force $mg$ acts here directly.
On the other hand, suppose we have a rod (length $L$) with a uniformly-distributed mass $m$ (no weight on the end). Then the center of gravity is at the center of the rod, rather than at one end, so the force of gravity $mg$ produces a torque $\tau=(L/2)\cdot(mg)=mgL/2$. But the moment of inertia of this rod (relative to the chosen axis) is $I=\frac{1}{3}m L^2$. Thus Newton's 2nd law for torques implies an angular acceleration of $\alpha=\tau/I=3g/2L$. Since this angular acceleration is valid throughout the rod, it applies as well at the end of the rod; the relation between linear and angular acceleration then gives an initial linear acceleration of $a=L\alpha=3g/2$.
For the problem at hand, the moment of inertia $I$ is no longer so simple but can still be calculated (as you've already done.) Moreover, the object is sufficiently symmetric such that the center of gravity still lies halfway between the point of interest and the axis. Therefore, one can use the result from part $(a)$ to deduce the initial acceleration.


Upper semicontinuity on a normal space

Question: If $X$ is a normal Hausdorff space and $f:X \rightarrow \mathbb{R}$ is upper semicontinuous ( $\{ f < a \}$ is open for $a \in \mathbb{R}$), then how can we show $f(x) = \inf \{ g(x): g \in C(X), f \leq g\}$?
It seems to me that Urysohn's Lemma is involved. I wanted to consider functions of the form $f_k = \sum_{j=1}^{k 2^k} \frac{j}{2^k} \chi_{ \{ \frac{j-1}{2^k} \leq f < \frac{j}{2^k} \} }$ and use Urysohn's Lemma on the sets $\{ \frac{j-1}{2^k} \leq f < \frac{j}{2^k} \}$, but these may not be closed.
Answer: Thinking out loud: consider the set $U(f):=\{g \in C(X): f\le g\}$. This has a lower bound $f$, trivially. The $\inf$ of $U(f)$ is the largest such upper bound. So consider $h(x) = \inf U(f)$, where the $\inf$ is taken pointwise, so is well-defined by order-completeness of $\mathbb{R}$. Then we know that $h$ is upper semi-continuous (for a proof see here, e.g.)
Suppose we have $p \in X$ where $f(p) < h(p)$.
Then $O = \{x: f(x) < h(p) \}$ is open by usc and non-empty, as $p$ is in it.  Maybe this will allow you to construct new functions in between but larger than $f$.
If $f$ were lsc we'd have $f \le h$ $f$ lsc and $h$ usc and then normality gives us a continuous $g$ with $ f \le g \le h$ (this is classical for normal spaces, an interpolation theorem). But we only know $f$ is usc not lsc.
Answer: It is possible that $f$ is upper semicontinuous and there is no continuous $g$ above $f$, e.g. $f(x)=1/x$ for $x>0$ and $f(x)=0$ for $x\le 0$. (Edit: This example is wrong. A corrected example is appended at the bottom.) So the statement you want to prove is not valid.
If you add the assumption that there exists a continuous $g\ge f$ then the complete regularity of $X$ will suffice:
we can assume that $f(x)<g(x)$ for every $x$. Then for every $u\in X$ and every $r$ such that $f(u)<r<g(u)$ there exists an open neighborhood $U$ of $u$ such that $f(x)<r<g(x)$ for every $x\in U$.
Since $X$ is completely regular, there exists a continuous function $t\colon X\to [0,1]$ such that $t(u)=1$ and $t(x)=0$ for $x\in X\setminus U$.
Define $h:X\to \mathbb{R}$ given by $h(x)=g(x)-t(x)\big(g(x)-r\big)$.
Then $h$ is continuous, $f(x)< h(x)\le g(x)$ for every $x\in X$, and $h(u)=r$.
It then follows that $f=\inf\{g\in C(X)\!:g\ge f\}$.
In fact, the following theorem holds.

Let $X$ be a $T_1$-space. The following conditions are equivalent.

For every upper semicontinuous $f\colon X\to\mathbb{R}$, if there is $g\in C(X)$ such that $g\ge f$ then $f=\inf\{g\in C(X)\!:g\ge f\}$.
$X$ is completely regular.

Edit:
Let $X$ be a Dowker space.
Then there exists a decreasing sequence $\langle D_n\!:n\in\omega\rangle$ of closed sets with
$\bigcap_{n} D_n=\emptyset$ such that $\bigcap_n U_n\neq\emptyset$ whenever $\langle U_n\!:n\in\omega\rangle$ is a sequence of open sets
such that $D_n\subseteq U_n$ for every $n$.
Let us define $f\colon X\to\mathbb{R}$ by $f(x)=-1$ iff $x\in X\setminus D_0$ and $f(x)=n$ iff $x\in D_n\setminus D_{n+1}$.
Then $f$ is an upper semicontinuous function such that there is no continuous $g$ above $f$.
Otherwise, $U_n=\{x\!:g(x)>n\}$ would be open sets such that $D_n\subseteq U_n$ for every $n$, hence
$\bigcap_n U_n\neq\emptyset$, which is impossible.
Conversely, it can be proved that if $X$ is a normal space such that for some upper semicontinuous $f\colon X\to\mathbb{R}$ there exists no continuous $g$ above $f$, then $X$ must be a Dowker space.
Comment: Your alleged counterexample is lower semicontinuous, not upper semicontinuous.
Comment: You are right. I have realized that I swapped the definitions of upper and lower semicontinuity in the middle of the proof, and then I forgot to check the counterexample. However, I don't know how to repair it. I can even show that there is no counterexample on $\mathbb{R}$.
Comment: I hope that my new counterexample is correct. Thank you very much for alerting me; I have learned a lot.
Comment: I think you have answered the question perfectly now. Thank you.

Upper semicontinuity on a normal space


find $\lim_{x \to 1} \frac{2x -\sqrt{x^2 +3}}{\sqrt{x+3} \ -\sqrt{2x+2}}$ without l'hospital rule

Question: EDITED VERSION
find $$\lim_{x \to 1} \frac{2x -\sqrt{x^2 +3}}{\sqrt{x+3}
   \ -\sqrt{2x+2}}$$ without l'hospital rule.
using l'hospital rule, you'll have: $\lim_{x \to 1} \frac{2x -\sqrt{x^2 +3}}{\sqrt{x+3}
   \ -\sqrt{2x+2}} = -6$.
I can show my attempt but it's pointless as the result i achieved $+\infty$, which is very wrong. is there an strategy trying to calculate a limit without l'hospital rule.
Comment: You can't use L'Hopital's Rule to solve the above limit problem because you don't have an indeterminate form. Just plug $x=1$ in the above expression
Comment: I think it's $\color{red}{-}$ in the denominator...
Answer: The expression tends to $$\frac{2\cdot1-\sqrt{1^2+3}}{\sqrt{1+3}+\sqrt{2\cdot1+2}}=0.$$
You may not use L'Hospital here.
(Or is there a typo in the question ?)

Update:
$$\frac{2x-\sqrt{x^2+3}}{\sqrt{x+3}-\sqrt{2x+2}}=\frac{\sqrt{x+3}+\sqrt{2x+2}}{2x+\sqrt{x^2+3}}\cdot \frac{4x^2-x^2-3}{x+3-2x-2}\to\frac{4}{4}(-6).$$
Comment: There was a typo. Thank you.
Comment: Is it possible that you meant $\sqrt{x^2 + 3}$ and not $\sqrt{x^3 +3}$?
Comment: I don't understand exactly what did you do in this solution
Comment: @Jneven: sorry, I made an inversion.
Answer: I will assume that you meant$$\lim_{x\to1}\frac{2x-\sqrt{x^2+3}}{\sqrt{x+3}-\sqrt{2x+2}}.$$Multiplying the numerator and the denominator by $\sqrt{x+3}+\sqrt{2x+2}$, this becomes$$\lim_{x\to1}\frac{\left(2x-\sqrt{x^2+3}\right)\left(\sqrt{x+3}+\sqrt{2x+2}\right)}{1-x}.$$So, define $f(x)$ as $2x-\sqrt{x^2+3}$ and then the limit that you're after is just$$-f'(1)\left(\sqrt{1+3}+\sqrt{2+2}\right)=-4f'(1)$$(which is $-6$ indeed).
Answer: Starting from J.C.Santos result
$$\lim_{x\to1}\frac{\left(2x-\sqrt{x^2+3}\right)\left(\sqrt{x+3}+\sqrt{2x+2}\right)}{1-x}.$$
I'd multiply num and den by $\left(2x+\sqrt{x^2+3}\right)$ to get
$$\lim_{x\to1}\frac{\left(4x^2-x^2-3\right)\left(\sqrt{x+3}+\sqrt{2x+2}\right)}{(1-x)\left(2x+\sqrt{x^2+3}\right)}.$$
that is
$$\lim_{x\to1}\frac{3(x+1)(x-1)\left(\sqrt{x+3}+\sqrt{2x+2}\right)}{(1-x)\left(2x+\sqrt{x^2+3}\right)}.$$
and then
$$-\lim_{x\to1}\frac{3(x+1)\left(\sqrt{x+3}+\sqrt{2x+2}\right)}{\left(2x+\sqrt{x^2+3}\right)}=-\frac{24}{4}=-6$$
Answer: Multiplying the top and the Bottom by $ \left(2x+\sqrt{x^2+3}\right)\left(\sqrt{x+3}+\sqrt{2x+2}\right) $, gives the following :
\begin{aligned} \lim_{x\to 1}{\frac{2x-\sqrt{x^2+3}}{\sqrt{x+3}-\sqrt{2x+2}}}&=\lim_{x\to 1}{\frac{-3\left(x+1\right)\left(\sqrt{2x+2}+\sqrt{x+3}\right)}{\sqrt{x^{2}+3}+2x}}\\ &=\frac{-3\left(1+1\right)\times\left(\sqrt{2\times 1+2}+\sqrt{1+3}\right)}{\sqrt{1^{2}+3}+2\times 1}\\ \lim_{x\to 1}{\frac{2x-\sqrt{x^2+3}}{\sqrt{x+3}-\sqrt{2x+2}}}&=-6 \end{aligned}


Using contour integrals to evaluate sum - Problem calculating residues

Question:
"Compute $$\sum_1^{\infty} \frac{1}{{n^2}{(n+1)^2}}$$ using contour integration"

I have used the function $F(z) = \frac {\pi cot\pi z}{z^2(z+1)^2}$
Which has double poles at $z=0$ and $z=-1$
For the pole at $z=0$, if I calculate the residue by taking the limit of $\frac{dF}{dz}$ as $z \to 0 $, I end up with a $cosec(0)$ term, which is $\infty$
Instead I can try to calculate the residue using the Laurent series, and about $z=0$ again I find;
$\frac {\pi cot(\pi z)}{z^2{(z+1)^2}} = \frac{\pi}{z^2} [(\pi z)^{-1} - \frac {1}{3}(\pi z) - \frac {1}{45}(\pi z)^3 ...][1 - 2z +3z^2 -...]$
And I find the residue to be $3-\frac{1}{3} \pi^2$
To compute the residue at $z=-1$, however, I can't compute the expansion of $\pi cot(\pi z)$ about $z=-1$ using normal Taylor expansion methods, because if:
$g(z) = \pi cot(\pi z)$, then $g(-1) = \frac{1}{0}$
and that's where I'm stuck - computing the residue at $z=-1$.
Once I've found the residue, computing the series is simple:
$$\sum_1^{\infty} \frac{1}{{n^2}{(n+1)^2}} = \frac{1}{2} \sum_{Res}$$
Any help would be greatly appreciated!
Comment: The poles at $0$ and $-1$ are triple poles, since $\cot (\pi z)$ has a simple pole at every integer.
Comment: The series gets you half the sum of the residues at the points in $\mathbb{Z}\setminus \{0,-1\}$. The singularities at $0$ and $-1$ must be treated separately.
Comment: @DanielFischer I was under the impression that because of the way the series is manipulated using a contour integral, the poles created by the $\pi n$ at$ cot(\pi z)$ were already accounted for?
Answer: First of all, $z=0$ and $z=-1$ are triple poles. Secondly, you can either use that
$$
\frac{1}{1+z} = \frac{1}{1-(-z)} = \sum_{k=0}^\infty (-z)^k = \sum_{k=0}^\infty (-1)^k\,z^k
$$
and
$$
\frac{1}{(1+z)^2} = - \frac{d}{dz} \left( \frac{1}{1+z} \right) = - \sum_{k=1}^\infty k(-1)\,z^{k-1}
$$
to get enough terms in your Laurent series. Alternatively: the residue at $z=0$ is given by
$$
\frac{1}{2!} \lim_{z\to 0} \frac{d^2}{dz^2} \big( z^3 F(z) \big)
$$
and similarly for $z=-1$.

The residue at $z=0$ turns out to be $-\frac13\pi^2+3$ and the same at $z=-1$.
Answer: Consider
$$f(a) = \sum_{n=-\infty}^{\infty} \frac1{(n^2+a^2)[(n+1)^2+a^2]} $$
The sum we want will be $\frac12 \lim_{a \to 0} [f(a) - \frac{2}{a^2 (1+a^2)}]$.  (These represent the $n=0$ and $n=-1$ terms in the sum that become singular as $a \to 0$.)  We may evaluate this sum using the residue theorem.  Recall that, from considering the integral
$$\lim_{N \to \infty} \oint_{C_N} dz \, \cot{\pi z} \, h(z) = 0$$
where $C_N$ is the square with vertices $(\pm (1 \pm i) N/2$.  The integral is also equal to $i 2 \pi$ times the sum of the residues, which all must sum to zero.  Thus
$$\sum_{n=-\infty}^{\infty} h(n) = -\pi \sum_k \operatorname*{Res}_{z=z_k}[ \cot{\pi z} h(z) ] $$
where the $z_k$ are the non-integer poles of $h$.  In this case, we see that
$$f(a) = -\pi \sum_k \operatorname*{Res}_{z=z_k} \frac{\cot{\pi z}}{(z^2+a^2)[(z+1)^2+a^2]}$$
In this case, we have these poles at $\pm i a$ and $-1\pm i a$.  Thus,
$$\begin{align}f(a) &= -\pi \left [\frac{-i \coth{\pi a}}{i 2 a (1+i 2 a)} + \frac{i \coth{\pi a}}{-i 2 a (1-i 2 a)} + \frac{\cot{\pi (-1+i a)}}{i 2 a (1-i 2 a)} + \frac{\cot{\pi (-1-i a)}}{-i 2 a (1+i 2 a)} \right ] \\ &= \frac{\pi}{a} \left (\frac{\coth{\pi a}}{1-i 2 a} + \frac{\coth{\pi a}}{1+i 2 a}  \right )\\ &= \frac{2 \pi \coth{\pi a}}{a (1+4 a^2)} \end{align}$$
The sum is
$$\begin{align}\sum_{n=1}^{\infty} \frac1{n^2 (n+1)^2} &= \frac12 \lim_{a \to 0} \left [ \frac{2 \pi \coth{\pi a}}{a (1+4 a^2)}- \frac{2}{a^2 (1+a^2)} \right ] \\ &= \frac12 \lim_{a \to 0} \left [\frac{2}{a^2} \left (1+\left (\frac{\pi^2}{3} - 4 \right ) a^2+\cdots \right ) - \frac{2}{a^2} (1-a^2+\cdots) \right ] \end{align} $$
The singular pieces cancel, and we finally have

$$\sum_{n=1}^{\infty} \frac1{n^2 (n+1)^2} = \frac{\pi^2}{3} - 3$$


Prove that $n(n-1)<3^n$ for all $n≥2$ By induction

Question: Prove that $n(n-1)<3^n$ for all $n≥2$. By induction.
What I did:
Step 1- Base case:
Keep n=2
$2(2-1)<3^2$
$2<9$ Thus it holds.
Step 2- Hypothesis:
Assume: $k(k-1)<3^k$
Step 3- Induction:
We wish to prove that:
$(k+1)(k)$<$3^k.3^1$
We know that $k≥2$, so $k+1≥3$
Then $3k<3^k.3^1$
Therefore, $k<3^k$, which is true for all value of $n≥k≥2$
Is that right? Or the method is wrong? Is there any other methods?
Comment: @YvesDaoust, look more closely at what the OP is doing in Step 3.  He's actually assuming what he wants to prove when he says "Then $3k\lt 3^k.3^1$" (i.e., $k+1\ge3$ implies $3k\le(k+1)k\lt3^k.3^1$).
Comment: Yes, this is right. (But in the last line $k\ge2$, or use $n$ everywhere.)
Comment: @BarryCipra: you are quite right, I didn't see that. Actually the induction hypothesis is used nowhere. He should have said $k(k-1)<3^k\implies k(k+1)<3^k+2k<3.3^k$ and proven $k<3^k$.
Answer: We know that  $k(k-1)<3^k$ (The induction assumption)
Multiply 3 both sides, and we get:
$3k(k-1)<3^{k + 1}$
Now we will be done if we prove that
 $k(k+1)\le3k(k - 1)$.
This can be rearranged as  $2k - 4 \ge 0$, which is true since $k \ge 2$.
Hence proved.
Answer: Other approach (not induction): by the binomial theorem,
$$(1+2)^n=1+n.2+\frac12n(n-1).2^2+\frac1{3!}n(n-1)(n-2).2^3\cdots>n(n-1).$$
Answer: I think that your solution is fine. However, I would phrase it slightly different.
Step-2. To be completely formal, I would say: Let $k>2$ and assume $k(k-1)<3^k$.
Step 3. We need to show $k(k+1)<3^{k+1}$. We have $$k(k+1)=k(k-1)+2k<3^k+2k<3^k+3^k+3^k=3^{k+1}$$
Where we have used the inductive hypothesis and the fact that $k<3^k$, which is true because $k>2$.
Notice that you can prove that the inequality is true for all $n\geq0$ (indeed the base case will become trivial!).


how high to position the snare drum?

Question: I'm not a drummer. But sometimes I play basic beats on my brother's kit when at his house.
His snare it positioned so the head is around 5 inches above my lap. He and I are about the same height 5'10" and the stool is set so my feet are flat on the ground and thighs parallel to the floor.
OK, those are the basic measurements.
I feel like the snare is too high. Not a lot, I might drop it 2 or 3 inches.
How much variation is there in snare height? Any standard for height?
You see so many variations on kit layouts. It seems like anything goes. But it also seems posture and position are pretty standard for all instruments in formal education. I'm interested in both formal and informal perspectives.
Answer: I'm sure there are as many setups as there are drummers.
I sit so my knees are just under 90° & my thighs maybe 2" higher than level. That gives me my optimum pedal position. This, btw, is with my feet on the pedals. Distance to the ground is absolutely unimportant - distance to pedals is the one you need. Get this right before you even think about anything else. This is your entire balance & feel, too low you'll always feel like you're lifting your legs, too high & you'll be resting too much weight on them, even when static.
If after 10 minutes of getting the entire kit right this starts to feel uncomfortable… change the throne height, then move the whole kit to match.
Snare I have almost level - I play matched grip so I don't like it tilted sideways, but I have a very slight slope so the section nearest my body is about ½" lower than the far edge. The height I set so that on a hard rimshot [not side-stick, rimshot] my hands just hit my thighs. I find that makes for greater accuracy when a track needs constant rimshots. I never miss that way - there's nothing more embarrassing than 20 massive rimshots in a row in the big last chorus… then a small click as you hit just the rim;)
I do a similar thing with the toms - they're tilted to make rimshots easy & repeatable, without the embarrassing click. That gives another 'measure' for repeatable rimshots; the difference between clean strike & rimshot is probably less than an inch in terms of where my hand aims for, as opposed to the stick. It gives you an amount of 'push-through'[1] for intensity.
My entire technique is based on being able to be delicate, then raise very high volume levels without breaking a sweat. Call me idle, I call it efficiency :P
Part of my setup for snare & toms is that if you take a ruler & place it over each drum, pointing in towards where my right knee is, then the lines all converge at a point about 2" above that knee & an inch in front.
That's where I put my mic - a very expensive omni - so it can pick up all the top skins evenly, & never get hit by a stick.[2]
Hats & cymbals I place high enough that I can never accidentally hit them on an upstroke if I'm going a bit 'mental' in a wild section, except for the ride, which I keep low but further out, as that never gets belted like a crash. All cymbals I keep the felts tight so they don't swing around much - that way if you go for two quick crashes in a row without looking, the cymbal is always in the same place.
Everything relies on muscle memory, not looking for where it is.
[1] I don't know if there's an actual musical term for this 'push-through' but I would liken it to the part in any kung fu movie where the old master tells the student. "Don't aim to hit him in the face, aim to hit him two inches behind his face".
It's a volume-gaining technique that requires no more effort than playing quietly.
[2] This is a mic technique I've used for 30 years. I worked it out painstakingly in the studio in the 90s, when I would spend maybe 80 hours a week in the studio. It also works live, up to about a 3,000-seater so long as you don't push it through the on-stage monitors. I've never tried it in anywhere bigger.
It does rely on a good omni. I used to use a B&K 4006 but I later discovered a tiny lav mic which sounds almost identical, the DPA 4060 [DPA is the new name for Brüel & Kjær, it's the same company] which is easier to put where it can't get hit & is a 'mere' £450, rather than the £2,500 or so the B&K cost.
Answer: A similar question would be - 'how high should I wear my guitar?'. Check hundreds of guitarists, and the obvious answer is - where the heck you like - as long as you can reach what you need.
One basic start point is where you are in relation to the kit. How high is your throne? If it's too low, or too high, your thigh, knee and ankle angles will be adversly affected. Heel up or down for kick drum will be a main consideration. So once that's established, we can move on to snare. Usually between your thighs, but, height? Our arms aren't all standard length, and the way we use them isn't either.
For me, slight slope from hips to knees, foot on pedal (that adds an inch or two!), snare's about an inch above thighs. Any lower, and rimshots aren't easy. Some slant the drum towards, to one side or the other, mine's level-ish.
Comment: I did think about the parallel with guitar straps. But, there is a formal guitar position. Your snare about an inch above thighs seems to be my preference too.
Comment: After 60+ yrs of playing and teaching, it's news that there's a formal guitar position. I look forward with scepticism as someone explains it ..!
Comment: I'm not necessarily advocating it, but it's usually shown in pictures at the beginning of classical method books. I'm sure you know what I'm talking about.
Comment: Ah, you meant *classical*. Other guitars (and their positioning)  are available...
Answer: The first question: does HE feel comfortable?
Regarding your height(s): it depends on which "part" of these 5'10" belong to your legs and which to the upper part of your body. In German we have the word "Sitzriese" for a person which legs are shorter compared to the upper body. Also the upper arm might be shorter compared to the forearm. There are different aspects of anatomy to take into account.
If your forearm and the stick fall in line and the snare is too high you could only touch the rim with your stick (because the drumhead is lower). If you lower the snare a bit (or rise the stool) there will be a point where you - technically - could reach the drumhead with the tip of your stick. That's the point to start trying out. The more you lower to snare the more you can lower your forearms which might be more comfortable if you play over a "longer" time (so not only 15min or so).
And that's only the snare part - and also very theoretical. Detailed practical examples are already given.
Answer: I'm not a drummer, either, but I play one in my garage, so this answer should go under "informal perspectives."
I prefer a higher throne than you describe, with my thighs sloped downward from hips to knees. I find the obtuse angles at hips, knees and ankles make it easier to relax and I feel less strain in my legs and back (none at all) than with a lower throne that puts those angles at 90 degrees or less.
My snare sits with top at about same level as upper thighs, sort of right in front of and flush with my lap, and tilted toward me slightly. With a traditional grip (maybe matched grip, too,) I am able to play relaxed, with elbows at my sides, comfortably and with no strain to arms, wrists or any other part of body.
The floor tom head is at the same level as snare. My rack tom and crash/ride sit about 4-5 inches higher and are also on same level with each other. High-hat is somewhere in between. I find this setup facilitates efficient movement between drums and cymbals, and I need all the help I can get!

how high to position the snare drum?


mongoimport : 'error validating settings: only one positional argument is allowed'

Question: Ok so I am trying.... to Importing a dummy JSON file into MongoDB and getting this error, a Google search yields no definitive explanation, and though this topic is already on here, that's more a syntax related error.
I think my syntax is ok, however if it is not please point it out and let me know. Also I think the other issue is my path [format correct] ? or is it something entirely different I am missing.
I don't understand the error and thus can't find a suitable "plain English" explanation anywhere to figure it out myself, so if you have a link please drop it in for me, it will be appreciated....
The error:
$ mongoimport --jsonArray --collection bank_data /Macintosh HD/Users/Tinus/Downloads/bank_data.json/bank_data.json
2016-09-20T13:23:56.592+1200    error validating settings: only one positional argument is allowed

-: Running OSX
-: Mongod started
-: Using /data/db path and connected to test "All good"
-: running mongoimport from separate shell

$ mongo --version MongoDB shell version: 3.2.8

$ mongoimport --jsonArray --collection some_data --file /path/path/data.json
$ mongoimport --jsonArray --collection some_data /path/path/data.json

A) Also when adding --file i get: incompatible options: --file and positional argument(s)
Answer: Try it like that by quoting your path
$ mongoimport --jsonArray --collection bank_data '/Macintosh HD/Users/Tinus/Downloads/bank_data.json/bank_data.json'

The error
error validating settings: only one positional argument is allowed

comes from the fact that your path contains a space which results in splitting it into two separate arguments (if not guarded by surrounding quotes)

BTW: Are your sure your path ends with '...bank_data.json/bank_data.json' and not just one 'bank_data.json'?
Comment: Mine was a different import scenario. I was using data types and trying to specify date format like date_ms\(yyyy-MM-dd H:mm:ss\) [as shown in mongoimport docs]. got this same error and when quoted such as date_ms\('yyyy-MM-dd H:mm:ss'\), the error's gone and import worked!
Comment: Thanks so much mate! Will give it a go and let you know. I
Answer: ~Fix~
A) I changed the path to reed direct from a new folder on root
B) For any other's having the same issue on mac osx —leave out the base root in your path , in my example above it was [ Macintosh HD]
the import works without specifying it. thus it was changed to ..
        $ mongoimport --jsonArray --collection bank_data '/Users/Tinus/Downloads/bank_data.json/bank_data.json'

C) Yes the quotes are essential and was also added…
D) Remember not to run it inside the mongo shell.
thumbs Up again to DAXaholic
Answer: I also had the same error and the reason was my mistake of specifying options. Instead of --collection or -c, I had -collection. Below is what worked for me.
mongoimport --db ShardTestDB --collection Test --host : --jsonArray --file "<path_to_json>/Substations_new.json"
Make sure that the file is included inside quotes.
Answer: even i faced same issue while importing tsv file to db including --headerline to the command line solved the issue.please find entire import command used to successfully import tsv file
mongoimport --host Cluster0-shard-0/cluster0-shard-00-00-qvmvm.mongodb.net:27017,cluster0-shard-00-01-qvmvm.mongodb.net:27017,cluster0-shard-00-02-qvmvm.mongodb.net:27017 --ssl --username learning --password --authenticationDatabase admin --db node_deploy --collection node_deploy --type tsv --file games.tsv --headerline
[Note]
above command is to import a database in tsv format to mongodb hosted in AWS using mongodb.com
Answer: Above solutions did not work for me on Windows 10.  I figured out solution as follows:
mongoimport --jsonArray --db=db_name --collection=collection_name --file=file_name.json

Which resulted in:
2019-12-29T02:26:50.041-0700    connected to: mongodb://localhost/
2019-12-29T02:26:50.088-0700    2411 document(s) imported successfully. 0 document(s) failed to import.

Answer: This worked for me:
mongoimport --host 172.18.60.1 --port 50000 --db MYDB --collection BUSINESS_FILE --file "/opt/data/JSON/BUSINESS_FILE.json"

P.S. My port is not default port of MongoDB so make sure you put your mongos port there instead of 50000 which is mine.


Find any two consecutive $100$-digit numbers whose sum of digits is a perfect square

Question: Find any two consecutive $100$-digit numbers whose sum of digits is a perfect square.
this is all I did and I am stuck
lets say $abc \dots m$ is a $100$ digit number whose sum of its digits is a perfect square
$$a+b+c+.....+m = k^2$$
lets say $abc \dots m+1$ is a $100$ digit number whose sum of its digits is a perfect square
$$a+b+c+.....+m+1 = q^2$$
$$k^2 = q^2 - 1$$
and I am just stuck
Comment: @GregMartin has the correct hint... you're stuck because if adding $1$ doesn't lead to carrying over into the tens place, the digit sum will just increase by $1$, and there *aren't* two (positive) perfect squares that differ by $1$.  What if the last few digits go from $09$ to $10$, though?  Or from $099$ to $100$?
Comment: When you add $1$ to a number, usually its digit sum will increase by $1$ ... could that possibly result in consecutive digit sums equaling squares? How else could the digit sum change when $1$ is added to the original number?
Comment: What are the possible limits on the squares that could be the results of this effort?  Would it make sense to start with all zeros except the leading and last digits?
Comment: Hint #1: In base-ten, all perfect squares end in 0, 1, 4, 5, 6, or 9.

Hint #2: All integers are congruent modulo 9 to the sum of their digits.

Work it out from there.
Comment: @Dan i'm a 9th grade student i dont know what congruent modulo is could you please explain in details
Comment: @MiaGenov: I mean that they have the same remainder when divided by 9.
Answer: Let the lower number end in $n$ $9$s. Then, the digit sum of that number is $9n-1$ more than the digit sum of the number above, so $9n-1$ is a difference of two squares.
If $n=2$ then $9\times2-1=17=9^2-8^2$.
A potential lower number could be:
$$\underbrace{11\ldots11}_{63\,1\mathrm{s}}\underbrace{00\ldots00}_{35\,0\mathrm{s}}99$$
so the higher number is $$\underbrace{11\ldots11}_{63\,1\mathrm{s}}\underbrace{00\ldots00}_{34\,0\mathrm{s}}100$$
Answer: Let $Q(n)$ (from German Quersumme) denote the sum of the (base-ten) digits in the integer $n$.
It is a well-known fact that $Q(n)$ is congruent modulo 9 to $n$.
Also, if you look down the diagonal of the base-9 multiplication table, you'll see that all the perfect squares end in 0, 1, 4, 7.  Put another way, if $n$ is a perfect square, then:
$$Q(n) \equiv n \in \{0, 1, 4, 7\} \pmod{9}$$
For both $Q(n)$ and $Q(n+1)$ to be perfect squares, the only possible combination is $Q(n) \equiv 0 \pmod{9}$, so that $Q(n+1) \equiv 1 \pmod{9}$.
Now, let's choose two perfect squares, one of which is a multiple of 9, and one that's one more than a multiple of 9.  I'll pick $Q(n) = 81$ and $Q(n + 1) = 64$.
Note that in order for $Q$ to decrease when $n$ is incremented, we need a rollover from 9 to 0 in the unit's place.  So, we have:

$n$ = (99 digits adding to 72)$9$
$n + 1$ = (99 digits adding to 64)$0$

Since $72 > 63$, we'll need another place-value column affected by rollover.

$n$ = (98 digits adding to 63)$99$
$n + 1$ = (98 digits adding to 64)$00$

OK, so now we just need two consecutive digits in the hundred's place.  I'll pick $8$ and $9$.

$n$ = (97 digits adding to 55)$899$
$n + 1$ = (97 digits adding to 55)$900$

And the "97 digits adding to 55" must be the same string of digits for the two numbers.  I'll choose to construct it as 1 + 90 0's + 6 9's.  giving the pair of numbers:

1000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000999999899
1000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000999999900

So there you go: Two consecutive 100-digit integers whose digit sums (81 and 64) are both perfect squares.
Answer: Use $n=4040404...$
The sum of the digits would  $4\times 50 = 200$
Since $15$ squared is $225$, you'll need to add $25$
Divide $n$ by two $=2020202...$ and make two copies, then change $12$ of the $0$s to $1$s (same digits for each copy) and add an extra $1$ to one of the numbers.


Get path of uploaded file inside a Twig template

Question: I've created a teaser template like this node--type--teaser.html.twig.
Within that template I want to conditionally create a link to a file that was uploaded via the field field_pdf.
How do you extract JUST the path to the pdf in the template.
I've tried {{ file_url(node.field_pdf.entity.url.value) }} but that just brings back an empty path.
If thats not possible, is there a way to get a file path from the fid in twig?
Comment: I think the field name is `uri`, not `url`.
Comment: Yo, thinking the same. See https://www.drupal.org/docs/8/theming/twig/functions-in-twig-templates#file_url there it's `{{ file_url(node.field_example_image.entity.uri.value) }}`.
Comment: Per the answer below, make sure the field type is set as `File`.
Answer:
Manage teaser Display : Change Format of your file field to Generic File From  admin/structure/types/manage/YouRContentType/display/teaser .
In your twig node--type--teaser.html.twig just print  {{
file_url(node.field_pdf.entity.uri.value) }} you will get the path to your file.
Note : As mentioned in comment it's uri Not url.
Comment: Thanks for the response. What is this `generic file` setting? All i see is `Rendered Entity`, `Entity ID`, `Label` and `Thumbnail` as output options.
Comment: is your field of type `File ? ` if is the case From your Manage display page of your content type you will see a dropdown `Column FORMAT` some option `RSS enclosure, Generic file, URL to file, Table of files` .
Comment: Ah, thats probably what the issue is. I set the file type as `Media`. Updating this now.
Comment: Thanks all for the help. The issue was as stated where I'd selected the `Media` field type instead of the `File` field type. With the `File` field type, the `Generic File` format is available in the teaser view mode.
Comment: You are welcome, Can you just please add this as note to the question `Field of type File` just in case someone need it.   Good luck.
Answer: In my case I had a paragraph type with a file field.
I wanted to get a url of file-field inside paragraph's template.
Not sure why but above solution of @berramou did not work for me.
So what I did is, in manage display I changed the file field's format to "URL to file".
Then I rendered the file field, stripped its tags, trimmed and passed it to file_url like follows:
{% set url = file_url(content.field_pdf_file|render|striptags|trim) %}

Answer: In a field template file (for example, /themes/custom/y_subtheme/templates/field/field--node--field-brochure--course.html.twig), it will be {{ file_url(item.content['#file'].getFileUri()) }}.


How can I connect my CDJ / DJM 2000 Nexus with Traktor?

Question: I would like to connect my CDJ / DJM 2000 Nexus with Traktor. How should I configure Traktor?
Answer: For Windows:

Install CDJ drivers (and ideally update firmware): http://pioneerdj.com/english/products/player/cdj-2000nexus.html
Connect the 2 CDJ 2000 through USB to your computer
Start Traktor and configure as follow (tested with Traktor 2.6.3 and Traktor 2.6.5 with Windows 7 x64 Ultimate):

Not necessary (it should be automatically well configured), but in case of issue here is the mapping:

It should be working now. If needed, you can watch the official Pioneer tutorial.
FYI hardware connections:


Recebendo paramento na View

Question: Olá! Estou tentando receber um parâmetro de filtro em minha view com o seguinte código no Controller:
public ActionResult Cadastro(int? idParente)
    {
        var tab_Documentos_Parente = db.Tab_Documentos_Parente.Where(campo => campo.Id_Parente == idParente).Include(t => t.Tab_Documentos_Cadastrais_Par).Include(t => t.Tab_Parente);
        return View(tab_Documentos_Parente.ToList());
    }

Mas quando informo a url: http://localhost:53316/Documentos_Parente/Cadastro/1
Simplesmente não executa o filtro. Fazendo um Debugno Controller vejo que meu parâmetro está sempre sendo recebido como null.
Não basta apenas informar .../1 ao final na URL?
Como então posso enviar o id que quero filtrar?
o modelo é o seguinte:
public partial class Tab_Documentos_Parente
{
    public int Id { get; set; }

    [Display(Name = "Nome do Parente")]
    public int Id_Parente { get; set; }

    [Display(Name = "Descrição do Documento")]
    public Nullable<int> Id_Documento { get; set; }

    [Display(Name = "Documento")]
    [DataType(DataType.Upload)]
    public byte[] Documento { get; set; }

    public virtual Tab_Documentos_Cadastrais_Par Tab_Documentos_Cadastrais_Par { get; set; }
    public virtual Tab_Parente Tab_Parente { get; set; }
}

Comment: Tenta com a url ` http://localhost:53316/Documentos_Parente/Cadastro?idParente=1 ` se funcionar é porque você não configurou a rota corretamente.
Comment: Alam, você configurou a rota para que ela entenda que o `/1` é um parametro?
Comment: Tem razão @LeonardoBonetti a url que você sugeriu funcionou. Mas como funciona com as Views de Edit e Delete geradas pelo Scaffold, imaginei que seria apena seguir o mesmo modelo. Onde configuro essa rota?
Comment: vou criar uma resposta FODA, me aguarde.
Comment: Kkkkk! Aguardando de boa...
Answer: Como não sei toda a hierarquia do seu projeto vou dar um exemplo do meu projeto.
Eu tenho um HomeController com a view Image(é uma view de resultado de imagem):
public class HomeController : Controller
{
    public ActionResult Image(string id)
    {
        //Processa id
        return View(id);

    }
}

Quando eu fosse chamar essa view passando o id eu teria que requisitar isso: http://localhost:53316/Home/Image?id=1 porém contudo todavia, como já diria aquele sábio chamado Google, nada melhor que uma URL amigável.
A url amigável ficaria assim: http://localhost:53316/Home/Image/1 Mas  como fazer isso? Você precisa MAPEAR uma nova rota(Route).
Para configurar uma nova rota, você deve editar o arquivo RouteConfig.cs na pasta App_Start da raiz do seu projeto. Como rota padrão você já tem:
routes.MapRoute(
            name: "Default",
            url: "{controller}/{action}/{id}",
            defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);

Você irá criar uma nova rota, não exclua a rota padrão(Pelo amor que você tem no seu projeto), a nova rota ficaria assim:
routes.MapRoute(
            "Home",
            "Image/{produtoid}",
            new { controller = "Home", action = "Image" },
            new { produtoid = UrlParameter.Optional }
);

Nesse link você pode ver o overload que usamos para mapear essa rota.

"Home" - nome da sua rota.
"Image/{produtoid}" - o padrão de url para sua rota.
new { controller = "Home", action = "Image" }, - você passa o controller/view que a sua rota irá ser aplicada.
new { produtoid = UrlParameter.Optional } os parametros da url

Agora sim ! você já pode utilizar o padrão da pergunta: http://localhost:53316/Documentos_Parente/Cadastro/1    , se você configurou tudo certinho, com os nomes corretos e etc tudo funcionará. Pelo que eu entendi do pouco código que você inseriu, a rota ficaria assim:
routes.MapRoute(
        "Documentos_Parente",
        "Cadastro/{parenteid}",
        new { controller = "Documentos_Parente", action = "Cadastro" },
        new { parenteid= UrlParameter.Optional }
);

Eu aprendi a fazer isso no post: Customizando Rotas  do site do José Carlos Macoratti(que é um site MUITO bom para quem aprende MVC, tem bastante conteúdo e de fácil entendimento. Espero que isso resolva, espero o retorno(comentários) de você ou qualquer outro com o mesmo problema.
Comment: Você realmente fez uma super resposta, clocou até a referencia do msdn.microsoft.com e do site do macoratti... Não ficou nenhuma dúvida. A rota que você sugeriu funcionou perfeitamente. Obrigado mesmo.
Comment: @AlamBique eu que agradeço pela oportunidade de  ajudar.

Recebendo paramento na View


Folland Chapter 3 Problem 4 (real analysis)

Question: Problem 3.4 If $\nu$ is a signed measure and $\lambda$, $\mu$ are positive measures such that $\nu = \lambda - \mu$, prove that $\lambda \geq \nu^+$ and $\mu \geq \nu^-$.
Here is my attempt.
By the Jordan Decomposition Theorem, there exist unique positive measures $\nu^+$ and $\nu^-$ such that $\nu = \nu^+ - \nu^-$ and $\nu^+ \perp \nu^-$. So we fall under two cases.
The first case is when $\lambda \perp \mu$, then $\lambda = \nu^+$ and $\mu = \nu^-$, by uniqueness.
The second case is when $\lambda$ and $\mu$ are not mutually singular. From here I tried to argue by contradiction. It would be impossible for there to exist a set $E$ such that $\lambda(E) < \nu^+(E)$ and $\mu(E) \geq \nu^-(E)$ since $\nu(E) = \lambda(E) - \mu(E) < \nu^+(E) - \nu^-(E) = \nu(E)$. Similarly, we cannot have a set $E$ such that $\lambda(E) \geq \nu^+(E)$ and $\mu(E) < \nu^-(E)$, as we will reach a similar contradiction.
So it remains to find a contradiction by assuming the existence of a set $E$ such that both $\lambda(E) < \nu^+(E)$ and $\mu(E) < \nu^-(E)$.
If $\lambda$ and $\mu$ are not mutually singular, then for the positive and negative sets through which $\nu^+$ and $\nu^-$ are defined in the Jordan Decomposition theorem, call them $P$ and $N$, we must have that $\lambda$ is not null on all of $N$ and similarly, $\nu$ is not null on all of $P$.
I'm not sure how to reach a contradiction from here. Am I even going in the right direction?
Answer: Forget those cases. You need to show that $\lambda(E)\ge\nu^+(E)$. Note that $$\lambda(E)=\lambda(E\cap P)+\lambda(E\cap N),$$and similarly for $\nu^+(E)$. So it's enough to show that $\lambda(E\cap P)\ge\nu^+(E\cap P)$ and $\lambda(E\cap N)\ge\nu^+(E\cap N)$.
Answer: Hint: You assumed that there is a set $E$ such that $\lambda(E)<\nu^+(E)$. Try to use $\nu^+\perp\nu^-$ to adjust your set $E$ so that in addition $\nu^-(E)=0$.


Problema com mascara em jQuery

Question: Gostaria de saber se é possível fazer umas mascara mais completa para o campo data usando esse plugin(jQuery-mask) por exemplo o usuário consegue colocar no campo mês 99 quando na verdade o mês só vai até o 12 e no campo dia também a mesma coisa consegue colocar 99 quando na verdade o máximo seria 31 existe alguma forma de mascarar isso segue o formulário do site
Trecho do código usado no site:

Comment: @VirgilioNovic você poderia me indicar algum plugin que faça isso?
Comment: Tem que utilizar uma validação como complemento. Esse plugin só segue a mascara e não possui validação embutida, isso é feito por outro `plugin`
Comment: indiquei dois um que confere a data e o outro que pode fazer um validação de vários campos, só coloquei o de data que era o seu principal problema na pergunta.
Answer: Você pode fazer da seguinte forma:
$('#input-custom-field3').focusOut(function(){ //você pode alterar aqui o seletor para alguma classe, para validar todos os campos de data
    var valid = true;
    var date = $(this).val().split('/');
    var day = date[0];
    var month = date[1];
    var year = date[2];

    if(day < 1 || day > 31)
        valid = false;
    if(month < 1 || month > 12)
        valid = false;
    if(year <= 1990 || year >= 2099) //aqui você pode ajustar o range a seu critério
        valid = false;

    if(!valid)
        $(this).val('');
});

Dentro de cada if você pode exibir algum alert ou alguma mensagem que desejar para informar o erro ao usuário...
Answer: Tem vários plugin por exemplo jQuery.validation e um outro plugin para verificar a data o momentjs. Cria um método no validator ($.validator.addMethod) que vai verificar a data no formato brasileiro (dia, mês e ano) conferindo inclusive anos bissextos. Nas regras de validate só chamar o nome da função que é date_br pronto com isso terá uma validação no lado do cliente.
Recomendação: Cuidado com validações somente do lado do cliente, faça também no lado do servidor via programação.
Exemplo minimo:

$(document).ready(function() {
  $.validator.addMethod("date_br", function(value, element)   {
    return moment(value, 'DD/MM/YYYY', true).isValid();
  }, "Data inválida.");

  $("#form1").validate({
    rules: {
      data: {
        required: true,
        date_br: true
      }
    }
  });

  $('#data').mask('99/99/9999');

});

<form id="form1" method="post">
  <input type="text" name="data" id="data">
  <button>Gravar</button>
</form>

Referencias:

jQuery.validation
momentjs
jQuery validation plugin: validate custom date format
How to test a string is valid date or not using moment?

Problema com mascara em jQuery


Printing multiple solved Sudoku arrays to a text file

Question: Having some issues with a print to .txt function. There are a lot of options available, and I've tried several methods, but I'm running into errors.
I've created a Sudoku solver that reads an amount of 9×9 arrays from a text file and solves all of them. I have a working function that prints them into the terminal, but I need to output the results, formatted as they are in the terminal, into a text file.
Is there someway to amend the print function below to achieve that? I have a semi-working separate function that outputs to a .txt, but in an unformatted method and only one of the four puzzle arrays I've been using.
Thank you for your help.
def print_board(board):

  for x in range(len(board)):
    if x % 3 == 0 and x != 0:
        print("- - -   - - -   - - - ")
    for y in range(len(board[0])):
      if y % 3 == 0 and y != 0:
        print("| ", end="")
      if y == 8:
        print(board[x][y])
      else:
        print(str(board[x][y]) + " ", end="")
  return

This is the export function that is only displaying one array.
def export_board(board):

  outputfile=open('solvedpuzzles.txt', 'w')
  print(output, file=outputfile)
  outputfile.close()

This is the format I need to achieve, that is currently working in the terminal from print_board
4 8 3 | 9 2 1 | 6 5 7
9 6 7 | 3 4 5 | 8 2 1
2 5 1 | 8 7 6 | 4 9 3
- - -   - - -   - - -
5 4 8 | 1 3 2 | 9 7 6
7 2 9 | 5 6 4 | 1 3 8
1 3 6 | 7 9 8 | 2 4 5
- - -   - - -   - - -
3 7 2 | 6 8 9 | 5 1 4
8 1 4 | 2 5 3 | 7 6 9
6 9 5 | 4 1 7 | 3 8 2

Edit:
I have made some adjustments, and have this:
def print_board(boards):

  output = ''

  with open("puzzleoutput.txt", "a") as file:
    for x in range(len(board)):
        if x % 3 == 0 and x != 0:
            output += (str("\n - - -   - - -   - - - "))
        for y in range(len(board[0])):
          if y % 3 == 0 and y != 0:
            output += (str(" | "))
          if y == 8:
            output += (str(board[x][y]))
          else:
            output += (str(f"{board[x][y]} "))

    file.write(str(output))
    return

Can someone please let me know how to add a new line for the individual rows of 9? It prints out the array as such, and I think I've nearly cracked it
4 8 3  | 9 2 1  | 6 5 79 6 7  | 3 4 5  | 8 2 12 5 1  | 8 7 6  | 4 9 3
 - - -   - - -   - - - 5 4 8  | 1 3 2  | 9 7 67 2 9  | 5 6 4  | 1 3 8
 - - -   - - -   - - - 3 7 2  | 6 8 9  | 5 1 48 1 4  | 2 5 3  | 7 6 9

Answer: Could you not simply replace the print() statement with a writelines([]) statement?
output = []

with open("demofile3.txt", "a") as file:
    for x in range(len(board)):
        if x % 3 == 0 and x != 0:
            output.append("- - -   - - -   - - - ")
        for y in range(len(board[0])):
          if y % 3 == 0 and y != 0:
            output.append("| ")
          if y == 8:
            output.append(board[x][y])
          else:
            output.append(f"{board[x][y]} ")

    file.writelines(output)

Comment: Thanks Lawrence. I'm very, very new to Python. This is giving me an error however, of:line 91, in print_board
    output.append(str(board[x][y]) + " ", end="")
TypeError: list.append() takes no keyword arguments
Comment: Hi Ian, sorry I was a little lazy with my copy and pasting, I'd think you could just remove the 'end=""' statement. Let me modify my answer!
Comment: I also changed to using string interpolation; note 'f"{bard[x][y]} "' - its a neater way of including variables in a string if you are running Python3.
Comment: Thank you mate. That's now printing all four boards that have been processed - but unfortunately not in the desired format. It's just printing the arrays flat out, as such:
4 8 3 | 9 2 1 | 6 5 ['4 ', '8 ', '3 ', '| ', '9 ', '2 ', '1 ', '| ', '6 ', '5 ', 7, '9 ', '6 ', '7 ', '| ', '3 ', '4 ', '5 ', '| ', '8 ', '2 ', 1, '2 ', '5 ', '1 ', '| ', '8 ', '7 ', '6 ', '| ', '4 ', '9 ', 3, '- - -   - - -   - - - ', '5 ', '4

and so on :( I had to amend the file.writelines(output) to file.writelines(str(output)) as it was returning an error message. Any idea how to retain the format?
Comment: Hey mate. I've edited my post, because I made some changes to the code. I think all I need to do is place each row of the array in its own line, but I don't know where to add the code. Would you happen to know? Thank you
Comment: Hi mate - I wasn't able to edit my last comment. I used output += (str(' \n ')) to add line breaks where needed, and was able to achieve the formatting. Thank you for your help!
Comment: Awesome! Well done! Sorry I wasn't as helpful! Feel free to create your own answer and mark it as solved or I can modify mine to include your new line break :)
Answer: Preface
When I searched the web for a solved Sudoku, which is much harder than searching for Sudokus to solve. Here I found what I was looking for, so thank you for posting one.
That's what I want to give back, be it to you, be it to others who stumble upon this question someday.
Printing to files
The print function that's a Python 3 built in has an optional parameter file, which defaults to sys.stdout for the print calls you already know. The best way to solve your problem is to pass an (again optional) parameter through your print_board function to print. The following script contains a modified version of your function. It not also shows the usage of print function's the file parameter but also removes the flaw of mixing up x and y (if we take x as the horizontal and y as the vertical coordinate) because you are processing rows in the outer loop. This script also contains a function that turns what you define as output into a board (I was too lazy to type a nested python list):
# The optional `output` parameter specifies an
# open file; leave out to print to the console
def print_board(board, output=None):
  for y in range(len(board)):
    if y % 3 == 0 and y != 0:
        print("- - -   - - -   - - - ", file=output)
    for x in range(len(board[0])):
      if x % 3 == 0 and x != 0:
        print("| ", end="", file=output)
      if x == 8:
        print(board[y][x], file=output)
      else:
        print(str(board[y][x]) + " ", end="", file=output)

# Read a bord from a string that was formatted by
# the `print_board` function
def text_to_board(text):
    text = text.strip()
    board = list()
    for line in text.split('\n'):
        if '-' not in line:
            row = list()
            for letter in line.split():
                if letter != '|':
                    row.append(letter)
            board.append(row)
    return board

text = """
4 8 3 | 9 2 1 | 6 5 7
9 6 7 | 3 4 5 | 8 2 1
2 5 1 | 8 7 6 | 4 9 3
- - -   - - -   - - -
5 4 8 | 1 3 2 | 9 7 6
7 2 9 | 5 6 4 | 1 3 8
1 3 6 | 7 9 8 | 2 4 5
- - -   - - -   - - -
3 7 2 | 6 8 9 | 5 1 4
8 1 4 | 2 5 3 | 7 6 9
6 9 5 | 4 1 7 | 3 8 2
"""

board = text_to_board(text)
print_board(board)

with open('puzzleoutput.txt', 'w') as f:
    print_board(board, f)

Performance considerations
Normally it's efficient to directly writing to file, I experienced it to be fast enough. So I'd not suggest build a text buffer that's written at once: String concatenation, especially if done for character by character, involves a lot of allocating and freeing memory operations.
If performance really matters, I'd recommend a redesign not only the print_board function but also of the board storage itself. And of course, a solid knowledge about how to measure performance.
Further reading
print to file

print in: Built-in Functions — Python 3.10.4 documentation
How to redirect 'print' output to a file? and its answers


IPv6 only bound services accessible from IPv4 on dual stack Linux host: how does it work?

Question: I have this situation where Apache is listening on :::443 only
on a Linux host that has both IPv6 and IPv4 enable.
I can access the content served by that Apache from IPV4 only enabled computer.
Can someone help me understand what's happening, and how to verify this configuration on a Linux host (CentOS in my case)
I read somewhere that

[...] servers bind to IPv6 addresses (on all interfaces or on a specific one, if needed) and treat IPv4 as mapped ones because IPv6 and IPv4 share the same port space on the same machine. This works transparently thanks to glibc and is a recommended way to write networking applications. See man ipv6(7) for details.

I'd guess this means the only way this could happen would be with Ipv4 mapped address. However I can't get this working with ping6 ::ffff:127.0.0.1 or to my public IPv4 address.
Besides I don't see any config that would support this when looking at ip a
Comment: You cannot use IPv4-mapped Addresses (`::ffff:0:0/96`) as source or destination addresses, they are not forwardable (routable), nor globally reachable, and they are reserved by the IPv6 protocol, itself; see _[IANA IPv6 Special-Purpose Address Registry](https://www.iana.org/assignments/iana-ipv6-special-registry/iana-ipv6-special-registry.xhtml)_. Basically, you can use those addresses to store IPv4 addresses in a common format with IPv6 addresses, e.g. a database.
Answer: You can tell these are in use when ss output shows sockets with mapped addresses.
From ipv6(7)

IPv4 connections can be handled with the v6 API by using the
  v4-mapped-on-v6 address type; thus a program needs to support only
  this API type to support both protocols.  This is handled
  transparently by the address handling functions in the C library.

Note "transparently". You don't give programs v4 mapped v6 addresses, you give them v4 addresses.
Socket option IPV6_V6ONLY defaults to v6 listening to v4 mapped v6, per the default of /proc/sys/net/ipv6/bindv6only.
This behavior is platform specific. Notably, it is a peculiarity of Linux.
Comment: Note that I find this incredibly good and convenient. It's just that I got used to read `netstat` to understand what was listening to what, usually making sure services were listening to both ipv4 and ipv6.
I just don't understand how this work. If a service is not listening on a port on ipv4, how the hell can the listener for ipv6 receives ipv4?
This incidently also means that there no point for `sshd` for instance to listen to both stack as it usually does. I guess it's a matter of compatibility with older system.
Comment: I was not able to "see" anything about mapped address with `ss`. Just says `[::]:443` the same way `netstat` does.
Comment: Test by connecting to a service over both v4 and v6. If both are successful, you have the configuration correct. This functional test also will detect problems above layer 4.


Nested linear mixed effects model with time interaction

Question: I am dealing with a fairly complex model in my current analysis and I think that I am not able to model it correctly. My data come from a database in which 40 subjects pig are divided into two groups high.low and subsequently in three more called a.b.c. Basically we have two levels of power delivered in three different ways. These groups are also studied over time. My goal is to understand if:
1) The groups are different, for example: is low power B different than high power B?
2) Are the groups evolving differently over time?
My model:
m1 <- lme(dependent_variable ~ hour * high.low/a.b.c, random = ~1|pig, data = dataframe)

Do you think this is a correct way of modeling the problem?
Comment: to clarify, each individual `pig` is treated with a single level each (i.e., a single combination) of `high.low` and `a.b.c`?
Comment: Exactly, each pig receives a single combination, meaning it will be for example high power A or , for example, low power C
Answer: You can run then compare the following models:
m0 <- lme(dependent_variable ~ hour, random = ~1|pig, data = dataframe)
m1 <- lme(dependent_variable ~ hour + high.low/a.b.c, random = ~1|pig, data = dataframe)
m2 <- lme(dependent_variable ~ hour * high.low/a.b.c, random = ~1|pig, data = dataframe)

You can use a combination of likelihood ratio tests and information criteria for comparison.
If your comparisons unambiguously lead to:

m2: at least one of the groups evolves differently from the others over time, this simultaneously answers question 1
m1: the groups are different from each other but insufficient evidence to distinguish their evolution from each other
m0: only growth over time is relevant, insufficient evidence to tell the groups apart

There is also a baseline no predictor model as an alternative to any of the three models above.


derivative of square root of $x_1$ and $x_2$

Question: I am confusing with calculation of derivative of $$\sqrt{x_1x_2}$$ I am very thankful if anyone help me out of this problem.
my question is that,
(1) $x_1$ and $x_2$ are two different variable i just want to calculate the derivative with respect to $x$.
(2) if $x_1=x_2$ what would be the value of derivative.
Thanks in advance
Comment: If you don't tell what's the relation between $\,x\,$ and $\,x_1,x_2\,$ then it is impossible to solve this.
Comment: x1 and x2 are the function of x.
Comment: Do you mean $\;x= x_1\cdot x_2\;$ or **each** is a function *of* $\,x\,$ ?
Comment: Each is a function of x
Answer: Ok then: so $\,x_i=x_i(x)\;,\;i=1,2\,$ , and then:
$$\frac d{dx}\left(\sqrt{x_1x_2}\right)=\frac{x_1' x_2}{2\sqrt{x_1x_2}}+\frac{x_1x_2'}{2\sqrt{x_1x_2}}=\frac{x_1'x_2+x_1x_2'}{2\sqrt{x_1x_2}}$$


Link poco static library to target in cmake

Question: I read a lot of post but I don't yet well understood how to link my target to a static version of a library.
My project depends on poco libraries and, while in linux they are stored in /usr/local/lib (both the static and shared versions) in my windows machine are in d:\libs\poco\lib and d:\libs\poco\bin (where I have an enviroment variable called POCO_DIR = D:\libs\poco)
So, how can I have to write the find_library() directive in cmake file?
Thanks in advance.
Answer: You never link with a Poco DLL on windows, not even when you use shared Poco libraries. Linking is always with entries in the %POCO_BASE%/lib. For shared builds, .lib is just a stub ("import library") that takes care of loading the DLL at runtime. See Linking Implicitly for details on how this works.
Poco static libraries can be distinguished from the import libraries for DLLs by the file name - static libs have "mt" ("mtd" for debug binaries, "md" and "mdd" when runtime library DLLs are used) appended to the name. So the import library for PocoFoundation.dll will be named PocoFoundation.lib, while the static library using static runtimes is named PocoFoundationmt.lib. Static library using dynamic runtimes is PocoFoundationmd.lib. See Use Run-Time Library for details.
As for CMake, I am not an expert, but for e.g. static Foundation and Net libraries should be something like this:
<code>FIND_LIBRARY(Poco_LIBRARIES NAMES PocoFoundationmt PocoNetmt PATH_SUFFIXES ${POCO_DIR}/lib)
</code>
EDIT: If you define POCO_STATIC in your project, static linking will be automatic through library headers, see e.g. Foundation.h.
Comment: Use if(WIN32) to detect the OS.
Comment: Hi Alex, thanks for the reply. I know how linking works :) My doubt is only which name I have to use in FIND_LIBRARY(). If in Windows there is the suffix to distinguish between various kind of builds, in Linux there is the extension only (.a or .so). So if I write 'PocoFoundationmt' maybe is valid only for Windows. I'm asking myself is there a way to use the same directive both for every systems.


Entity Reference Autocomplete module: hook_entity_info definition?

Question: I have tested the Entity Reference Autocomplete module by defining a form field of type entityreference (via hook_form) on the user entity - and it works as advertised.
When I try it on my own entity an AJAX error is thrown.
My form element definition:
$form['name'] = array(
  '#title' => t('Ground'),
  '#type' => 'entityreference',
  '#era_entity_type' => 'ground',
  '#size' => 32,
);

I can't imagine the problem is my entity's base table. So, the only thing I can think of, which may be the source of the error, is my hook_entity_info definition:
/**
 * Implements hook_entity_info().
 */
function scorebook_entity_info() {
  $return = array(
    'ground' => array(
      'label' => t('Ground'),
      'controller class' => 'EntityAPIController',
      'base table' => 'scorebook_ground',
      'entity keys' => array('id' => 'grid'),
    ),
  );
  return $return;
}

It contains the minimum keys. Do I need to add some other keys to my definition? If anyone knows of a working example of this module working with a custom entity that may help too. Thanks.
UPDATE:
Here is the correct hook_entity_info definition for anyone who doesn't want to read everything below. You need to define an access callback function, also, to return either TRUE/FALSE accordingly.
'ground' => array(
  'label' => t('Ground'),
  'controller class' => 'EntityAPIController',
  'base table' => 'scorebook_ground',
  'entity keys' => array(
    'id' => 'grid',
    'label' => 'name',
  ),
  'access callback' => 'scorebook_access',
),

Answer: I'm the module maintainer. Thanks for using the module, hope you're finding it useful. You need to add a 'label' key to your entity definition, like:
'entity keys' => array(
  'id' => 'grid',
  'label' => 'table-column-that-contains-the-human-name-of-entity',
),

With that, and after flushing caches, etc, your form should work fine. The reason is that entityreference_autocomplete assumes that (as a best practice), every entity would have, apart of the ID, which will be normally just a number, some friendly way to identify it through a label. Therefore, you need that on your custom entity.
However, I get that not everyone might want / need that 'label' key or a column for the label in their schema, for whatever reason, and I've added support to the module to work without that. That bit is on the dev version on the module, and will be rolled out in the next stable version. So it's up to you, to define a column for the 'label' key in your schema, or download the dev version, or wait a  couple days for the stable release that supports entities without the 'label' key.
Cheers!
Comment: Thanks. Adding the 'label' key stopped the error, but I don't get any suggestions dropping down. Do I need any other keys in `hook_entity_info`?
Comment: The 'label' key is supposed to map to a column in the schema table of your entity in the database. Of course that needs to be prefilled with some values through your entity class / controller. Is that column in there an populated with any values?
Comment: Yes, there are rows in the base table, but the autocomplete widget is not returning any matches. Would it help to see my module? Thanks.
Comment: Yes, that would definitely help! It's worth if you double check the db as well to make sure those columns for the label are populated, and to use xdebug to see what's happening in the autocomplete callback, to see if all the args are passed to the query as expected, and the results of it.
Comment: Module sent to the contact email on your website.
Comment: I swapped in the Entity_Autocomplete module and it is now working. Let me know if I can provide you with anymore information to solve the problem with Entity_Reference_Autocomplete.
Answer: Right. Checked your module, and your issue here is permissions.
Before returning results, the module checks whether the user has actually permission to see those results, and cuts the ones that the user is not supposed to see.
In this case, none of your entities define an 'access callback' in hook_entity_info(), which ultimately translates in the Entity API returning NULL when permissions are checked, which my module treats as "nothing defined, better be safe and don't return results".
So you were probably using my module in the right way, but your entities are missing the access checks.
I suggest you add at least a global check for them, like
      'access callback' => 'scorebook_entity_access',

And then implement that function.
function scorebook_entity_access($op, $entity, $account = NULL, $entity_type = '')
{
 // Edit to fit your requirements.
  return TRUE;
}

I've tested it with grounds, which are the ones defining a label, and it works all right.
Hope it helps!


How to handle Forms with Phoenix LiveView

Question: I have a form in phoenix which looks like this
<%= form_for @changeset, Routes.post_path(@conn, :create, @post), [method: "post", multipart: true], fn f -> %>

      <%= input f, :title, "Title", [class: "form-control", type: "text", placeholder: "Enter Title", required: true] %>

     <%= input f, :description, "Description", [class: "form-control", type: "text", placeholder: "Enter Description", required: true] %>

   <%= submit "Create Post" %>

<% end %>

The above form works fine, Now I want to change this form to implement LiveView. So I have done something like this
<%= form_for @changeset, "#", [method: "post", multipart: true], fn f -> %>

      <%= input f, :title, "Title", [class: "form-control", type: "text", placeholder: "Enter Title", required: true] %>

     <%= input f, :description, "Description", [class: "form-control", type: "text", placeholder: "Enter Description", required: true] %>

   <button phx-click="create-post" phx-value="form-value">Create Post"</button>

<% end %>

I am confused in the place of form-value, what needs to be send so that I will get the correct form data which contains title and description in my handle_event function.
I tried passing the @changeset and also f, but they are sending proper phx-value which will contain my title and description.
Not sure, If am implementing Form with LiveView correctly or It needs to be done in different manner.
Answer: The only once difference here is that you don't want to use an anonymous function with form_for.

<%= form_for @changeset, "#", [phx_submit: "post", multipart: true], fn f -> %>
...
<% end %>

becomes
<%= f = form_for @changeset, "#", [phx_submit: "post", multipart: true] %>
...
</form>

Anonymous function content can't be diffed.
Answer: This is the right way to implement the form with phoenix liveview
<%= form_for @changeset, "#", [phx_submit: "post", multipart: true], fn f -> %>

        <%= input f, :title, "Title", [class: "form-control", type: "text", placeholder: "Enter Title", required: true] %>

       <%= input f, :description, "Description", [class: "form-control", type: "text", placeholder: "Enter Description", required: true] %>

      <%= submit "Create Post", phx_disable_with: "Posting..." %>

<% end %>


How to run Drupal console command from code?

Question: I have found a lot of documentation on how to run Drush commands from code, but I'm specifically looking on how to run a Drupal Console command from code.
I have some experience in Symfony and I know how to run a Symfony command from code. Since a Drupal console command extends on Symfony command, I thought this should be rather easy. Simply following this tutorial doesn't amount to anything though.
I am trying to run a command in a hook_cron() implementation in a custom module.
Comment: Please elaborate why you would downvote my question. I've spend close to an hour in the code and over an hour on the internet for a solution, but I just can't get there.
Comment: Thanks. I've added the answer with refernces to the php docs to help others as well
Comment: What if you use the php functions exec() or shell_exec() ? I haven't done it before but it's the first thing I would try.
Comment: It's weird how you can become so fixated on doing it 1 way that forget about the other, way easier ways.. Will accept as answer if you add it ;)
Answer: Run shell commands via the Process class available in the Symfony framework.
From the Symfony docs:
use Symfony\Component\Process\Process;
use Symfony\Component\Process\Exception\ProcessFailedException;

$process = new Process('ls -lsa');
$process->run();

// executes after the command finishes
if (!$process->isSuccessful()) {
    throw new ProcessFailedException($process);
}

echo $process->getOutput();

The component takes care of the subtle differences between the
  different platforms when executing the command.

Replace the ls -lsa command in the Process() constructor with your Drupal console command.
Comment: This is more in the way I was looking for indeed. Sticking with `exec` for now since there aren't any parameters and the command is fixed, but this is nice for better handling of your commands.
Comment: Thank you, this approach looks good. There is a function `drush_shell_exec_interactive` which shows more imformation for interactive commands, like `drush cim -y`. But it is deprecated. I am still looking for a replacement for this function.
Answer: Try using the PHP functions exec() or shell_exec().
Comment: But do so carefully and responsibly.
Answer: In D10 at least you can now run e.g.:
  $modules = ['redis'];
  \Drupal::service('module_installer')->install($modules, TRUE);

So many things you would want to do with Drush now can be called directly through Drupal services.


How to send the file to node.js and back end when using ng-flow to take the file

Question: I am using angularJS's ng-flow to upload a img in my app. the prob is that I successfully upload the file flow and I am not able to send the file to node.js and save it to mongoDb.
Code (FrontEnd)(HTML):

JS:
$scope.saveImage = function(flow){
console.log('hello')
            if(flow){
            var abc = !!{png:1,gif:1,jpg:1,jpeg:1}[flow.files[0].getExtension()]
            if(abc == true){
                $scope.groupData.picURL = flow.files[0];
                $scope.img = flow.files.length;
            }else{
                flow.cancel()
            }
            }
        }

I have file object in flow.files[0] and $scope.groupData.picURL.
Now can I make a POST request to the server and then save it to mongoDB.
Please help with the example Code
Answer: The problem is that your not actually reading the file at all, you're just retrieving the file object. You will need to use the FileReader object to read the data, so that it can be passed to the server. I've set up a function which returns the FileReader object which will get the resulting data from the image. You can call that function from within your existing save function.
var getFileReader = function( $scope ) {

    var fileReader = new FileReader();

    fileReader.onloadend = function() {

        $scope.img = fileReader.result;

    }

    return fileReader;
};

And then within your function call:
$scope.saveImage = function(flow){

        if(flow){
            var abc = !!{png:1,gif:1,jpg:1,jpeg:1}[flow.files[0].getExtension()]

            if(abc == true){
                var fileReader = getFileReader( $scope ),
                    file = flow.files[0];

                 fileReader.readAsDataURL(file);

                 $scope.$apply();

            }else{
                flow.cancel()
            }
      }

 }

Comment: I have solved that issue by passing flow.files[0].file instead of flow.files[0].
Comment: getting this err  TypeError: Failed to execute 'readAsDataURL' on 'FileReader': The argument is not a Blob
Comment: That means the `flow.files[0]` object is not a readable image file, which means you're not selecting the correct file.  See for more info: https://developer.mozilla.org/en-US/docs/Web/API/FileReader.readAsDataURL  Can you set up a jsfiddle?
Comment: Is it possible to get on server side as req.file. If so which object is passed along with http post request?


IIS 7.5 returns error 401 instead of 500

Question: I have a strange problem with ASP.NET MVC web application. IIS 7.5 throws back error 401 instead of 500 when application error occurs. This happens in production environment only, dev or staging works fine; the difficulty here is that I don't have access to the production environment so I have to replicate issue on my own to see what is wrong.
Any suggestions?
Answer: 401 means that Authorisation is required.. Do you use custom error pages? and if so does your application have access to the custom error pages? that would be my first guess.
Comment: Yes, I do have custom error pages, but for some reason they are ignored by IIS. I will try look into that. Thanks for a clue!


Why is an adjustable bridge needed?

Question:
Possible Duplicate:
Why is my guitar's saddle at an angle?

I think my acoustic has a bridge that makes each string a slightly different length, and I'm assuming an adjustable bridge does the same thing.  Doesn't a slight change to tuning of each string have the same effect, or is it something to do with temperament?
Comment: @Alex - you're right, that's exactly the question I was trying to ask.  Can someone close my duplicate question?
Answer: Here is all you need to know about why the bridge on your acoustic is angled: Why is my guitar's saddle at an angle?
An adjustable bridge on an electric guitar is exactly the same, but is adjustable so that it is easier to adjust the intonation settings when strings are changed or a heavier/lighter string gauge is used on the guitar.

Why is an adjustable bridge needed?