PrinterSettings.InstalledPrinters on Vista

Question: I have a WCF service hosted on a Windows Service application and it should return all installed printers on the machine it is hosted on. I have used System.Drawing.Printing.PrinterSettings.InstalledPrinters to retrieve the list of installed printers but I don't know why in Windows Vista it doesn't return all printers.
The host Windows service is run using an account which is a member of Administrators group, has "Log on as a Service" privilege and added app.Manifest with the "requireAdministrator" execution level.
UPDATE:
If I use the InstalledPrinters property on a windows application in Vista it returns all printers!
Answer: Do you have any printers installed for the user running the application that the other member does not have installed?
This might be one avenue to check, since any printers that are setup just for the user you are running the application as may not be setup for the user you are running the service as.
(this is, of course, a moot point if you are running both as the same user)
Comment: You are right. The problem is that my service is running under a different user account. Is there anyways to install printers for the user account that my service uses, without having to logging in to that account?
Answer: You should install your printers locally to use them from a Windows service. When you start the Add Printer wizard you get to choose whether to add a local or remote printer.


$L^{\infty}$ norm is bounded by $L^2$ norm for holomorphic functions

Question: I want to prove that, given $f$ holomorphic in a disc $D_r(z)$ and $0<s<r$, we have
$$\sup_{D_s(z)}|f| \leq \|f\|_{L^2(D_r(z))}$$
where the $L^2$ norm is defined on an open set $U \subset \mathbb{C}$ as $$\|f\|_{L^2(U)} = \Bigl(\int_U |f(z)|^2\,\mathrm dx\,\mathrm dy\Bigr)^{1/2}$$
I know I should use the mean value principle somehow, but I'm not sure how we can pull out the $L^2$ norm from it.  I can see that by the max modulus principle, we have that
$$\sup_{D_s(z)} |f| \leq \sup_{C_s(z)}|f| \leq \sup_{C_r(z)}|f|$$
where $C_k(z)$ is the circle of radius $k$ centered on $z$.
After a while of trying to figure out how to apply the mean value principle, I tried working backwards from the $L^2$ norm via polar coordinates to get
$$\frac{r}{\sqrt 2} \Bigl(\int_{0}^{2\pi} |f(z+r\mathrm e^{\mathrm i\theta})|\,\mathrm d\theta\Bigr)^{1/2}.$$
Can we say that the integral is the mean value principle applied to $|f^2|$? I wanted to use max modulus and the fact that $D_s(z_0) \subset D_r(z_0)$ to conclude $\sup_{D_s}|f| \leq |f(z)|_{z \in D_r}$, but this inequality may not be true - it only applies if we consider $z \in D_r \setminus D_s$, correct?
I'd appreciate it if anyone could lead me into the right direction with this. It seems like the related questions on here have answers beyond the scope of this course.
Answer: Let $d > 0$. If $g$ is holomorphic on some neighbourhood of $\overline{D_d(z)}$, the mean-value theorem tells us that
$$g(z) = \frac{1}{2\pi} \int_0^{2\pi} g(z + \rho e^{i\varphi})\,d\varphi$$
for $0 \leqslant \rho \leqslant d$, hence
$$| g(z)| \leqslant \frac{1}{2\pi} \int_0^{2\pi} | g(z + \rho e^{i\varphi}|\,d\varphi. \tag{1}$$
Multiplying $(1)$ with $\rho$ and integrating from $0$ to $d$ we obtain
$$|g(z)| \frac{d^2}{2} \le \frac{1}{2\pi} \int_0^d \int_0^{2\pi} | g(z + \rho e^{i\varphi})|\,\rho\,d\varphi\,d\rho = \frac{1}{2\pi} \iint_{\lvert w - z\rvert \leqslant d} | g(w)|\,dx\,dy.\tag{2}$$
Letting $g = f^2$ in $(2)$ and dividing by $d^2/2$, then  taking the square root, we obtain
$$|f(z)|\le \frac{1}{\sqrt{\pi}\,d} \,\lVert f\rVert_{L^2}(D_d(z)). \tag{3}$$
Choose $d = r-s$ to see
$$\lvert f(z)\rvert \le \frac{1}{\sqrt{\pi}\,(r-s)} \,\lVert f\rVert_{L^2(D_{r-s}(z))} \le \frac{1}{\sqrt{\pi}\,(r-s)} \,\lVert f\rVert_{L^2(D_r(z_0))}\tag{4}$$
for all $z \in D_s(z_0)$, whence
$$\lVert f\rVert_{L^{\infty}(D_s(z_0))} \le \frac{1}{\sqrt{\pi}\,(r-s)} \,\lVert f\rVert_{L^2(D_r(z_0))}.$$
Comment: Where does $0 \leqslant \rho \leqslant d$ come from ?
Comment: @Zophikel By deformation of the contour, we can integrate over any circle of radius $\rho \leq d$.


Is it possible to graph this?

Question: Is it possible to graph this?  I tried doing it on a calculator but didn't have any success.  If someone can and post the graph I would greatly appreciate it.
$$\frac{1}{\bar{m}_{T}}\sqrt{\frac{1}{12} \sum_{h=T-11}^{T} (m_{h} - \bar{m}_{T})^2}.$$
If the equation is hard to read, it is just the standard deviation of 12 observations $(m_{h})$, $h=T-11, T-10, \ldots, T$, over the mean of the same 12 observations. The standard deviation is the population standard deviation and the mean $\bar{m}_{T}$ is simple average.
Comment: It is possible to write well-formed $\LaTeX$ on this site.  Please rewrite so that you're sure you know what should be written - otherwise it's guesswork for answerers.
Comment: What, precisely, do you mean by "graph this"?  The expression depends on 12 variables!
Comment: IMO you are asking a bad question; the core idea behind visualization is to see something, not just to make a picture -- i.e. what is your aim here? Check the behavior for some specific case? Compare to some other statistic?
Comment: Check the behavior as these variables move around.
Comment: I dont know latex? This was written in equation editor in office. i added the "bar" because that didnt translate.
Comment: I'm not yet very familiar with CV myself, but there may be a FAQ around here that points to LaTeX formatting (cue: moderators :)).  Another more immediately useful option is to post an image of the formuala you intend - you can do a printscreen & save the image to a jpg, then post into your question.
Comment: @Iterator Links to the TeX formatting help appear on the right of the textbox when asking a question.
Comment: @whuber: Can you provide a direct link?  I looked at the FAQs that appear when asking a question, but couldn't find where to direct the OP.  Thanks!
Comment: @Iterator Start [asking a question](http://stats.stackexchange.com/questions/ask).  Put the cursor in the question textbox. Look at the right.  There are two links to TeX help at the bottom.
Comment: @whuber: Thanks for reformatting.  JM: what do you intend to graph?  As whuber says, it is a lot of variables.
Comment: @whuber: Aha!  I didn't click in the textbox. Nice bit of interface magic there. :)
Comment: @JM: But it has 12 values of `h` - hence the 12 variables that whuber mentioned.
Comment: @whuber@Iterator The reason I am trying to calculate this is after using this a bunch of times I have started to notice a pattern that resembles something like a higher order polynomial equation might look like when graphed. I know there are a lot of variables going on.
Comment: Note to whoever edited my $\LaTeX$ comment (1st one): Thanks!  I am amused I forgot the correct coding.  The reminder is helpful.
Comment: @JM IF you want to know what happens when your variables 'move around', can you enlighten us how you expect them to move around? Do these come from (e.g.) a normal distribution? Are they limited to a certain region? etc. Once you know that: generate (repeatedly) 12 observations and calculate your statistic of interest. If you do this 10000 times, you can then look at the histogram (or even a smoothed version) of these 10000 values for the statistic. Is this what you want?
Answer: I have no idea if this is what the poster is looking for, but I was curious so started exploring and thought I'd share.  Using more traditional notation, let $X_1, ..., X_{n}$ be i.i.d. with $X_i \sim N(\mu, \sigma^2)$.  Then $E(\bar X | X_1)$ is a linear function of $X_1$ and $E(\sum(X_i-\bar X)^2/n | X_1)$ is a quadratic function of $X_1$; so if the mean is always positive, the expected value of the variance/mean is quadratic also.  Not too hard to check if you're patient with your algebra; I'm not, so will demonstrate by simulation. Whether the sd/mean is quadratic or not is left to the reader, who is again hopefully more patient with algebra than I.
An intuitive explanation is that when one of the random variables is above or below the true mean, the sample mean is also more likely to be above or below the true mean.  But the sample standard deviation is more likely to be large when one of the random variables is far from the true mean (either above or below) and more likely to be small when it's near the true mean.

<code>set.seed(5)
N <- 1000
n <- 12

d <- matrix(rnorm(n*N,mean=8),ncol=n)
m <- rowMeans(d)
s <- apply(d, 1, sd)

par(mfrow=c(1,3))
plot(d[,1],m, col="#88888888", xlab=expression(m[1]), ylab="mean", main="mean")
lines(lowess(d[,1], m))
plot(d[,1],s, col="#88888888", xlab=expression(m[1]), ylab="sd", main="sd")
lines(lowess(d[,1], s))
plot(d[,1],s/m, col="#88888888", xlab=expression(m[1]), ylab="sd/mean", main="sd/mean")
lines(lowess(d[,1], s/m))
</code>
Answer: Typically, when data are serially indexed like this, they form a series (usually a time series): the formula asks for the coefficient of variation within a twelve-period moving window (as if the data were monthly and the moving window were a year, for instance).  If this is the case, graphing takes two steps:

For each index $T$ of 12 or greater, compute the CV for the window spanning indexes $T-11$ through $T$.  This gives a derived series $CV_T$, also indexed by $T$, for all $T \ge 12$.
Plot the pairs $(T, CV_T)$.

For example, the data (shown for $T=1, 2, \ldots, 100$) might look like

and the derived series--the "moving CV"--would then look like

Is it possible to graph this?


Is there a cardinal $\kappa$ with uncountable cofinality such that $\kappa<\kappa^{\aleph_0}$?

Question: Is there a cardinal $\kappa$ with uncountable cofinality such that $\kappa<\kappa^{\aleph_0}$? The question is motivated by the observation that $\kappa< \kappa^{{\rm cf}\kappa}$ for any $\kappa$.
Comment: It depend on the continuum hypothesis, or more generally what the kind of cardinal arithmetic holds.
Answer: Assuming $\sf GCH$ then the answer is no, almost trivially. Since in that case $\kappa^{<\operatorname{cf}(\kappa)}=\kappa$ for every cardinal.
If $\sf CH$ is false, then $\aleph_1$ is an example; it is possible that $\sf GCH$ is false, but only $2^{\aleph_1}=\aleph_3$ is an example, in which case, despite the failure of $\sf GCH$, the statement is true.
And it is possible that the counterexamples are of this flavor, and they occur on a much later stage (e.g. $\aleph_{\omega_1+\omega}^{\aleph_0}=\aleph_{\omega_1+\omega+3}$ in which case $\aleph_{\omega_1+\omega+2}$ is an example as well).

So from $\sf ZFC$ this is neither provable nor disprovable, and will depend a lot on additional assumptions.


Smallest possible subgroup of $\,D_6\,$ containing two elements of $\,D_6\,$

Question:
Let $\,G = D_6;\;$ let $\,H\,$ be the smallest subgroup containing the elements $\,r^2s\,$ and $\,sr^2.\;$ List all the elements in $\,H\,$ and explain.

My intuition leads me to $H =  \{ r^2s, \,sr^2,\, e \}$.
Comment: Those elements must indeed be in the subgroup. But what you have written is not a subgroup, so you will need to include some more elements.
Answer: You should be more precise in specifying your problem.  I'll assume that $D_6$ refers to the symmetry group of a regular hexagon.  (There are different conventions as to how to index the dihedral groups.)  I assume furthermore that $r$ refers to a rotation of $60^{\circ}$, say counterclockwise for definiteness, and that $s$ refers to a reflection symmetry, say for definiteness a reflection across the horizontal axis that runs through two vertices of the hexagon.
The key relation is that $rs = sr^{-1}$.  Another way of writing is this that $srs^{-1} = r^{-1}$; in fact, this can be generalized to the statement that conjugating any counterclockwise rotation by a reflection yields the clockwise rotation by the same angle as the original counterclockwise rotation.
For $H$ to be a subgroup, it must be closed under products and inverses.  Now $r^2 s$ and $s r^2$ are both reflections (why? there's an easier answer in terms of linear algebra).  So squaring either of these elements will produce the identity and they are their own inverses, so we haven't produced any new elements yet.  But we can multiply these two elements together: $(r^2 s)(s r^2) = r^4$ and $(s r^2)(r^2 s) = s r^4 s = r^2$.  Furthermore, it is easy to see that $(sr^2)r^4 = s$ is also in $H$.  Thus, $$H \supset \{ e, s, r^2, r^2 s, r^4, r^4 s = s r^2 \}.$$  But the set on the right hand side is already a subgroup; you could either argue that elements of the form $r^i s^j$ where $i$ is an even integer are closed under taking products and inverses.  Or you could recognize these six elements as the symmetries of the inscribed equilateral triangle whose vertices are every other vertex of the hexagon.
Answer: Use what you know about the elements of the Dihedral group of order 12(the symmetries of a regular hexagon) which is denoted here as $D_6$ and work to obtain a subgroup generated by the elements you're given $r^2s, sr^2$. (The linked pages denotes r by R, and s by r.)
But for your elements, $r, s$, we take $r$ to be a rotation of $60^\circ$ (counterclockwise, perhaps, just be consistent) where $r$ has order $6$, and $s$ refers to a reflection, e.g., the reflection across the horizontal axis that runs through two opposing vertices of the hexagon, with $s$ of order $2$. See this link for more information on $D_6.$

More to the point, you need to obtain "closure" of the group generated by $r^2s$ and $sr^2$ under the group operation of $G = D_6$. We want to be sure to include all possible (unique) products in $H$, and ensure each element's inverse is included in $H$.
As you probably noted, the squares of each of your elements $r^2s$ and $sr^2$ is the identity $e$, hence of the given elements is of order 2. This means that each of these elements must is its own inverse. But we need to obtain closure in $H$: what elements do you get when you compute $(r^2s)(sr^2)=r^2s^2r^2$?: you get $r^4\in H$ since $s^2 = e$. And what do you get when you compute $(sr^2)(r^2s) = sr^4s$? You get: $r^2 \in H$. (Why?). Note that $r^4r^2 = e$, since $r$ is of order 6. But we also need to look at $(sr^2)(r^4) = sr^6 = s \in H.$ Finally, we compute $(r^4)s = sr^2$, which we already know is in $H$.
Thus, we have $\bf{H = \{e, s, r^2,  r^4, r^2s, sr^2\}},$ which is closed under taking inverses and closed under taking products, and $e\in H$. So $H$ is indeed a subgroup, and in particular, $H \leq G = D_6$. It cannot be any smaller without failing then to be a subgroup. Indeed, it's the smallest subgroup of $G$ containing the given elements $r^2s, sr^2$!
Comment: @bobdylan: In fact you are looking for $\bigcap_{x\in D_6}xHx^{-1}$. +1
Comment: Thanks for the input, @Babak I never know how much to give away, or whether to just give answers. It depends in part, on follow-up questions/effort from the asker, I guess.
Comment: Yes. I agree with you.
Comment: In the image above, $R_0 = e$, $R2 = r^2$, $R4 = r^4$, and $s = S0$. Let me know, bobdylan, if you have any questions :-)
Comment: This is wonderful,amWhy. How could you prepare such this illustration. I don't think I can find such this in any books. There is a good exercise for every one to reflect it again. Thank you for sharing it here.
Answer: Let me add a couple of comments. I assume the notation @MichaelJoyce has spelled out.
Both $r^2 s$ and $s r^2$ are involutions (elements of order 2), so by Lagrange's Theorem the order of $H$ must be divisible by 2. This is a helpful piece of information, signalling that your first guess had to be corrected.
Also, it is not difficult to prove that any group generated by two involutions $a$ and $b$ is dihedral, of order $2 n$, where $n$ is the order of $a b$ (or infinite, if $a b$ has infinite order).
In your case $r^2 s \cdot s r^2 = r^4$ has order 3, so you get a dihedral group of order 6 as shown in the other answers.
Comment: @MichaelJoyce, thanks!


Multiple results being returned using search for same node

Question: I have a view-based search in my site. I notice that when I type a phrase like so "search terms" or even just search terms (no quotes) into the search box it returns all results that match that exact phrase as you'd expect BUT it also returns multiple versions of the same node!
I checked to make sure they are the exact same node and I think they are. One of these nodes is returned 6 times. I clicked on each linked result and the pathauto-altered URL is exactly the same for each. So for some reason it's returning it 6 times and I don't know why. Other nodes get returned fewer times. Some don't get returned more than once. I've checked some of the items that get returned multiple times in the mysql database and they appear to only be in there once...
I've cleared caches and run cron/re-indexed site...nothing.
I've got into 'find content' and looked to see if there are multiple copies of the nodes. Nope just the one.
And if, when I search, I just search for one word in the profile it only returns it once.
However, when I search for multiple terms I get multiple copies. I've reviewed the SQL of the returned view and it doesn't look like anything funky is going on.
Any idea why this might be happening?
Answer: There is a join in the query that is causing multiple instances of the same node to be returned.
Edit the view and under the "Other" section click on Query settings and choose Distinct.
The description says:
"This will make the view display only distinct items. If there are multiple identical items, each will be displayed only once. You can use this to try and remove duplicates from a view, though it does not always work. Note that this can slow queries down, so use it with caution."
Here is the "Other section" in the view settings:

EDIT:
If this doesn't work then try the Views Distinct Module that Sage mentions in his comment below.
Comment: thanks for your help. I 'solved' the problem by adding Views Distinct module. I'd rather add code but sometimes if it works it works. Turns out this is something Views just has problems with when you have complicated filtering mechanisms already in place (as I do). I think it has to do with each node having multiple selections for certain multiple select fields. Thanks for your help though. I'll give you correct answer since it would probably help some people with less complicated setups.
Comment: Hi, yes, you'd think that would work, but it doesn't. I also tried enabling aggregation, adding the nid field (and hiding it) and aggregating on the nid field with 'count distinct' and it's still displaying multiples of each node for some reason. I don't understand it's duplicates of the exact same node! and they don't even exist (as far as I can tell).
Comment: @Sage can you add the SQL generated by the view to the question as will make it easier to see what's going wrong


the general form of SDE

Question: Why do various SDE books consider only equations with the following form:
$$\displaystyle \mathrm {d} X_{t}=\mu (X_{t},t)\,\mathrm {d} t+\sigma (X_{t},t)\,\mathrm {d} B_{t}$$
I understand that it is analytical and computational convenient, and also many time-varying phenomena in various fields in science and engineering can be modeled as the above form. But I still wonder

What is the exact reason that we just assume SDE with this form?
Can you give me some examples of SDE that do not fall into the above form? Are they solvable?
Are there any textbooks that consider other forms?
Comment: I guess that multi-dimensional Brownian Motion is not much of a stretch from first order. There is certainly a research literature on stochastic PDE's, integration with respect to more general processes (Poisson and so on) and even quantum stochastic processes. As you suggest, this may currently require too much machinery for a textbook and someone has to have the time to write one too!
Comment: What other form would you suggest - what form is not there in your view?
Comment: For example, I think multiple noise sources

$\displaystyle \mathrm {d} X_{t}=\mu (X_{t},t)\,\mathrm {d} t+\sigma (X_{t},t)\,  (\mathrm {d} B_{t} + dC_t)$

or higher order:

$\displaystyle \mathrm {d} X_{t}=\mu (X_{t},t)\,\mathrm {d} t+\sigma (X_{t},t)\,  \mathrm {d}^2 B_{t}$

And also instead of noise-ODE, I think that SDE with PDE is also possible.

(Since I'm a noob in differential equations, please understand me for silly question)
Answer: Remaind that $\sigma(t,X_t)dW_t$ is a notation for the stochastic integral
$$
\int_0^t \sigma(s,X_s)dW_s
$$
There is no good way to define the term $d^2 W_t$.
SPDES instead are the infinite dimensional generalization of  the formula that you have written.
The most famous example is the stochastic heat equation
$$
\partial_t u= \Delta u + \xi
$$
where $\xi$ is the white noise
More generally one can define as SPDE as
$$
dx_t=L x_t +F(x_t) dt +Q dW_t
$$
where $L$ is the generator of a $C_0$ semigroup on a separable Banach space $B$, $F$ is measurable in $\mathcal{D}(F) \subseteq B$, $Q : K \to B$ is a bounded linear operator form an Hilbert space $K$ to $B$ and $W_t$ is a cylindrical B.M. see e.g these lecture notes  on the subject.
Many of these condition can be probably lifted as well e.g you can consider multiplicative noise $Q(x_t) dW_t$, or you can consider integration w.r. to non Gaussian measures, but these are actually research topics and I'm not expecting to see that in any textbook (so far at least)

the general form of SDE


QQ plot in Python

Question: I generated a qq plot using the following code. I know that qq plot is used to check whether the data is distributed normally or not. My question is what do the x and y axis labels indicate in qq plot and what is that r square value indicating??
  N = 1200
  p = 0.53
  q = 1000
  obs = np.random.binomial(N, p, size = q)/N

import scipy.stats as stats

z = (obs-np.mean(obs))/np.std(obs)

stats.probplot(z, dist="norm", plot=plt)
plt.title("Normal Q-Q plot")
plt.show()

I know that already there is a discussion about qq plot, but  I couldnt understand the concept of despite of going through that discussion.
Comment: This is very close to being a duplicate of the linked thread - Python vs R is not an important distinction here - but the $R^2$ aspect is new. It might be a good idea for question and answers to focus a little more on that aspect to avoid duplication. (I wonder whether $R^2$ is prone to being misunderstood, since even for poor fit, the upwards slope that's inevitable in a QQ plot means we expect an $R^2$ somewhat larger than zero. So values that might be quite impressive in a regression analysis may not be quite so impressive here.)
Comment: @Silverfish I would not find it helpful or worthwhile to focus on the $R^{2}$.  Q-Q plots are typically *seen*, not just reported with a table of myriad $R^{2}$ values.  As long as the visualization is there, why reduce it to a single number?  If the Q-Q plot looks "bad", but the $R^{2}$ somehow looks "good", would you still claim it's normal?  Most good packages do not even provide the $R^{2}$ for precisely this reason.  This viz-versus-moment argument even has a cute name: [Anscombe's quartet](https://en.wikipedia.org/wiki/Anscombe%27s_quartet).
Comment: @MikeWilliamson I agree that the $R^2$ is not likely to prove especially useful (this was part of my point, though I may have expressed it poorly). My main point was that "how to interpret a QQ-plot" has been discussed at length [here](https://stats.stackexchange.com/questions/101274/how-to-interpret-a-qq-plot), as the question already notes - the only reason this thread should not be closed as a duplicate is the query about $R^2$, so that really ought to be discussed in the answers here (even if it is to say that it is not useful!)
Comment: Are you sure that you plot a Q-Q plot? `help(probplot)` states:
_`probplot` generates a probability plot, which should not be confused with a Q-Q or a P-P plot._
Answer: Macond's answer is accurate, however from the original post, I thought it might be helpful to simplify the verbiage a bit.
A Q-Q plot stands for a "quantile-quantile plot".
It is a plot where the axes are purposely transformed in order to make a normal (or Gaussian) distribution appear in a straight line.  In other words, a perfectly normal distribution would exactly follow a line with slope = 1 and intercept = 0.
Therefore, if the plot does not appear to be - roughly - a straight line, then the underlying distribution is not normal.  If it bends up, then there are more "high flyer" values than expected, for instance.  (The link provides more examples.)

What do the x & y labels represent?

The theoretical quantiles are placed along the x-axis.  That is, the x-axis is not your data, it is simply an expectation of where your data should have been, if it were normal.
The actual data is plotted along the y-axis.
The values are the standard deviations from the mean.  So, 0 is the mean of the data, 1 is 1 standard deviation above, etc.  This means, for instance, that 68.27% of all your data should be between -1 & 1, if you have a normal distribution.

What does the $R^2$ value mean?

The $R^2$ value is not particularly useful for this sort of plot.  $R^2$ is typically used to determine whether one variable is dependent upon another.  Well, you are comparing a theoretical value to an actual value.  So there will necessarily be some sort of $R^2$.  (E.g., even a random uniform distribution will have a moderately decent $R^2$.)

Lastly, there is a similar plot that is rarely used called the p-p plot.  This plot is more useful if you are interested in focusing upon where the bulk of the data lies, instead of the extremes.
Comment: The word _skewed_  is not the best choice here: I'd say _transformed_.
Comment: Great explanation. Can you please explain how the x-axis (expected values) are generated ?
Comment: @VivekAnanthan The x-values are generated just as most other plots: they are the independent variables and you just choose them.  For instance, if you have a normal distribution, then x=0 is the mean, -1 is 1 std dev below the mean, etc.  Since these distributions are defined, you can calculate it. Let me pretend, but let's say that with 10 values, the extreme values *should* be at +/- 1.2 std dev, then the leftmost and rightmost points will have x=-1.2 and x=+1.2 and will align with the min and max.  Make sense?
Answer: Y axis shows values of observed distribution and X axis, values of theoretical distribution.
Each point is a quantile. Let's say, if there were 100 points on the plot, the first point (the one on lower-left side) indicates an upper bound for an interval, and when ordered from smallest to largest, the smallest 1 percent of the data points of the corresponding distribution stays in this interval. Similarly, 2nd point is upper bound of an interval, where smallest 2 percent of data points from the distribution is located. This is the concept of quantile. But it is not limited to a case with 100 intervals, it is a general concept and you can have as many intervals as possible, then you will have that many quantiles describing boundaries of the intervals.
What is special about this plot is, each point's position determines actual value of the given quantile in both distributions, as corresponding value on the axis. Let's think as if there are 100 such points (quantiles) again, this plot tell that smallest 1 percent of data points from observed distribution is between ($ -\infty $, -3.5] and also smallest 1 percent of data points from theoretical distribution is between ($ -\infty $, -3.2]. This way you can see locations of each interval boundary's position in both distributions.
I used data points throughout my answer, like ordered data points etc. This refers to discrete distributions, but the concept can be generalized for continous distributions.
$R^2$ is a measure of how good the points fit to the red line. If both axes had the same distribution, all of the points would be exactly on the line and $R^2$ would equal 1. You can learn more about it in any text explaining linear regression.
Comment: The texts on linear regression will not explain, though, how to interpret $R^2$ when the points are as severely constrained as the ones on a QQ plot are! In particular, the points on a QQ plot must be monotonically non-decreasing.  This forces $R^2$ to be extraordinarily high no matter what.

QQ plot in Python


Erro ao converter bitmap para pictureBox no C#?

Question: Estou criando um caminho dentro do C# para poder sempre chamar imagens deste caminho,estou instanciando uma referência (using namespace.Properties) e através dela estou conseguindo chamar o Resources e usando o seguinte código :
var myIcon = (Bitmap)Resources.imagem;

Mas mesmo assim dentro do pictureBox ele não funciona,dá o seguinte erro :

Cannot implicitly convert type 'System.Drawing.Bitmap' to 'System.Windows.Forms.PictureBox'    teste   c:\users\Lucas\documents\visual studio 2015\Projects\teste\teste\Form1.cs   31  Active

Tentativa de chamar a imagem :
var myIcon = (Bitmap)Resources.imagem;
pictureBox1 = myIcon;

Eu quero que dentro desta pictureBox eu consiga chamar minha imagem que eu já estou chamando através do Resources,mas como posso arrumar este erro ?
Answer: O problema está no jeito que você está setando a picturebox
o correto é pictureBox1.Image=myIcon
Comment: Muito obrigado,funcionou agora perfeitamente :)


Deploying Python behind Nginx?

Question: What is the best method deploying Python (including Django) behind Nginx?
Comment: Define "best"...
Comment: I would say "with the package manager of your distribution"
Answer: The official django documentation says that apache and mod_wsgi is the recommended way to get django into production.
We use nginx to proxy through to apache running mod_wsgi to serve our django site.  We have apache listening on 127.0.0.1 and use proxy_pass to pass requests to Apache.  The nginx wiki has a bunch of examples.
I've also heard good things about gunicorn. (and you would still use proxy_pass in nginx)
Comment: Did you mean pass the requests to nginx instead of Apache?
Comment: No, nginx listens on our public IP and takes all requests.  It passes django requests to apache and handles the static file itself.
Answer: I use FastCGI for this on one of my sites (it's built on Django), both nginx and Django can do FastCGI natively. Addition: I have stress tested various approaches: nginx w/FastCGI, nginx w/Apache and then FastCGI, nginx w/Apache and then mod_wsgi and even nginx w/Apache and then mod_python. Performance was pretty much the same for a real application, so I chose nginx w/FastCGI without Apache to save RAM a bit.

Deploying Python behind Nginx?


Proving some trig identities.

Question: Stuck on two questions.
First one: $\tan^2x - \sin^2x = (\sin^2 x)(\tan^2 x)$
Tried solving that with the right side but wasn't able to.
Second one: $\csc x / \sec x = \cot x$
I tried solving this one with the left side doing,
L.S = $\csc x / \sec x $
L.S = $(1 / \sin x) / (1 / \cos x) $
L.S = $\sin x / \cos x\quad$    [(1's cancel out]
L.S = $\tan x$
Don't know what I'm doing wrong here.
For reference, here is the trig identity worksheet we're supposed to use.
https://i.stack.imgur.com/v1eDl.jpg
Comment: $\sin^2 x(1/\cos^2 x-1)=\sin^2 x \tan^2 x$, just carrying $\sin^2 x$ and using a known expression for $1/\cos^2 x$ (which in turn comes from dividing $\cos^2 x + \sin^2 x =1$ by $\cos^2 x$).
Answer:
$$
\begin{align}
\tan^2x - \sin^2x&=\frac{\sin^2x}{\cos^2x}-\sin^2x\quad;\ \text{where}\ \tan x=\frac{\sin x}{\cos x}\\
&=\sin^2x\left(\frac{1}{\cos^2x}-1\right)\\
&=\sin^2x\left(\frac{1}{\cos^2x}-\frac{\cos^2x}{\cos^2x}\right)\\
&=\frac{\sin^2x}{\cos^2x}\left(1-\cos^2x\right)\\
&=\color{blue}{\tan^2x \cdot \sin^2x}\quad;\ \text{where}\ \sin^2x + \cos^2x=1.
\end{align}
$$
$$$$
$$
\begin{align}
\frac{\csc x}{\sec x}&=\dfrac{\dfrac{1}{\sin x}}{\dfrac{1}{\cos x}}\\
&=\frac{1}{\color{red}{\sin x}}\times\frac{\color{red}{\cos x}}{1}\\
&=\frac{\cos x}{\sin x}\\
&=\color{blue}{\cot x}.
\end{align}
$$
Answer: Note first that IF $\,\sin(x)= 0,\,$ then clearly also $\tan(x) = 0$ in which case the equation evaluates to $\,0 = 0\,$ which certainly is true.
Now, in the case that $\,\sin x\neq 0\,$ (so also $\tan x\neq 0$), we can divide both sides of the equation  $$\tan^2 x - \sin^2 x = \sin^2 x\tan^2 x$$ by $\sin^2 x\tan^2 x,\,$ giving us $$\csc^2 x - \cot^2x = 1$$
But $\csc^2 x = 1 + \cot^2 x,\,$ so that gives us $$1 + \cot^2 x - \cot^2 x = 1,$$ as desired.
Answer: For $\#1$ $$\sin^2x+\sin^2x\cdot\tan^2x=\sin^2x(1+\tan^2x)=\frac{\sin^2x}{\cos^2x}$$
$$\implies \sin^2x+\sin^2x\cdot\tan^2x=\tan^2x$$
For $\#2$  $$\csc x=\frac1{\sin x},\sec x=\frac1{\cos x}$$
Answer: I just wanted to point out that when doing proofs like this that your argument should lead from the initial form (e.g. $\tan ^2 x - \sin^2 x$) to the final form ($\sin^2x \tan^2 x$). That should be your final answer, but sometimes it is just easier to prove that the LHS and RHS are equal.
For example, my doodles may look like this
$$\tan ^2 x - \sin^2 x = \sin^2x \tan^2 x$$
$$\tan ^2 x  = \sin^2x \tan^2 x + \sin^2 x$$
$$\tan ^2 x  = \sin^2x(\tan^2 x + 1)$$
$$\tan ^2 x  = \sin^2x(\sec^2 x)$$
$$\tan ^2 x  = \sin^2x\bigg(\frac{1}{\cos^2 x}\bigg)$$
$$\tan ^2 x  = \tan ^2 x$$
Now, I'm going to use my doodles to present my real argument (the one I hand into my teacher).
Recall that I ended up $\tan^2 x$, but started with $\tan ^2 x - \sin^2 x$, so I'm just going to take $\sin^2 x$ along for the ride for a bit, and work backwards from my doodles.
$$\tan ^2 x - \sin^2 x = \frac{\sin^2 x}{\cos^2 x}-\sin^2 x = \sin^2 x \sec^2 x-\sin^2 x = \sin^2 x(\sec^2 x-1) = \sin^2 x \tan^2 x $$
Try doing the same for the other problem.
By the way, this is how I remember the Pythagorean identities.

It's unfortunate that Geometry has been downplayed so much in our high schools in recent years.

Proving some trig identities.


HTTP FAILED: java.net.SocketException: Socket closed Retrofit

Question: tried with multiple ways still facing this issue as
I am using RxJava and Retrofit to do all my network operations. Below is my code.

<-- HTTP FAILED: java.net.SocketException: Socket closed

Service.kt
<code>@GET("/v1/contact/{id}")
fun getContactDetails(@Path("id") id:String): Flowable<ContactDetailResponse>
</code>
AccountRepositoryImpl.kt
<code> override fun contactDetails(contactId:String) {
    mContactResponse.loading(true)
    remote.getContactDetails(contactId)
            .performOnBackOutOnMain(scheduler)
            .subscribe({
                data -> mContactResponse.success(data)
            },{
                error -> mContactResponse.failed(error)
            })
            .addTo(compositeDisposable)
}
</code>
Extentions.kt
<code>fun <T> Flowable<T>.performOnBackOutOnMain(scheduler: Scheduler):
Flowable<T> {
  return this.subscribeOn(scheduler.io())
        .observeOn(scheduler.mainThread())
}
</code>
NetworkModule.kt
<code>@Module
class NetworkModule(val key: String, val secret: String) {

 @Provides
 @Singleton
 fun providesRetrofit(jacksonConverterFactory: JacksonConverterFactory,
                     rxJava2CallAdapterFactory:
 RxJava2CallAdapterFactory,
                     okHttpClient: OkHttpClient,
                     baseUrl: String): Retrofit {

    return Retrofit.Builder().baseUrl(baseUrl)
            .addConverterFactory(jacksonConverterFactory)
            .addCallAdapterFactory(rxJava2CallAdapterFactory)
            .client(okHttpClient)
            .build()
 }

  @Provides
  @Singleton
  fun providesOkHttpClient(cache: Cache, httpInterceptor:
  HttpLoggingInterceptor): OkHttpClient {

    val client = OkHttpClient.Builder()
            .cache(cache)
            .addInterceptor(httpInterceptor)
            .retryOnConnectionFailure(true)
            .connectTimeout(100, TimeUnit.SECONDS)
            .writeTimeout(100, TimeUnit.SECONDS)
            .readTimeout(100, TimeUnit.SECONDS)

    return client.build()
  }

}
</code>
Comment: Do you by any chance dispose the `compositeDisposable`?
Comment: INTERNET permission set in Manifest?
Comment: @Christopher Already given the permission
Comment: Ok, I think we need a more detailed error description. SocketException has several causes. Does the same HTTP request work with a different tool, e.g. Postman? To ensure that the cause is not your backend.
Comment: yes getting response on postman but i issue with this.
Comment: i have also checked this link but not getting where to do it : https://stackoverflow.com/questions/40823134/retrofit-api-call-receives-http-failed-java-io-ioexception-canceled/46885714?noredirect=1#comment88485479_46885714
Comment: `yes getting response on postman` On your PC? Use a browser on your device.
Comment: can you show me your baseUrl ?
Answer: You can Create your OkHttp Client like below, I have faced socket closed exception in the low network, after adding following like in OkhttpClient issue resloved
connectionPool(ConnectionPool(0, 1, TimeUnit.NANOSECONDS))
protocols(listOf(Protocol.HTTP_1_1))
<code>        OkHttpClient.Builder().apply {
        .connectionPool(ConnectionPool(0, 1, TimeUnit.NANOSECONDS))
        .protocols(listOf(Protocol.HTTP_1_1))
        connectTimeout(CONNECT_TIMEOUT, TimeUnit.SECONDS)
        writeTimeout(WRITE_TIMEOUT, TimeUnit.SECONDS)
        readTimeout(READ_TIMEOUT, TimeUnit.SECONDS)
        retryOnConnectionFailure(false)
        }.build()
</code>


How can I get form_ids for all forms my module implements?

Question: I have a custom contact module that we periodically add new forms to - how can I get a list of all forms implemented by this module?
I'm integrating mollom and I want to just loop through all my forms in hook_mollom_form_list().
Answer: Forms aren't implementations of anything as such, they're just plain PHP functions that happen to return a certain structure by convention. There's no registry of forms or anything like that, and the module that a form is defined in isn't tracked anywhere (it's not information that Drupal needs). Form functions don't even have to be named in any particular way.
There's also hook_forms() which allows you to map multiple form IDs to a single form callback function, so that's an extra layer of complexity that would need to be handled somehow.
I can't think of a single reliable way you could get that information through code. Well, I'm sure you could use reflection to write something very specific to your module, provided your own form functions follow a predictable naming convention; but as far a generic solution goes, I'm 99.9% sure it isn't possible. Unless there's a creative way around that I'm just not thinking of.
If it's just for this single module, why not just write a function which returns an array of all the known form IDs. Then when you add a new form, update that function manually. It will be much easier than implementing the reflection code to do this.


Cakephp 3 DebugKit

Question: No CakePHP 2 eu costumo habilitar/desabilitar o DebubKit pelo AppController, de acordo com o usuário que está logado no sistema:
<code>// AppController -> CakePHP 2
public function beforeFilter(){
   parent::beforeFilter();
   ...
   if($this->usuario_logado_id > 1)
      Configure::write('debug', 0);
}
</code>
Porém, no CakePHP 3, o DebugKit é carregado do arquivo "Application.php"
<code>// Application.php -> CakePHP 3
public function bootstrap(){
   parent::bootstrap();
   ...
   $this->addPlugin(\DebugKit\Plugin::class);
}
</code>
Existe alguma forma de desabilitar o DebubKit pelo AppController como faço no Cakephp 2 ?
Já tentei muitas formas diferente, mas sem sucesso.
Comment: Você pode desabilitar no arquivo de configuração (config/app.php), setando a flag debug como false
Comment: Pelo que li na documentação, não é possível fazê-lo por uma controller, apenas pelo Application.php
Comment: O problema de desabilitar pelo app.php é que deve ser manual.
No Cakephp2 eu habilito para mim e deixo desabilitado para os demais usuários.
Comment: você utiliza o DebugKit ou somente o debug? O debug é possível ter seu valor dinâmico da forma que quer, já o debugkit não é possível
Comment: O debug eu consegui desabilitar dinamicamente...
O DebugKit não, as vezes é necessário utilizar ele.
Answer: Você, programador, vai usar a aplicação em ambiente de desenvolvimento. Os demais usuários vão usá-la em ambiente de produção. A cópia que está na sua máquina deve ter o debug ativado. A cópia que está no servidor deve tê-lo desativado. Não se mistura isso, e também não se deve colocar esses arquivos no git. É mais seguro fazer via ftp.

Cakephp 3 DebugKit


Getting text before element

Question: How could I get the text of the body that is before a specific element using Javascript/jQuery?
What I want to achieve is finding out the position of an element respect of the body, for instance, if the body text is 100 characters long and the text before the node is 50, that node would be at 50%.
Getting body's length is easy, but getting the text before an element is not as trivial as I'd thought in first instance.
EDIT:
To make it clear, I'll give an example:

      ...some text that could have sub-elements

      ...some text

now with a list

why not?

...some text...

...some text...

what's there in the body before this element?

...some text...

...some text...

      </div

In this case, the specific node would be #this_is_the_element and what I would expect to get is something like:
...some text that could have sub-elements
...some text
now with a list
why not?
...some text
...some text

Comment: Can you include some HTML to illustrate what you want to achieve?
Answer: I can propose this function :
function textUntil($element) {
    var T = '#~~~#';
    var $marquer = $(''+T+'');
    $marquer.insertBefore($element);
    var text = $(document.body).text().split(T)[0];
    $marquer.remove();
    return text;
}

The trick is to insert a unique marker and get the text until this marker. Of course the inserted element is removed before the HTML is rendered. It will work for any kind of body.
Demonstration (open the console)
EDIT :
Demonstration with the HTML of your edit (open the console)
Answer: Denys's answer will work most of the time, but it will not work correctly if the original text contains the same string of characters you chose to use for your marker.
I propose a different approach, using Ranges. Ranges are supported on all major browsers, including IE 9.
Here is my solution:
const rangeBefore = document.createRange()
rangeBefore.setStart(parent.firstChild, 0)
rangeBefore.setEndBefore(targetEl)

const textBeforeTarget = rangeBefore.toString()

And if you want all text after the element:
const rangeAfter = document.createRange()
rangeAfter.setStartAfter(targetEl)
rangeAfter.setEndAfter(parent)

const textAfterTarget = rangeAfter.toString()

And here is my answer adapted to your question:

const parent = document.querySelector("#common-ancestor")
const targetEl = document.querySelector("#target")

const rangeBefore = document.createRange()
rangeBefore.setStart(parent.firstChild, 0)
rangeBefore.setEndBefore(targetEl)

const textBeforeTarget = rangeBefore.toString()

document.querySelector("#output").textContent = textBeforeTarget

      ...some text that could have sub-elements

      ...some text

now with a list

why not?

...some text...

...some text...

what's there in the body before this element?

...some text...

...some text...

 Text before element:

Getting text before element


EntityMetaDataWrapper exception when calling commerce_cart_product_add()

Question: In brief, I'm trying to create and order and add a line-item as part of a form submission callback. Here's the sauce:
if (!commerce_cart_order_session_exists())
{
    $order = commerce_cart_order_new();
    $order->log = t("Created by $product_type checkout page.");
    commerce_cart_order_session_save($order->order_id);
} else
{
    $order = commerce_order_load($form_state['order']->order_id);
}
$wrapper = entity_metadata_wrapper('commerce_order', $order);
$sku = get_sku($product_type, $adj_age);
commerce_cart_product_add($uid = 0, $sku = 2, $quantity = 1, $display_uri = NULL, $combine = FALSE);

I'm getting the following error:
EntityMetadataWrapperException: Missing data values. in EntityMetadataWrapper->value() (line 83 of /srv/www/mtairy.toomodernmedia.com/public_html/sites/all/modules/entity/includes/entity.wrapper.inc).

In some very similar case I was getting the same error message, but in the commerce_cart_product_add function definition where the metadatawrapper was being called.
If I comment out the commerce_cart_product_add() line I can instantiate an order object. Not sure what I'm doing wrong here.
Comment: Have you already seen http://www.commerceguys.com/resources/articles/245?
Answer: You are using commerce_cart_product_add wrong.
You can pretty much replace your entire code with:
$product_id = ...; // You need to product id, from somewhere, you can get it from the SKU
commerce_cart_product_add_by_id($product_id);


Special multiserial algebra and monomial special multiserial algebra

Question: Let $K$ be an algebraically closed field. $Q=(Q_0,Q_1)$ is a quiver($Q_0$ is a finite set of vertices and $Q_1$ is a finite set of arrows). An algebra $KQ/I$ is called monomial if $I$ is a ideal consisting of monomial relations. A finite dimensional algebra $A$ is special multiserial if it is Morita equivalent
to an algebra $KQ/I$ such that for all $a \in Q_1$ there exists at most one arrow $b \in Q_1$ such that $ab \not \in I$ and there exists at
most one arrow $c \in Q_1$ such that $ca\not \in I$.
Now assume that $A$ is special multiserial. I have seen in a place that "by successively factoring out the socles of indecomposable projective-injective modules, we  get a monomial special multiserial algebra
$B$. I don't know why the above  conclusion hold. Also I want to know whether it is hold for general quiver algebras. Thank you for some reference about it and help.
Answer: This is not true as stated. For example take the path algebra of the quiver with 5 vertices and 5 arrows: $1\to 2\to 4$, $1\to 3\to 4$, and $1\to 5$. Impose the relation $(1\to 2\to 4)=(1\to 3\to 4)$. Then, this algebra is obviously special multiserial, but it does not have indecomposable projective-injective modules.
An easier example in the general case is the path algebra of $D_4$ with non-special-multiserial orientation. It also does not have indecomposable projective-injective modules.
Comment: Thank you for your examples. I have seen the words here:https://arxiv.org/pdf/1704.00612v1.pdf, in the last paragraph of the paper. So, is there something wrong?


How can I have device-specific block layouts?

Question: I'm fairly new to Drupal. In my current project, I'm using Drupal 8. The site is supposed to have a fairly different look depending on the device, in a way such that being responsive is not enough here.
So, within a single custom theme, I would like my site to have two different block layouts depending on the type of device (mobile / desktop) on which it is displayed. This can be achieved by showing / hiding blocks depending on the device. For performance reasons it is important for the hidden blocks to not be rendered at all in the HTML code (i.e. merely hiding with CSS won't do).
For this it seems that a combination of the Context module and its little brother Context Mobile Detect would do the trick. However, Context Mobile Detect is not yet available in Drupal 8, preventing me of using the Context module with the relevant condition.

Is this the right approach? Any other solutions for achieving what I'm trying to do here? This seems like a common enough problem to me and I'm expecting other developers to have found a way.
If it is: I'm tempted to write my own custom condition (wrapping the project Mobile Detect) so I can use it with the Context module. It seems Context uses the Drupal 8 Condition API, but I can't find any useful resource on how to write my own custom conditions in version 8 of Drupal. The official doc is sparse at best and I would rather avoid trying to reverse-engineer the thing. Any of you have a useful link/video/advice for this?
Comment: IMHO, this is a bad idea. You're going to have a lot of problems with caching, internal page cache and also external caches like Varnish do by default (varnish could be configured to do so) not cache by device, and you'd end up caching *many* different variations. What we've done for this use case is actually using a separte subdomain and theme to have a separate "mobile site". And then we have some JS to detect mobile clients and redirect them. Anything else is IMHO going to get you into trouble.
Comment: I agree with Berdir on this. If the layout changes to a degree that responsiveness is not an option, you should opt in for a complete different site and host it on a separate domain.
Comment: @Berdir: I guess this solution does not imply to have two separate instances of Drupal 8 for the same website? Did you achieve this with any specific module / method?
Comment: No, it does not. What you need is a custom theme negotiator that picks your theme if you're on the mobile domain. Similar to how to admin theme selection works in Drupal 8, so you can look that up, copy and adjust it for your use case. See http://drupal.stackexchange.com/questions/201530/how-can-i-change-the-active-theme-programmatically for example
Answer: I followed the counsel of Berdir and Ash Upadhayay. Having a sub-domain dedicated to mobile devices is a sound advice as many important websites currently use this method. As they say, using the same domain for both version could cause problems with caching and referencing by indexation robots.
This however doesn't clash with my requirements, and I was able to fulfill them using the Drupal 8 version of the Domain Access module.
The Domain Access module allows to define specific sub-domains that Drupal 8 will be able to recognize. The module then makes possible to condition all manner of things depending on the current domain, including the block layout.
I installed the module itself and its contrib module (packaged with it) Domain Alias. This last module allows you to associate various patterns to a domain that works as an alternative way of detecting the domain. This allows to match the URLs of local installs of the project without changing the Domain configuration.
This is the perfect solution for me as I am now able to condition the display of blocks from a single page - the block layout page.
All that's left to do then is to redirect the user on the correct sub-domain depending on the device, using a module such as Mobile JS Redirect.


Exchange Online MailFlow Rule - Identify recipient group by display name

Question: Using O365 Exchange Online, I have a scenario where I've got a bunch of distribution lists whose display name is in the format "CDL-blahblah" but their email address is not necessarily predictable. I want to prepend a disclaimer on messages such as these using an Exchange Mail Flow Rule. I have attempted variations of the following, but this does not seem to identify messages to these lists correctly:
Answer: There are other sites where you can learn and test regular expressions.
• https://regex101.com/
• https://regexr.com/
• http://regexstorm.net/tester
• https://regexlib.com/RETester.aspx
I don't think you need to add 'DisplayName:' in the condition.
everything that starts with CDL, would be like 'CDL.+' or 'CDL.*'.


are there sqlite admin chrome extension?

Question: Is there such thing? I have been searching the net for something similar to phpmyadmin but i cannot seem to find one.
I know there are SQLite managers but I want something that can be used for web development. So something like a chrome extension that will provide an interface where the database can be edited or a greasemonkey script or a bookmarklet or a JS file that can be included.
The Resources tab in the Developer tools of chrome already provides this but is there a way to edit this information just like in phpmyadmin? Or like an "sqlite shell" where queries can be executed?
I find such a tool very useful in developing applications using Databases. Developers would want to be able to edit the database quickly. Or if there aren't any, could you suggest a way to ease this? Thanks!
Comment: Why do you want this in-browser and not as a standalone application?
Comment: Why not just use SQLite?
Comment: How can I access databases created by browsers for websites using a standalone application? If I update it using a standalone application, will the changes also reflect in the browser?
Answer: Nothing seems to exist after weeks of researching. The best thing that can be done is to access the SQLITE database using a third-party sqlite browser. The database file is in:
<code>C:\Users\(username)\AppData\Local\Google\Chrome\User Data\Default\databases
</code>


defining a topology on a group by defining a fundamental system of neighborhoods of zero

Question: Let $G$ be an abelian group and $\left\{G_i\right\}$ a family of subgroups. I would like to make sure i fully understand what we mean when we say that "we take the $\left\{G_i\right\}$ to be a fundamental system of neighborhoods of zero, thus making $G$ into a topological group".
Interpretation 1: this means that we define for every point $x \in G$ a fundamental system of neighborhoods to be $\left\{x + G_i \right\}$. This defines a topology on $G$. From this it follows that the addition map is continuous, since the inverse image of the open set $y+G_i$ under addition with $x$ is the open set $y-x+G_i$.
Interpretation 2: this means that we define only the neighborhoods of $0$ to be $\left\{G_i\right\}$ plus the addition map to be continuous. We further define the open sets to be inverse images of the sets $G_i$ under addition maps. Then the inverse image of the open set $G_i$ under addition with $-x$ is $x+G_i$ and so $x+G_i$ has to be open. Then the $\left\{x+G_i\right\}$ form a fundamental system of neighborhoods for $x$. To see this, let $U$ be an open set containing the point $y$. Let $V$ be the inverse image of $U$ under addition with $y$. Then $V$ must contain $0$ and so $V$ contains some $G_k$. It follows that $U$ contains $y+G_k$.
Are the above interpretations sound?
Answer: Yes, both interpretations are correct (and in fact equivalent) although perhaps the second is a little more natural.
By definition a topological group is a group in which $$\cdot :G\times G\to G:(x,y)\mapsto x\cdot y$$ and $$^{-1}:G\to G:x\mapsto x^{-1}$$ are continuous maps. Therefore, a topology on a group $G$ which makes $G$ into a topological group is sufficiently characterised by a system of fundamental neighborhoods of some point $x\in G$. Note, however, that not every such system of neighborhoods for some point $x$ characterises a topology that makes $G$ a topological group, because $^{-1}$ may not be continuous. This is why we typically take a system of subgroups as a fundamental system of neighborhoods of $1$.
Comment: Thanks for your interesting answer. Could you please elaborate on your second to last sentence? What form would have a system of neighborhoods of an arbitrary point $x$? Would it be a family of cosets?
Comment: Not necessarily. It could be any family $\{B_i\}$ of subsets of $G$ satisfying $(1)$ $\forall i\in I: x\in B_i$ and $(2)$ for all $i,j\in I$, there is a $k\in I$ such that $B_k\subseteq B_i\cap B_j$.
Comment: So the problem is that if $B_i$ is an open set containing $x$, then the inverse image of $B_i$ under the inversion map is $-B_i$ and this need not be  a neighborhood of $-x$, i.e. $-B_i$ need not contain a set of the form $-x+B_j$, right? Also, why do we need condition (2)?
Comment: What are fundamental neighborhoods?


Still stuck on simplifying terms while doing linear combinations

Question: So I'm currently trying to wrap my head around finding gcd through the Euclidean Algorithm in order to write the integers as a linear combination.
For example, a problem is to express the gcd(9999,11111) as a linear combination of these integers.

11111 = 9999 * 1 + 1112
9999 = 1112 * 8 + 1103
1112 = 1103 * 1 + 9
9 = 5 * 1 + 4
5 = 4 * 1 + 1

So gcd(11111,9999) = 1.
Going back, it's time to rewrite the equations as an expression of the remainder.

1112 = 11111 - 9999
1103 = 9999 - 1112 * 8
9 = 1112 - 1103
5 = 1103 - 122 * 9
4 = 9 -5
1 = 5 -4

Then, as I understand it, you work your way up and substitute.

1 = 5 - 4
1 = 5 - (9 - 5) = ?

My problem is, I don't understand how to simplify. That's as far as I've got. How to do this?!
Comment: Have a look at the questions listed under "Related" on this page to see whether one or another answers your question.
Answer: There is an error at the last but one line: you should divide $1103$ by $9$, not $9$ by $5$.
The systematic way consists in using the Extended Euclidean Algorithm, which gives Bézout's coefficients for every remainder in the Euclidean Algorithm:
$$ \begin{array}{rrrr}
   r_i  & u_i & v_i & q_i\\
   \hline
 11111 & 1 & 0 & \\
  9999 & 0 & 1 & 1\\
     \hline
 1103 & -8 & 9 & 1\\
 9 & 9 & -10 & 122 \\
5 & -1106 & 1229 & 1 \\
 4 & 1115 & -1239 & 1\\
 1 & -2221 & 2468 \\
\hline
\end{array}
$$
Thus $1=2468\times 9999-2221\times11111$.
Comment: Thanks for that! I realize what I was thinking wrong and I've got the hang of it now. I appreciate it. Great answer.


Making a new jQuery array from a JSON object

Question: I have a PHP script that returns a JSON object which looks like this in the console:
[{"CONTAINER_NUMBER":"CONT1234567","RETURN_POOL":"GARDENCITY"},{"CONTAINER_NUMBER":"CONT987654","RETURN_POOL":"NORTHTOWN"}]

All I need to do is create another array that contains only the CONTAINER_NUMBER value.  It should look like this:
 "CONT1234567", "CONT987654"

I found this:  http://jsfiddle.net/arunpjohny/ygqaa/
I changed it around to look like the below:
$.POST('phpScript.php', {cntArray:cntArray}, function(data)
{
  var containers = JSON.parse(data);

  var obj = {};
  $.each(containers, function(i, v){
   obj[v.CONTAINER_NUMBER]
  });
  console.log(obj)
});

But the console only shows a blank array.
Comment: you mean a blank object?
Answer: If you just want an object whose keys are the ID:
obj[v.CONTAINER_NUMBER] should be obj[v.CONTAINER_NUMBER] = ''
If you want an array of IDs:
$.post('phpScript.php', {cntArray:cntArray}, function(data)
{
  var containers = JSON.parse(data);

  var ids = [];
  $.each(containers, function(i, v){
   ids.push(v.CONTAINER_NUMBER);
  });
  console.log(ids)
});

Or, a bit cleaner:
$.post('phpScript.php', {cntArray:cntArray}, function(data)
{
  var containers = JSON.parse(data);

  var ids = $.map(containers, function(i, v){
   return v.CONTAINER_NUMBER;
  });
  console.log(ids);
});

Comment: Not sure who downvoted you, but your first answer worked for me.  Thank you very much.  I'm upvoting and accepting your answer.
Comment: I can only assume its the completely unnecessary use of jQuery for this?
Comment: @ste2425 I guess that's fair but a blind/unexplained down vote for working code seems odd, especially since OP is already using jquery.
Answer: The problem with your code, is that you're passing a value has the key of the object!
var x = {}
x[1]
x[2]

So you get an empty object! But as you mentioned, that's not what you're looking for, you don't want to get an Object, but an Array.
What you can do instead, is to use map and get all the values into an array as you wish! See below:
var json = [{"CONTAINER_NUMBER":"CONT1234567","RETURN_POOL":"GARDENCITY"},{"CONTAINER_NUMBER":"CONT987654","RETURN_POOL":"NORTHTOWN"}]

var res = json.map((obj) => obj.CONTAINER_NUMBER)

console.log(res)

Or check the live example,

var json = [{"CONTAINER_NUMBER":"CONT1234567","RETURN_POOL":"GARDENCITY"},{"CONTAINER_NUMBER":"CONT987654","RETURN_POOL":"NORTHTOWN"}]

var res = json.map((obj) => obj.CONTAINER_NUMBER)

console.log(res)


Transfer learning for regression problems?

Question: How does transfer learning work for regression tasks? Can someone point to an application where transfer learning has been successfully applied for regression tasks.
Comment: Do you need it to be regression to regression transfer learning or can be from classification to regression? The latter is quite common actually.
Comment: It would be great to know about both. If you can shed some light on either/both or point me to an application/papers that would be great.
Comment: https://www.kaggle.com/c/diabetic-retinopathy-detection and https://www.kaggle.com/c/aptos2019-blindness-detection is one example of classification to regression.
Answer: Consider the denoising autoencoder. The input features to a neural network are contaminated by a small amount of noise, sent through one or more intermediate layers, and then through a final layer of the same size as the input layer. This network is optimized to reconstruct the original data which can be seen as a form of regularization.
The resulting network weights (minus the final layer) are frozen and transferred to a supervised learning task (perhaps added to another neural network). It has been found that the features constructed by this process are quite valuable. This applies to regression or classification.
Comment: Could you add some references/links/examples to this answer?


What does it mean to indicate correlation in lavaan CFA?

Question: I am an undergraduate psychology student and I've been doing basic statistical analysis for professors, post-grad students, etc for their work. I use R for almost everything
I've recently faced myself with exploratory and confirmatory factor analysis for psychological test validation, etc. When talking about EFA, everything went well.
The scale has 10 items, Likert 1 to 5.
I'm going straight to my question:
When I'm creating CFA model in lavaan, there is possibility to create latent factors and observed variables relationship (=~), but you can also create covariance relationship (~~). I tried to explain my professor that we could insert those covariances in the model to improve model fit, etc. But she would not understand (even me, I don't completely comprehend it), because she was saying that the factors on EFA are already created based on item correlations in the instrument, and then it wouldn't make sense to assign those correlations.
What I did is, I ran three models (single factor, two factor and three factor) and also those three including two correlations observed in polychoric correlation matrix. So, in total, 6 CFA models. The ones with the correlations in the model performed better based on fit indices (CFI, RMSEA, SRMR, etc)
Could someone clarify it to me? Is it important to put those covariances in CFA model? Is it good practice? What does it mean in "human/eli5 language"?
If I forgot to give some information, feel free to ask me.
Thanks in advance, love this community!
Comment: Do you mean adding covariances between latent variables or between manifest variables?
Comment: I mean between manifest variables. Between for example, two items from the scale.
Answer: Here's an example. The PTSD Checklist (PCL) has 17 items. Two of them are:

Being "super alert" or watchful on guard?
Feeling jumpy or easily startled?

These two are very similar, and the items are highly correlated. Some people say that this means that these two items form a single factor (hyperactivity). Other people say that these are part of another factor (anxiety and reactivity).
If you put the same question, or a slight rewording of your question, into a factor analysis, you might find a new factor or you might just create a factor from nothing - the factor is an artifact. (And int the case of the PCL, the items are next to each other, which might make it worse). Thurstone called this a 'bloated specific' the IRT literature calls this a 'local dependency'. If you do exploratory factor analysis, you keep the two items, and accept another factor (probably). If you do CFA you can add a correlation - you can say that these are very similar items, not a separate factor.
I was involved in a paper about the PCL which talked about this issue here: https://pubmed.ncbi.nlm.nih.gov/23128035/
Another example: Looking at assessment of Socio-economic status of areas in the US. There are various measures you can use: education, household size, unemployment, median income, poverty. Median income and poverty are more closely related to one another - again, putting a correlation between these two items will improve the model fit. https://www.ncbi.nlm.nih.gov/pmc/articles/PMC4794463/ (not trying to blow my own trumpet here, you can easily find many more papers, it's just that these are ones I'm familiar with).


Como faço para adicionar library jQuery com JavaScript?

Question: Gostaria de saber como fazer para carregar a biblioteca do jQuery com JavaScript puro e rodar algo simples com jQuery após sua carga?
Meu código está desta forma:
function colocaScript(){
    var scriptJquery   = document.createElement('script')
    scriptJquery.type  = 'text/javascript';
    scriptJquery.src   = "http://code.jquery.com/jquery-1.10.2.min.js";
    scriptJquery.async = true;
    headHTML = document.getElementsByTagName('head')[0];
    headHTML.insertBefore(scriptJquery,headHTML.firstChild);
}

colocaScript()
$(document).ready(function () {
        alert("Ola Mundo");
})

Ele retorna este erro:
Uncaught ReferenceError: $ is not defined

Comment: Testei seu código e está funcionando perfeitamente, tente em uma página nova, limpa, sem nenhum conteúdo, apenas o esqueleto html.
Answer: Passe uma função de callback como parâmetro para a função "colocaScript" e esse callback deve rodar no "onload" do script.
        function colocaScript(callback)
        {
            var scriptJquery = document.createElement('script')
            scriptJquery.type = 'text/javascript';
            scriptJquery.src = "http://code.jquery.com/jquery-1.10.2.min.js";
            scriptJquery.async = true;
            scriptJquery.onload = function()
            {
                callback();
            };
            headHTML = document.getElementsByTagName('head')[0];
            headHTML.insertBefore(scriptJquery, headHTML.firstChild);
        }

        colocaScript(function()
        {
            $(document).ready(function()
            {
                alert("Ola Mundo");
            })

        });

Answer: Use está função
src = url do arquivo por exemplo http://code.jquery.com/jquery-1.10.2.min.js
uso do callback
LoadScript("http://code.jquery.com/jquery-1.10.2.min.js",function(){ alert('Acabou de carregar')  })

Função
 LoadScript = function (src, callback) {
            var s,
                r,
                t;
            var callback = (typeof(callback)=='function')? callback : function(){};
            r = false;
            s = document.createElement('script');
            s.type = 'text/javascript';
            s.src = src;
            s.async = true;
            s.onload = s.onreadystatechange = function () {
                //alert(this.readyState);
                if (!r && (!this.readyState || this.readyState == 'complete' || this.readyState == 'loaded') ) {
                    r = true;
                    console.log("js carregado: "+src);
                    callback.call(this);
                }
            };
            try {
                t = document.getElementsByTagName('script')[0];
                t.parent.insertBefore(s, t);
            } catch (e) {
                t = document.getElementsByTagName('head')[0];
                t.appendChild(s);
            }
        }

Comment: Acho que é por isso que ele tem erros, deve estar tentando utilizar jQuery antes de terminar de carregar o script, boa sacada ;)
Comment: Hein? Injeção de script assim não sofre problema de cross-domain. O erro que você postou tem a ver com outra questão de segurança, HTTP vs. HTTPS
Comment: tem razão, é que eu não tenho muito conhecimento nisso mas se você quiser editar minha pergunta eu agradeço
Comment: Eu somente removeria o final.
Comment: Pronto, removi....
Answer: O problema é que o seu script carrega assíncrono, e por causa disso o jQuery é chamado directamente depois de colocaScript() e que é antes do script ter carregado.
Use assim:
window.onload = function () {
    $(document).ready(function () {
        alert("Ola Mundo");
    })
}

Exemplo
Neste caso usei window.onload, mas pode usar o onload também para controlar quando o script tiver carregado como o Lucas referiu.


A sequence defined by $(2^n-1)\,a_n=\sum_{k=1}^n\binom n k\,a_{n-k}\,(k+1)^{-1}$

Question: Let $a_n$ be the sequence of rational numbers defined by the recurrence
$$a_0=1,\quad\left(2^n-1\right)a_n=\sum_{k=1}^n{\small\binom n k}\frac{a_{n-k}}{k+1}.\tag1$$
It begins
$$\small1,\,\frac12,\,\frac5{18},\,\frac16,\,\frac{143}{1350},\,\frac{19}{270},\,\frac{1153}{23814},\,\frac{583}{17010},\,...\tag2$$
and is apparently related to $\texttt{A272755}$ and the Fabius function.
It appears that the following simpler identity holds:
$$a_n\stackrel{\small\color{silver}?}=\sum_{k=0}^n{\small\binom n k}\,(-1)^k\,a_k.\tag3$$
How can we prove it?
(Note that $(3)$ could not be used as a definition of $a_n$ because the term $a_n$ is canceled for even $n$.)
Answer: If we call $f(x)=\sum \frac{a_n}{n!}x^n$, then the first recursion is equivalent to $$f(2x)=\frac{e^x-1}{x}f(x).$$
In this paper (page 5), one can see that $f(x)=e^{x/2}\hat{\text{up}}(\frac{ix}{4\pi}),$ where $$\hat{\text{up}}(x)=\prod _{n = 0}^{\infty}\frac{\sin(\pi x/2^n)}{\pi x/2^n}.$$
notice that $\hat{\text{up}}(x)$ is an even function and so
$$f(-x)e^x=e^{x/2}\hat{\text{up}}(\frac{ix}{4\pi})=f(x),$$
and so checking at the coefficient of $x^n$ on that equation, we get that
$$\sum _{k=0}^{n}\binom{n}{k}(-1)^ka_k=a_n.$$
Comment: Thanks! Indeed, I've seen this paper by J. Arias de Reyna before, but forgot about that part (curiously, he proves one of my conjectures in the paper). Do you think we can find a discrete arithmetic or combinatorial proof that doesn't go through the Fabius and Rvachev functions and their Fourier transforms?
Comment: @VladimirReshetnikov You are welcome. I tried a bit using just the recursion but failed. I can't think of any combinatorial description, do you know if there is any? Maybe that way we can think of  an inclusion-exclusion argument.


Ajax variable ignores line breaks

Question: I´ve got a problem when I try to send the value of a textarea through Ajax in Joomla.
The variable looks correct right before the ajax request. But when returned from helper.php, the success response var ignores all the line breaks.
My jQuery / Ajax:
var curBody = jQuery(this).closest("div").children("div").children('textarea').val();
//var curBody = curBodyVal;//.replace("/\r\n/","
");
console.log(curBody);
jQuery.ajax({
    url: "index.php?option=com_ajax&module=usernotes&method=edit&format=json&Id="+edit_id+"&body="+curBody,
    success: function( response ) {
        console.log(response);
    }
});

In my helper.php file at the function for the ajax call:
public static function editAjax()
{
    $input = JFactory::getApplication()->input;
    //$bodyToUpdate = $input->get("body", 'default_value', 'raw');
    $bodyToUpdate = $_GET['body'];

    return($bodyToUpdate);
}

Comment: What do you mean "all line breaks are ignored"?  Where/how are you observing this?
Comment: [`nl2br()`](http://php.net/manual/en/function.nl2br.php) will help you. Your JavaScript has `\n` as line breaks, when you output with PHP you need to convert those to `` if you want to maintain the line breaks.
Comment: use method as post don't use get for this
Comment: @David sorry, I´ve updated det question, so it´s more clear
Comment: @JayBlanchard Thanks! I also need to use nl2br() in my SQL query to get it working right
Answer: Whenever you are trying to send values, which are not simple strings, send it ina a POST method instead of GET,
GET is used for simple strings, only used for characters within ASCII character range.
POST is used for any other complicated strings, you can send binary data as well, for example you can send files and images using POST method, but you cannot send using GET method
Change your ajax to this:
$.ajax({
  method: "POST",
  url: "index.php",
  data: { option: "com_ajax", module: "usernotes" , method: "edit", format: "json" , Id: edit_id, body: curBody },
  success: function( response ) {
    console.log(response);
          }
});

Comment: Thanks! but I´m getting this error **Uncaught SyntaxError: Unexpected token )**
Comment: Why should the OP change their code? A ***good answer*** will always have an explanation of what was done and why it was done in such a manner, not only for the OP but for future visitors to SO.
Comment: @Jay Blanchard  in GET only ASCII letters allowed, in POST method no restrictions, binary data is also allowed, REFERENCE; https://www.quora.com/HTTP-What-is-the-difference-between-GET-and-POST
Comment: *I know that* @vSugumar, but you need to include that in your original post to make your answer have more value. Right now you're just saying "change it" without explaining what you did.
Comment: After a quick check of your other answers I see that you have a lot of "change this" or "try this" answers. Those are not good answers IMHO because you never explain why.
Comment: @Jay Blanchard, Thank you very much for pointing out that, I have edited my answer with little bit of information

Ajax variable ignores line breaks


How to resolve Xcode 13.2.1 compile time error "The data couldn't be read because it isn't in the correct format."?

Question: I am working in my XY branch and whenever I checkout to my YZ branch, and try to build the project, I am getting error "The data couldn't be read because it isn't in the correct format.", while other co-workers can checkout to YZ branch easily and aren't facing any problems. I tried following things:

Deleting Derived data.
Restarting the mac and hence Xcode.
Clean the project.
Replaced Info.plist (Thought may be some key is the cause of that error.)

Logs aren't helpful at all, and just showing the error that I've mentioned above.
Kindly guide me what can be the possible problem here.Thanks.
Comment: Did you check your git diff after checking out YZ? It should give you some clue.
Answer: I've had this happen a couple of time. Things to note are that you might be having files persist between branch changes (ie - anything that's noted in your .gitignore file) and if you have Xcode open between branch changes. I've especially seen this be an issue if your dependencies are different between the branches (ie cocoapods/ versions of the installed version).
When collaborating with teams on Xcode projects, it can be especially tricky when things like the .xcproj file is out of sync/ has merge conflicts, or you have different versions of Xcode/ cocoapods/ any other packages installed.
To start with, I would make sure you have the same packages installed across all machines. Something like Bundler is good for this, but can be carried out manually. Also, before changing branches, it's a good idea to make sure you discard your changes. It's easiest to do this in a GUI tool such as SourceTree, but via CLI you can run something like git reset --hard AFTER closing Xcode.
Then, once you've done that, try changing branches, running things like pod install and make sure to open the correct .xcproj vs .xcworkspace file. Once you've done that, you might need to reset package caches if you use SPM and it should build correctly.
If you're still having difficulties, after changing branches, run git status to see if you have anything other than nothing to commit, working tree clean to see if there's anything strange going on.
Comment: Thanks! I was able to resolve this issue earlier. It was being caused by one of our frameworks. Deleting the framework and adding it again solved it for me.

How to resolve Xcode 13.2.1 compile time error "The data couldn’t be read because it isn’t in the correct format."?


Interpretation of a $P$ value of a categorical variable?

Question: glm(formula = seagulls$attack ~ seagulls$bird_sex, family = "binomial",
    data = seagulls)
Deviance Residuals:
   Min      1Q  Median      3Q     Max
-1.310  -1.218   1.050   1.138   1.138
Coefficients:
                   Estimate Std. Error z value Pr(>|z|)
(Intercept)         0.09403    0.16403   0.573    0.566
seagulls$bird_sexM  0.21300    0.23243   0.916    0.359
(Dispersion parameter for binomial family taken to be 1)
    Null deviance: 412.88  on 299  degrees of freedom
Residual deviance: 412.04  on 298  degrees of freedom
AIC: 416.04

How do I interpret the $P$ value of the intercept? Does it mean seagulls$bird_sexF has this $P$ value and we reject the hypothesis of female seagulls having a higher probability of attack?
Comment: Looking at p = .359, you would fail to reject the null hypothesis of no association between sex and attacking. I don't think the intercept matters in that interpretation. In fact, I've never interpreted or reported the intercept's coefficient or p-value in a logistic regression.
Answer: I'm guessing you're trying to estimate the probability that a seagull attacks...something, conditioned on its sex.  The model is
$$ \operatorname{logit}(p) = \beta_0 + \beta_1x $$
Here, $x$ is a binary indicator for sex (1 if male, else 0).  The null hypothesis for $\beta_1$ is
$$ H0: \beta_1 = 0$$
versus the alternative
$$ HA: \beta_1 \neq 0$$
Failing to reject this null means that, at least from these data, we can not conclude that seagull sex has an effect on the propensity to attack.  It may very well be the case however that with ore data, the effect would become significant due to the standard errors shrinking like $1/\sqrt{n}$.


Bounds for $S_N(\alpha) = \sum_{n=1}^N \sin(\alpha n)$

Question: Let $\alpha \in \mathbb{R}$ and $N$ be a positive integer. Are there any good bounds known for the absolute value of the sum
$$
S_N(\alpha) = \sum_{n=1}^N \sin(\alpha n)
$$
for $N$ large and which are uniform in $\alpha$? That is, what can we say about $\|S_N\|_{\infty}$? Clearly $\|S_N\|_\infty \leq N$. But can we do better? Thanks.
Answer: HINT
Notice that
\begin{align*}
S_{N}(\alpha) = \sum_{n=1}^{N}\sin(\alpha n) = \mathrm{Im}\sum_{n=1}^{N}e^{i\alpha n} = \mathrm{Im}\left[\frac{e^{i\alpha} - e^{i(N+1)\alpha}}{1 - e^{i\alpha}}\right]
\end{align*}
Comment: Thanks. If I'm correct, the imaginary part of that is $(\cos(\alpha/2) - \cos(\alpha(N + 1/2)))/2\sin(\alpha/2)$. When $\alpha/2$ is far from an integer multiple of $\pi$, the absolute value of this is at most $|\csc(\alpha/2)|$. How about the case when $\alpha/2$ is close to an integer multiple of $\pi$?
Comment: You mean $\alpha = 2k\pi$? In such case, $\sin(\alpha n) = \sin(2kn\pi) = 0$. Hence $S_{N}(\alpha) = 0$.
Comment: Of course, but I didn't mean the case when $\alpha$ is precisely $0 \pmod{\pi}$. I meant in a neighbourhood of that, with the radius of the neighbourhood small in terms of $N$. For example, for $\alpha$ close to 0, the numerator has essentially a Taylor expansion of the form $\alpha^2 N^2 + O(\alpha^4 N^4)$ while the denominator is essentially $\alpha + O(\alpha^3)$ (I'm omitting some constants here). Thus for $\alpha$ close enough to $0$, the imaginary part above is essentially $\alpha N^2$. This is smaller than $N$ for $\alpha \leq 1/N$.
Comment: But in the case when $\alpha \geq 1/N$, the bound $1/\alpha$ gives $N$, the trivial bound. So no improvements from what I see...
Comment: Thus we have good bounds when $\alpha \pmod{\pi}$ is either much larger or much smaller than $1/N$, but the problem is the case when $\alpha \pmod{\pi} \asymp 1/N$.


ISA Server VSS Writer encountered a failure while backing up

Question: On our ISA system the following warning is logged:
Event Type: Warning
Event Source: Microsoft ISA Server Storage
Event ID: 21326
Description: The ISA Server VSS Writer encountered a failure while backing up
the ISA Server configuration.

The system configuration is:

Windows 2003 Standard SP 2
Microsoft ISA 2006 SP 1

Backup agent: EMC NetWorker 126.96.36.199
Running vssadmin list writers returns
Writer name: "ISA Writer"
Writer Id: {25f33a79-3162-4496-8a7d-caf8e7328205}
Writer Instance Id {f958b2f0-7ad1-4326-9ddc-51aee0ef24c4}
State: [8] Failed
Last error: Retryable error

I'm looking for any hints on what's going wrong here and how I can fix this.
Answer: The cause for this issue is that the function CryptSignHash passes AT_SIGNATURE as a parameter. This will fail if the "signature" key pair / certificate is missing. See http://msdn.microsoft.com/en-us/library/aa380280(v=vs.85).aspx
The only supported solution is to set up the machine and ISA Server from scratch.

An unsupported solution ist to create a new key container for ISA.


INSERT Statement in PL/SQL fails in Oracle database

Question: When executing an SQL statement in PLSQL with
DBMS_SQL.EXECUTE('insert into tablename VALUES(aNumber)');

It gives an ASCII character error.
And when inserting it directly it succeeds and inserts it.
Comment: The closing parenthesis is missing.
Comment: Please provide a complete example. As it is `tablevalue` is an invalid identifier and can't be inserted.
Comment: Why do you want to use DBMS_SQL? If you really need dynamic SQL, EXECUTE IMMEDIATE seems a much more sensible choice for such a simple task.
Comment: @Toru That was just a typo when I wrote this question.
Answer: In PL/SQL you could write the INSERT statement directly.
DECLARE
  tablevalue      varchar2(200);
BEGIN
  tablevalue := 'Hello World!';

  INSERT   INTO tablename
         VALUES (tablevalue);
END;

Your statement fails because that is not the way DBMS_SQL.EXECUTE works. Check out the documentation and the example: http://docs.oracle.com/cd/B28359_01/appdev.111/b28419/d_sql.htm#BABBFFFJ
According to the example given in the reference documentation you should do it like this (first you prepare the statement, then bind the variable and then run it).
CREATE OR REPLACE PROCEDURE demo(tablevalue IN varchar2) AS
    cursor_name INTEGER;
    rows_processed INTEGER;
BEGIN
    cursor_name := dbms_sql.open_cursor;
    DBMS_SQL.PARSE(cursor_name, 'INSERT INTO tablename VALUES(:x)',
                   DBMS_SQL.NATIVE);
    DBMS_SQL.BIND_VARIABLE(cursor_name, ':x', tablevalue);
    rows_processed := DBMS_SQL.EXECUTE(cursor_name);
    DBMS_SQL.CLOSE_CURSOR(cursor_name);
EXCEPTION
WHEN OTHERS THEN
    DBMS_SQL.CLOSE_CURSOR(cursor_name);
    raise;
END;

You use it then like this
 exec demo('something');

Hope it helps


Permanent Views Pages

Question: Something I've been battling for some time: Is there any way to make the results of a views page permanent?
For Instance: There is a club racing website that inputs Entrants as nodes, to events, which are also nodes. The entrants get scores based upon their performance at the event. However, Entrants come and go in the club, and as they come and go so should their nodes.
Is there any way to make their scores still appear on a views page, even if I happen to delete or unpublish their node? Is there a, 'print as static' option?
Answer: The views module actively queries (and caches) a database table for results; trying to make the results static or somehow retrieving deleted content would be much work fighting against views' design. I'd say if you're already using unpublishing to designate former entrants, you're better off using the View Unpublished module to give roles the ability to see unpublished entrants.
Comment: Thank you for the answer! I don't know if that is exactly what I am looking for, because anonymous users will most likely be viewing these event result pages, and wouldn't be restricted to roles. However, your answer did lead me to a workable conclusion:  Simply change the view to show published AND not-published nodes, so that I may unpublish any racers whom are no longer with the club.
Comment: So testing this has indeed, come down to using the View Unpublished module, because by default, a anonymous user is unable to see unpublished content. Thank you again for you insight :)

Permanent Views Pages


Taxonomy vocabulary templates

Question: I have three taxonomy vocabularies in my site and one of them using custom template files.. Parent and child term pages and that's ok.. But I don't want to use these template files for two other vocabularies.
I was trying to use TVI module and I get nice views for these vocabulary terms, but I have one huge problem. It messed up my third category page.. It's override template files.
3 vocabularies: Articles, Blogs and Notes..
Articles uses parent-term.tpl files and it's ok, but blogs and notes uses views with TVI module. When I enable TVI module my article category pages messed up..
So what I can do? I love this module, but I don't want automatic override article term pages or nothing.. Only use this module for blog and notes category pages.
Answer: To use TVI with individual vocabularies instead of all vocabularies, first make sure it is not globally overriding your vocabulary term pages. Go to Admin > Configuration > User Interface > TVI Settings (admin/config/user-interface/tvi) and uncheck the Use view override checkbox.

Then edit each vocabulary to apply the TVI view override individually. Admin > Structure > Taxonomy > edit vocabulary. In your case, you would edit your Article vocabulary and make sure the Use view override checkbox is unchecked.

Then edit the two vocabularies you do wish to override with the appropriate view. The fields for selecting the view appear once you check the Use view override box:
Comment: Thanks for your response. I have uncheck overrides, but still my article term pages changes. Even I uncheck "Use view override."

Is there any alternative for that module or is there some bug?
Comment: Have you tried clearing your cache? When I tested it, I got the expected results, but there could be other factors at play with your set up. You could also try disabling the default Taxonomy term view if it's enabled and you aren't using it (though that didn't make a difference in my testing), or uninstalling and reinstalling the module. I'm not sure about alternatives or bugs, you could check out the issue queue for the project.
Comment: I just disabled all views, but it's broken my custom parent and sub term pages for articles.

Don't know why it won't work with my custom taxonomy module. Is there anything where I can trying to find solution?
Comment: Hey, I just checked this line of tvi.module file

// Taxonomy is last resort - used if no standard views are found.

I think I just need to replace module_load_include for my own taxonomy module, but I can't get it working so I'm going to ask:

How I can load custom module from folder "test/site/modules/custom/site_taxonomy" ?
Comment: I think that might be a question on its own! If you post it, it would be good to include your custom module code so others can troubleshoot. Also the TVI project's issue queue would be a good place to start with questions about why you're not getting expected results.

Taxonomy vocabulary templates


Getting the client certificate with OpenVPN options

Question: I want to make custom certificates for OpenVPN without using the username and the password authentication option but rather directly putting the authentication credentials within the client certificate. This will be used for a more flexible authentication system across multiple nodes without the need to create client certificates locally on each node.
Basically, the client certificate will remain the same except for the fact that there is a token inside the certificate itself, and when the client connects to a node. The node will authenticate the client with the token. What is the best way to achieve this without the use of usernames and passwords.
Thank you.
Comment: The best way is still to generate each client its own certificate and distingush them by the CN field. You can embed certificates and keys directly into OpenVPN config file, thus having only one file to configure VPN. And, by the way, without usernames and passwords.
Comment: Thank you! How do I add the CN field in the client config.
Comment: This question demonstrates you didn't tried to read OpenVPN manual. Because this field is the one you can't *remove*, nothing you need to do to add it. Please, do your homework, at least this: https://openvpn.net/community-resources/reference-manual-for-openvpn-2-4/ and it links to the CA management tool: https://github.com/OpenVPN/easy-rsa/blob/master/README.quickstart.md
Comment: Yeh, its something cryptographic, but by asking this question I was hoping to get an alternative. Like putting the username and password in the client certificate so that the user will not need to input it. Is there way?
Comment: Certificate is a public key plus some additional data, all signed by CA. By putting or changing *anything* in the certificate you change it, so it needs to be signed again. This signing process is no different from just issuing a new certificate with altered data. But, there will be new key pair generated, so each certificate will have its own corresponding private key. Issuing different certificates *is* the proper way to get several certificates with distinct data inside. Think public and private keys as username and password; put them inside OpenVPN config files so need nothing to enter.
Comment: The thing is that I don't want to go into each VPN node to create the public key for the client certificate. I want a centralized system where OpenVPN will use the scripts I wrote to authenticate the user. Right now its using the username and password, but I want to make it so the user does not need to input the username and password each time. Is it possible? Thank you.
Answer: This is covered by the OpenVPN manual.
Create for each user a credential file, which is a text file witch just two lines:
username
password

The line separator must be CR or CRLF (e.g. standard Unix or Windows separator). Let's call this file vpn.auth.
Then, add the following line into client config:
...
auth-user-pass vpn.auth
...

If auth-user-pass was already presend, you need to add an argument to it — a filename containing username and password.
For this to work your OpenVPN must be compiled with ENABLE_PASSWORD_SAVE define (which usually is the case). It is also not supported on OpenVPN 3.x (a client-only OpenVPN release), so don't use that version; use OpenVPN community edition 2.5 or later.
Relying on this as a sole authentication mechanism is inherently insecure. This should be implemented only as an additional mechanism. It is not intended to replace the primary asymmetric crypto-based authentication mechanism with personal certificates and private keys, but to enhance it. When planning OpenVPN, you must take as granted the fact it uses personal keys and certificates, and implement your VPN user management so it performs all necessary key generation and signing. If you have some scripts already, you must update them as to include key generation for everyone!


Run Karate Tests written in another folder and not in main / src

Question: I am trying to build a Jenkins Pipeline for my Spring Boot (Maven) project. It is all working fine. However, i am trying to run my Karate Framework related tests under my project. However my Karate tests are not written in src directory of the project.
Here is the project, that I am trying to build: https://github.com/shah-smit/spring-boot-karate-contract-testing
Here is my Jenkins File, that can be also found in the above repo:
pipeline{
    agent any

    stages {
        stage('Compile Stage'){
            steps {
                withMaven(maven: 'maven_3_6_3'){
                    sh 'mvn clean compile'
                }
            }
        }

        stage('Testing Stage'){
            steps {
                withMaven(maven: 'maven_3_6_3'){
                     sh 'mvn test'
                }
            }
        }

        stage('Package Stage'){
            steps {
                withMaven(maven: 'maven_3_6_3'){
                    sh 'mvn package'
                }
            }
        }

    }
}

Here is my pom.xml
<build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>

            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-surefire-plugin</artifactId>
                <version>2.22.1</version>
                <configuration>
                    <excludes>
                        <exclude>karate/**/*.java</exclude>
                    </excludes>
                    <includes>
                        <include>com/**/*.java</include>
                    </includes>
                </configuration>
            </plugin>
        </plugins>
    </build>

Answer:
However my Karate tests are not written in src directory of the project.

And this is your problem. Don't try to go against the Maven conventions, they are like that for good reasons.
I suggest you look at this example (also for Spring boot) and use the same directory structure and naming conventions:
https://github.com/Sdaas/hello-karate
Comment: @Smit I certainly don't know the answer - maybe it is possible, try read the Maven documentation - but this response of mine should give you a hint as to why this is a bad idea :)
Comment: Thanks. But I understand that is out of convention (at least against Maven). However is there a way to configure?


HTML form disapearing after Error/Email is sent (PHP)

Question: weird problem here, my html form disapears from the page when I click the send button regardless of success or not.
I display an alert box to indicate if the email was sent or not.
here is the code
<?php
$action = $_REQUEST['action'];
if ($action == "") /* display the contact form */ {
    ?>
    <form  action="" method="POST" enctype="multipart/form-data">
        <input type="hidden" name="action" value="submit">

        <input class="champTextFormulaire" placeholder="Votre Nom" name="name" type="text" value="" size="30"/>

        <input class="champTextFormulaire" placeholder="Votre email" name="email" type="text" value="" size="30"/>

        <textarea id="champMessage" placeholder="Votre Message..." name="message" rows="7" cols="30"></textarea>

        <input class="btnEnvoiFormulaire" type="submit" value="Envoi"/>
    </form>
    <?php
} else /* send the submitted data */ {
    $name = $_REQUEST['name'];
    $email = $_REQUEST['email'];
    $message = $_REQUEST['message'];
    if (($name == "") || ($email == "") || ($message == "")) {
        print '';
    } else {
        $from = "From: $name<$email>\r\nReturn-path: $email";
        $subject = "Message sent using your contact form";
        mail(email@example.com", $subject, $message, $from);
        print '';
        }
    }
    }
?>

Comment: For one thing, get rid of `enctype="multipart/form-data"` that's for file attachments/uploading.
Comment: Guys, I have done the code edited, so added double quotes!!!
Comment: @AjithS **It's not up to you to "fix" OP's posted code**, because that's where one of  the problem was. Do a "rollback". Have you not read the editing rules?
Comment: I have updated old code
Comment: I posted a "Working" answer Mathieu. Give it a try.
Answer: Try it this way.
First off, you forgot a double quote just after mail( that read like this:
mail(email@example.com", $subject, $message, $from);

and needed to be changed to:
mail("firstname.lastname@example.com", $subject, $message, $from);

Plus enctype="multipart/form-data" is for file attachments/uploading so you don't need that.
I also removed this line, which was no longer required:
<input type="hidden" name="action" value="submit">

This works and tested:
Note: I added a name to your submit button in order to give it an extra condition. Plus, you basically had your conditions already set, it just needed to be reworked/rethinked and using less code to achieve the same result.
<form action="" method="POST">
<input class="champTextFormulaire" placeholder="Votre Nom" name="name" type="text" value="" size="30"/>

<input class="champTextFormulaire" placeholder="Votre email" name="email" type="text" value="" size="30"/>

<textarea id="champMessage" placeholder="Votre Message..." name="message" rows="7" cols="30"></textarea>

<input class="btnEnvoiFormulaire" type="submit" name="submit" value="Envoi"/>
</form>
<?php

$name=$_REQUEST['name'];
$email=$_REQUEST['email'];
$message=$_REQUEST['message'];

if (isset($_POST['submit'])) {
if (($name=="")||($email=="")||($message==""))
    {
    print '';
exit;
   }

else
{
    $from="From: $name<$email>\r\nReturn-path: $email";
    $subject="Message sent using your contact form";
    mail("email@example.com", $subject, $message, $from);
    print '';
exit;
    }
}
?>

Answer: This is happening because you are using $_REQUEST['action']
After your are submitting the form, your hidden field action becomes $_REQUEST['action'];
And after you submit the form, you get $action = $_REQUEST['action']; to be submit.
Where as you should have a blank value for $_REQUEST['action'] to display the form.
Solution:
1) Either, modify if ($action == "submit")
2) Or, assign blank value to the action (hidden) field