Problem (perhaps trivial) with the continued-fraction approach to (generalized) Pell-solutions

Question: I've seen some Q&A's here which put light on the continued-fractions approach to finding solutions for the Pell-equation. I'm trying to get familiar with this method to apply it to my style of generalized Pell-equations $$ a^2 + b^2 = D \cdot c^2 \qquad \qquad \text{always with }D=u^2+v^2 \tag 1$$
For many of combinations of $(u,v)$ my understanding suffices to get the correct set of solutions from the convergents of the cont.frac, of $\sqrt D$ , but some combinations give problems, and while the brute-force search gives solutions, my cont.-frac. search gives nothing.
The problematic cases seem to be those when $u=v$.
I start with the ansatz $a=u$ and thus look at solutions of (eq 1)
with the constant parameters $(u,v)$ used for some set of solutions
$$u^2 + b^2 = (u^2+v^2) \cdot c^2 \qquad \text{solving for integer $b$ and $c$} \tag 2 $$
(Of course, I ignore cases where $(u,v)$ are part of of a pythagorean triple)
For instance, with $(u,v)=(2,2)$ I get the c.f.-convergents for $\sqrt D$
  2  3  14  17  82  99  478  577
  1  1   5   6  29  35  169  204

and the solutions of the (eq.2)
$$\small \begin{array} {rrr|r}
 a& b& c& \text{iteration-height} \\ \hline
 2 & 2 & 1 & 0.0 \\
 2 & 14 & 5 & 1.00000000000 \\
 2 & 82 & 29 & 2.00000000000 \\
 2 & 478 & 169 & 3.00000000000 \\
 2 & 2786 & 985 & 4.00000000000 \\
 2 & 16238 & 5741 & 5.00000000000 \\
 2 & 94642 & 33461 & 6.00000000000 \\
 2 & 551614 & 195025 & 7.00000000000
 \end{array}$$
(here "iteration-height" is the exponent to which I have to take the power of the iteration-matrix to arrive at the solution given in the row).
We see, that the values in $(b,c)$ can be found in the c.f.-convergents above.
This worked for all tested (small combinations) of $(u,v)$ until suddenly just the very small problemparameter $(u,v)=(3,3)$ breaks.
The c.f.-convergents are
  4  17  140  577  4756  19601  161564  665857
  1   4   33  136  1121   4620   38081  156944

The list of solutions for (eq.2) found by brute-force is
$$\small \begin{array} {rrr|r}
 a& b& c& \text{iteration-height} \\ \hline
 3 & 3 & 1 & 0.0 \\
 3 & 21 & 5 & 0.500000 \\
 3 & 123 & 29 & 1.00000 \\
 3 & 717 & 169 & 1.50000 \\
 3 & 4179 & 985 & 2.00000 \\
 3 & 24357 & 5741 & 2.50000 \\
 3 & 141963 & 33461 & 3.00000 \\
 3 & 827421 & 195025 & 3.50000 \\
 3 & 4822563 & 1136689 & 4.00000
 \end{array}
$$
but I can't see any relation to the convergents of the continued fraction of $\sqrt D$...
(The existence of half-integer values in the iteration-heights indicate that we have actually 2 separate lists of solutions and don't matter much here).

Update
Just found the/a relation using the generalized convergents. Using (in my notation) the "upper gen. cvgts" which occur as list:
***                                ***                                           ***                                                        ***
  4  21  38  55  72  89  106  123  140  717  1294  1871  2448  3025  3602  4179  4756  24357  43958  63559  83160  102761  122362  141963  161564  827421  1493278  2159135  2824992  3490849  4156706  4822563
  1   5   9  13  17  21   25   29   33  169   305   441   577   713   849   985  1121   5741  10361  14981  19601   24221   28841   33461   38081  195025   351969   508913   665857   822801   979745  1136689
     *                         *         *                                   *           *                                            *              *                                                    *

Here the entries marked with *** are true convergents, and the entries marked with * the solutions found by brute-force.
end-update

One more example which is working: $(u,v)=(3,7), D=58$.
The first few c.f.-convergents:
  7  8  15  23  38  61  99  1447  1546  2993  4539  7532  12071  19603  286513  306116
  1  1   2   3   5   8  13   190   203   393   596   989   1585   2574   37621   40195

The first few solutions,
$$ \small \begin{array} {rrr|r}
 a& b& c& \text{iteration-height} \\ \hline
 3 & 7 & 1 & 0.0 \\
 3 & 297 & 39 & 0.350284 \\
 3 & 12071 & 1585 & 0.700567 \\
 3 & 286513 & 37621 & 1.00000 \\
 3 & 11644479 & 1528995 & 1.35028 \\
 3 & 473255633 & 62141509 & 1.70057 \\
 3 & 11233028671 & 1474968925 & 2.00000 \\
 3 & 456533443377 & 59945777931 & 2.35028
 \end{array}
$$
Some solutions are found assuming they have common factor $a=u=3$ and multiples of $3$ in the convergents are tested (for instance $(279,39) = 3\cdot (99,13)$).
(Again, the fractional iteration-heights indicate, that we have three intertwined subsequences of solutions here)

The problem seems to occur with all cases $(u,v)$ with $u=v$ except for $u=v \in [2,5,25,???]$

Q: Is there any (possibly obvious) reason for this inconvenient behave and some remedy?
Comment: Upps, I see now in the $(u,v)=(3,3)$ case, that the first brute-force-found solutions agree to *generalized convergents* , but still cannot recognize some generalizable rationale behind this...
Comment: Hmm, and with $(u,v)=(8,8)$ we have solutions which are not even in the generalized convergents...
Answer: The problem of finding the sequences of solutions for the "problematic cases" - in my question focused to cases of $u^2+v^2=D$ and $u=v$ such that $D=2u^2$  - seems to be intractable with the tools shown so far.
With the help of heuristics we can find some suggestive scheme which at least reduces the complexity.
Of course, for the combination $(u,v)=(u,u), D=2 u^2$ and the "keys" $[a,b_k,c_k]=[u,b_k,c_k]$ with $u^2+b^2 = D c^2= 2 u^2 c^2$ we find, using brute force, some solutions in small numbers. The first is of course trivial; we must have a first solution as $[a,b,c]=[u,u,1]$ and need only a second one to generate an initial transfer-matrix $T$ which allows then to create the sequence of solutions by $[u,u,1] \cdot T^k$ .
Heuristics gave a simple scheme to compute $T$ directly from the value $u$:
$$ \begin{matrix}T_u=\begin{bmatrix}1 & .& .\\. & 3& \frac2u\\. & 4  u& 3 \end{bmatrix} & \to & R_u=\begin{bmatrix} 3& \frac2u\\ 4  u& 3 \end{bmatrix}  \end{matrix} \tag 1$$
In the following I reduce the notation to the $2x2$-matrix $R_u$ which contains only the nontrivial part of $T_u$ : $R_u=T_u[2..3,2..3]$
So, having some initial key $[u,1]$ we can construct all further solutions by $$[b_k,c_k] = [u,1] \cdot R_u^k \tag 2$$
Now, by basic assumptions, we do not allow transfer-matrices $R_u$ with fractional values. But, again heuristically, we find, that each $u$-parameter produces a $R_u$ matrix, having fractional entries, but whose $ex$'th-power gives a full integer matrix:
$$ R_u ^{ex_u} = S_u \qquad \text{ having $ex_u$ such that $S_u$ is an integer matrix} \tag 3$$
This is a pattern which gives consistent results (which means: solutions of the associated generalized Pell-equation) without referring to very likely intractable compositions of generalized convergents of the continued fraction for $\sqrt D$.
However, still I don't have an analytic formula for the results involved, but a pattern that emerges and helps to reduce the searchspace for solutions.
Here is a subset of solutions which I got by heuristics. The matrices $R_u$ are created following my mentioned heuristic.
For $u=v=2$ we have
u=2 D=   8 ex=1   R=[3, 1; 8, 3]        S=R^ex=[3, 1; 8, 3]

Note: the matrix-notation is that of Pari/GP, which means that a ";" indicates beginning of a new row.
for $u=v \in [2,3,4,6,12]$ we have
 2 D=   8 ex=1   R=[3, 2/ 2;   8, 3]   S=R^ex=[3, 1; 8, 3]
 -----------------------------------------------------------------
 3 D=  18 ex=2   R=[3, 2/ 3;  12, 3]   S=R^ex=[17, 4; 72, 17]
 4 D=  32 ex=2   R=[3, 2/ 4;  16, 3]   S=R^ex=[17, 3; 96, 17]
 6 D=  72 ex=2   R=[3, 2/ 6;  24, 3]   S=R^ex=[17, 2; 144, 17]
12 D= 288 ex=2   R=[3, 2/12;  48, 3]   S=R^ex=[17, 1; 288, 17]
=========================================================================

for $u=v \in [2,5,7,10,14,35,70]$ we have
 2 D=   8 ex=1   R=[3, 1; 8, 3]        S=R^ex=[3, 1; 8, 3]
-----------------------------
 5 D=  50 ex=3   R=[3, 2/ 5;  20, 3]   S=R^ex=[99, 14; 700, 99]      --> krit=5*14=70
 7 D=  98 ex=3   R=[3, 2/ 7;  28, 3]   S=R^ex=[99, 10; 980, 99]
10 D= 200 ex=3   R=[3, 2/10;  40, 3]   S=R^ex=[99, 7; 1400, 99]
14 D= 392 ex=3   R=[3, 2/14;  56, 3]   S=R^ex=[99, 5; 1960, 99]
35 D=2450 ex=3   R=[3, 2/35; 140, 3]   S=R^ex=[99, 2; 4900, 99]
70 D=9800 ex=3   R=[3, 1/35; 280, 3]   S=R^ex=[99, 1; 9800, 99]
=========================================================================

Here we find the pattern, that after we have heuristically found the $ex$ for $u=v=5$ we can immediately conclude the transfermatices for all that $u$ which are divisors of $5 \cdot 14$ where $14$ is the entry $S[1,2]$ and we have for all that $u$ a constant product of $u \cdot S[1,2]$
The next block for illustration is longer, but I'll not continue that more.
We find (for $u \in $ divisors of $408 = 8 \cdot 3 \cdot 17$) for $ex=4$
  2 D=   8 ex=1   R=[3, 1; 8, 3]        T2^ex=[3, 1; 8, 3]
-----------------------------
  3 D=  18   ex=2   R=[3, 2/ 3;  12, 3]    S=R^ex=[17, 4;  72, 17]
  4 D=  32   ex=2   R=[3, 2/ 4;  16, 3]    S=R^ex=[17, 3;  96, 17]
  6 D=  72   ex=2   R=[3, 2/ 6;  24, 3]    S=R^ex=[17, 2; 144, 17]
 12 D= 288   ex=2   R=[3, 2/12;  48, 3]    S=R^ex=[17, 1; 288, 17]
-----------------------------
  8 D= 128   ex=4   R=[3, 2/ 8;   32, 3]   S=R^ex=[577, 51;  6528, 577]   --> krit=8*51=8*3*17=408
 17 D= 578   ex=4   R=[3, 2/17;   68, 3]   S=R^ex=[577, 24; 13872, 577]
 24 D=1152   ex=4   R=[3, 1/12;   96, 3]   S=R^ex=[577, 17; 19584, 577]
 34 D=2312   ex=4   R=[3, 1/17;  136, 3]   S=R^ex=[577, 12; 27744, 577]
 51 D=5202   ex=4   R=[3, 2/51;  204, 3]   S=R^ex=[577, 8;  41616, 577]
 68 D=9248   ex=4   R=[3, 1/34;  272, 3]   S=R^ex=[577, 6;  55488, 577]
102 D=20808  ex=4   R=[3, 1/51;  408, 3]   S=R^ex=[577, 4;  83232, 577]
136 D=36992  ex=4   R=[3, 1/68;  544, 3]   S=R^ex=[577, 3; 110976, 577]
204 D=83232  ex=4   R=[3, 1/102; 816, 3]   S=R^ex=[577, 2; 166464, 577]
408 D=...    ex=4   R=[3, 1/204;1632, 3]   S=R^ex=[577, 1; 332928, 577]
=========================================================================

Well, this is an interesting and not too complex pattern. Unluckily it still does not allow to determine the sequences of solutions for some pair $(u,v=u)$ for that type of generalized Pell-equations which are considered here without heuristical search.
So the question is still unresolved, and I hope someone steps in and has possibly a more productive idea...


Search API / Facet API hierarchy based on taxonomy term reference across vocabularies

Question: With Search API + Facet API it is possible to create search facets for taxonomy term reference fields, that reflect the hierarchy of terms in the vocabulary, based on the taxonomy_term_parent table. (With Facet API Taxonomy Folding it is even possible to browse these hierarchies as folders.)
Sometimes hierarchical information is not represented in the taxonomy_term_parent table, and the relations exist between terms of different vocabularies.
E.g. in a site I am building, a "Product series" has a term reference field to "Product family", which has a term reference to a "Supplier". Suppliers, Product families and Product series are 3 distinct taxonomy vocabularies.
Some products only have a supplier. Others have a supplier and a product family. And some have all three. If a product has a series, then its product family is the same as that of the series. And if it has a product family, then the supplier is the same as that of the product family.
I would like to expose this structure as one hierarchical facet, similar in appearance and behavior to that for a single hierarchical vocabulary.
Any ideas?
What I managed so far is to assemble the terms from different vocabularies into a common entity property. I also managed to unify the two different "parent term" relationships (series -> family, family -> supplier) into a common entity property. But then what?
Answer: One alternative, which is not quite the same, is to use dependencies between facets.
So, the product families facet is shown only if a supplier is chosen. And the product series facet is shown only if a product family is chosen.
With hook_block_view_alter() one can rewrite the block title, so that the product family facet block says e.g. "Acme product family", if "Acme" is chosen as a supplier.
Again, this is not quite the same. But it provides an acceptable user experience, I would say. And it might be a suitable solution for some visitors of this question.


global minimum of the square of a multivariate polynomial

Question: I consider the square of a multivariate polynomial $f\in\mathbb{R}[x_1,\cdots,x_n]$  with real coefficients in $n$ variables of maximum order $m$.
(e.g. $f=x^3+2yx^2-3y^2-xy+2 \rightarrow m=3,n=2$)
My goal is to minimize $g=f^2$, so I want to find the (global) minimum of $g=f^2$. My question:

Since $g$ is lower bounded ($g\geq0$), is it guaranteed that there is always a global minimum?
Can i somehow estimate (given $n$ and $m$) the number of local extremas?

Thanks in advance :)
Answer: Every polynomial of even degree and positive coefficient has a global minimum and since squaring doubles the degree of $f$ in every dimension you can definitively say that it has a global minimum. Proving it is easily possible since $g$ is finite for all finite coordinates, but $\forall n \lim_{x_n \rightarrow \infty}{g} \rightarrow \infty$.
Your second question: There is no trivial way to estimate the actual number of local minima. You can calculate the maximum amount of extrema/minima possible, but that's it. -> $\nabla = 0$, in 1D see Sturm's theorem, Descartes Rule of Signs. You cannot predict how the maximum amount of extrema have merged -> think about merging minima, maxima and sattlepoints in 1D of degree 6 and up -> Abel-Ruffini.


Antonym of variance

Question: Is there a word that means the 'inverse of variance'? That is, if $X$ has high variance, then $X$ has low $\dots$?  Not interested in a near antonym (like 'agreement' or 'similarity') but specifically meaning $1/\sigma^2$?
Comment: Agreement and similarity are in any case pretty much preempted, at least in formal definitions, for pairwise and other comparisons. However, that doesn't rule out informal talk, e.g. _you can see from the low variance that different measurements tend to agree_
Comment: I added `[bayesian]` tag since, as you can see from my answer and comments, the answer is closely related to Bayesian statistics and it will be easier to find tagged like this.
Answer: $1/\sigma^2$ is called precision. You can find it often mentioned in Bayesian software manuals for BUGS and JAGS, where it is used as a parameter for normal distribution instead of variance. It became popular because gamma can be used as a conjugate prior for precision in normal distribution as noticed by Kruschke (2014) and @Scortchi.

Kruschke, J. (2014). Doing Bayesian Data Analysis: A Tutorial with R, JAGS, and Stan. Academic Press, p. 454.
Comment: (+1) I don't recall seeing it outside of this context, where it's convenient to be able to say things like "add the precisions of the prior & the data to get the precision of the posterior", & to use the familiar gamma distribution as a conjugate prior for precision.
Comment: Also common in multivariate settings, where the precision becomes the inverse of the covariance matrix. (And again, is useful as a parameter for a normal distribution when  you need a conjugate prior).
Comment: Yes, precision matrix is very helpful when dealing with multivariate Gaussians (as @Peter said), e.g. the formulas for conditional distributions are simpler in terms of precision matrices. Bishop spends many pages describing how this works in the Chapter 3 of his *Pattern Recognition and Machine Learning*, and this then reappears many times throughout the book.

Antonym of variance


Python Image tutorial works, other images behaves differently (showing images with Pylab)

Question: I just started experimenting with Python and image processing. I followed this very well structured tutorial: http://pythonvision.org/basic-tutorial/ . Everything in the tutorial seems to work, with the image provided (the one with the cells). Now I wanted to try how this behaves when inputting another image. So I took another image (the one at the bottom of this post) and suddenly stuff is behaving differently. First off, pylab.show() doesn't show the image heatmap but the regular image, while it should give the heatmap when no colormap is defined.
As a cause of this everything is behaving differently and it only recognises one component (everything that is not white). What am I missing? Does the input image have to be black and white/ grayscale? Does .jpg and .jpeg matter?
I can't seem to find the problem, help would be appreciated.
This code should give the default heatmap view but gives the regular image instead:
dna = mahotas.imread('tools.jpg')
dna = dna.squeeze()

pylab.imshow(dna)
pylab.show()

The image I'm trying to use:
Answer: Most likely the image you're inputting is three channel (r,g,b) and the example image is grayscale/1-channel.  Matplotlib will try to apply a colormap to a 1-channel image, but will render the three-channel as is.  You can use scikit-image to downconvert:
from skimage.color import rgb2gray
img_gray = rgb2gray(img)
pylab.imshow(img_gray)

The library you're using for image processing may also have these color-conversion utilities.
Comment: This has already been a huge help, pymorph can transfer to grayscale. I'm still struggling though because it still only detects one object being all the tools as one, I don't really see why because not all objects are touching on the image.
Comment: You're trying to segment the tools from background?
Comment: Yes but I think I know what is wrong! it interprets the background as main object (because it's white?) so that is the one object and the tools are seen as background. I somehow need to make it inverse... Would inverting colors of the image be a good method?
Comment: Honestly, image segmentation is a huge discipline and there's many approaches to it.  In your case, you're lucky because your backbround is completely white, so you can just retain pixels that are not white and that should be sufficient.  I only use scikit-image in Python for my image processing, so I don't know what your library is doing.  If you post this as a separate question and link it, I will put the solution to that problem using scikit-image if you'd like.
Comment: That would be great, I'll try making a separate topic in a bit! Thanks in advance!
Comment: Just add a link in the comment here and I'll get a notification.
Comment: The question is ready but I have to wait another 40 minutes before I can post again, will post link here hope you have a minute when it gets posted ;)
Comment: The seperate question is here: http://stackoverflow.com/questions/28032722/detect-objects-on-a-white-background-in-python thanks in advance!


How do I install the JRE on a Windows server without Oracle adware?

Question: I would like to install Java on one of our servers, but I am reticent due to Oracle's bundling of an Ask.com toolbar and some virus scanner.  I've read that the java updater even installs these for important security fixes if they are missing, and the toolbar install has a 10 minute delay built-in so you can't immediately remove it if you realized you installed it by accident.
There is no need or desire to have even the java browser plugin installed, I just want a nice clean JRE install.
I've noticed some applications such as Atlassian Stash install their own JRE, is there some automated installer that I can't find?  Can I just copy the JRE directory to my server from one of these?
Comment: throw-the-baby-out-of-the-bath-solution: switch to Linux and install Java from the package manager, and you will never have to deal with these kind of malware ever again.
Comment: IBM also publishes a very good JVM with much better debugging facilities (http://www.ibm.com/developerworks/java/jdk/) and none of that Oracle adware/spyware baggage attached.
Comment: Would you be able to compile from oppenjdk sources?
Comment: @zxq9 A non-Oracle JVM? Oh thank god. Or perhaps more pertinently, thank *you*.
Answer: The off-line installers at http://oracle.com/technetwork/java/javase/downloads/index.html do not include bundled software.
Comment: Awesome!  The "Server JRE" is exactly what I was looking for.
Comment: +1 Only the on-line installer has the bundled software.
Answer: There is an option to disable future adware installation in the Java Control Panel.
The Java Control Panel (jre\bin\javacpl.exe) can be found in the start/app menu under the name Configure Java or in the Windows Control Panel, under the Programs group.
In the Java Control Panel, the option is hidden under the Advanced tab, at the very bottom. It is named Suppress sponsor offers when installing or updating Java.
Answer: If you are willing to use third-party software, try Ninite (ninite.com). I've been using it for the past few years for a lot of updating.
It's a free unattended installer/updater for things like Java, Flash, Silverlight, web browsers, utilities, developer tools etc., The install/update doesn't need any interaction, just start it and it will install everything by itself, excluding any toolbars or other things bundled with the applications you are installing.
On their website, just select which stuff you want from a list, and then a small ~300kb exe file will either update the selected software to the latest version, or install it if it's not installed already. I actually put it on a Task Scheduler job on some computers to make sure their software is kept updated (esp. the Flash runtime).
They don't have every piece of software available, but it covers most of what I need, including the Java JRE and JDK. The paid-for Pro version also gives you centrally managed updating, which could be useful for a server.
Disclosure: I'm only a satisfier free-tier customer, never had the paid service from or worked for them.
Note: Adobe asked them to remove Flash from update choices. It's still available if you pay for the Pro version or if you find an old Ninite Flash installer file online (just verify the signature first).
Comment: Also worth looking at is http://Chocolatey.org which is command line/powershell based and based on NuGet.
Answer: Allow me to refer to the answers given to a similar question I asked over at Superuser.com, which I think are especially suited for the ServerFault.com/enterprise segment.
Ninite packages cannot, as far as I know, be installed silently (unless you pay) and GUI options are not practical in any environment larger than a few computers.
Two answers include registry settings (which can be deployed using Group Policy Preferences) and administrative templates, which can be deployed via traditional GPO's.
In this answer, Danilo Roascio notes that you can add a REG_SZ registry value of SPONSORS in HKEY_LOCAL_MACHINE\SOFTWARE\JavaSoft and HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\JavaSoft. Set the value to DISABLE. This value can of course also be deployed using Group Policy Preferences.
In another answer, Mike provides a neat administrative template that configure the same, for importing into a GPO.
Answer: No. Installing Ask is completely optional (although this option is checked by default). So uncheck it and only Java gets installed!
Comment: @JasonGoemaat I think you can also uncheck it during installing updates. I'm not advocating adware - it totally sucks, and it sucks that it's included with jre, but I installed countless updates, unchecked and never had problems.
Comment: Even if you uncheck it though, when Java does an automatic update it will try to install it again.  Forget to uncheck it and it will install itself 10 minutes later, then you have to remember to uninstall it after that later and you've still probably lost your search and home page to ask in your browsers.
Comment: Unfortunately I'm not the only one that would perform updates on the server, besides I've breezed through what I thought would be a normal update without installing additional software without recognizing the box to uncheck myself  :)


Minimum variance linear unbiased estimator of $\beta_1$

Question: I am studying Applied Linear Statistical Models (Kutner et al, 2005). They present a proof for minimum variance unbiased estimator of $\beta_1$ as follows:

For regression model $Y_i=\beta_0+\beta_1x_i+\epsilon_i$, the
  estimator $b_1$
$b_1 = \dfrac{\sum(X_i-\bar{X})(Y_i-\bar{Y})}{\sum(X_i-\bar{X})^2}$
has the minimum variance among all linear unbiased estimators of the
  form:
$\hat{\beta}_1=\sum c_iY_i$
where the $c_i$ are arbitrary constants.
Since $\hat{\beta}_1$ is required to be unbiased, the following must
  hold:
$E\left[\hat{\beta}_1\right] = E\left[{\sum{c_iY_i}}\right]=\sum c_iE\left[Y_i\right]=\hat{\beta}_1$
Substituting $E[Y_i]=\beta_0+\beta_1X_i$
$E\left[\hat{\beta}_1\right]=\sum{c_i(\beta_0+\beta_1X_i)} =  \beta_0\sum c_i +\beta_1\sum c_iX_i=\beta_1$
For the last equation to hold, the $c_i$ must follow the restrictions:
$\sum c_i =0$ and $\sum c_iX_i=1$

The proof continues but my question is about the last line. I can see that when $\sum c_i =0$ and $\sum c_iX_i=1$ the equation holds but I am not sure how to show that this is a unique solution. I should be able to reach a conclusion based on the number of variables and number of linearly independent equations but I don't see how. Should I treat $\beta_0$ and $\beta_1$ as constants? If so, does summing over $i$ make it a single equation? How should I approach this problem?
Comment: To be unbiased, an estimator (by definition) must have the correct expectation *no matter what the parameter values might be*--not just for the values that happen to be correct in your particular situation.
Answer: So we know its sufficient for that estimator to be unbiased if $\sum c_i=0$ and $\sum c_iX_i=1$
We want to show it's necessary:
Obviously if one of these holds and the other doesn't then we won't get unbiased.
Now suppose both fail:$\sum c_i=\gamma\not=0$ and $\sum c_iX_i=\delta\not=1$, then
$E(\hat\beta_1)=\beta_0\gamma+\beta_1\delta\not=\beta_1$ in general.
The reason is because these constants cannot be based on the parameters because our estimator has to work for any possible value the parameter may take on.


Finding all continuous solutions to an integral

Question:
I need help with both parts of this problem. Part (i) seems obvious, because the integrand $f(t)$ would become $F(t)$, which is obviously differentiable because its derivative is $f(t)$ by construction. I just don't know how to prove it.
For part (ii), I am not sure how to find all continuous solutions..
Thanks!
Answer: To formalize your idea for the first part, note that if we define
$$F(x) = \int_0^x f(t) dt$$
then $F$ is continuously differentiable (since $f = F'$ is continuous). Now $f$ is the sum of continuously differentiable functions.
To find solutions, differentiate, and notice that
$$f' = 5 + 2f$$
which is a first-order ODE that can be solved with any number of techniques.
Comment: thanks! I haven't really studied ODEs yet, so I think I need help solving that, even though it looks so simple..


capturing video source on html5 video play event

Question: My goal is to get the src of the video playing, when the video is played.
I currently have the following code:
<!doctype html>

<video width="320" height="240" controls>
  <source src="video.mp4" type="video/mp4">
  <source src="movie.ogg" type="video/ogg">
Your browser does not support the video tag.
</video>

So my first problem is that this.src doesn't work; it outputs an empty string. I assume this is because the src isn't actually part of the video tag, but is in the source child tag.
I then tried to add into my function the following:
for (var p in this) {
  console.log(p, this[p]);
}

I did this to see if I could find any properties referencing it.. but I don't see anything that directly references it?  So is the only way to get the source really to grab the child source nodes?  If so... then...
My 2nd question, how would I determine which src attribute is actually being used to play the video? IOW if video.mp4 was actually used to play the video, I want to know that value, but if video.ogg was actually used to play the video, I want to know that value instead.
Comment: Check this out: https://developer.mozilla.org/en-US/docs/Web/Guide/HTML/Using_HTML5_audio_and_video
Answer: You can try this way:
var vid = document.getElementsByTagName('video')[0];

vid.addEventListener('play', function() {
    console.log('video source:',this.currentSrc);
}, false);

Comment: i went back and looked at the stuff that output from my loop and sure enough it was there..i'm blind!  thanks!
Answer: Looks like media elements have a currentSrc property to get the chosen media file.
Answer:
The HTML5 video element already has events, so there is no need to add a listener. This is how I would do it.

var myVid = document.getElementById('videoId');
if(myVid != null)//if possibility of no video loaded in DOM
{
    myVid.onplay = function () {
        console.log('video source: ' + myVid.currentSrc);
    };
}


If $d(x,y)$ is a metric, then $\frac{d(x,y)}{1 + d(x,y)}$ is also a metric

Question:
Let $(X,d)$ be a metric space and for $x,y \in X$ define
$$d_b(x,y) = \dfrac{d(x,y)}{1 + d(x,y)}$$
a) show that $d_b$ is a metric on $X$

Hint: consider the derivative of $f(t)$ = $\dfrac{t}{1+t}$

b) show that $ d$ and $ d_b $ are equivalent metrics.
c) let $(X,d) $ be $(\mathbb{R}, |\cdot|)$ Show that there exists no $ M>0$ such that $ |x-y| $ $\leq$ $Md_b$ $(x,y)$ for all $ x,y$ $\in$ $\mathbb{R}$

I have calculated $f(t)$ and $f'(t)$ and from this I know $f(t)$ is an increasing function as $f'(t)$ is strictly positive. But I don't know where to go from here or how to do parts b) and c)
Comment: I don't believe we can use the derivative to show the triangle inequality, since the original problem does not specify that X = R. I vote for the answer of ippiki-ookami.
Comment: From which book is this from?
Answer: a) Separation and symmetry are clear. For the triangular inequality, there is a bit more work.
Let $$f(t):=\frac{t}{1+t}\qquad f'(t)=\frac{1}{(1+t)^2}.$$
Since this function increases on $[0,+\infty)$, the triangular inequality of $d$ yieds
$$
d_b(x,y)=f(d(x,y))\leq f(d(x,z)+d(z,y))=\frac{d(x,z)}{1+d(x,z)+d(z,y)}+\frac{d(z,y)}{1+d(x,z)+d(z,y)}
$$
$$
\leq f(d(x,z))+f(d(z,y))=d_b(x,z)+d_b(z,y).
$$
b) You need to show that a sequence converges to $x$ for $d$ if and only if it converges to $x$ for $d_B$.
Assume first that $d(x_n,x)\rightarrow 0$.
Then
$$
d_B(x_n,x)=\frac{d(x_n,x)}{1+d(x_n,x)}\leq d(x_n,x)
$$
so $d_B(x_n,x)$ tends to $0$.
Now if $d_B(x_n,x)$ tends to $0$, $d(x_n,x)$ is bounded by some $M>0$. Indeed, assume for a contradiction that $d(x_n,x)$ is unbounded. So there exists a subsequence $d(x_{n_k},x)$ which tends to $\pm\infty$. Then $d_B(x_{n_k},x)$ must tend to $1$. Contradiction.
Now
$$
\frac{d(x_n,x)}{1+M}\leq \frac{d(x_n,x)}{1+d(x_n,x)}=d_B(x_n,x).
$$
So $d(x_n,x)$ tends to $0$.
c) Observe that $d_B$ is bounded while $|x-y|$ is unbounded. So such a minoration is impossible.
Comment: Im still a little confused with c) and how i can use that fact to prove that no M>0 exists
Comment: @Mathsstudent147 Assume such an $M>0$ exists. Then consider $x=n\geq 0$ and $y=0$. You would have $n\leq M n/(1+n)\leq M$ for all $n$. A contradiction.
Comment: Hello can i ask why So there exists a subsequence  which tends to infinity then dB(xn ,x) tends to 1 ??
Answer: Separation, identity of indiscernibles and symmetry are immediate by the properties of $d$. For the triangular inequality, here is a simpler step-by-step proof without having to consider derivatives:
$$d_b(x,z) = \frac{d(x,z)}{1 + d(x,z)} = \frac{1 + d(x,z) - 1}{1 + d(x,z)} = 1 - \frac{1}{1 + d(x,z)}$$
$$\leq 1 - \frac{1}{1 + d(x,y) + d(y,z)} = \frac{1 + d(x,y) + d(y,z) - 1}{1 + d(x,y) + d(y,z)} $$
$$  = \frac{d(x,y)}{1 + d(x,y) + d(y,z)} + \frac{d(y,z)}{1 + d(x,y) + d(y,z)}$$
$$\leq \frac{d(x,y)}{1 + d(x,y)} + \frac{d(y,z)}{1 + d(y,z)} = d_b(x,y) + d_b(y,z) $$
where the first inequality is from the sub-additivity of $d$, and the second inequality is from the fact that reducing a positive denominator can only increase a positive quotient.
Comment: Great answer! Thanks a lot
Answer: you know that $d$ is a metric so
$$d_b=\frac{d(x,y)}{1+d(x,y)}=1-\frac{1}{1+d(x,y)}$$ as $d(x,y)$ is greater equal zero, you have the positiv definit here, and the symmetrie. The triangle inequality should be shown similar.
for c ) take that $d_B$ is bounded (1 is a bound), but $|x-y|$ is not.
Comment: My turn to be picky. The first two properties are trivial,  but for the triangular inequality, there is some work to do. Then note that there are several notions of equivalence for norms. The one you mention is Lipschitz-equivalence, and it is not true here (take $d(x,y)=|x-y|$ on $\mathbb{R}$, one is unbounded, the other one is bounded, that's the point of question c). But they are topologically equivalent, which means that they define the same topology.
Comment: @julien thanks cause I already thaugt that they are not equivalent.  we did only have the lipschitz equivalence.
Comment: That's the other way around. They are equivalent (topologically), but not Lipschitz equivalent.
Comment: oh sry my english is bad. I will correct it
Comment: I was figurring out how to proof triangle inequality, but I see now you already linked it.
Answer: [Tried to generalise part (a), along the lines of Julien's proof, and David Ullrich's proof here]
Obs: Let ${ (X, d) }$ be a metric space. Suppose ${ \varphi : \mathbb{R} _{\geq 0} \to \mathbb{R} _{\geq 0} }$ is continuous, ${ \varphi(0) = 0 },$ and ${ \varphi (t) \gt 0, \varphi ' (t) \geq 0, \varphi '' (t) \leq 0 }$ for ${ t \in (0, \infty) }.$
Then ${ \rho (x,y) := \varphi (d (x,y))  }$ is also a metric on $X.$
Pf: Firstly, ${ \varphi (d(x,y)) = 0 \iff d(x,y) = 0 \iff x=y. }$
Let ${ x,y,z \in X }.$ Triangle inequality ${ \varphi(d(x,y)) + \varphi(d(y,z)) \geq \varphi(d(x,z)) }$ also holds : Notice ${ \varphi }$ is increasing on ${ [0, \infty) }$ and ${ \varphi ' }$ is decreasing on ${ (0, \infty) }.$ From ${ d(x,y) + d(y,z) \geq d(x, z) },$ we have ${ \varphi (d(x,y) + d(y,z)) \geq \varphi(d(x,z)) }.$ So it suffices to show ${ \varphi (d(x,y)) + \varphi(d(y,z)) \geq \varphi( d(x,y) + d(y,z) ) }.$
It suffices to show ${ \varphi(a) + \varphi(b) \geq \varphi(a+b) }$ for all ${ a,b \in \mathbb{R} _{\geq 0} }.$ Rephrasing, it suffices to show that for every ${ a \in \mathbb{R} _{\geq 0} },$ ${ \phi _a (t) := \varphi (a) + \varphi (t) - \varphi(a+t) }$ is ${ \geq 0 }$ on ${ [0, \infty) }.$
Let ${ a \in \mathbb{R} _{\geq 0} }.$ We have ${ \phi _a (0) = 0 },$ and ${ \phi ' _a (t) }$ ${ = \varphi'(t) - \varphi'(a+t) \geq 0 }$ for ${ t \in (0, \infty) }.$ So ${ \phi _a }$ is ${ \geq 0 }$ on ${ [0, \infty) },$ as needed.

So if ${ d }$ is a metric on set ${ X },$ so are ${ d _1 (x,y) = \frac{d(x,y)}{1+d(x,y)} ,}$ ${ d _2 (x,y) = 1 - e ^{ - d (x,y) } },$ ${ d _3 (x,y) = \log (1+d(x,y)) },$ etc.

Edit If further ${ \varphi ' (t) \gt 0 }$ for ${ t \in (0, \infty) },$ the identity map ${ (X, d) \overset{\text{id}}{\to} (X, \rho) }$ is a homeomorphism, because ${ \varphi }$ has a continuous inverse ${ \varphi ^{-1} : \mathbb{R} _{\geq 0} \to \mathbb{R} _{\geq 0} }$ and now ${ (x _n \to x \text{ in } (X,d) ) }$ ${ \iff ( \lim _{n \to \infty} d(x _n, x) = 0 ) }$ ${ \iff ( \lim _{n \to \infty} \varphi(d(x _n, x)) = 0 ) }$ ${ \iff (x _n \to x \text{ in } (X, \rho) ) }$ as needed.


Determine whether vector system $x^2, x^3, |x^3|$ is linearly independent

Question: How to determine whether vector system $x^2, x^3, |x^3|$ is linearly independent in vector space $\mathbb{R}^{\mathbb{R}}$ or not?
I know that linear independence means that $\lambda_1x^2+\lambda_2x^3+\lambda_3|x^3|=0 \Rightarrow \lambda_1=\lambda_2=\lambda_3=0$.
From that I get $x^2(\lambda_1+\lambda_2x)+\lambda_3|x^3|=0$ and
\begin{cases}{
  x^2(\lambda_1+\lambda_2x) = 0, \\
  \lambda_3|x^3|=0
  }
\end{cases}
But how to finish this using definition?
Comment: Substitute $x=1,-1,2$ to get three equations in $\lambda_i$.
Comment: Your conclusion from $x^2(\lambda_1+\lambda_2x)+\lambda_3|x^3|=0$ is not correct, because it is not a sum of two positive quantities. However, note that $|x^3| = x^2|x|$, which you can follow similarly.
Answer: I would proceed like that. Dividing by $x^2$ for $x \neq 0$ you get
$$\lambda_1 + \lambda_2 x + \lambda_3 \vert x \vert =0$$
Taking the limit at $0$ implies $\lambda_1 =0 $. Dividing again by $x$ you get the equality $\lambda_2 + \lambda_3 = 0$ valid for all $x \gt 0$. And therefore $\lambda(x - \vert x \vert)=0$ for all $x \in \mathbb R$ where $\lambda=\lambda_2=-\lambda_3$.
Taking finally $x=-1$ you get $\lambda=0$ and can finally conclude.
Comment: Why take the limit? Just set $x=0$.
Comment: @lhf Good remark !!!


Probability of finding a Hamilton circuit in a graph

Question: In short, I would like to know either/both the probability that there exists a Hamiltonian circuit within a graph, or the number of circuits expected to exist. (Without actually finding all the circuits). If I run an algorithm to find all circuits, how many should I expect to find, if any? I am fine with a close approximation if it simplifies the calculations substantially.
If I have a given number of vertices and the average number of edges, is this enough information? Each vertex may have many out-edges but no two vertices share more than one edge. Also, a vertex cannot belong to two circuits. Once a circuit is found, those vertices that comprise it are removed from the graph.
My example graph has 10,000 vertices and each vertex has three out-edges to other vertices.
And a follow up question: How could I formulate the question to figure out the minimum average number of out-edges per vertex to give me an arbitrary level of certainty that I would find at least one circuit? Stated another way, if I want 50% certainty in finding a circuit, and I have 10,000 vertices, what is the minimum number of out-edges each vertex should have? (not the average, but actual minimum)
I have some scratchpad notes where I've worked this out, but would really appreciate the guidance of someone more knowledgeable. Thanks!
Answer: The answer depends a lot on how one defines "random cubic graph" with $n$ vertices (necessarily $n$ is even), we may try the following to find Hamilton circuits:
Fix a vertex $a_1$, pick one of its neighbours $a_2$ at random. Then, assuming we have $a_1a_2\ldots a_k$ with $k\ge 2$, toss a coin to decide which of the other two (i.e. $\ne a_{k-1}$) neighbours of $a_k$ to pick as $a_{k+1}$ and continue. It may be adequate to assume that $a_ka_{k+1}$ could be any of the $3(n-k)$ edges to a "new" vertex, or any of the $k-3$ not yet used edges to one of the vertices $a_2,\ldots, a_{k-2}$, or any of the two not yest used edges to $a_1$. This makes us guess that the probability to hit a new vertex is $\frac{3(n-k)}{3(n-k)+(k-3)+2}=1-\frac{k-1}{3n-2k-1} $. And when $k=n$, the probability of succesfully coming back to $a_1$ is $\frac{2}{n-1} $. This would suggest that there are about
$$\tag13\cdot 2^n\cdot\prod_{k=2}^{n-1}\frac{3(n-k)}{3n-2k-1}\cdot \frac2{n-1}=3^{n-1}2^{n+1}(n-2)!\frac{(3n/2-3)!\cdot 2^{3n/2-3}}{(3n-5)!\cdot (n/2)!\cdot2^{n/2}}\cdot\frac1{n-1} $$
Hamilton cycles.
Or: There are $\frac12(n-1)!$ Hamilton cycles in the complete graph $K_n$. For each of these, the probability that the first edge is also in $G$, is $\frac3{n-1}$; for later edges, the probybility that the edge is in $G$, given that the previous edge is in $G$, is $\frac{2}{n-2}$; we should make a special consideration for the final edge, but ignore that. With this Hamilton cycle of $K_n$ is also in $G$ with probability $ \frac3{n-1}\cdot\left(\frac2{n-2}\right)^{n-1}$, giving a total expected number of
$$ \frac12(n-1)!\cdot \frac3{n-1}\cdot\left(\frac2{n-2}\right)^{n-1}=\frac{3\cdot 2^{n-2}\cdot (n-2)!}{(n-2)^{n-1}}$$
Hamilton cycles. With Stirling, this simplifies to
$$\tag2\approx {3\cdot \left(\frac 2e\right)^{n-2}\sqrt{\frac{2\pi}{n-2}}}\approx 0.$$
Or: If we remove a random edge from a cubic graph, we produce two vertices of degree $2$, which can be replaced with an edge directly connectng their neighbours, thus resulting in a cubic graph with two vertices less. However, this step may have produced a double edge, in which case we can drop one of the edges, obtain degree-two vertices again, which can be removed. This could repeat, but for large $n$ we can consider each of these special cases rare. Thus the Hamilton circuits of $G$ that do not use a specific edge are in correspondance with the Hamilton circuits of a smaller cubic graph. For a fixed vertex $a_0$, each Hailton circuit avoids precisely one of the three incident edges. Hence this suggests that the expected number of circuits for an $n$-vertex cubic graph are essentially $3$ times the expected number of the number of circuits in an $(n-2)$-vertex cubic graph, so their count should be
$$\tag3 \sim 3^{n/2}.$$
Now that I have heuristically(!) obtained three totally different results, it appears that this answer should rather be considered an oversized comment - sigh.
Comment: Thanks Hagen, Your first line of thinking is how I was approaching it too, and I think will work for me. Would the result hold if three were not the actual number of edges of each vertex, but rather the mean number of out-edges per vertex?

Also, could you refactor formula(1) to take a variable 'E' instead of a constant as the number of out-edges?
Comment: I realized I was asking the 'wrong question,' but you answered what I asked so I'll go ahead and award the answer and thank you for the discussion!


How do I delete all the nodes in my custom linked list?

Question: Is is possible for me to delete all nodes of my linkedlist to delete by my this code piece? If no then how is it possible to delete all the node at once!
my code is
EditNode mynode=start;
while(mynode!=null){
    mynode.editnext=null;
    mynode=mynode.editnext;
}

Help needed! Thanks in advance...
Comment: How should we know, you hide your implementation of `LinkedList` from us.
Comment: If you've *really* got a linked list, you can just call `clear()`.
Comment: Set the head node to equal null, then let the gc do its thing.
Comment: Use temporary space reservation for a node reference before you lost a node.
Answer: Your code dosen't work because you are setting mynode.editnext to null and then trying to reference it.  So that's not going to work.
To delete all nodes in a linked list, in Java, just clear the head pointer.  Java will garbage collect the rest.
start = null;

Please note that this answer is meant for your custom linked list.  In production, you should use the Java implementation of LinkedList, which has a .clear() method on it.  This is a much cleaner way to handle a list.
This is because you may have stray pointers which point to an item in the list, and this will keep a reference around to the rest of the list and prevent garbage collection.  You shouldn't build organizational structure like the editnext property into the data structure.  They should be separate classes.
To clear all of your pointers in each node, use the following code:
EditNode mynode;
while (start != null){
    mynode = start.editnext;
    start.editnext = null;
    start = mynode;
}

Comment: Actually, the OPs code does almost work in an efficient way (but most likely not as intended). The only mistake is that `start` is not set to `null`.
Answer: Did you check clear() method of LinkedList?
public void clear() - Removes all of the elements from this list. The list will be empty after this call returns.
Comment: I'm doing it without using java built in classes! so I need to do it manually like from my code? need help


Gradle : Unable to generate QueryDSL classes

Question:
Gradle version: 5.1
Java version: 11

I have the following task defined in gradle file to generate QueryDSL classes:
task generateQClasses (type: JavaCompile) {
    source = sourceSets.main.java.srcDirs
    classpath = sourceSets.main.compileClasspath
    destinationDir = file('src/main/java')
    options.annotationProcessorPath = configurations.annotationProcessor
    options.compilerArgs = ['-proc:only', '-processor', 'com.querydsl.apt.jpa.JPAAnnotationProcessor', '-Aquerydsl.packageSuffix=.querydsl']
}

Below is my dependencies block:
annotationProcessor "com.querydsl:querydsl-apt:4.2.1:jpa"
annotationProcessor "org.hibernate.javax.persistence:hibernate-jpa-2.1-api:1.0.2.Final"
annotationProcessor "javax.annotation:javax.annotation-api:1.3.2"

If I execute `gradlew generateQClasses, I see the following in the logs:
Attempt to recreate a file for type foo.bar.QClass
error: Attempt to recreate a file for type foo.bar.QClass

It fails with error saying the file already exists. How can I configure this task to overwrite the files if they exist?
Also, the above config is the config for the root project and it has 5 subprojects. AnnotationProcessor is able to overwrite the files in one of the sub project but not the others (all the subprojects have the same config). Am I missing anything?
Comment: Is your goal to move the generated source code out of the build folder, or is it to only generate them when you run your custom task (instead of being part of the normal compile task), or both?
Comment: It's only to generate them when someone executes that task explicitly or when the code is compiled. I do not want to move the generated source code out of the build folder.
Comment: Are you saying you like to have them generated when running `compileJava` but also `generateQClasses`? Isn't it easier to just rely on the former, or at least only one of them? Sorry if I am being a bit dense :)
Comment: I only have this task as a separate because it requires different `annotationProcessorPath` and `compilerArgs` values compared to `compileJava`.
Comment: for reference: https://stackoverflow.com/questions/54134455/java-11-querydsl-4-gradle-5-springboot-2-1-not-generating-qclasses/58375764?noredirect=1#comment110277657_58375764
Answer: I had the same behavior here... It happens when the generated sources folder isn't empty. Try to execute with gradle clean before. Then will be OK. But I'm trying to replace the default QueryDSL task, with the task that you've done. If I have success, I'll update the answer here.
Comment: @Darshan Mehta I did some question about it: https://stackoverflow.com/questions/69885572/querydsl-with-gradle-configuration-of-annotation-processor.


"angular way" for dynamically adding directives

Question: I'm very impressed with Josh's answer  about 'angular way'  and declarative style in client-side.
But can you help me to understand, how to do that:
I have a single-page app with the menubar in the left side, and div container on the right-side.
When user clicking the menu item in the left menubar, on the right side I must to open the new tab with some grid,like this:

In angular I realized the <grid> directive.
When user click menuitem, I must add dynamically this grid directive with params on the right side.
What is the angular way for doing  this functionality?
Update:
I found article about dynamic tabs, and this is example how I use it in my case
Comment: Ask a concrete question!
Answer: Since you asked a general question, let me give you a general answer. It should be helpful :)
AngularJS is model/data driven, and if you want to make any change to the UI, the first thing you may think is how to achieve it by changing data. Given this idea, we can implement it like this:

Define a ng-repeater, which should render tabs for a list of Tab objects called MyTabs, for instance.
When you want to add a new tab, then create a tab object and add/push it to MyTabs.
AngularJS will magically render it on the UI, thanks to the 2-way data binding.
Comment: sza, thank you, I've dicided using ui-tabs, like here http://plnkr.co/edit/yVAFAk8nFfI45VEsjVZ3?p=preview
Comment: This general answer is extremely helpful! Shame it hasn't reached much attention.


Should both mysqld_safe and mysqld be running at the same time on startup?

Question: On launching my CentOS VPS (setup by someone else), MySQL starts two processes on boot:

mysql : /usr/libexec/mysqld --basedir=/usr --datadir=/var/lib/mysql --user=mysql
root: /bin/sh /usr/bin/mysqld_safe --datadir=/var/lib/mysql --socket=/var/lib/mysql/mysql.

Is this normal / the correct way to setup MySQL (that root is running mysqld_safe?)
Thanks!
Comment: all the parameters like key_buffer_size need to be on mysqld or mysqld_safe?
Answer: Yes, that's the way it's supposed to be. mysqld_safe spawns a mysql-user run daemon (mysqld).
Answer: If you take a peek into the contents of mysqld_safe you'll find that it is merely a shell script wrapper for launching mysqld.
Comment: Oh,... if you look inside mysqld_safe it does quite a bit more than a mere wrapper.


How to prove an ordinary differential equation is not separable?

Question: Some elementary exercises require one to determine whether or not an ordinary differential equation is separable. For example, it is understood that the equation $$y'=\frac{1-2xy}{x^2}$$ is not separable. An easier example is $y'=x+y$. Usually this is intuitive understandable; however, can one give a strict proof that the right hand of these equations cannot be written as a product of the form $p(y)q(x)$?
I am aware of this question, but am not sure if the method mentioned in one of the answers is a good approach.
Answer: In general, a $\mathcal{C}^2$ function $f(x,y) \neq 0$ can be expressed in the form $p(x) q(y)$ if and only if
$$
\frac{\partial^2 \ln f}{\partial x \partial y} = 0.
$$
Proof:  First, note that if $f(x,y) = p(x) q(y)$, we have
$$
\frac{\partial^2 \ln f}{\partial x \partial y} = \frac{\partial}{\partial x} \left( \frac{1}{f} \frac{\partial f}{\partial y} \right) = \frac{\partial}{\partial x} \left( \frac{p(x) q'(y)}{p(x) q(y)} \right) = \frac{\partial}{\partial x} \left( \frac{q'(y)}{q(y)} \right) = 0.
$$
To prove the converse, suppose that
$$
\frac{\partial^2 \ln f}{\partial x \partial y} = \frac{\partial}{\partial x} \left( \frac{\partial \ln f}{\partial y} \right)= 0.
$$
If this is true, the quantity in square brackets must be a function of $y$ only:
$$
\frac{\partial \ln f}{\partial y} = g(y).
$$
We can then integrate this with respect to $y$;  if $G(y)$ is the antiderivative of $g(y)$, we must have
$$
\ln f = G(y) + h(x).
$$
(Note that we are free to add a "constant with respect to $y$", i.e., a function $h$ that depends only on $x$, to the antiderivative.)  We conclude that
$$
f(x,y) = e^{G(y) + h(x)} = p(x) q(y)
$$
where $p(x) = e^{h(x)}$ and $q(y) = e^{G(y)}$.
(I have implicitly assumed throughout that $f(x,y) > 0$, but the above proof can be easily extended to domains where $f(x,y) < 0$ as well.)
Comment: Thanks for the answer! Just to clarify one thing about the part "$\ln f$": What if $f<0$?
Comment: @Zuriel:  See my note at the bottom.  Basically, the same proof can be applied to $\ln (-f)$.
Comment: Thanks again! Is it a theorem from Calculus?
Comment: @Zuriel:  I came up with the proof on my own, but given that it didn't take terribly long, I suspect it was already known.  :-)  The techniques I used in this proof are well-known in the study of partial differential equations (PDEs).
Comment: Thank you! Do you also require that $f(x,y)\neq 0$ for all $x,y$?
Answer: Using the approach you've linked, let $f(x,y) = \frac{1-2xy}{x^2}$. Consider $(x_0,y_0) = (1,0)$ and notice that $f(x_0,y_0) = f(1,0) = 1 \neq 0$. We now show that $f(x_0,y_0)f(x,y) \neq f(x,y_0)f(x_0,y)$ which will show that $f(x,y)$ is not separable.
Notice that,
$$f(x_0,y_0)f(x,y) = 1\cdot f(x,y) = f(x,y) = \frac{1-2xy}{x^2}$$
and
$$f(x,y_0)f(x_0,y) = f(x,0)f(1,y) =  \frac{1}{x^2}\frac{1-2y}{1} = \frac{1-2y}{x^2}.$$
Since $\frac{1-2xy}{x^2}$ and $\frac{1-2y}{x^2}$ are not the same function, then we've shown that $f(x,y)$ isn't separable.


What statistical test should I use and for what reason?

Question: My dependent variable is an index from annual reports of companies (ranging from 0 to 1). The independent variables will be measured with Likert scales (individuals in each company will respond to the questions – a group of items rated with a Likert scale). What is the most appropriate statistic to use in this scenario? I need help please.
Dependent variable (index from one company) $=f$(Three separate Likert Scales measuring three different issues)
Comment: @DoctorAmbient The (0,1) variable is the DV (the $y$), while the Likert scales are the IVs (the $x$'s).
Comment: @Glen_b Sorry!  Totally misread that!  Does the index have an interpretation as a probability or as something else?  The suggestions below deal with the transformation of $y$, but should the $x$'s be transformed, too?  Are they all the same Likert scale, or do the scales vary?  (I've seen that happen more than you think!)
Comment: Why is the index bounded between 0 and 1, in terms of the data-generating process?
Comment: Yes, how do you get numbers between 0 and 1 from a Likert which is most often 5 points?
Answer: Transform the dependent variable by taking ln(y/(1-y)) in a way as with the logistic regression and regress that on the predictors. After that check the residuals for normality.
Answer: Papke and Wooldridge (J. Appl. Econometrics, 1996) suggest a so-called fractional logit model, a GLM with a binomial distribution and a logit link function, since the traditional tobit regression is non-applicable when outcomes outside of [0,1] are unfeasible.
Answer: I propose a much more simple model. try first to fit a simple linear model. Your likert variables can be coded as dummy variables.


Can a Function have Multiple Valid Indefinite Integrals

Question: Working with U-substitution, I have to integrate the following.

$\int x\cos(x^2)\sin(x^2)dx$

From my understanding you can take the integral by substituting $u$ for either $\cos(x^2)$ or $\sin(x^2)$.
EG:
Solution 1:

$u = \sin(x^2)$
$\frac{1}{2}du=x\cos(x^2)dx$
$\frac{1}{2}\int udu = \frac{u^2}{4}+c = \frac{\sin^2(x^2)}{4}+c$

Solution 2:

$u = \cos(x^2)$
$-\frac{1}{2}du=x\sin(x^2)dx$
$-\frac{1}{2}\int udu = -\frac{u^2}{4}+c = -\frac{\cos^2(x^2)}{4}+c$

The two answers are shifts of each other, but are not equivalent. Is one correct and the other incorrect, or are they both valid indefinite integrals of the original function?
Comment: Keep in mind that $\sin^2x+\cos^2x=1$, so $\dfrac{\sin^2(x^2)}{4}=\dfrac{1-\cos^2(x^2)}{4}$, and the constant $\dfrac{1}{4}$ can be absorbed into $C$.
Answer: Since they only differ by a constant, both are correct. One might say that they both represent the same set of functions, because of the arbitrary constants.


How to convert text extracted from tesseract to pandas dataframe

Question: This is the text I extracted from a cropped image containing table:
S No PART CODE PART DESCRIPTION
HSN
QTY RATE(Rs)
VALUE DISCOUNT SGST SGST%
CGST CGST%
AMOUNT(Rs)
CHAIN LUBE &
CLEANER KIT-
34039900
0.16
1,406.78 213.5648
11.52
19.22
19.22
9
252.00
1
3600008
S00ML.
141715
BULB 12V-2VW(BA9S)
85392940
4
10.17
10.17
0
0.92
0.92
9
12.01
2)
(PARKING)
20.14
18
264.01
TOTAL
223.73
11.52
20.14
18
0.01
ROUND OFF
TOTAL
264
This is the image

I want to convert this into pandas dataframe. How should I do it?
df = pytesseract.image_to_data('1.jpg', lang='eng', output_type='data.frame')
display(df)

Answer: You will need to specify output_type='data.frame'.
from PIL import Image
import pytesseract

df = pytesseract.image_to_data(Image.open('your_image.jpeg'),lang='eng',output_type='data.frame')

Comment: It displays dataframe of size 170 row X 12 columns with required data on the last column that too in 170 rows. Is there any way to process it to obtain the same table from the image?
Comment: Include the output and I can try. You will need additional preprocessing.
Comment: https://colab.research.google.com/drive/1Tpc6ppQUi3QgBDQzT70WHlf-kAH35xDy?usp=sharing This is the link to the mini project


Triangulating Polyhedron faces in CGAL

Question: Having an arbitrary polyhedron in CGAL (one that can be convex, concave or, even, have holes) how can I triangulate its faces so that I can create OpenGL Buffers for rendering?
I have seen the convex_hull_3() returns a polyhedron that has triangulated faces, but it won't do what I want for arbitrary polyhedrons.
Answer: The header file <CGAL/triangulate_polyhedron.h> contains a non-documented function
template <typename Polyhedron>
void triangulate_polyhedron(Polyhedron& p)

that is working with CGAL::Exact_predicates_inexact_constructions_kernel for example.
Comment: My project's working with Simple_cartesian kernel. Is there a way I can use that function with this kernel? Sorry, I'm new to CGAL...
Comment: You can try, but there is no guarantee on the result. See http://www.cgal.org/FAQ.html#inexact_NT.
Comment: What can I do to convert from a polyhedron with a Simple_cartesian to one with Exact_predicates_inexact_constructions_kernel?
Comment: You just need to change the kernel and that should work.
Comment: FYI: this header has since been removed from the CGAL project. A new package for triangulations has been introduced: http://doc.cgal.org/latest/Triangulation/index.html
Comment: @scry: Note that you should use this package in case you have a dimension greater than 3. For dimension 2 and 3, dimension dedicated packages are more efficient.
Answer: The Polygon Mesh Processing package provides the function CGAL::Polygon_mesh_processing::triangulate_faces with multiple overloads. The simplest thing to do would be
typedef CGAL::Simple_cartesian<float> Kernel;
typedef CGAL::Polyhedron_3<Kernel> Polyhedron_3;

Polyhedron_3 polyhedron = load_my_polyhedron();
CGAL::Polygon_mesh_processing::triangulate_faces(polyhedron);

After that, all faces in polyhedron are triangles.
The function modifies the model in-place, so one has to use a HalfedgeDS that supports removal. This is the default, but, for example, HalfedgeDS_vector won't do.
See also an official example that uses Surface_mesh instead of Polyhedron_3:
 Polygon_mesh_processing/triangulate_faces_example.cpp

Triangulating Polyhedron faces in CGAL


How can you summarize growth in the "production" rate per person?

Question: I have been reading the book, Good to Great by Jim Collins.  It says that you should focus on information that "cannot be ignored," and that you should focus on the right "denominator."
I thought it would be good to measure "Average Growth Rate per Producing Entity." If we are providing value and support, we would expect to be helping them "produce more."
I have production data in an excel spreadsheet that I can summarize.
I primarily use "pivot tables" for my data analysis.  I know that you can do "percentage change over previous time period" but I end up with distortions for the first year, when people don't have a full period to produce.  I also am not sure how to summarize it.
Is there a better program that I should use for this? Is there a good way to do this in excel?
I was thinking you could take the geometric mean (what growth rate would you need on the initial production number in order to end up with the final number -- or so I believe it is explained) and besides that I'm not sure where to start.  I would love to use pivot tables or something similar where I can just hit refresh and get the updated version of the numbers.
Any ideas out there?
Answer: I think the standard thing to use is the annualized rate.  If you have less than one year, you simply multiply the current observed value by the reciprocal of the proportion of a year that it represents.  For example, if you have one month (1/12th of a year), you multiply by 12, for one quarter, you multiply by 4, with just 16 days, you multiply by 365/16, etc.  With observations over a shorter time period, you will have more measurement error in your estimate, as you suspect.  Unfortunately, this is unavoidable.  As for better software, I would argue that a programming language (such as R) may offer advantages in the long run, but require a lot of effort to learn up front.  For a project such as this, it may not be worth it.
Comment: Yeah. Annualization would work but it would have to be done manually. :(
Comment: If you have a column in which the proportion of the year covered by each datum is noted, you should be able to pretty easily code up a new column w/ a function that will compute the appropriate multiplicative factor & then drag or copy-&-paste that function across the needed range of cells. That shouldn't take too long. As I note above, learning a programming language that will allow you to do this with a few lines of reusable code will pay off in the long run, but will require an investment of time up front.
Comment: I am comfortable with PHP for programming and I have been able to make some visual basic work within excel...
Comment: I don't know PHP, nor do I really know visual basic, but you should be able to make the latter work to calculate the multiplicative factors for you in excel.


node-soap: It not found the distribution method

Question: Try using the node soap call a web service does not work, but if it works in SoapUI
var soap = require('soap');
var url = 'http://22.214.171.124:96/PasarelaServices/CustomerServices?wsdl';
var args = { "key": '12345', "parametros": 'parameters...' };
soap.createClient(url, function (err, client) {
  console.log(client.describe());
  console.log(client.describe().CustomerServices.CustomerServicesPort.solicitarPago);
  client.CustomerServices.CustomerServicesPort.solicitarPago(args, function (err, result, raw, soapHeader) {
    console.log(err);
    console.log(result)
    console.log(raw);
  });
});

in SoapUI request would:
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ser="http://services.vlink.com.bo/">
   <soapenv:Header/>
   <soapenv:Body>
      <ser:solicitarPago>
         <key>12345</key>
         <parametros>parameters...</parametros>
      </ser:solicitarPago>
   </soapenv:Body>
</soapenv:Envelope>

Thank you
Comment: Please check the raw request in soapui and see if any of the headers being missed in `node-soap` call?
Comment: I suspect it may be the prefix function
Answer: Can solve it with:
var soap = require('soap');
var url = 'http://126.96.36.199:96/PasarelaServices/CustomerServices?wsdl';
var wsdlOptions = {
  "overrideRootElement": {
    "namespace": "ser",
    "xmlnsAttributes": [{ "name": "xmlns:ser", "value": "http://services.vlink.com.bo/" }]
  }
};
var args = { "key": '12345', "parametros": 'parameters...' };
soap.createClient(url, wsdlOptions, function (err, client) {
  client.solicitarPago(args, function (err, result, raw, soapHeader) {
    console.log(result);
  });
});

The problem was: it was necessary to establish the prefix "ser" with
wsdlOptions


Is there a bounded connected set $X$ such that for all point $b$ there exists $r > 0$ such that $X \setminus O(b, r)$ is disconnect?

Question: I find a question by myself, and I do not know if it is an interesting question.
Let $X \subseteq \mathbb{R}^n$ be a bounded connected set. And I define a "bad point" $b \in \mathbb{R}^n$ with respect to $X$ if there exists $r > 0$ such that $X \setminus O(b, r)$ is not connect, where $O(b, r)$ is a ball with center point $b$ and radius $r$. Let $B(X)$ be a set of all "bad point" with respect to $X$.
Strong question: Is there a bounded connected set $X$ such that $B(X) = \mathbb{R}^n$?
Weak question: Is there a bounded connected set $X$ such that $X \subseteq B(X)$?
I have no idea how to solve my question. I give some examples of my definition.
(1) If $X$ is a ball or spherical surface, then $B(X) = \varnothing$.
(2) If $X = \{(x,0, \ldots, 0) \mid x \in [0,1] \}$ is a close line segment, then $$B(X) = \{(x,a_{1}, \ldots, a_{n - 1}) \mid x \in (0,1), a_{i} \in \mathbb{R} \}$$
(3) If $X = \{(x,0, \ldots, 0) \mid x \in (0,1) \}$ is a open line segment, then $$B(X) = \{(x,a_{1}, \ldots, a_{n - 1}) \mid x \in (0,1), a_{i} \in \mathbb{R} \}$$
Comment: Wouldn't you be able to take $X$ to be one entire axis? So $X = \{(x, 0, \ldots, 0) : x \in \mathbb R\}$, or do I misunderstand your question? This is essentially as your examples (2) and (3), but now $B(X) = \mathbb{R}^n$ and that should answer your strong question.
Comment: @YuiToCheng that is assuming we fix $r$ at the start, but the question is whether for every $b \in \mathbb R^n$ we can find $r$ such that $X - O(b, r)$ is disconnected. So $r$ can depend on $b$.
Comment: @MarkKamsma Yes, I considered this example, I forget to write that X is bounded.
Comment: @TeamBright I see, that makes the question less trivial. Still, you have already answered your own weak question with example (3). The strong question, I wouldn't know an answer to right away.
Comment: @MarkKamsma Oh, yes. I answered the weak question. I did not realized it. I focused some sets which is $n$-dimensional set.
Answer: As commented, the weak question is already solved.
For the strong one, I think there is a simple example if I've understood your question well. Consider a cross $C$ in $\Bbb{R}^2$ center at the origin, i.e the union of $I_x=\{(x,0)\mid x\in[-1,1]\}$ and $I_y=\{(0,y)\mid y\in[-1,1]\}$.
Any ball that covers $(0,0)$ by not the whole cross would disconnect $C$. But you can see that for any point $b\in\Bbb{R}^2\setminus\{(0,0)\}$, the (closed) ball $O(b,|b|)$ contains $(0,0)$ but not the whole cross (if you mean open ball then just take a slightly bigger radius). Note that for $b=(0,0)$ you can take a small radius and it will work as well.
So, for every $b\in\Bbb{R}^2$ there exists $r>0$ such that $C\setminus O(b,r)$ is disconnected. This example can be easily generalized to any higher $\Bbb{R}^n$.
Comment: Love it, easy and elegant. Only case that is left is $n = 1$, but the answer to that is an (almost trivial) exercise left to the reader.
Comment: Right, I didn't consider the case $n=1$, where that is surely not possible, since a [connected set in $\Bbb{R}$ is an interval](https://math.stackexchange.com/questions/239063/intervals-are-connected-and-the-only-connected-sets-in-mathbbr), so any point outside of the interval is not a bad point. @MarkKamsma
Answer: Your weak question is most assuredly true -- just take $X=\{(x,0,\ldots,0):x\in(-1,1)\}$. Since deleting any sufficiently small neighborhood of any point in $X$ will leave behind two disjoint line segments, we are done.
Your strong questions is interesting, but I don't know how to answer it well, so bear with me as I describe a construction in $\mathbb{R}^2$:
Consider the curve (in polar coordinates)
$$
(r,\theta) = \left(\exp(f(\theta)),\theta\right)
$$
where $f(\theta)$ is any continuous, monotonically increasing function with range $\left(-\ln(2),0\right)$, such as an appropriately scaled and translated $\arctan$ function. Take this curve, a circle with radius $1/2$ centered at the origin, and the unit circle, and define $X$ to be their union.
Where are the "bad points"? If you take a point outside the unit circle, say $(0,2)$, then we can find a radius $r=1+\epsilon$ which will "cut" the spiral off from the unit circle, leaving us a disconnected set. The same will be true for a point inside the circle of radius $1/2$, and a point inside the annulus can have a radius chosen to "cut" the two circular boundaries off from one another. Thus, all of $\mathbb{R}^2$ is "bad".
How do we take this construction and make it work in higher dimensions? There may or may not be an elegant equation for it, but the idea definetely generalizes -- take some increasingly fine "spiral" along the surface of hyper-sphere shells, and then take many such shells nested together, limiting towards to bounding shells, and link them together with line segments.
I wish I could describe that better, but I don't know how. Hopefully your mental picture is the same as mine.
EDIT: Please just use Javi's answer if you want a good example. This is far too complicated, even in $\mathbb{R}^2$.
Comment: @MarkKamsma Truthfully my example doesn't matter anymore, as Javi's answer has a *much* simpler construction that will work in higher dimensions.
Comment: Also thank you, you try to find a more general solution. It is a good approach.
Comment: I do not directly see picture you are trying to describe, but isn't this unbounded? The $y$-coordinate ($\theta$) can get arbitrarily large.
Comment: @MarkKamsma The polar coordinate description of the curve is unbounded in $\theta$, but the radius is bounded, leaving the entire object bounded.
Comment: Ah, I wasn't aware you were using polar coordinates. You may want to explicitly note that (even though you use the standard notation for it). On another note: once you have found an example in $\mathbb R^2$, I think you have an example for $\mathbb R^n$, $n \geq 2$, because you can just include your example as a subspace.

Is there a bounded connected set $X$ such that for all point $b$ there exists $r > 0$ such that $X \setminus O(b, r)$ is disconnect？


How to db_insert into users?

Question: I'm inserting new users into tables users (using a webservice that insert), but how to make uid being automatically inserted and it would be always the next value of the current maximal value on table users (and auto-increment too) ?
Thank you
Answer: The users table doesn't have an auto-increment constraint on the primary key (or any field).
The recommended way to add users is using the API (user_save() etc), that will handle the ID for you.
Failing that, just query for the maximum ID in the table before you perform the insert; after the first insert, assuming you have exclusivity on this database while you're developing, you can maintain the increment in your code (no need to check the table each time).
Drupal does exactly the same thing in user_save():
$account->uid = db_next_id(db_query('SELECT MAX(uid) FROM {users}')->fetchField());

Comment: Because of the anonymous user @ar7max, that needs an ID of `0`, so auto-increment isn't an option
Comment: Hi @Clive, thank you for your helpful answer ,as always, I didn't mentioned in my question that i've tested inserting using max + 1 in another query that fetch users etc.. So i'll keep it right now because as you said user_save do the same, so thank you
Comment: Sorry for off-topic, but what may be purpose of avoiding autoincrement?
Comment: But we still can create user, change id to 0 and reset autoincrement counter O.o
Comment: Can do, but one might consider that to be doing things the wrong way round. There may be other reasons I'm not aware of/have forgotten, but that's the one that sticks out in memory
Comment: I wonder if there are some if(userId) checks in code. Searched a little, but drupal inserts zero id manually on install :/
Comment: Found https://www.drupal.org/node/356074#comment-1819516
Comment: @Clive, i'm facing a new issue (using user_save()) in past days , i was creating new users , ones from drupal "create new user" and others from a mobile app (using services) the users added using the app were inserted by a custom query db_merge (fetching users and looking for max(uid), make max + 1 and putting it for the new user) it was always uid = 24 or 25...ect but in the other hand, i was adding users via drupal and uids were in interval 80,81..ect if i delete users (with uids 80s) and insert new with app, it's always showing message : duplicated 25 uid (for example)
Comment: @Clive even if the last user in users table is uid = 24 (after deleting all users and keeping last : 24). the probleme is the error message is shown but the user is added normally. and if i add a new user using drupal (user_save) it will not take uid = 26 but 82 for example
Comment: Mitch, as was described via link above its a problem of drupal. It uses sequences instead of auto incrementing
Comment: @ar7max yes i see. but how do user_save retrieve uids that are actually deleted. is there another table where there is uids ?
Comment: That's because in that example there's another record in there with an ID of 81. So the next available ID is 82. You would see identical behaviour if the DBMS was handling the auto-increment - they don't try to fill in gaps, they just keep going up from the highest available number (or in the case of a DB-side auto-increment, the current seed). @ar7max I wouldn't call it a problem, personally, it was a decision taken to minimise other issues related to the users table
Answer: Use
user_save()
and try to avoid direct db_insert for new user creation. With direct db_insert you cut off the whole functionality of Drupal and other Modules
Answer: you can enter new user using user_save()
$account = (object) array ();
$options['name'] = $username;
$options['mail'] = $email;
$options['pass'] = md5($passwd);
$result = user_save($account, $options);
if ($result === FALSE) {
   //take some action
} else {
   //$result is the loaded user object
}

Comment: That snippet is for VERY OLD Drupal 5

How to db_insert into users?


How can execute a block of code with loops into the intern framework

Question: I´m using intern framework with selenium, I want to execute a loop which look for elements in the table. The loop find each element and saves them in array, after the  elements will be obtained to do operations later.
The idea is next:
browser.wait(2000)
.then(function () {
    while (true) {
    ifHasElements=browser.isDisplayed("/html/body/div[1]/div[5]/div[3]/div/div[3]/div[1]/table[2]/tbody/tr["+contRowsTable+"]").end()
    if (ifHasElements) {
        console.log("into if")
        browser.elementByXPath("/html/body/div[1]/div[5]/div[3]/div/div[3]/div[1]/table[2]/tbody/tr["+contRowsTable+"]/td[1]")
        .clickElement()
        .end()
        rows[contRowsTab]=browser.elementByXPath("/html/body/div[1]/div[5]/div[3]/div/div[3]/div[1]/table[2]/tbody/tr["+contRowsTable+"]")
        } else {
           break
         }
    contRowsTab++;
    contRowsTable++;
    }
})

I dont know if I execute a loop and at the same time obtain elements into the then block. Somebody who can help me with this, thanks a lot..
Answer: Try something like:
var visibleRows = [];
var stopStoring = false;

return browser
    .wait(2000)
    .then(function () {
        return this.parent
            // find all the rows
            .findAllByXpath('/html/body/div[1]/div[5]/div[3]/div/div[3]/div[1]/table[2]/tbody/tr')
            .then(function (rows) {
                // store the visible rows until the first non-visible row is encountered
                return rows.reduce(function (chain, row) {
                    return chain.then(function () {
                        return row
                            .isVisible()
                            .then(function (isVisible) {
                                if (!isVisible) {
                                    stopStoring = true;
                                }
                                if (isVisible && !stopStoring) {
                                    visibleRows.push(row);
                                }
                            });
                    });
                }, this.parent);
            })
            .then(function () {
                // for each visible row, click the first td in the row
                return visibleRows.reduce(function (chain, row) {
                    return chain
                        .findByXpath('./td[1]')
                        .click()
                        .end();
                }, this.parent);
            });
    });

In this code I'm first finding and storing the first contiguous run of visible rows. Then, for each of those rows, I click the first table cell in the row.


What is the correct way of finding mass of a uniform flat plate?

Question: I am trying to solve this mass of a flat plate question and I no matter what way I try, I cant solve it.
To find the mass, I tried doing
$f(x) = 1/sqrt(x^2+6x+13) $
$p\int_0^2 f(x) dx$ where density $p = 1$
and also
$\int_0^2\int_0^f p$ $dy$ $dx$
I tried doing those two since those are the two formulas I have been using and I have been getting them right on other questions. But in this particular one, I just cant. I would appreciate any help! thanks!
Answer: Hint: You need to evaluate $\int \frac{1}{\sqrt{x^2+6x+13}}\,dx$. Try completing the square: $$\frac{1}{\sqrt{x^2+6x+13}} = \frac{1}{\sqrt{x^2+6x+9+4}}= \frac{1}{\sqrt{(x+3)^2+2^2}}$$ and using an appropriate substitution.


Changing column value by finding substring in string values

Question: I'm trying to change the values in a single column using pandas apply(). My function partially worked, but I'm stuck on how to fix this other half.
Data Column:
County Name
 Riverside County
 San Diego County
 SanFrancisco County/city
I'm trying to get rid of " County" so I'm left with just the name of the county. I successfully got rid of the " County" with the function but I'm having trouble removing the " County/city" from San Francisco.
Code:
def modify_county(countyname):
  if "/city" in countyname:
    return countyname.replace(" County/city","")
  return countyname.replace(" County","")

lfd["CountyName"] = lfd["CountyName"].apply(modify_county)

Output:
CountyName
Riverside
San Diego
San Francisco County/city

Is something wrong with the conditional in the function?
Comment: Why have an if statement at all? If "/city" isn't in the string, then countyname.replace(" County/city", "") just won't do anything
Comment: I copied your code and input and it worked fine.
Answer: This is an alternative way. It works with the data you have provided.
import pandas as pd

s = pd.Series(['Riverside County', 'San Diego County', 'SanFrancisco County/city'])

res = s.apply(lambda x: ' '.join([w for w in x.split() if not 'County' in w]))

print(res)

# 0       Riverside
# 1       San Diego
# 2    SanFrancisco
# dtype: object

Answer: @jpp's answer is the literal way of doing what you asked for. But in this case I would use pandas.Series.replace and some regex to substitute the entire thing in one go:
import pandas as pd

s = pd.Series(['Riverside County', 'San Diego County', 'SanFrancisco County/city'])

res = s.replace(' County(/city)?', '', regex=True)

Answer: @jpp, used suggestion to apply to entire column. Not sure if this is the best way, but it worked.
lfd["CountyName"] = pd.Series(lfd["CountyName"])
lfd["CountyName"] = lfd["CountyName"].apply(lambda x: ' '.join([w for w in x.split() if not 'County' in w]))


How does DKfindout.com (website) annotate the image?

Question: Here is An example in DKfindout.
I'm wondering how to make predefined annotation (not user-defined annotation, e.g. drag a box and add comment) on images.

I have no idea how to locate the place where I want to add an explanation.
Is there any javascript library can do this job?
Or I have to find the relative position of the annotation of the image (e.g. left:10%, top:10%), then add all annotations one by one?
Or any other solutions?
Answer: I strongly believe they're using https://anseki.github.io/leader-line/


Stored Procedure Fill Variable with a ResultSet of a Query

Question: I have a little Problem but don't know the Solution!
I have wrote a Stored Procedure. The function of this isn't necessary.
I want to declare a Variable from Type int.
This Variable must get the Value of a SQL Query.
My attempt:
DECLARE @ParentServiceProviderId int = null
SET @ParentServiceProviderId  = (SELECT ParentServiceProviderId
                                 FROM ServiceProvider
                                 WHERE ServiceProviderId = @ServiceProviderId)

It didn't work! The ResultSet of the Query have one Row every Time!
I don't know how to solve this Problem!
Here is the complete Stored Procedure:
ALTER PROCEDURE [dbo].[InsertCarmakerPartnership_ChildToParent]

    @ServiceProviderId int,
    @CarmakerId int,
    @ValidFrom datetime,
    @ValidTo datetime
AS
BEGIN
    -- SET NOCOUNT ON added to prevent extra result sets from
    -- interfering with SELECT statements.
    SET NOCOUNT ON;

    DECLARE @parentSPPId int, @parentSPPParentId int, @superParentId int, @ParentServiceProviderId int = null

    SET @ParentServiceProviderId  = (SELECT ParentServiceProviderId
                                     FROM ServiceProvider
                                     WHERE ServiceProviderId = @ServiceProviderId)

    DECLARE ServiceProviderParent_Cursor CURSOR FOR

    SELECT ServiceProviderId, ParentServiceProviderId
    FROM ServiceProvider
    WHERE ServiceProviderId = @ParentServiceProviderId

    OPEN ServiceProviderParent_Cursor;

    FETCH NEXT FROM ServiceProviderParent_Cursor INTO @parentSPPId, @parentSPPParentId

    IF (@ParentServiceProviderId is NULL)
    BEGIN
        SET @superParentId = @ServiceProviderId
        EXEC InsertCarmakerPartnership_ParentToChild @superParentId, @CarmakerId, @ValidFrom, @ValidTo;
    END

    WHILE @@FETCH_STATUS = 0
BEGIN
    IF @ServiceProviderId > 0
    BEGIN
        EXEC InsertCarmakerPartnership_ChildToParent @parentSPPId, @CarmakerId, @parentSPPParentId, @ValidFrom, @ValidTo  ;

        IF (SELECT COUNT(*) FROM dbo.CarmakerPartnership WHERE ServiceProviderId = @parentSPPId AND CarmakerId = @CarmakerId AND IsDeleted = 0) = 0
        BEGIN
            INSERT INTO dbo.CarmakerPartnership (CarmakerId, ServiceProviderId, CreatedBy, ChangedBy, ValidityPeriodFrom, ValidityPeriodTo) VALUES (@CarmakerId, @parentSPPId, SYSTEM_USER, SYSTEM_USER, @ValidFrom, @ValidTo)
        END
    END
    FETCH NEXT FROM ServiceProviderParent_Cursor INTO @parentSPPId, @parentSPPParentId
END;
    CLOSE ServiceProviderParent_Cursor;
    DEALLOCATE ServiceProviderParent_Cursor;
END

Thanks for your help and sorry for my bad english!
Best regards.
Comment: `It didn't work! The ResultSet of the Query have one Row every Time!` - I'm not sure I understand the problem here. Do you expect it sometimes to return more than one row? Or should it be no rows? Or do you mean to say that it always returns the same value? Please clarify this bit. If possible, please use some examples for better illustration.
Answer: Anyway, use next code to populate a variable:
DECLARE @ParentServiceProviderId int

SELECT @ParentServiceProviderId = ParentServiceProviderId
FROM ServiceProvider
WHERE ServiceProviderId = @ServiceProviderId

Answer: do not assign default value to this variable and the rest of the code is:
DECLARE @ParentServiceProviderId int

SELECT @ParentServiceProviderId = ParentServiceProviderId
                                FROM ServiceProvider
                                WHERE ServiceProviderId = @ServiceProviderId


If $a\leq b$ and $-a\leq b$, then $|a|\leq b$.

Question: I have arrived at the two separate conclusions:

$a\leq b$
$-a\leq b$

Can I conclude that $|a|\leq b$? I am missing something as it is not by definition of the absolute value.
Comment: Yes, because one possible definition of the absolute value is $\;|a|=\max(a,-a)$.
Answer: Yes, your conclusion is correct; just note that $\max(a,-a)=|a|$.
Answer: You could prove it by proving the contrapositive, as follows.
Assume $|a|>b$.
Now $|a|=a$ or $|a|=-a$.
Therefore $a>b$ or $-a>b$.
Answer: Yes, it is! Since $\lvert a\rvert$ is one of the numbers $a$ or $-a$, and since both of these numbers are smaller than or equal to $b$, $\lvert a\rvert\leqslant b$.


In Bach's Prelude in A Minor, what chord is B D G# and what's its function?

Question: A Piano Beginner: I am playing A Bach Prelude in A Minor:
Bar 1 A C E, Bar 2 A D F, Bar 3 B D G# Bar 4 C E A.
The G# chord has been described as a VII dim (G# dim) and a ii dim 7 (B dim7) giving progressions of 1 4 7 1 or 1 4 2 1. Does anyone have any suggestions as to the "correct" description for Music theory? Perhaps one is Classical and the other Jazz!
Answer: The vii dim is a somewhat-frequently-used chord in the Baroque, especially in first inversion, as here (G#dim/B). This chord is typically used as a substitute for the dominant seventh (e.g. E7 in this case), as it shares the V7's leading tone (the G♯) and it's melodic tendency to resolve upwards towards tonic (A). Indeed, a vii dim chord is essentially a V7 chord without the root.
Technically speaking, a B dim7 chord would have the notes B D F A♭. While G♯ and A♭ are enharmonically equivalent, they imply different voice leading. The A♭ would want to resolve downwards. This difference would have been especially important in the Baroque, to a contrapunctally-minded composer such as Bach.
Comment: A G# diminished will have the notes G# B D F with the G# resolving to A, the B to C and the F down to E. The ii dim will be half-diminished meaning it'll have the notes B D F A with the B resolving to C and the F down to E the very same way as will a fully diminished G# dim, both resulting in the tonic A minor.
Comment: In this case, there's no mention of an F in the G# dim chord, so it's just a regular diminished chord (G# B D), not a diminished 7th (G# B D F). Nor is there a mention of an A in the chord, so it isn't half diminished.
Comment: Sorry @CalebHines, your mention of Ab as a seventh note got me confused.
Comment: Historical note: Bach didn't have the modern theoretical concepts of 7th chords, inversions, chords with missing notes, etc. Following his son CPE's textbook, it would just be described as a 6-3 chord (counting intervals for the bottom note, with the accidentals following the A minor scale). That is the same basic idea as a modern first inversion of the triad on the leading-note, which just happens to be a diminished triad in both major and minor keys. (Note, I said a diminished triad, not a four-note diminished 7th chord in the modern terminology).
Comment: True, in line with basso continuo terminology, first inversion chords were referred to as 6-3 chords. But the idea of chord inversions, though not popularized until Rameau (1722), was still a useful working concept that at least some musicians were familiar with. Explicit reference to moving the bass note to a higher voice to create an inversion can be found as early as Otto Siegfried Harnisch (1608) and Johannes Lippius (1610).
Answer: In A minor, the V harmony, from the E dominant 7th notes, is E-G#-B-D.I see the chord as a V7 with no root. Often the root can be found elsewhere in the bar. So I'd call it an inversion of V7 .
Comment: It certainly *functions* as a V7, but assuming the notes listed in the OP are correct, there is no indication of a root elsewhere in the bar, and a rootless V7 is essentially identical to a vii dim. Furthermore, if this were an inversion of V7, it would be a second inversion, which is rarely used in Baroque music, outside of a handful of special cases (e.g. cadential I 6\4), due to it's containing a dissonance (the 4th between the bass and the root). Of course, that goes back to the chord being rootless, and why we name the chord after a missing note, when it already has a perfectly good name.
Comment: @CalebHines - You're correct, and your answer is the better one. I wondered about calling it a second inversion, but with a note (E) missing from the sequence, thought maybe not.
Comment: Thank you all for the responses. The AMEB goes for the vii dim however I find that the ii dim 7 with a missing dominant is common in jazz. Clarification the bar has a left hand pedal point of A3 then right hand B D G# D B so no easy solution. It is probably simplified from the original as it is an Australian Music Education Board beginner piece.


Retornar Valor de Spinner Pra String

Question:
Preciso retornar o valor de um spinner , pra fazer um post , mas o spinner está retornando nulo !

    catliv = (Spinner) findViewById(R.id.catergorialiv);

    List<String> list = new ArrayList<String>();
    list.add("Categoria");
    list.add("Direito");
    list.add("Didatico");
    list.add("Informática");
    list.add("Ficção Cientifíca");
    list.add("Infantil");
    list.add("Drama");
    list.add("Contos");

    ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,
            android.R.layout.simple_spinner_item, list);

    dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    catliv.setAdapter(dataAdapter);

    System.out.println(mCatliv);

      btnadd1.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View view) {

            if (mCatliv.equals("Romance")) {
                postCatLivro("http://192.168.1.207/api/v2/bookdemo/_table/cad_categorias?fields=id_cat&filter=tx_cat%3Dromance", 2);
            }
            else if (mCatliv.equals("Direito")) {
                postCatLivro("http://192.168.1.207/api/v2/bookdemo/_table/cad_categorias?fields=id_cat&filter=tx_cat%3DDireito", 3);
            }
            else if (mCatliv.equals("Didatico")) {
                postCatLivro("http://192.168.1.207/api/v2/bookdemo/_table/cad_categorias?fields=id_cat&filter=tx_cat%3DDidatico", 4);
            }
            else if (mCatliv.equals("Informática")) {
                postCatLivro("http://192.168.1.207/api/v2/bookdemo/_table/cad_categorias?fields=id_cat&filter=tx_cat%3DInform%C3%A1tica", 5);
            }
            else if (mCatliv.equals("Ficção Cientifíca")) {
                postCatLivro("http://192.168.1.207/api/v2/bookdemo/_table/cad_categorias?fields=id_cat&filter=tx_cat%3DFic%C3%A7%C3%A3o%20Cientif%C3%ADca", 6);
            }
            else if (mCatliv.equals("Infantil")) {
                postCatLivro("http://192.168.1.207/api/v2/bookdemo/_table/cad_categorias?fields=id_cat&filter=tx_cat%3DInfantil", 7);
            }
            else if (mCatliv.equals("Drama")) {
                postCatLivro("http://192.168.1.207/api/v2/bookdemo/_table/cad_categorias?fields=id_cat&filter=tx_cat%3DDrama", 8);
            }
            else if (mCatliv.equals("Contos")) {
                postCatLivro("http://192.168.1.207/api/v2/bookdemo/_table/cad_categorias?fields=id_cat&filter=tx_cat%3DContos", 9);
            }

            else {
                return;
            }

@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {

    mCatliv = parent.getItemAtPosition(position).toString();

}

@Override
  public void onNothingSelected(AdapterView<?> parent) {

}

Answer: Para resgatar o valor do Spinner selecionado, use o método getSelectedItem. Veja abaixo:
String value = catliv.getSelectedItem().toString();

Retornar Valor de Spinner Pra String


Equal temperament nearest possible to the just intonation

Question: It is ever possible to have an equal temperament  without  using the pure octave. In this case we can produce equal temperament  where an universal half tone is used. It will permit to stay nearest possible to the just intonation and in the same time to modulate in all tonalities. This temperament exist and is named TEDJ.
French name where TemperamentEquale with DifferencialeJust. Who know more about this temperament?
Comment: Stretch tuning is designed to give the illusion of pure octaves.
Comment: I don't know about TEDj (nor can I find much online), but why would you want a nearly just tuning system that doesn't match octaves? (I'm not saying it's a bad question, I'm legitimately curious...it seems to defeat the purpose!)
Comment: @Richard It's a sensible idea on piano, and any other instrument with "stretched" tuning because of unavoidable inharmonicity which makes the harmonics "sharp" compared with the fundamental. Somebody came up with a piano tuning system based on just intonation 12ths (slightly wider than conventional ET 12ths) and wide octaves - sorry, I can't remember what it was called, but I'm pretty sure it wasn't "TEDj".
Comment: Ah - I found the reference: Bernhard Stopper proposed it. And this is what it sounds like: https://www.youtube.com/watch?v=5BrcWplvGJY. Stopper's own website seems to be down right now, but Google will find it for you.
Comment: @LaurencePayne the usual definition of "stretch tuning" is an empirical system  - it's different for every piano, and different over different parts of the pitch range. Stopper's tuning system is mathematically consistent, and it's designed to give the illusion of pure diatonic *chords*, not just *octaves.*
Comment: "French name where TemperamentEquale with DifferencialeJust" - are you trying to translate the French name into English? Because "equale" and "differenciale" aren't English words. What's the original, un-translated name? Are you talking about the *tempérament égal à quintes justes*, the equal temperament with just fifths?
Comment: Here's a related question. In my answer there, I mention EDOs that abandon the just octave in favor of improvements in other intervals:  https://music.stackexchange.com/questions/118044/when-you-specify-an-edo-equal-divisions-per-octave-value-is-it-always-a-whole
Answer: 31 tone et gets very close to providing all of the just intervals that can be produced from voices and fretless instruments. But it is unwieldy to play a keyboard with 31 keys to the octave. I would suggest getting a piano tuned to well temperament. While some of the keys contain wildly sharp Pythagorean thirds they at least want to go outward and suggest movement to the fifth versus the sickly sounding thirds of et. Also, keys have different feeling in well temperament due to the different intonation they possess. Of course this can be grouped between closely related keys. Also c major and it's closely related keys contain practically perfect triads that sound sweet and glorious. I think overall the temperament that satisfied Bach's disappointment with mean tone is the best solution for keyboard instruments.
Comment: It's also possible to use a subset of 31-edo **as** a kind of well temperament. That gives all the nice intervals within one key without impeding playability, but also allows modulations without wolves quite easily by picking a different subset.


Nonlinear Gronwall inequality

Question: Suppose a (continuous, non-negative) function $f$ satisfies
$$ f'(t) \leq f(t)^2 $$
for $t \in [0,1]$. Set
$$ g(t) = \exp\left(-\frac{1}{f(t)}\right). $$
Then
$$ g'(t) = \frac{f'(t)}{f(t)^2} g(t) \leq g(t), $$
so applying the standard Gronwall inequality one has $g(t) \leq g(0) e^t$. Since $\log$ is an increasing function, applying $\log$ to both sides and rearranging gives
$$ f(t) \leq \left( \frac{1}{1-tf(0)} \right) f(0). $$
Thus if $f(0) \leq \epsilon$ for $\epsilon >0$ small enough, we get $f(t) \leq C f(0)$ for all $t \in [0, 1]$. This proves a kind of small data nonlinear Gronwall inequality, but only starting from the differential form of the inequality.

My question: Suppose instead that we have
  $$ f(t) - f(0) \leq \int_0^t f(s)^2 \, ds. $$
  Can we deduce the same result?
Comment: I added  additional details in my answer
Comment: Recently, I wrote an [answer](https://math.stackexchange.com/a/4773819/447852) which contains this question as a special case.
Answer: Here is an easy way to get the first part: $$\color{red}{f'(t) \leq f(t)^2} \Longleftrightarrow \frac{f'(t) }{ f(t)^2}\le 1 \Longleftrightarrow  \left(-\frac{1}{f(t)}\right)'\le 1$$
integrating this latest gives
$$\left( -\frac{1}{f(t)}+\frac{1}{f(0)}\right)\le t\Longleftrightarrow  f(t) \leq \left( \frac{1}{1-tf(0)} \right) f(0).$$

Now if you have, $$f(t) - f(0) \leq \int_0^t f(s)^2 \, ds\implies \color{blue}{f^2(t)\le \left(f(0) + \int_0^t f(s)^2 \, ds\right)^2} \\\implies g'(t) \le g^2(t)$$
  where we set $$g(t) = f(0)+\int_0^t f(s)^2 \, ds\implies   g'(t)= f^2(t)$$
  This is  of the same type as the previous inequality.
Comment: Upon closer inspection I think this answer is the most easily generalizable one, so I've now accepted it.
Comment: @onamoonlessnight great that you noticed that.
Answer: You get faster to the final inequality of the first part by just dividing by $f(t)^2$, as then
$$
\frac1{f(0)}-\frac1{f(t)}=\int_0^t\frac{f'(s)}{f(s)^2}\,ds\le\int_0^t 1\,ds=t
$$
so that indeed
$$
f(t)\le \frac{f(0)}{1-tf(0)}
$$

For the second part, the question itself, consider the function $$g(t)=-\frac{1}{f(0)+\int_0^tf(s)^2 ds}.$$
Then
$$
g'(t)=\frac{f(t)^2}{\left(f(0)+\int_0^tf(s)^2 ds\right)^2}\le 1
$$
so that
$$
g(t)\le -\frac1{f(0)}+t
$$
and finally again
$$
f(t)\le -\frac1{g(t)}\le \frac{f(0)}{1-tf(0)}
$$

Nonlinear Gronwall inequality


What is a design matrix? How do I build a design matrix for Rasch analysis?

Question: I am trying to do an LRSM Rasch analysis of 72-item data. This data has 67 binary items and 5 ternary items. I need to create a "design matrix" in order to analyze this data. I do not really know what a design matrix is, nor do I know how to create one for my data. Could someone please give me some clues on getting started?
Comment: A [design matrix](http://stats.stackexchange.com/search?q=%22design+matrix%22) is also called a [model matrix](http://stats.stackexchange.com/search?q=%22model+matrix%22). Follow the links to find hundreds of posts about them.
Answer: Design matrix groups all your variables together, typically for regressions. If a variable is categorical, it'll be coded.
You can use model.matrix in R to construct one. However, you shouldn't need to do it yourself because whatever analysis you'll be using should automatically do it for you.
Comment: Thank you very much! That tells me a lot.

It turns out I was having trouble due to using an improper analysis. So, I really did not need to construct one.