Explaining problem in Gadea's "Analysis and Algebra on Differentiable Manifolds"

Question: I have a lot of trouble trying to explain to myself what the author did in problem 1.102 (the answer is in the link):

Let $TM$ be the tangent bundle over a differentiable manifold $M$. Let $\varphi: \mathbb R\times TM \to TM$ defined by $\varphi(t, X)=e^tX$.
   (i) Prove that $\varphi$ is a $1$-parameter group of transformations of $TM$.
   (ii) Calculate the vector field $Y$ on $TM$ associated to $\varphi$.
   (iii) Prove that $Y$ is invariant under $\varphi$.

I'm interested in the first point since maybe the rest continues from in.
The definition of $1$-parameter group (or flow) is given for maps that go from $M\times \mathbb R$ to $M$, where $M$ is a smooth manifold. Althought we know that the tangent bundle $TM$ gives a manifold structure to tangent vectors, applying straight the definition of flow doesn't seem like the way  the author took. $(1)$ I don't uderstand why does he prove that $\varphi_t \circ \varphi_s=\varphi_{t+s}$, I saw that he used that too in the problem before. $(2)$ Later when he is defining the chart in $TM$, I don't quite get the definition of $\Psi$. I thought the charts in $TM$ where given like this: if you take a chart of $M$, say $(U,\phi)$ then it induces the chart of the tangent bundle  like $(\pi^{-1}(U),\tilde \phi)$, with $\tilde\phi(X_p)=(\phi(p),\omega)$ and $\omega\in T_pM$. I don't know if my diagram is correct, but that's what I understand, and I don't see how did he got the so called $\Psi$ and $\tau$.
Answer: $\newcommand{\Reals}{\mathbf{R}}\newcommand{\dd}{\partial}\renewcommand{\phi}{\varphi}$If $M$ is a smooth manifold, a one-parameter group on $M$ is usually defined to be a smooth homomorphism from $(\Reals, +)$, the additive group of real numbers, into the diffeomorphism group of $M$ under composition.
The condition $\phi_{t+s} = \phi_{t} \circ \phi_{s}$ is the homomorphism condition.
I didn't read the linked solution, but perhaps it helps first to look at $M = \Reals^{n}$, so $TM = T\Reals^{n} = \Reals^{n} \times \Reals^{n}$. Let $x$ denote base coordinates and $v$ denote fibre coordinates. If I understand the notation, the one-parameter group in question is $\phi(t, x, v) = (x, e^{t}v)$, homothetic scaling in the fibres. The vector field generating the flow is the Euler field
$$
\frac{\dd}{\dd t}\bigg|_{t=0} \phi(t, x, v) = (0, v),
$$
whose value at $(x, v) \in TM$ is $(0, v) \in T_{(x, v)}(TM)$.
Generally, if $x = (x_{1}, \dots, x_{n})$ are local coordinates on $U \subset M$, then the coordinate vector fields $\dd_{1}, \dots, \dd_{n}$ are a frame for $TU = TM|_{U}$. The "natural" coordinates on $TU$ are
$$
\tilde{\phi}\left(x, \sum_{j=1}^{n} v_{j} \frac{\dd}{\dd x_{j}}\right)
  = (x_{1}, \dots, x_{n}, v_{1}, \dots, v_{n}).
$$
(Your picture looks fine; the only potential missing detail is the relationship of the fibre coordinates $\omega$ with the coordinate vector fields.)
Now, the flow mapping is $\phi(t, x, v) = (x, e^{t}v)$, namely
$$
\phi(t, x_{1}, \dots, x_{n}, v_{1}, \dots, v_{n})
  = (x_{1}, \dots, x_{n}, e^{t}v_{1}, \dots, e^{t}v_{n}).
$$
Formally, everything looks exactly as if $M = \Reals^{n}$.
Comment: Thank you for your answer. Now, when looking at the flow $$\frac{\dd}{\dd t}\bigg|_{t=0} \phi(t, x, \color{red}{v}) = (0, \color{blue}{v})$$
is $\color{red}{v}$ the same as $\color{blue}{v}$? I'm confused because if $(0, \color{blue}{v}) \in T_{(x, \color{red}{v})}(TM)$, then wouldn't the flow '_change_' $\color{red}{v}$? I mean $(0, \color{blue}{v})$ is an element of the tangent space based at $(x, \color{red}{v})$, then $\color{blue}{v}$ can't be the same as $\color{red}{v}$. Or am I missing something? Thanks again.
Comment: Ah, good eye. :) The red $v$ represents a point of $TM$, while the blue $v$ represents a tangent vector to $TM$. However, as lists of numbers in local coordinates, they are the same. More invariantly, we're using the fact that $T_{x}M$ is a vector space to identify $T(T_{x}M) = T_{x}M \times T_{x}M$. (You might say the same type of identification occurs when we write $f'(t) = f(t)$ in elementary calculus; the red $v$ is $f(t)$ and the blue $v$ is $f'(t)$.)


How do I change the output filename of cuda_compile_ptx in CMake?

Question: In CMAKE with FindCUDA, given an input file filename.cu, the cuda_compile_ptx command generates output filenames of the form cuda_compile_ptx_generated_filename.cu.ptx, but I need the output filenames to be of the form filename.ptx.
Is there a simple way to make this work?
Comment: I think the only way to do this is to hack cuda_wrap_srcs macro, ie.
in the following line:

set(generated_file_basename "${cuda_target}_generated_${basename}.ptx")
Answer: Ideally you should be able to specify -o <outputName>. However the issue is that the CUDA_COMPILE_PTX macro actually overrides the -o option with cuda_compile_ptx_generated_${filename}.ptx
Here are two alternate ways add CUDA compilation to your project

You can still use CUDA_COMPILE_PTX but work around the issue by renaming it with add_custom_command: add_custom_command(OUTPUT ${CMAKE_BINARY_DIR}/my_ptx.ptx COMMAND ${CMAKE_COMMAND} -E copy ${cuda_ptx_files} ${CMAKE_BINARY_DIR}/my_ptx.ptx DEPENDS ${cuda_ptx_files}) and use ${CMAKE_BINARY_DIR}/my_ptx.ptx in add_custom_target
There are better alternatives for compiling CUDA PTXs with CMake. One very good example of a macro do to this: https://github.com/nvpro-samples/shared_sources/blob/master/cmake/private/FindCuda.cmake. An example of how to use this macro can be found here: https://github.com/nvpro-samples/gl_cuda_interop_pingpong_st/blob/master/CMakeLists.txt.
Comment: The links are no longer valid


ABRSM Practical Musicianship Exam - Do I need an accompanist?

Question: I am planning to take the ABRSM practical musicianship exam grade 5 in London this year, for euphonium.
I have read through the rules myself, but it does NOT seem to require me to bring an accompanist.
However, I would like to make sure, so I ask here for anyone who has done it before.
Update : I got the confirmation that you do NOT need an accompaniment fo the Practical Musicianship Exam 5+.
Comment: The comment thread seems to have been deleted, but there was a good deal of confusion about the exam the poster was referring to. The ABRSM "Practical Musicianship" exam is not the standard instrumental exam. Grade 5 Practical Musicianship can be taken as an an alternative to Grade 5 Music Theory as an entry requirement for taking Performance Grades 6 to 8.  It is described at https://www.abrsm.org/en-gb/other-assessments/practical-musicianship and its syllabus is at https://www.abrsm.org/sites/default/files/2023-09/praccomplete10.pdf
Comment: @JamesMartin You should turn that into an answer.
Answer: Not having done this particular exam, but reading through the syllabus, it appears any accompaniment will be done by the examiner. Other parts of the exam will be solo.
A clue as to what instrument OP is using would be interesting, but not essential in answering this question.
A quick call to ABRSM themselves would be appropriate and simple - I've found them to be quite accommodating with queries in the past.
EDIT - having actually contacted ABRSM, they verified that in fact yes, the candidate does have to bring their own accompanist - who can be their teacher - but that person can only be in the room for the time they're accompanying.
Reading the syllabus on their website is confusing, but there's the definitive answer, now!
RE-EDIT!!Still awaiting a reply (by email) from AB, but reading the practical Musicianship syllabus, there will only be the examiner present, who will play - on piano, presumably, anything which needs playing. There is no accompaniment mentioned in this particular exam. Not to be confused with solo instrument which will most likely need an accompanist, as the examiner will be busy doing what they're there for - examining. Apologies for the change of mind - but a good question, which, actually, teacher should have provided an answer to by now.
RE-RE-EDIT - finally had the answer from AB - the examiner WILL accompany. Straight from the horse's mouth... Thank you AB!
Comment: Does this apply to *any* grade?  I would think for a higher grade that has many selections, would it be fair to expect the examiner to sight read (or prepare) to play moderate to difficult accompaniment?  A relevant question: does a candidate have the option of bringing their own accompanist?
Comment: -1. This answer is incorrect. The examinee supplies the accompanist, and examiners will not accompany. See the ABRSM website for regulations.
Comment: I am going to play the euphonium. Ok, so it seems that I do not need to bring an accompanist... But anyway, I will call them to check again. Thank you very much!
Comment: @Keith Update the question with ABRSM's reply!
Comment: I am confused by the edit. Was the ABRSM person you spoke to on the phone definitely aware that you were asking specifically about the Practical Musicianship exam? Which of the activities involved in the Grade 5 exam listed on p.93 of https://www.abrsm.org/sites/default/files/2023-09/praccomplete10.pdf is the accompanist supposed to be involved in?
Comment: @JamesMartin - I think there is some confusion between standard *instrumental* exams, which for solo instruments will obviously need an accompanist, and Practical musicianSHIP exams, where most likely the examiner would provide any accompaniment needed. In the LCM exams  gtr and bass)I used to host, any accompaniment was always done by the examiner, but that's a different board. I have re-posed the question, and await the answer.
Comment: The answer now looks very confusing with the no/yes/no/yes edits. I suggest deleting everything except for the information in the very last paragraph.
Comment: @PiedPiper - just thought I'd leave it for a bit - showing the trouble some of us go to..! Yes, it does need re-re-re-editing. Get round to it soon. Love to know how te 2 dvers came to their conclusions, soon after the 1st part (correct) was written, though.
Comment: I've reverted my DV. I was as confused as everybody else was.
Comment: @PiedPiper - thank you for that - but - as you probably know by now, I'd have appreciated a reason in the comments as to your original reasons. That way, we all know where we're coming from. Hence all my moans about unsupported dvs.
Comment: James Martin had already supplied the reason.
Answer: According to the ABRSM website:
For in-person exams:

Applicants must make sure that candidates bring their own accompanist. The candidate's teacher may accompany; the examiner will not accompany under any circumstances (except in the Prep Test). The accompanist may stay in the exam room only while accompanying. (https://www.abrsm.org/en-gb/about-our-exams/exam-regulations, under Regulations -> Instrumental and singing exams -> paragraph l; emphasis mine.)

For digital exams:

Applicants must make sure that candidates perform with a live accompaniment, which should be organised by them. The candidate's teacher may accompany.  (ibid., section q.)

See also sections aa, bb, and cc. The last of these mentions that a separate copy of the score for the examiner is not required.
Comment: Yes. That's when you are playing an actual music piece like a concerto. Practical Musicianship is not like that, according to the syllabus.
Comment: I feel this answer is based on the good old instrumental exams, for solo instruments The Musicianship exam is fairly new, and has quite a different slat on what happens. There is no time where the candidate will perform rehearsed pieces with  the player with whom they've practised.
Comment: Surely, I don't need accompaniment when I am doing transposition?
Comment: See my re-re-edit for the definitive on this one. Always worth asking the 'powers that be'.


Irreducible implies prime norm in quadratic integer ring

Question: Let's denote $\mathbb{Z}[\lambda_d]$ where
$$
 \lambda_d = \begin{cases} \sqrt{d} & \text{ if } d\equiv 2,3 \; (\text{mod }4),\\
   \frac{1+\sqrt{d}}{2} & \text{ if } d\equiv 1 \; (\text{mod }4),
 \end{cases}
$$
with $d\neq 0$ is a square-free integer.
Let $\alpha=a+b\lambda_d\in \mathbb{Z}[\lambda_d]$, with $a,b\in\mathbb{Z}$. It is well known that if $N(\alpha)=\alpha\overline{\alpha}$ is a prime in $\mathbb{Z}$, then $\alpha$ is irreducible in $\mathbb{Z}[\lambda_d]$. My question is: What restrictions can be given to $d$ such that the converse holds? That is for which $d$ if $\alpha$ is irreducible in $\mathbb{Z}[\lambda_d]$, then $N(\alpha)$ is a prime in $\mathbb{Z}$?
I believe that the answer is no for every $d$. For example when $d=-1$ the following famous exercise in Marcus' Number Fields:

Let $\alpha\in\mathbb{Z}[i]$. Show that if $N\left(\alpha\right)$ is a prime in $\mathbb{Z}$ then $\alpha$ is irreducible in $\mathbb{Z}[i]$. Show that the same conclusion holds if $N\left(\alpha\right)=p^{2}$, where $p$ is a prime in $\mathbb{Z}$, $p\equiv 3\pmod{4}$.

Any help will be appreciated. Thank you in advance!
Answer: Splitting of primes in quadratic extensions is controlled by the quadratic character (the Legendre symbol). More concretely an odd prime $p\nmid d$ splits in $\mathbb{Z}[\lambda_d]$ if and ony if $d$ is a square modulo $p$. You can always find a prime $p$ such that $d$ is not a square modulo $p$, so $p$ will be inert (so irreducible in $\mathbb{Z}[\lambda_d]$) and $N(p)=p^2$. In particular for $d=-1$ the quadratic character of $-1$ tells you that this happens for every prime $\equiv 3 \pmod{4}$. The answer to your question is then that the converse does not hold for any $d$.


Find the maximum value of the following function?

Question: $ f(x,y) = x^2 + y^2 + xy + \frac1x + \frac1y $
Find the extremum values of the above function.
For your reference, answer to the problem is - minima at $(3^{-1/3},3^{-1/3})$
But how? Please help!
Comment: You should probably specify that $x$ and $y$ are positive, else there is no minimum. Or are you looking for local extrema?
Comment: The maximum value is $+\infty$, for $x=0^+$ or $y=0^+$.
Answer: Differentiate $f$ wrt $x$ and $y$ and set the partial derivatives equal to zero.
$\frac{\partial f}{\partial x}=2x+y-x^{-2}$, $\frac{\partial f}{\partial y}=2y+x-y^{-2}$
Set these equal to zero and solve for $x$ and $y$ and you're done.
Now, it's important not to confuse local extrema (minima or maxima) with global extrema.
See this nice picture from Wikipedia to help demonstrate the difference:

A global min/max is the absolute min/max that a function can attain; a local min/max can be seen as a little bump where the gradient is zero.
This function has no global extrema. Justification: $x$ and $y$ can be as big as we like, and as $(x,y) \to (\infty,\infty), f(x,y)\to \infty$
However, this function does have a local extremum.
Answer: $$\frac{\partial f}{\partial x}=2x+y-\frac{1}{x^2}=0$$
$$\frac{\partial f}{\partial y}=2y+x-\frac{1}{y^2}=0$$
These two equations can be solved for x and y.
Answer: Corrections thanks to André Nicolas and Sanchay Javeria!!
Given $f(x,y)$ you search for $df(x,y) = 0$, so in this case
$$2x dx + 2y dy + x dy + y dx - \frac{dx}{x^2} - \frac{dy}{y^2} = 0$$
or
$$ \left( 2x + y - \frac{1}{x^2} \right) dx + \left( 2y + x - \frac{1}{y^2} \right) dy = 0 $$
So we obtain
$$ \frac{2x^3 + x^2 y - 1}{x^2} = 0 $$
and
$$ \frac{2y^3 + x y^2 - 1}{y^2} = 0 $$
Then we find
$$ \big( 2 x^2 + x y + 2 y^2 \big) \big( x - y \big) = 0$$
 thus
$$ x=y$$,
whence
$$ 3 y - \frac{1}{y^2} = 0$$
So
$$ y^3 = \frac{1}{3} $$
Whence
$$ x = y = 3^{-1/3} $$
Comment: No complex solutions. We are finding extrema of a function defined for real $$x$ and $y$.
Comment: One you were at $2x^3-2y^3=0$, you could immediately conclude that $x=y$.
Comment: But we may include complex solutions...

That is $x^3 = y^3$ means that $x = \big( -\tfrac{1}{2} + \tfrac{1}{2} \textbf{i} \sqrt{3} \big)^\jmath y$, for $\jmath = 0, 1, 2$...
Comment: Then indead we can set $x=y$ directly... Thanx!
Comment: I think you made a mistake while solving the coefficient of dy = 0 in the second step.
It should be
2x^3 + xy^2 − 1x^2=0 instead of 2x^3 + x^2y − 1x^2=0
That's where I was also stuck on.
Comment: You are correct!

I have changed it - thanks!!!


NPM not working (Cannot find module 'internal/fs' - nodejs)

Question: NPM error on update. I recently update to Node version 7.x. Now npm is not working.
I am unable to locate the error, it may be due to -
npm ERR! Cannot find module 'internal/fs'.
 I get the following when I run sudo npm update -g -
npm ERR! Linux 3.13.0-101-generic
npm ERR! argv "/usr/bin/nodejs" "/usr/bin/npm" "update" "-g"
npm ERR! node v7.1.0
npm ERR! npm  v3.10.8
npm ERR! code MODULE_NOT_FOUND

npm ERR! Cannot find module 'internal/fs'
npm ERR!
npm ERR! If you need help, you may report this error at:
npm ERR!     <https://github.com/npm/npm/issues>

My /etc/profile.d/nodejs.sh has the following contents:
NODE_PATH=/usr/lib/nodejs:/usr/lib/node_modules:/usr/share/javascript
export NODE_PATH

Answer: You should be able to remove the npm directory (typically /usr/local/lib/node_modules/npm) and then reinstall one of the official node tarballs, which includes npm (you can find the latest from http://nodejs.org/dist/latest-v7.x/).
Did you upgrade from an older version of node?
If so, that is probably part of the reason why you are having this issue. Older versions of graceful-fs (a dependency of npm) did things that are no longer available in node v7.
Comment: Reinstallation worked, commands run in order - `sudo apt-get remove nodejs` ;`sudo apt-get remove npm`; `sudo apt-get install nodejs`
Answer: According to this thread, updating npm to version 4 will solve your problem, try:
npm i -g npm@4

If this doesn't work, try:
~/.n/n/versions/node/7.0.0/bin/npm i -g npm@4

Comment: Along those lines I was not able to do that until I downgraded using `n` to 6.x.x, ran `npm i -g npm@4`, then upgraded back to 7.x.x.
Comment: For Mac OS X and Homebrew: [1] Find out which versions of node have been installed with `brew info node` [2] Switch the node version back to the one before 7, eg: `brew switch node 6.2.0` [3]  Update npm as matheusr suggests - `npm i -g npm@4` [4] Switch back to the latest version of node - `brew switch node 7.2.1`
Answer: delete node_modules directory and then type in your console "npm install". For a reason that I dont know, if you only update npm, it does not fix the error, but re-installing npm everything is gonna be allright.
Comment: i know this is old, but when you say `delete node_modules directory` do you mean that folder in a project, or your main one on your system? I'm on OSX 10.10.5
Comment: If you are using a framework, delete from your project, and then reinstall from your framework's console.
Answer: For me, if I facing error "cannot find module internal/fs", it would be refer to command path. Better find the command path:
npm config get prefix

put into system environment path.
It is worked for me after facing the error several days.


Proving that the sum of the first $2n$ terms of the series $1^2 - 3^2 + 5^2 - \cdots$ is $-8n^2$ by induction

Question:
Use mathematical induction to prove the following for the first $2n$ terms of the series $$1^2 - 3^2 + 5^2 - 7^2 + \cdots = -8n^2.$$

As we have odd numbers that are squared we could use $n = 2k-1$.
But the $2$ sides do not equate for $n=1$ or $2k-1$ (if you set $k=1$).
Also need to find the sum to $2n+1$ terms.
Comment: If you set $n=1$ you have $1^2-3^2=-8=-8n^2$ just fine. I suggest you look at [this answer](http://math.stackexchange.com/questions/19485/dominoes-and-induction-or-how-does-induction-work/19488#19488) for how to structure an induction proof.
Comment: The i'th term of the sequence (not the sum) should be $(-1)^{i+1}(2i-1)^2$. Then you sum up to $2n$, which goes in place of i, and add on $2n+1$'th term and $2n+2$ term. Then you should be able to solve easily enough.
Comment: Yes, you can use (-1)^(i+1) or, as below, (-1)^(i -1)
Answer: Here is the main part of the inductive step:
\begin{align}
\sum_{i=1}^{2(k+1)}(-1)^{i-1}(2i-1)^2&=\sum_{i=1}^{2k}(-1)^{i-1}(2i-1)^2+\underbrace{(-1)^{2k+1}(4k+3)^2}_{i=2k+2}+\underbrace{(-1)^{2k}(4k+1)^2}_{i=2k+1}\\[0.5em]
&= -8k^2-(4k+3)^2+(4k+1)^2\\[0.5em]
&= -8k^2-16k-8\\[0.5em]
&= -8(k^2+2k+1)\\[0.5em]
&= -8(k+1)^2.
\end{align}
Do you see where the induction hypothesis was used?
Comment: Thanks for your answer. You can see here that the last 2 terms for i=2k+2 and i=2k+1 give you the next term in the sequence i.e. (-1)^3(7)^2 and (-1)^2(5)^2 = -49 + 25, which is why you need to add these 2 terms to the first one to get to the result. Only, the third line up should read -8k^2 -16k - 8 so the factorisation for -8 works.
Comment: @J132 Good eyes! I'm not sure how I muffed that up. Just fixed it.
Answer:
As we have odd numbers that are squared we could use n = 2k-1

You are summing the sequence:  $\{1^2-3^2, 5^2-7^2, 9^2-11^2, \ldots (4n-3)^2-(4n-1)^2, \ldots\}$

But the 2 sides do not equate for n=1 or 2k-1 (if you set k=1)

See above. The first term is $-8$, and so...

Also need to find the sum to (2n+1) terms.

You need to show that if the sum of the first $n$ terms is $-8 n^2$, then if you add $-16(n+1)+8$ you obtain $-8(n+1)^2$.
Comment: I love the pairing approach. highlights the difference of squares bit at the core of this problem... can immediately see the sum is divisible by 8 and negative
Answer: $$a_n = \sum_{k=1}^{n}(-1)^{k+1}(2k-1)^2 $$
You need to rewrite your function to accommodate your analysis. If you have to analyse every pair of values you could rewrite it as:
$$b_m = \sum_{k=1}^{m}(4k-3)^2-(4k-1)^2$$
But that's
$$\sum_{k=1}^{m}(4k-3)^2-(4k-1)^2 = \sum_{k=1}^{m}(16k^2-24k+9 - 16k^2+8k-1) = \sum_{k=1}^{m}(-16k+8)$$
So:
for $$n = 2 \implies m = 1$$
$$\sum_{k=1}^{1}(-16k+8) = -16 + 8 = -8$$
Now, assuming for $2n$ works, what's $2n+2$ in $a_n$. But that's the same for testing $m+1$ assuming $m$ is true for $b_n$
$$\sum_{k=1}^{m+1}(-16k+8) = \left(\sum_{k=1}^{m}(-16k+8)\right) -16(m+1)+8  = -8m^2 -16m  -16 +8 =-8m^2 -16m  -8 = -8(m+1)^2$$
Answer: $1^2−3^2+5^2−7^2+⋯=−8n^2$
Last term of this series is $(4n-3)^2-(4n-1)^2$
$\Rightarrow P(n):1^2−3^2+5^2−7^2+⋯+(4n-3)^2-(4n-1)^2=−8n^2$
For n=1
$\Rightarrow P(1):1^2−3^2=−8(1)^2$
$\Rightarrow P(1):-8=−8$ which is true
Let P(k)be true,
$P(k):1^2−3^2+5^2−7^2+⋯+(4k-3)^2-(4k-1)^2=−8k^2$.......(1)
We have to prove P(k+1) as true.
$P(k+1):1^2−3^2+5^2−7^2+⋯+(4k-3)^2-(4k-1)^2+(4(k+1)-3)^2-(4(k+1)-1)^2=−8(k+1)^2$
$LHS=1^2−3^2+5^2−7^2+⋯+(4k-3)^2-(4k-1)^2+(4k+1)^2-(4k+3)^2$
$=-8k^2+(4k+1)^2-(4k+3)^2$
$=-8k^2+16k^2+8k+1-(16k^2+24k+9)$
$=-8k^2-16k-8=-8(k^2+2k+1)=-8(k+1)^2$=RHS
Therefore P(k+1) is true.So by Induction principle,P(n) is true for all $n$
Comment: In the last step the factorisation does not work: -8k^2 - 8k -8 is not -8(k^2 +2k+1), the first term would need to be -8k^2 - 16k -8. Try +(4k+1)^2 and -(4k+3)^2 for the LHS instead.
Comment: Thanks for pointing out,@J132,i have corrected it.


Question about Probabilities

Question: If my team wins 50% of the time when I wear my lucky tie and 90% when I wear my yellow sox, what is the probability of them winning if I wear both.  explain how you got to your response, please
Comment: The probability we **lose** wearing lucky tie is $0.5$, and the probability we lose wearing yellow socks is $0.10$. On the completely unjustifiable assumption of independence, the probability we lose if we wear both is $(0.5)(0.10)$. But maybe it is far higher than that. The gambling syndicate that has been stringing you along may get offended at being manipulated so crudely.
Comment: What are your ideas? Can you show your work so far?
Comment: +1 good question but you haven't seen your effort
Comment: Well the question is the information that you should supply. Are these two events dependent or independent?
Answer: The probability of them winning remains the same, since an individual's choice of clothes does not influence the results of sporting events (unless you're bribing the players).
On a more serious note, you can't calculate this without some more information, since:
$$P(C \ |\  A \cap B) $$
Is not necessarily related to $P(C\ | \ A)$ and $P(C\ | \ B)$, which is the information you provided.

Question about Probabilities


Lets Encrypt with Plesk

Question: I am trying to install a Let's Encrypt SSL certificate to a subscription held on a Plesk install.
I am running the following version of Plesk;

Plesk Onyx Version 17.8.11 Update #11

I then navigate to

Subscriptions > Domain > Lets Encrypt

From the setup screen I do not change anything, so
'Include a "www" subdomain for the domain and each selected alias'
and
'Secure webmail on this domain'
Remain unchecked. However, when I try to install the cert I get the following error;
Error: Could not issue a Let's Encrypt SSL/TLS certificate for domain.org.

The authorization token is not available at http://example.com/.well-known/acme-challenge/key.
The token file 'C:\Inetpub\vhosts\example.com\httpdocs\\.well-known\acme-challenge\key' is either unreadable or does not have the read permission.
To resolve the issue, correct the permissions on the token file to make it is possible to download it via the above URL.
See the related Knowledge Base article for details.
Details
Invalid response from https://acme-v01.api.letsencrypt.org/acme/authz/umis0L7-OVlu7SrSjMFHBsu-T7Cx0hwFS-WMxHgZgNA.
Details:
Type: urn:acme:error:unauthorized
Status: 403
Detail: Invalid response from http://example.com/.well-known/acme-challenge/key: "<!DOCTYPE html>

<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-sc"

It give a link to the following KB;
Plesk Suggested KB article
Which suggest I check the DNS resovles, so ipconfig shows me that the domain is pointing to the right IP.
However I dont have the ability for IPv6 and when i go to

domains > example.com> Web Hosting Access

I do not have the ability to select this.
Now from RDP to the server and looking I can see the directory structure is created i..e

.well-known > acme-challenge > key file

is created? Can anyone help with what the issue could be here please?
Answer: Check if the domain name resolves to IPv6 or not:
dig AAAA google.com @22.214.171.124
Check permissions for token file well-known > acme-challenge > key file
Try to access this file via browser, or create a new test text file inside of the acme-challenge folder and try to access it. There is a possibility that web.config file can cause the issue.

Lets Encrypt with Plesk


UMVUE for $\frac{p}{1-p}$

Question: Given a random sample of $X_1, X_2, ..., X_n$ of the negative binomial distribution $Nb(N,p)$, I am instructed to find the UMVUE for the parameter $\frac{1-p}{p}$.
In general, the mean $\mu$ of the negative binomial is given by the formula $\frac{N(1-p)}{p}$, and the UMVUE for $\mu$ is the sample mean $\overline X$. So essentially I'm asked to find the UMVUE for the parameter $\frac{\mu}{N}$.
So, would the UMVUE for $\frac{\mu}{N}$ be $\frac{\overline X}{N}$? This seems intuitively correct to me -since it indeed is an Unbiased estimator of $\frac{\mu}{N}$, and its variance is dropping by a lot (it's inversely proportional to $N^2$)- but I can't seem to find a way to prove this (or get to any result at all) using Lehmann–Scheffé theorem.
Any help would be greatly appreciated!
Comment: Your title says $\frac{p}{1-p}$ while your first paragraph says $\frac{1-p}{p}$.  An unbiased estimator for one will not be an unbiased estimator for the other; nor will its reciprocal be an unbiased estimator for the other
Comment: Just in case this helps someone else in the future, it seems the above is true (thanks to the invisible upvoter too, for hinting that it is), and not only that; turns out that: If a function $h$ is an UMVUE for the parameter $g(p)$, then the function $c \cdot h$ will be the UMVUE for the parameter $c \cdot g(p)$ - proof is the same as the Lehmann–Scheffé theorem proof, using mean values properties.
Comment: Yeah the one on the title is wrong, the parameter I was looking to estimate is $\frac{1-p}{p}$. Thanks for the catch!
Answer: To apply the Lehman-Scheffé Theorem, we require a complete sufficient statistic $S(\boldsymbol{x})$ for $\theta=(1-p)/p$ and an unbiased estimator $T(S)$ of $\theta$. Starting from the pmf of our data:
\begin{equation}
P(X_i=x_i)=\binom{x_i+N-1}{x_i}(1-p)^{x_i} p^N.
\end{equation}
Consider two sample points $\boldsymbol{x}$ and $\boldsymbol{y}$. Since
\begin{equation}
\frac{P(\boldsymbol{x};p)}{P(\boldsymbol{y};p)}=\frac{\prod_{i=1}^{n}\binom{x_i+N-1}{x_i}(1-p)^{x_i} p^N}{\prod_{i=1}^{n} \binom{y_i+N-1}{y_i}(1-p)^{y_i} p^N}\propto (1-p)^{\sum_{i=1}^{n} x_i-\sum_{i=1}^{n} y_i},
\end{equation}
does not depend on $p$ if and only if $\sum_{i=1}^{n} x_i=\sum_{i=1}^{n} y_i$, we may conclude that $S(\boldsymbol{x})=\sum_{i=1}^{n} x_i$ is a minimally sufficient statistic for $p$ by a result of Lehman and Scheffé ($1950$).
Noting that $X_i$ is in the exponential family,
\begin{align}
P(x_i;p)&=e^{\ln \phi(x_i)+x_i\ln(1-p)+N\ln p},\\
&=e^{h(x_i)+A(p)t(x_i)+B(p)},
\end{align}
we have that $\sum_{i=1}^{n} t(x_i)=\sum_{i=1}^{n} x_i=S(\boldsymbol{x})$ is a complete statistic, since the parameter space of $p$ contains an open set in $\mathbb{R}$ (this is a well known result in most mathematical statistics textbooks).
The conditions used above hold when considering any 'nice' transformation of $p$ (we may have written our pmf in terms of $\theta$ and derived the same results). So, $S(\boldsymbol{x})=\sum_{i=1}^{n} x_i$ is a complete sufficient statistic for $\theta$.
Now let's consider your claim that $T(S)=\bar{X}/N=S/nN$ is the MVUE (one may also find such a $T$ from the Rao-Blackwell Theorem). Since
\begin{align}
E\left[T(S)\right]&=E\left[\frac{\sum_{i=1}^{n}x_i}{nN}\right],\\
&=\frac{1}{nN}\sum_{i=1}^{n}E[x_i],\\
&=\frac{1}{nN}\frac{Nn(1-p)}{p},\\
&=\frac{1-p}{p},\\
&=\theta,
\end{align}
we have that $T(S)$ is an unbiased estimator for $\theta$ and is a function of the complete sufficient statistic $S$ for $\theta$. Hence, by the Lehman-Scheffé Theorem, $T(S)$ is the UMVUE for $\theta$.
Comment: Magnificent! To be honest I didn't quite catch the part in which you prove that $S(\boldsymbol{x})=\sum_{i=1}^{n} x_i$ is a sufficient statistic for P, and I'm on a quite difficult place to look into it thoroughly now, but I'll scan it once I get home. The rest of your explanation was really easy to grasp the way you presented it. Thanks a lot!!

UMVUE for $\frac{p}{1-p}$


Enviar variável do PHP para Shell Script

Question: Tenho um arquivo .sh e ele tem variáveis que preciso receber do PHP, segue um exemplo:
//variavel 1 que preciso receber externamente
NAME=""
//variavel 2 que preciso receber externamente
DIR=""

tar -zcf $HOME.tar.gz $DIR

A chamada do arquivo por PHP séria assim:
shell_exec('sh arquivo.sh');

só preciso saber como enviar os dados das 2 variáveis.

Outra forma seria enviar o script todo direto pelo php via shell_exec(), como enviaria um script desse tipo?
(Isso não funciona):
shell_exec('VAR=tar -zcf teste.tar.gz teste/testeDir
if [ "$SUCCESS" == "0" ]; then
   echo "Sucesso!"
else
   echo "Sucesso!"
fi');

Comment: Não sei se ajuda, mas pelo próprio PHP você pode executar comandos do bash acrescentando variáveis e pegando o retorno, desta forma dispensaria a necessidade deste arquivo bash externo.
Comment: Só uma coisinha: JS é client-side! Não estou entendendo qual o motivo de envolver o JS nisso.
Comment: viajei, pensei em fazer com ajax, mas ia usar php do mesmo...
Comment: Cara isso não funciona? `echo "{$HOME}";` e `echo "{$DIR}";` ?
Comment: não entendi Ivan, como eu uso isso ? li algo sobre enviar a variavel desse jeito: $page = shell_exec('my_script.sh "{$var1}" "{$var2}"'); mas não sei se tá certo e não consigo pegar ela no sh
Comment: tipo assim: `NAME="$(ls -1)"`. `echo "{$NAME}"`
Answer: Passe os dados através de argumentos, que podem ser lidos nos scripts bash através de $1, $2, etc. Seu script bash ficaria assim:
#!/bin/bash
NAME="$1"
DIR="$2"

tar -zcf $NAME.tar.gz $DIR

No PHP, informe os argumentos na respectiva ordem:
shell_exec('sh seu_script.sh nome_qualquer diretorio_qualquer');

Comment: tb não funcionou!
Comment: Ok, primeiro verifique se o problema está no script bash ou no PHP. Rodando no terminal, o script bash vai bem?
Comment: desculpa, acho q era cache, funcionou!
Comment: No PHP, tenha certeza de informar o caminho completo do script bash.
Comment: só tava com um problema na variavel do php q ficou assim $teste = 'teste2'; $saida = shell_exec('sh ../script.sh '.$teste);
Answer: Ao executar a função shell_exec é possível passar os valores de variáveis como argumentos ao comando que será executado:
$arquivo = "teste";
$dir = "testeDir";

$resultadoExec = shell_exec("sh script1.sh $arquivo $dir");

echo $resultadoExec;

Para receber as informações no arquivo .sh use as variáveis especiais $1 e $2:
#!/bin/bash

arquivo=$1".tar.gz"
dir=$2

# Verifica se o script recebe os argumentos
if [ $# -ne 2 ] then
   echo "Atenção! É necessário informar o arquivo e diretório de destino!"
   echo "Exemplo: \n $0 <nomeArquivo> <diretorio>"
   exit
fi

tar -zcf $arquivo $dir
if [ $? -eq 0 ] then
   echo "Arquivo descompactado com sucesso no diretório: $dir"
else
   echo "Erro! Não foi possível realizar a operação! Tente novamente"
fi

Comment: não funcionou nem o php nem o sh
Comment: era cache, provalvemente está funcionando!
Answer: No arquivo shell script.sh faça o seguinte:
#!/bin/bash

NAME='filename'
DIR='path'

echo $NAME
echo $DIR
tar -zcf $NAME.tar.gz $DIR

No PHP faça assim:
$file = "script.sh";
if (file_exists($file)) {
   chmod($file, "go+x");
   $string = shell_exec('sh '.$file);
   $data = explode("\n", $string);
   //Nome: filename - Diretório: path
   echo 'Nome: '. $data[0] . ' - Diretório: ' . $data[1];
} else {
  echo 'arquivo  não existe';
}

Se precisar passar parâmetros, no shell:
  #!/bin/bash

    NAME=$1
    DIR=$2

    echo $NAME
    echo $DIR
    tar -zcf $NAME.tar.gz $DIR

No PHP:
 $file = "script.sh";

   $params = array('filename', 'path');
   $param = ' '.implode(' ', $params);
    if (file_exists($file)) {
       chmod($file, "go+x");
       $string = shell_exec('sh '.$file.$param);
       $data = explode("\n", $string);
       //Nome: filename - Diretório: path
       echo 'Nome: '. $data[0] . ' - Diretório: ' . $data[1];
    } else {
      echo 'arquivo  não existe';
    }


Input dentro de DIV com visibility:hidden

Question: Galera é o seguinte, ocultei umas div,que possuem inputs de um formulário dentro, com
style='visibility:hidden; position:absolute'

E gostaria que essas DIV não enviassem informação quando o formulário fosse encaminhado.
A minha questão é: Só tem como fazer isso usando JS ou existe uma forma mais simples e menos braçal pra fazer isso?
Comment: O máximo que você pode fazer é agrupar inputs usando um `fieldset` ao invés de uma `div` e marcar este `fieldset` com a property `disabled`, infelizmente esta abordagem não funciona no IE.
Comment: @TobyMosque acabei de testá-la e realmente não funciona no IE
Answer: para ocultar campos de um formulário use
<input type="hidden" name="NomeDoInput">

Ao invés de fazer isso via CSS.
caso não queira que os dados de um formulario não sejam enviado para outra pagina usando form, deixe esses inputs fora do form ou se preferir use:
unset($_POST['nomeDoCampo']); //Com PHP

caso esses dados já tenham sido enviados.
Comment: +1 Concordo que a melhor forma de não enviar os inputs com o form seja, justamente, deixá-los fora deste.
Comment: A pagina dele pode ser feita em ASP.NET WebForms com o form1 na MasterPage, a visibilidade da div pode está sendo controlada por algum script, alem de outros fatores que podem inviabilizar de colocar os inputs fora do form. Em todo caso esta resposta não responde a pergunta, "como impedir o envio de um input através de alguma marcação em um parent".
Comment: A questão é justamente essa que @TobyMosque disse. Está sendo controlada por um script, existe a necessidade de deixar os inputs dentro do form.
Comment: Por favor especifique a linguagem que esta usando, deixar HTML e CSS abre muitas possíveis opções usando diversas outras linguagens.
Comment: @RafaelAcioly alterei lá, to usando php + javascript.
Comment: quando o parâmetro for passado pelo form para a outra pagina tente usar unset($_POST['seuCampo']) para que ele deixe de "existir", já tentou isso?
Comment: atualmente estou utilizando essa solução, mas estou procurando encontrar uma forma menos braçal, como essa.


How to use an encrypted disk without needing an unencrypted boot partition

Question: I would like to know if there is a way to encrypt a linux system which does not require a small unencrypted /boot partition.
In addition I would like to know if encryption can be implemented on an existing unencrypted system in such a manner that it will encrypt "on the fly" whilst a user is using the system. Thus requiring no re-install of the OS.
Right now the solution I use for linux is luks. I typically re-install the OS (backing up and restoring any data that needs to be kept) create a small /boot partition to boot from and all other partitions are encrypted, including swap. I use either kickstart for redhat or preseeding for debian based systems. The install, either encrypted or not is fully automated.
I understand for all practical purposes this encryption method is safe and there is no way (unless the password is actually saved there or something similarly stupid) to find information on how to decrypt the partitions using the small unencrypted /boot partition, as opposed to having an unencrypted swap partition which could potentially reveal data to help decrypt a partition. The reason I am looking into a solution like this is more practical.
I assume something like this would need to be started from the disk's boot block (mbr or otherwsise), or possibly chainloaded. It probably requires some functionality added to the bootloader, grub for example, to prompt for a password and use it to open the partitions so those can be read.
I did some research trying to find solutions, but I have not yet found one that works, or even if it may work, it's not practical at all (especially with a 100+ user base).
Comment: It's a reasonable question. After all, BitLocker does this to some extent. Though as far as I know, no Linux solutions offer it.
Comment: @aseq You don't have some sort of automated deployment, standardized images, etc.?
Comment: Your question generated some discussion [in chat](http://chat.stackexchange.com/rooms/127/the-comms-room). Feel free to join us.
Comment: If you're that hard up for uptime, methinks you're doing it wrong.
Comment: Not doing it wrong. If disk encryption requires you to re-install the OS it will become a bit prohibitive with regards to time and resources spent when you have to do it for more than a couple of users.
Comment: @MichaelHampton not just BitLocker, but also FileVault on OS X can encrypt on the fly. I'm really surprised there's not a standard Linux solution.
Comment: I am more thinking of existing systems that need to be encrypted. It would be nice you can just install it, start it up and hand it back to the user. Time spent 10-20 minutes, instead of half a day rebuilding someone's system, plus user not being able to work.
Answer: Eventually, you will need to start the system from a cleartext stub. If this stub is not in clear in the disk, the next option would be in the firmware; maybe one day all UEFI motherboards will support full-disk encryption.
That said, what matters with the small cleartext boot partition is not to have confidentiality (because it normally only contains publicly known boot data), but to have integrity. You don't want an attacker to grab your machine while you are sleeping, and replace the mounting code with a malicious one that will grab your password when you enter it, and store it some hidden disk area.
This is the problem Secure Boot is fixing, and you can (in theory) use it on linux, as long as the boot firmware allows you to use custom keys. A hardware component (the TPM) will ensure (using crypto) that the system will complain when booting if the cleartext partition has been altered.
There is a basic, incomplete, and obsolete procedure for Gentoo, that gives a rough idea of what can be done.


Getting No Results from SQLite DB in iOS, but getting them using SQLite itself

Question: I'm checking and creating a database using the following function:
-(void) checkAndCreateDatabase
{
    // Check if the SQL database has already been saved to the users phone, if not then copy it over
    BOOL dbExists;

    // Create a FileManager object, we will use this to check the status
    // of the database and to copy it over if required
    NSFileManager *fileManager = [NSFileManager defaultManager];

    // Check if the database has already been created in the users filesystem
    dbExists = [fileManager fileExistsAtPath:_databasePath];

    // If the database already exists then return without doing anything
    if(dbExists)
    {
        //sqlite3_open([self.databasePath UTF8String], &_database);
        NSLog(@"DB DOES EXIST");
        return;
    }
    NSLog(@"DB DOES NOT YET EXIST");
    // If not then proceed to copy the database from the application to the users filesystem

    // Get the path to the database in the application package
    NSString *databasePathFromApp = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:_databaseName];

    // Copy the database from the package to the users filesystem
    [fileManager copyItemAtPath:databasePathFromApp toPath:_databasePath error:nil];
}

The database name and path are properly set here, in the init function for my Search class:
- (id)init
{
    if ((self = [super init]))
    {
        _databaseName = DB_NAME;

        NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        NSString *documentsDir = [documentPaths objectAtIndex:0];
        _databasePath = [documentsDir stringByAppendingPathComponent:_databaseName];

        if (sqlite3_open([_databasePath UTF8String], &_database) != SQLITE_OK)
        {
            [[[UIAlertView alloc]initWithTitle:@"Missing"
                                       message:@"Database file not found"
                                      delegate:nil
                             cancelButtonTitle:@"OK"
                             otherButtonTitles:nil, nil]show];
        }
    }
    return self;
}

Then, I query the database using:
-(void)search:(NSString *)searchTerm
{
    const char *dbpath = [_databasePath UTF8String];
    sqlite3_stmt *statement;

    /* Begin Database Work */
    if(sqlite3_open(dbpath, &_database) == SQLITE_OK)
    {
        NSString *querySQL = @"SELECT * FROM types";
        const char *query_stmt = [querySQL UTF8String];
        if (sqlite3_prepare_v2(_database, query_stmt, -1, &statement, NULL))
        {
           if(sqlite3_step(statement) == SQLITE_ROW)
           {
               NSLog([[NSString alloc] initWithUTF8String: (const char *) sqlite3_column_text(statement,1)]);
           }
           else
           {
               NSLog(@"nope2: query = ");
               printf(query_stmt);
           }
        }
        else
        {
            NSLog(@"nope1");
        }

    }
}

I'm always getting "nope2" returned, which seems to imply that no results are returned. When I run the exact same query on the database in SQLite directly, however, I get the results I expect. This leads me to believe that I'm doing something wrong in the code. What looks wrong here?
Comment: If `sqlite3_prepare_v2` succeeds, it returns `SQLITE_OK` (which is `0`). If it fails, it returns a non-zero value. So your check for the success of the prepare statement is backwards. You're also not looking at the error message returned by `sqlite3_errmsg`, which often will give you a very useful error message.
Comment: (id)init?  Copying a database file?  ...  Well, since rar is known to delete topics without the simplest form of appreciation, I have no advice to give.
Comment: Hello again, I explained that on another post. Is there something I should be doing besides copying the database file?
Answer: A couple of thoughts:

A very common problem is that, at some point in the past, the copy failed and the sqlite3_open would therefore create a blank database (this is why I generally use sqlite3_open_v2 with the SQLITE_OPEN_READWRITE option, but not the SQLITE_OPEN_CREATE option, to prevent it from ever creating a blank database). Anyway, if that ever happened, from that point on, checks for the existence of the file would succeed, even though the database in the Documents path was a blank database. You can confirm this by opening the database in the Documents path on your Mac and inspecting it (if using the simulator you can navigate to the ~/Library/Application Support/iPhone Simulator, finding the app, and then navigating to its Documents folder; if a device, you can use the Xcode organizer to select the app and download the app's package, and then look at the version of the database there). Even easier, just remove the app from your device/simulator, reinstall the app, and that should fix it.
But if you have questions, make sure to just examine the copy of the database in the Documents folder, and you should be able to quickly diagnose the problem.
Another issue is that you should replace:
if (sqlite3_prepare_v2(_database, query_stmt, -1, &statement, NULL))
{
    ...
}
else
{
    NSLog(@"nope1");
}

with
if (sqlite3_prepare_v2(_database, query_stmt, -1, &statement, NULL) == SQLITE_OK)
{
    ...
}
else
{
    NSLog(@"%s: sqlite3_prepare_v2 error: %s", __FUNCTION__, sqlite3_errmsg(_database));
}

Note that (a) I'm checking for SQLITE_OK, which, because it's is 0, and your code effectively does the exact opposite as what you obviously intended; and (b) if there's an error, I'll get the error message from SQLite. The error messages after sqlite3_prepare_v2 are generally very illuminating.
You should also check the result of the copyItemAtPath call and make sure it's returning YES. If not, you should report an error. Thus, replace:
[fileManager copyItemAtPath:databasePathFromApp toPath:_databasePath error:nil];

with
NSError *error = nil;
if (![fileManager copyItemAtPath:databasePathFromApp toPath:_databasePath error:&error])
{
    NSLog(@"%s: copyItemAtPathError: %@", __FUNCTION__, error);
}

In your original code, if you, for example, neglected to include the database in the bundle, the copy would fail, but you would not detect this failure, and, worse, because you're using sqlite3_open (instead of sqlite3_open_v2), you wouldn't see an error during the open process.
Comment: Thanks very much for the thorough answer! I have made the changes you recommend. However, for some reason, I'm still getting an empty DB (verified as you recommended). No error is being reported on copy, despite the changes, and I'm getting "nope1" now, which means the prepare is failing.
`if (sqlite3_prepare_v2(_database, query_stmt, -1, &statement, NULL) == SQLITE_OK)` is not true, so "nope1" is printed.
Comment: @rar Did you delete the app (or completely reset the simulator) before running it again? Just reinstalling the app isn't enough. You actually have to delete the old app and reinstall it fresh.
Comment: That did it. I then had to make sure the checkAndCreate function was called. It looks like it's working now. Thanks!


Why does scale not make mean of 0?

Question: I am using R and I want to scale some data. The code looks like this:
data <- read.table(file_name, header = TRUE)
rates <- scale(data[8])
mean <- mean(rates)
sd <- sd(rates)

My understanding is that this scale function should scale the data so the mean is 0 and the standard deviation is 1. The standard deviation seems correct but the mean is not 0. What causes this? And what is the solution to making the mean 0? Or am I interpreting something wrong?
Comment: Floating point arithmetic isn't exact. https://stats.stackexchange.com/a/525766/22311 The print out says that the mean is less than $2 \times 10^{-16}$ units away from zero. How much closer to zero do you need it to be?
Comment: Floating point arithmetic isn't exact & the inexactness of floating point arithmetic can't be fixed. The statement "`scale` makes the mean zero" means "`scale` makes the mean a value that is close to 0, relative to the machine precision of floating point representation." You can learn information about floating point arithmetic in its technical standard, IEEE 754.
Comment: Have you ever computed $1/3$ on a calculator and then multiplied by $3$ to obtain $0.99999999$?  According to the laws of arithmetic, the difference between this answer and the original value of $1$ is zero.  The calculator thereby "proves" that $0 - 1 - 0.9999999 = 10^{-8}.$  The computer is just a big calculator and is subject to the same breakdown of mathematical laws.  It is important to understand such things so you can use a computer wisely and well.
Comment: 1. See *What every programmer should know about floating-point arithmetic*: https://floating-point-gui.de/  2. For R specifically see the `Note`  section in `?Comparison`. Also see the references in `?Arithmetic`
Comment: what do you get if use instead `round(mean(x),10)` ?
Comment: What is the solution for this. It doesnt make sense to me that everywhere it says that scale makes the mean 0 and this function does not do that.
Comment: You should never be reporting your results out from the R terminal anyway. If you were producing values to include in a paper or table, you'd need to use the `?formatC` to specify such things as significant figures, rounding rules, etc.
Answer: As others have noted, this is a programming side-effect more than a statistical irregularity. For my example below, I set the scipen argument in options super high so you can see how many decimals are produced (this argument just shows the scientific notation explicitly so you can see how long the numbers are). An example should make it obvious that even if the mean isn't exactly zero, it is as close as it gets with floating points.
To demonstrate, I have simulated normally distributed data with a mean of 50 and SD of 20 (the values don't really matter but felt like I'd assign something higher than the defaults which won't say much). I also set a random seed to any generic number so it is reproducible.
#### Simulate Data ####
set.seed(123)
options(scipen = 1000000000)
x <- rnorm(n=100,
           mean=50,
           sd=20)

Then I scale the data and check the mean and standard deviation like you did.
#### Scale and Get Mean/SD ####
scale.x <- scale(x)
mean(scale.x)
sd(scale.x)

When running mean(scale.x), you will see the number is ridiculously long:
0.0000000000000001974408

You may notice there are exactly 23 numbers to the right of the decimal. This is not by accident. Computers that run on 32-bit computers only store 23 digits in binary. This makes sense. R would have to jam a theoretically infinite number of real numbers into a finite number of bits to get to zero. R instead creates a limited expression that is as close to zero as possible.
Running the function sd(scale.x) gives you exactly what you would expect though:
[1] 1

This is because unlike the mean, you are not rounding off a large list of numbers to get the answer. The standard deviation is just the squared root of the variance of $x$, which is usually going to be a non-zero value that will not have many decimals.
An accessible video to this topic can be found at this link.
Edit
While my overall point about the topic still stands, it appears I misspoke about the number of binary digits represented in this estimation. See the below comment by Whuber for more details.
Comment: My mistake. I have edited the answer to include what you said.
Comment: 23 is incorrect.  IEEE double precision floating point explicitly stores 51 binary digits and implicitly has a leading 1, being the equivalent of $(51+1)/\log_2(10)\approx 16$ decimal digits *in the mantissa.*  This is multiplied by a power of $2$ to shift the binary point, but you still get no more than 16 significant decimal digits no matter what.

Why does scale not make mean of 0?


Como saber a direção do scroll da roda do mouse

Question: Como saber a direção e quantidade do scroll quando se faz scroll com a roda do mouse?
Os browsers têm maneiras diferentes de passar informação no objeto event. Uns usam o .wheelDelta, outros o .detail, e outros (de nova geração) usam o evento DOM3 wheel passando informação relevante no deltaY ou deltaX.
Qual a melhor maneira de saber de maneira consistente a direção e eventualmente a quantidade do scroll em browsers diferentes?
Para completar a pergunta deixo uma pesquisa que fiz sobre isto, e fazendo a roda do mouse rodar para a frente:
| mousewheel        | Chrome (win) | Chrome (mac) | Firefox (win) | Firefox (mac) | Safari 7 (mac) | Opera 22 (mac) | Opera 22 (win) | IE11      | IE 9 & 10   | IE 7 & 8  |
|-------------------|--------------|--------------|---------------|---------------|----------------|----------------|----------------|-----------|-------------|-----------|
| event.detail      | 0            | 0            | -             | -             | 0              | 0              | 0              | 0         | 0           | undefined |
| event.wheelDelta  | 120          | 120          | -             | -             | 12             | 120            | 120            | 120       | 120         | 120       |
| event.wheelDeltaY | 120          | 120          | -             | -             | 12             | 120            | 120            | undefined | undefined   | undefined |
| event.wheelDeltaX | 0            | 0            | -             | -             | 0              | 0              | 0              | undefined | undefined   | undefined |
| event.delta       | undefined    | undefined    | -             | -             | undefined      | undefined      | undefined      | undefined | undefined   | undefined |
| event.deltaY      | -100         | -4           | -             | -             | undefined      | -4             | -100           | undefined | undefined   | undefined |
| event.deltaX      | 0            | 0            | -             | -             | undefined      | 0              | 0              | undefined | undefined   | undefined |
|                   |              |              |               |               |                |                |                |           |             |           |
| wheel             | Chrome (win) | Chrome (mac) | Firefox (win) | Firefox (mac) | Safari 7 (mac) | Opera 22 (mac) | Opera 22 (win) | IE11      | IE 10 & 9   | IE 7 & 8  |
| event.detail      | 0            | 0            | 0             | 0             | -              | 0              | 0              | 0         | 0           | -         |
| event.wheelDelta  | 120          | 120          | undefined     | undefined     | -              | 120            | 120            | undefined | undefined   | -         |
| event.wheelDeltaY | 120          | 120          | undefined     | undefined     | -              | 120            | 120            | undefined | undefined   | -         |
| event.wheelDeltaX | 0            | 0            | undefined     | undefined     | -              | 0              | 0              | undefined | undefined   | -         |
| event.delta       | undefined    | undefined    | undefined     | undefined     | -              | undefined      | undefined      | undefined | undefined   | -         |
| event.deltaY      | -100         | -4           | -3            | -0,1          | -              | -4             | -100           | -99,56    | -68,4 | -53 | -         |
| event.deltaX      | 0            | 0            | 0             | 0             | -              | 0              | 0              | 0         | 0           | -         |
|                   |              |              |               |               |                |                |                |           |             |           |
|                   |              |              |               |               |                |                |                |           |             |           |
| DOMMouseScroll    |              |              | Firefox (win) | Firefox (mac) |                |                |                |           |             |           |
| event.detail      |              |              | -3            | -1            |                |                |                |           |             |           |
| event.wheelDelta  |              |              | undefined     | undefined     |                |                |                |           |             |           |
| event.wheelDeltaY |              |              | undefined     | undefined     |                |                |                |           |             |           |
| event.wheelDeltaX |              |              | undefined     | undefined     |                |                |                |           |             |           |
| event.delta       |              |              | undefined     | undefined     |                |                |                |           |             |           |
| event.deltaY      |              |              | undefined     | undefined     |                |                |                |           |             |           |
| event.deltaX      |              |              | undefined     | undefined     |                |                |                |           |             |           |

Comment: A razão desta pergunta e resposta é porque estive a corrigir um bug sobre isto numa biblioteca de JavaScript. Publico aqui a resposta a que cheguei. Se houver falhas ou maneiras melhores de o fazer seria interessante ver aqui. Existe uma [pergunta relacionada](http://stackoverflow.com/q/5527601/2256325) no SOen, mas que não me deu a resposta completa...
Answer: Encontrei 2 abordagens partindo da mesma ideia.
Primeira abordagem, fazer uma função que retorne o valor original e relevante à roda do mouse em browsers diferentes, ajustando valores negativos para a direção ser consistente.
var roda = (event.wheelDelta) ? event.wheelDelta : -(event.detail || event.deltaY);

Exemplo: http://jsfiddle.net/RzPPp/
Nesta variante é ainda possivel reduzir o movimento a somente +1 ou -1 para ser usado como indicador de direção: http://jsfiddle.net/RzPPp/1/
A outra abordagem, mais complexa é tentar normalizar o valor para ter o mesmo comportamento em browsers diferentes. Servi-me da tabela da pergunta para perceber que os browsers usam multiplos de um numero base para mostrar a velocidade/quantidade que a roda mexe. Usando essa informação, fiz um check as resultados para saber via "feature detect" (ou mais exatamente "multiplo detect") qual o browser e como esse valor deve ser tratado.
Assim cheguei a este código:
var normalized;
if (event.wheelDelta) {
    normalized = (event.wheelDelta % 120 - 0) == -0 ? event.wheelDelta / 120 : event.wheelDelta / 12;
} else {
    var rawAmmount = event.deltaY ? event.deltaY : event.detail;
    normalized = -(rawAmmount % 3 ? rawAmmount * 10 : rawAmmount / 3);
}

Exemplo: http://jsfiddle.net/RzPPp/2/
function normalizarRoda(event) {
    var normalized;
    if (event.wheelDelta) {
        normalized = (event.wheelDelta % 120 - 0) == -0 ? event.wheelDelta / 120 : event.wheelDelta / 12;
    } else {
        var rawAmmount = event.deltaY ? event.deltaY : event.detail;
        normalized = -(rawAmmount % 3 ? rawAmmount * 10 : rawAmmount / 3);
    }
    return normalized;
}

Nota: Como browsers diferentes usam eventos diferentes, é preciso "ouvir" o evento certo. Então para amarrar um oscultador de evento uso assim, para detectar qual o browser certo e o evento que ele deve "ouvir":
var event = 'onwheel' in document ? 'wheel' : 'onmousewheel' in document ? 'mousewheel' : 'DOMMouseScroll';
meuElemento.addEventListener(event, callback);

Testei esta resposta no IE7~11, Firefox (mais recente) Win e Mac, Safari 7, Chrome (mais recente) Win e Mac, Opera (mais recente) Win e Mac. Reparei também que a plataforma Mac é mais generosa nos valores que retorna. Assim em Mac os valores de uma rodagem bem rápida são maiores que os do Windows, mas iguais entre browsers da mesma plataforma. O valor minimo é o mesmo.


Create a CSV file dump/feed whenever item of Content Type A is created

Question: I need to create a CSV dump/feed whenever a new item of "Content Type A" is created, with only that new item's info in the CSV. How can this be accomplished? For example, if 100 new items of "Content Type A" were created today, there would be 100 separate CSV files with the field values for each of those content items.
Thanks!
Answer: Look at Views Data Export. It can create a CSV from Node content.
It sounds like you need this to somehow be recurring over time ... this is a tall order and so I wont be providing much code, but will outline a possible solution:

Implement hook_cron_queue_info(). This is a cron task that runs off of a custom Queue. You can insert a NID every time a node is created into a custom queue you've created named MyCSVQueue. Every time a node is created it gets added to this queue -- when you process the queue you create individual csv files.
Use either hook_node_insert or Rules to place the NID into the work queue.
In your queue worker function you pass the NID to a custom view that uses a contextual filter to load the NID. Or, you may be able to use node_export to create the CSV data as well. You then simply use the Drupal File API and file_save() to store the csv file somewhere in your public/private drupal filesystem.

If the default Cron options of drupal dont suite your needs look at Ultimate Cron
EDIT
A slightly easier alternative:
Use:

Use either hook_node_insert or Rules to run a snippet of custom PHP code. Simply create a file directory using the File API in public files as: %files/csv_node_exports/MM-DD-YYYY. Your snippet can create the directory if it doesnt exist today yet.
then just export the node data to a CSV file. You may or may not have a NID yet ... you could always update the filename after the fact to reflect the actual NID assigned to the node.


Proof that any connected Graph has at least $n-1$ edges

Question: I would really appreciate if someone could check this proof i though. Bare in mind i learned this subject in another language so i apologize in advance for my english.
By Induction:
$G$ connected with n vertex $\implies G$ has at least $n-1$ edges
Base case: A graph with 1 vertex is defined to be connected. Clearly it has at least 0 edges.
Inductive case: Assume that for some $n \in \mathbb{Z}_{+}$, every connected undirected graph with n vertices has at least $n−1$ edges.
Let's grab G with $n+1$ vertex. If we proceed to delete one vertex $v \in G$, we have these 2 possibilities:
$v$ is not a cut vertex:
Then $G-v$ is connected and has n vertex, then has at least $n-1$ edges. If we proceed to re-add $v$, since $G$ is connected, $g(v) > 0$, then G has at least $n$ edges.
$v$ is a cut vertex:
Then $G-v$ has $K$ components, where $K$ cannot be greater than $g(v)$ since each deleted edges can only generate one more component. Then we proceed to add $e=(u,w)$ with $u \in K_i$ and $w \in K_j$ with $g(v)\geq K\geq j>i$ . This adds up to $g(v)-1$ edges to $G-v$. Now $G-v + edges$ is connected, then it has at least $n-1$ edges. $G-v$ has at least $n-1-(g(v)-1)$ edges, if we re-add $v$, we add $g(v)$ edges, then $G$ has at least $n$ edges.
Thank you very much in advance
Comment: Do you know about a spanning tree?
Comment: what's that? i know that a tree has n-1 edges and that if you delete any edge then it wont be connected, but i have to proof that as well
Answer: This is a nice proof, and I believe it's basically correct. I had to guess what you meant at one point, though:

Then we proceed to add $e=(u,w)$ with $u \in K_i$ and $w \in K_j$ with $g(v)\geq K\geq j>i$ . This adds up to $g(v)-1$ edges to $G-v$.

This sounds like you're adding either one such $e$, or all of them, but from the structure of the proof it seems that what you mean is something more like:

Then we proceed to add, for each $i$ with $1\le i\lt K\le g(v)$, a new edge $e=(u,w)$ for some $u\in K_i$ and some $w\in K_{i+1}$, for a total of up to $g(v)-1$ new edges.

(Also you should perhaps introduce the notation $K_i$ for the components.)
Comment: That sounds a lot better yeah, thanks for that. :)


CSS Drop Down List Hover mouse not work

Question: i have a code HTML CODE:

Sign in with

Twitter

Github

Facebook

AND CSS:
.wrapper-dropdown-2 {
position: relative;
width: 200px;
margin: 0 auto;
padding: 10px 15px;

background: #fff;
border-left: 5px solid orange;
cursor: pointer;
text-align: left;
cursor: pointer;
outline: none;

}

.wrapper-dropdown-2:after {
    content: "";
    width: 0;
    height: 0;
    position: absolute;
    right: 16px;
    top: 50%;
    margin-top: -3px;
    border-width: 6px 6px 0 6px;
    border-style: solid;
    border-color: grey transparent;

}
.dropdown {
    display:none;
}
.wrapper-dropdown-2:hover ul.dropdown  {
    position: absolute;
    display:block;
    top: 100%;
    left: -5px;
    right: 0px;
    background: white;
    -webkit-transition: all 0.3s ease-out;
    -moz-transition: all 0.3s ease-out;
    -ms-transition: all 0.3s ease-out;
    -o-transition: all 0.3s ease-out;
    transition: all 0.3s ease-out;
    list-style: none;
    opacity: 0;
    pointer-events: none;
}
.wrapper-dropdown-2 .dropdown li a {
    display: block;
    text-decoration: none;
    color: #333;
    border-left: 5px solid;
    padding: 10px;
    -webkit-transition: all 0.3s ease-out;
    -moz-transition: all 0.3s ease-out;
    -ms-transition: all 0.3s ease-out;
    -o-transition: all 0.3s ease-out;
    transition: all 0.3s ease-out;
}

http://jsfiddle.net/pvt3e/
and i try, in hover mouse to: Sign in with open the drop down but its not work !
i cant work with js. Because I have a problem with 1.8.2, but I think we can find a solution with CSS
Comment: `Sign in with` is not a part of menu
Comment: @BindiyaPatoliya can't you see shared fiddle..?
Comment: all code in jsfiddle: http://jsfiddle.net/pvt3e/
Answer: try this
.wrapper-dropdown-2:hover ul{
    display:block;
}

updated jsFiddle File
also remove .dropdown:hover from your style
Answer: You are missing to add hover code to see drop down when hover over. add css for hover.
.wrapper-dropdown-2:hover .dropdown
{
    display:block;
}

Live Demo
Comment: Thanks, but the mouse hover on the DROP DOWN is gone
Answer: You will need to initialize your javascript as well as link to jquery. I see you are using a dropdown from Codrops why dont you just download the source?
Comment: i cant work with js. Because I have a problem with 1.8.2, but I think we can find a solution with CSS
Answer: Just Replace Your This CSS
.dropdown:hover  {
  /* Size & position */
    position: absolute;
    display:block;
    top: 100%;
    left: -5px;
    right: 0px;

    /* Styles */
    background: white;
    -webkit-transition: all 0.3s ease-out;
    -moz-transition: all 0.3s ease-out;
    -ms-transition: all 0.3s ease-out;
    -o-transition: all 0.3s ease-out;
    transition: all 0.3s ease-out;
    list-style: none;

    /* Hiding */
    opacity: 0;
    pointer-events: none;
}

To My CSS and Get Result
.wrapper-dropdown-2:hover > .dropdown  {
   position: absolute;
    display:block;
    left: -45px;
       background: white;
      top:24px;
 }

CSS Drop Down List Hover mouse not work


Wanted output layer loss doesn't appear in caffe prints

Question: I'm fine-tuning an existing network, adding one output layer of my own.
The network i'm using is already tuned to recognize faces and extract the facial features.
My added layer is only added to the last part (i'm hoping there is still enough data left there), trying to extract the yaw angle.
The end of the prototxt file before my changes:
layer {
  name: "cls_prob"
  type: "Softmax"
  bottom: "fc6_3"
  top: "cls_prob"
}
layer {
  name: "bbox_reg_3"
  type: "InnerProduct"
  bottom: "fc5_3"
  top: "bbox_reg_3"
  inner_product_param {
    num_output: 3
  }
}
layer {
  name: "rotate_reg_3"
  type: "InnerProduct"
  bottom: "fc5_3"
  top: "rotate_reg_3"
  inner_product_param {
    num_output: 1
  }
}

Same segment with my changes + training changes:
layer {
  name: "cls_prob"
  type: "Softmax"
  bottom: "fc6_3"
  top: "cls_prob"
}
layer {
  name: "bbox_reg_3"
  type: "InnerProduct"
  bottom: "fc5_3"
  top: "bbox_reg_3"
  param {
    lr_mult: 0
    decay_mult: 0
  }
  param {
    lr_mult: 0
    decay_mult: 0
  }
  inner_product_param {
    num_output: 3
  }
}
layer {
  name: "rotate_reg_3"
  type: "InnerProduct"
  bottom: "fc5_3"
  top: "rotate_reg_3"
  param {
    lr_mult: 0
    decay_mult: 0
  }
  param {
    lr_mult: 0
    decay_mult: 0
  }
  inner_product_param {
    num_output: 1
  }
}
layer {
  name: "yaw_reg_3"
  type: "InnerProduct"
  bottom: "fc5_3"
  top: "yaw_reg_3"
  inner_product_param {
    num_output: 1
  }
}
layer {
  name: "loss"
  type: "EuclideanLoss"
  bottom: "yaw_reg_3"
  bottom: "label"
  top: "loss"
}

I've added yaw_reg_3, but i only see rotate_reg_3, bbox_reg_3, and cls_prob loss prints.
Thanks
Comment: is it possible you already have another layer with `name: "loss"`? please provide the log output of your net construction so we can see what you mean by "loss doesn't appear in caffe prints"
Answer: After debugging caffe itself with gdb:
After going over all the layers, if a layer doesn't appear as a bottom layer for another layer, it is determined as an output layer.
Since "yaw_reg_3" is the bottom for "loss", it is technically not an output layer, so only the loss for it is printed, and not the prediction itself.


More efficient way to grab MySQL row populated with single value

Question: Right now I'm trying to set a variable from an SQL response without doing it more than necessary.
The situation is I have a SQL result from a SELECT + JOIN query with a user_id column that has only a single value. The other columns are different per row and I need to loop through them for that data. I was wondering if there was a way to extract the homogeneous value from the user_id column without setting it over and over again to a variable in my while loop.
Code:
#where I would like the $user_id to be set
while($responseArray = $response->fetch_assoc()){
    $userId = $responseArray["user_id"]; #what I don't want to do
    #other fetching stuff
}

SQL:
SELECT users.username, users.user_id, posts.post_id, posts.post_content, posts.number_comments, comments.comment_id, comments.comment_post_id
FROM users
JOIN posts
JOIN comments
WHERE delete_bit = 0 AND username = "john";

Comment: Maybe show us your SQL... but I have a feeling you should be able to use a WHERE clause.
Comment: SELECT users.username, users.user_id, posts.post_id, posts.post_content, posts.number_comments, comments.comment_id, comments.comment_post_id FROM users JOIN posts JOIN comments WHERE delete_bit = 0 AND username = "john";
Comment: A) Does this work? I am fairly certain that `JOIN` needs an `ON` with it. B) Where/What is `posterId`
Comment: Oof. A lot of mistakes on this one. Sorry about that.
Comment: A) Based off what I saw online, I don't think it does? I might be wrong. B) I think I had some code mixed up.
Comment: I just tested the code with ON and I get the same result. The results I believe are correct. I think my discussion with Marc is probably enough from here for me.
Answer: You cannot get away from fetching at least one result row. Even the fetchOne()-type functions do this. But if you only want a single row, why even bother using a loop in the first place?
$result = $db->query(...);
$row = $result->fetchRow();
$value = $row['somefield'];

would be far better than something silly like
$result = $db->query(...);
while($row = $result->fetchRow()) {
    $value = $row['somefield'];
    break;
}

Comment: Oh. I typed it wrong. There's a column with all the same value. My bad.
Comment: you can't set the value outside the loop - you **HAVE** to fetch a row to get any data out of the query. if you fetch a row outside the loop just to get posterID, you'll also fetch all the OTHER fields in the result set for that row as well,w hich means you've now got one less row for the while() loop to deal with. don't worry if the posterID is the same in all rows. the microscopically minuscule overhead of setting the same value over and over is nothing to worry about it.
Comment: Ok. I was just worried that it was stylistically a bad choice. In my brain it kind of felt like a "hack" to just keep setting it each iteration.
Comment: no, it's not really a hack. but if the value doesn't change over the query set, then technically it could be regarded as a primary key for that result set e.g. `select foo, bar from baz where foo=$val` - you don't need to fetch `foo` in the first place, because you already have the only value it could ever be in `$val`.
Comment: mmm... It's kind of like that. In more detailed in terms of my situation, each user has a username and user_id. The user_ids are the primary key in my database. When I do my query, I'm trying to grab the user_id with the username and everything else in one query to reduce overhead. I unfortunately have to just add that primary-key-like value to my response.


Is there a way to predict multiple columns of NA values in a dataset using R?

Question: I have a data set that has 9 different variables, but 3 of the variables aren't complete. I'd like to find a way to use a prediction model to fill in those variables, but was wondering if there was a way to do it for all 3 at once, rather than creating 3 different regressions, then 20 different datasets for each line of data and then plugging it into the Predict() function. I feel like I'm doing a ton of unnecessary work but haven't found anything online for how to do what I'm looking for. I know how to do it in Stata, but would much rather use R for my work.
Comment: It might help if you explain what method you are using in Stata (not the details of the code, just the underlying machinery) so that people could point you to R equivalents ...
Answer: Check out the missing data view on CRAN:  here
A popular R package for imputation (which is the name of this general area of research) is mice:  here
Comment: I affirm that mice is one of the most popular packages to do what OP is asking. Here's a simple tutorial that shows how to impute missing values with mice: https://appsilon.com/imputation-in-r/.


Traefik SSL for a service that runs on non-standard port

Question: Disclaimer: My Docker and my Traefik knowledge is weak. I have several times tried following the Traefik docs and I usually just get confused, possibly because I want to tackle more than the simplest of cases but also, I'm sure I am missing some fundamentals.
In my current setup, I can create a web-based (port 80) Docker service that Traefik v2 picks up, creates a LE cert, redirects from http:80 to https:443, and exposes. Below is my docker-compose.yml for Traefik and also one for a sample service that works.
Let's say, however, that my web-based service really wants to run on a port other than 80. For instance, I want to run statping, which runs on port 8080. Is it possible, given the SSL setup that I currently have, to wire it up such that I can expose the entry point http://statping.MYTLD and rely on Traefik to: 1. redirect to https://statping.MYTLD, 2. obtain the certificate, and 3. expose my statping Docker container? Can Traefik handle the Acme http challenge even though the underlying service is not running on port 80? I figure it can, since my working sample isn't even exposing a port past the container level.
Note: I am most familiar with Docker Compose but perhaps for a service like statping, I need to figure out how to write my own DOCKERFILE so that I can cajole it into running on port 80 instead of port 8080?
Thanks for any insight!
Traefik docker-compose.yml:
version: "3.3"

networks:
  traefik:
    external: true

services:

  traefik:
    image: "traefik:v2.3"
    container_name: "traefik"
    command:
      #- "--log.level=DEBUG"
      - "--api.insecure=true"
      - "--providers.docker=true"
      - "--providers.docker.exposedbydefault=false"
      - "--entrypoints.web.address=:80"
      - "--entrypoints.websecure.address=:443"
      - "--entrypoints.web.http.redirections.entryPoint.to=websecure"
      - "--entrypoints.web.http.redirections.entryPoint.scheme=https"
      - "--entrypoints.web.http.redirections.entrypoint.permanent=true"

      - "--certificatesresolvers.myresolver.acme.httpchallenge=true"
      - "--certificatesresolvers.myresolver.acme.httpchallenge.entrypoint=web"

      # FOR TESTING.
      #- "--certificatesresolvers.myresolver.acme.caserver=https://acme-staging-v02.api.letsencrypt.org/directory"

      - "--email@example.com"
      - "--certificatesresolvers.myresolver.acme.storage=/letsencrypt/acme.json"

    ports:
      - "80:80"
      - "443:443"
      - "8080:8080"

    volumes:
      - "./letsencrypt:/letsencrypt"
      - "/var/run/docker.sock:/var/run/docker.sock:ro"

Sample service docker-compose.yml:
version: "3.3"

networks:
  traefik:
    external: true

services:

  whoami2:
    image: "traefik/whoami"
    container_name: "simple-service2"
    labels:
      - "traefik.enable=true"
      - "traefik.http.routers.whoami2.rule=Host(`whoami2.MYTLD`)"
      - "traefik.http.routers.whoami2.entrypoints=websecure"
      - "traefik.http.routers.whoami2.tls.certresolver=myresolver"

    networks:
      - traefik

    restart: unless-stopped

Answer: From the traefik docs:

If a container exposes multiple ports, or does not expose any port,
then you must manually specify which port Traefik should use for
communication by using the label
traefik.http.services.<service_name>.loadbalancer.server.port (Read
more on this label in the dedicated section in routing).

So if whoami was listening on 8080 and didn't expose exactly one port, you should specify the label:
"traefik.http.services.whoami2.loadbalancer.server.port=8080"

Comment: Works! Thank you. Yes, now that you point me to that specific section of the docs, it does explain it.


Loading a View Through Ajax - Slideshow not showing

Question: I have a view in node-view mode that has another view (a view slideshow) embedded into that view. I am using jquery and setTimeout to slideDown the hidden div that contains the view a few seconds after the page loads. The problem that I am running into is when the div slides down to show the view, the slideshow is not showing.
Here's my jquery
Drupal.behaviors.landing = function (context) {
if($('#portslide-wrap').children().children().next().hasClass('portfolio-direct')){

    setTimeout( function getSlide(){
        $('#portslide-wrap:not(.landing-processed)', context).addClass('landing-processed').each(function(){

            $('#portslide-wrap').slideDown();
            $.scrollTo('165','0');
            Drupal.attachBehaviors(context);

        });
    }   ,700)
  };

}

Answer: Are you using a Drupal module like Views Slideshow to create your slideshow?
Usually slideshows will need to dynamically calculate the height/width of the content in the slides in order to render correctly. If the slideshow is hidden when the slideshow's javascript is loaded, then there will effectively be no content for the slideshow's javascript to render, thus the slideshow will never render correctly.
Does the slideshow render with no problems if you remove your CSS and/or JS that hides (and then slides down) the slideshow?
I haven't dealt with this sort of issue directly, but hopefully I can point you in the right direction. I would guess that somewhere you are using JS or CSS to hide the #portslide-wrap div (i.e. display:  none;) until it is ready to slide down? I would suggest trying to hide that div behind some other element using z-index rather than display:none(so that the slideshow can render while being obscured) and then hide it using JS after the slideshow has processed (probably a class like "slideshow-process" is added to a wrapping div, which you can use to hide the slideshow via CSS).
Comment: Yep, I'm using the views slideshow module...and it does render correctly if I remove `display:none` from the class. I think this is a good start. I'll give it a try.
Answer: Old question, but if someone finds this via Google then this should help. The above JavaScript is close. Try:

(function($) {
  Drupal.behaviors.myFuncName = {
    attach: function(context, settings) {
      console.log('Do stuff');
    }
  };
})(jQuery);

There is no need to call Drupal.attachBehaviors unless you are returning new elements for the DOM. In that case your context variable would be the new elements. It's also worth noting that you are missing the "settings" object in the arguments of the function you are trying to attach.


Bitbucket: Update a fork to merge changes of master repo?

Question: I am working with a bitbucket git repo I have read-only access to, so I created a fork to work on my features.
Question: How do I update my fork to include changes made to the original repo made by the owner?
On github, it seems one has to do the following, so I suspect it's a similar to this:
 $ git remote add upstream git://github.com/octocat/Spoon-Knife.git
 $ git fetch upstream
 $ git merge upstream/master

I couldn't find any information on this in the Bitbucket Documentation for forking
Answer: Just like GitHub, you have to pull the commits down to your own machine, merge, and then push them back to your fork on Bitbucket.
If you go to your fork on Bitbucket you can click "compare fork" to get to a page where you see incoming and outgoing commits. If you go to the "incoming" tab, you will see instructions like
$ git remote add <remote_name> firstname.lastname@example.com:<upstream>/<repo>.git
$ git fetch <remote_name>
$ git checkout master
$ git merge <remote_name>/master

which correspond closely to the GitHub instructions.
Comment: Regarding the `merge` command, I have to use it without the leading `remotes/`
Comment: What does the `git checkout master` achieve here? Can it be done as step 1 or 2 or 3 since it only effects the local repo?
Comment: For me the `git remote add` needs to be without specifying the protocol `ssh://`. Just use `email@example.com:/.git
Answer:
Goto your fork on bitbucket
Click the Branches menu from the left navigation pane
Click on the "..." button to the right of the branch and select "Compare". Or, in the url add the word "compare". So that the URL looks like this: https://bitbucket.org/<user name>/<fork name>/branches/compare
Click on the switch icon (black up/down arrows between the branch segments) so that the blue arrow is pointing into your fork
Select the correct branches in your fork and the owner's repo
Click Compare
Click Merge
Answer: Here comes the easiest way...

Go to your forked repo.
Select Repository Settings.
Select Fork syncing tab.
Uncheck Enable fork syncing toggle.
Check Enable fork syncing toggle again.

It should update the Last automatic synchronization timestamp.
Comment: I do not see such setting in my repo settings, even though  I forked.
Answer: On the left hand side, the repository details panels shows a SYNC button IF AND ONLY IF there is any commit behind
Comment: That....forking button only appears if there is any newer commits and this is not written on any documentation. That's not very intuitive.
Comment: In Atlassian softwares is nothing intuitive. This button should be on very top of the UI appear. Seem like the devs wanted this to hide from customers :)
Answer: In the latest version there is a Repository-Details box on the right side with a sync button if the root has unmerged updates.
Answer: On Repository settings -> Fork Syncing
Uncheck & check option "Enable fork syncing"
You will see a message Last automatic synchronization: a moment ago
Answer: In Bitbucket, using the "Enable Fork Syncing" feature for your forked repo makes it super easy to pull new changes from the original repo into the forked repo.
e.g.

There is an original repo, and you create a forked repo.
While creating a fork on the bitbucket website, there is a check box for "Enable Fork Syncing", please check it.
Next, clone the forked repo into your local and create a feature branch from the master branch.

(master) $ git checkout -b feature

Anytime you want to pull new commits from the original repo into the master branch, run the below commands:

# below git command will fetch all the changes from the original repo's master branch
# into your local's master branch because we had enabled fork syncing.
(feature) $ git fetch origin master:master

# use merge or rebase as per your preference
(feature) $ git rebase master

Documentation @ https://confluence.atlassian.com/bitbucketserver/keeping-forks-synchronized-776639961.html


MX records for a domain with a CNAME

Question: Given something like this:
xxx.net.            CNAME    surrogate-xxx.net.
www.xxx.net.        CNAME    surrogate-xxx.net.
mail.xxx.net.       A        220.127.116.11
xxx.net.            MX       mail.xxx.net.

surrogate-xxx.net.  A        126.96.36.199

Should mail for xxx.net go to 188.8.131.52, as directed by the MX record, or to 18.104.22.168, as directed by the A record to which the CNAME points.
Comment: Most dns servers will not load this zone, as 'xxx.net' has "CNAME and other data' - namely the SOA, so it most likey won't get served.
Comment: You probably have messed up the dots in your example - it looks like it should be xxx.net. (note the trailing dot).
Answer: Actually the zone as noted here is considered a bad practice. Defining a CNAME for the label xxx.net just "remaps" all RRs of xxx.net. to surrogate-xxx.net. including the MX record. Defining the MX RR for xxx.net. is asking for trouble. RFC-1034 has a clear statement on this topic:

If a CNAME RR is present at a node, no other data should be present;
  this ensures that the data for a canonical name and its aliases cannot
  be different.  This rule also insures that a cached CNAME can be used
  without checking with an authoritative server for other RR types.

Further reading here.
Answer: Mail will flow to mail.xxx.net in that scenario.
Mail will flow to whatever the MX record(s) points to.
Now, if your MX record points to mail.xxx.net and mail.xxx.net points via CNAME to surrogate-mail.xxx.net, mail will flow to surrogate-mail.xxx.net.  Your MX record points to an endpoint - how you define that endpoint - A record, CNAME, etc. is up to you.

MX records for a domain with a CNAME


support.PluginAwareResourceBundleMessageSource Could not resolve any resources for plugin

Question: war file deploy to tomcat fails with a bunch of messages about plugins not found, these seem to be core plugins. It's my first deploy so likely this is a pretty basic question.
Am I missing some standard dependency?
support.PluginAwareResourceBundleMessageSource Could not resolve any resources for plugin logging-2.1.1
java.io.FileNotFoundException: ServletContext resource [/WEB-INF/plugins/logging-2.1.1/grails-app/i18n/] cannot be resolved to URL because it does not exist
        at java.lang.Thread.run(Thread.java:662)
support.PluginAwareResourceBundleMessageSource Could not resolve any resources for plugin core-2.1.1
java.io.FileNotFoundException: ServletContext resource [/WEB-INF/plugins/core-2.1.1/grails-app/i18n/] cannot be resolved to URL because it does not exist
        at java.lang.Thread.run(Thread.java:662)
support.PluginAwareResourceBundleMessageSource Could not resolve any resources for plugin url-mappings-2.1.1
java.io.FileNotFoundException: ServletContext resource [/WEB-INF/plugins/url-mappings-2.1.1/grails-app/i18n/] cannot be resolved to URL because it does not exist
        at java.lang.Thread.run(Thread.java:662)

app.grails.version=2.1.1
Simple application runs fine local desktop from
Eclipse SpringSource Tool Suite
Version: 2.9.2.RELEASE
Build Id: 201205071000
BuildConfig.groovy
grails.servlet.version = "2.5" // Change depending on target container compliance (2.5 or 3.0)
grails.project.class.dir = "target/classes"
grails.project.test.class.dir = "target/test-classes"
grails.project.test.reports.dir = "target/test-reports"
grails.project.target.level = 1.6
grails.project.source.level = 1.6
//grails.project.war.file = "target/${appName}-${appVersion}.war"

grails.project.dependency.resolution = {
    // inherit Grails' default dependencies
    inherits("global") {
        // specify dependency exclusions here; for example, uncomment this to disable ehcache:
        // excludes 'ehcache'
    }
    log "debug" // log level of Ivy resolver, either 'error', 'warn', 'info', 'debug' or 'verbose'
    checksums true // Whether to verify checksums on resolve

    repositories {
        inherits true // Whether to inherit repository definitions from plugins

        grailsPlugins()
        grailsHome()
        grailsCentral()

        mavenLocal()
        mavenCentral()

        // SendGrid repo http://grails.org/plugin/sendgrid
        mavenRepo "http://repo.desirableobjects.co.uk/"

        mavenRepo "http://m2repo.spockframework.org/snapshots"
        // uncomment these (or add new ones) to enable remote dependency resolution from public Maven repositories
        //mavenRepo "http://snapshots.repository.codehaus.org"
        //mavenRepo "http://repository.codehaus.org"
        mavenRepo "http://download.java.net/maven/2/"
        //mavenRepo "http://repository.jboss.com/maven2/"
        //mavenRepo "http://download.java.net/maven/2/"
    }
    dependencies {
        // specify dependencies here under either 'build', 'compile', 'runtime', 'test' or 'provided' scopes eg.
        //
        // runtime 'mysql:mysql-connector-java:5.1.20'
        //test "org.spockframework:spock-grails-support:0.7-groovy-1.7"

    }

    plugins {
        runtime ":hibernate:$grailsVersion"
        runtime ":jquery:1.8.0"
        runtime ":resources:1.1.6"
        runtime ":mail:1.0.1"
        runtime ':sendgrid:0.2'

        // Uncomment these (or add new ones) to enable additional resources capabilities
        //runtime ":zipped-resources:1.0"
        //runtime ":cached-resources:1.0"
        //runtime ":yui-minify-resources:0.1.4"

        build ":tomcat:$grailsVersion"

        runtime ":database-migration:1.1"

        compile ':cache:1.0.0'
        compile ":marshallers:0.4"
        //compile ":restrpc:0.9.6"
        runtime ":webxml:1.4.1"
        compile ":rabbitmq:1.0.0"

        test ":spock:0.7"
// add this for Grails 2.2 uses Groovy 2.0, when we upgrade
//              {
//              exclude "spock-grails-support"
//              }
    }
}

Comment: Now I get the answer from the other guy!
That's a message cause my app is in debug mode.  But doesn't stop the application, I had an error later that was in fact deadly to the application, hence the reason it wouldn't start.

Thus his comment about fixing a db conf or something.  Same thing here, the app was dying because of something else.   Now I fixed that, and the message warnings are still there.

:(
Answer: Tomcat fails to start app and times out -- last line in log is just the word "bad"
This question basically indicated that it was another problem. The real answer is that this was not causing the final war application startup problem, it was in his case the database config and in my case the rabbitmq config.
The verbose debug logging shows the error, the failure to startup is the fault of another error, this message can be effectively ignored.


Determining a coefficient in equations for planes, for which the planes do not have any point in common

Question: I have four planes in an ordinary orthogonal
(x, y, z)-coordinate system – given by the equations:
$$
\begin{cases}
α_1 :& x &+ 2ay + az &= a^2 \\
α_2 :& x &+ ay + az &= a  \\
α_3 :& x &+ a^2 z &= a^3 \\
α_4 :& ax &+ ay + a^2 z &= a \\
\end{cases}
$$
I'm asked to find a value for (a), for which the four planes do not have any point in common. What steps do you recommend taking towards a solution?
Comment: Welcome to MSE. Please read this text about [how to ask a good question](https://math.meta.stackexchange.com/questions/9959/how-to-ask-a-good-question).
Answer: Consider following system os equations:
$$\begin {cases} Ax+By+Cz=D \\A_1x+B_1y+C_1z=D_1\end{cases}$$
If:
$$\frac{A_1}A=\frac{B_1}B=\frac{C_1}C=\frac{D_1}D$$
then the system is consistent and it represent a line. Now we find thses for for equations:
1&2: $1/1=1,2a/a=2, 1/1=1, a^2/a=a$ or $(1, 2, 1, a)$
2&3: $(1, 0, a, a^2)$
3&4: $(1/a, 0, a, a^2)$
1&4: $(a, 1/2, a, 1/a)$
1&3: $(1, 0, a, a)$
2&4: $(a, 1, a, 1)$
As can be seen all systems of couple of plains are not consistent for any $a$ except the system of the couple 2&4 which can be consistent if $a=1$. Hence the condition is $a\neq 1$


What is the correct way of embedding tweets using twitter api

Question: I am working on a website where I want to show the most recent 3 tweets from my Twitter profile. There is a way to embed the tweets by using the publish.twitter.com URL, the problem with this method is that I cannot style my embedded tweets and it doesn't even show the number of likes and retweets. I want to get the recent tweets using the Twitter API where I am in control of the embedded tweets and can style them.
here is what I am using to embed tweets on my website.

     Tweets by dev_taimoor

I need to know a way of using Twitter API through javascript so that I can fetch tweets. I did some research but none of the articles were helpful for me.
Answer: Have you checked @Jason_mayes Twitter fetcher https://codepen.io/jasonmayes/pen/ndWRdd
see code above
Comment: Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer).


How can I find the remainder of this polynomial division?

Question: This is for algebra 2 honors. Of course I can long divide or use synthetic, but that would take a while.

Determine the remainder of
$$\frac{2x^{100}-3x+4}{x-1}$$
Comment: The remainder on dividing a polynomial $P(x)$ by $x-a$ equals $P(a)$.
Answer: If $r$ is the remainder of dividing $2x^{100}-3x+4$ by $x-1$, then $r$ is a constant and there exists a polynomial $q$ such that
$$p=2x^{100}-3x+4=q(x-1)+r,$$
which shows that $p(1)=r(1)=r$, so $r=3$.
Answer: It's a theorem that the remainder  on dividing a polynomial $p(x)$ by $x-\alpha$ is simply $p(\alpha)$.
Comment: Why the downvote, without any explanation?
Answer: The short, easy answer is that the remainder when you divide a polynomial $p(x)$ by $x-a$ is $p(a)$. This is a very useful fact, and not hard to prove.
However, even if you've forgotten this, brute force isn't as slow as you suggest, provided that you keep your eyes open and spot the pattern. The first stage of an ordinary long division gives you a partial quotient of $2x^{99}$ and a remainder of $2x^{99}-3x+4$. The next stage extends the partial quotient to $2x^{99}+2x^{98}$ and leaves you a remainder of $2x^{98}-3x+4$. Clearly this is going to continue until at some point you have a partial quotient of
$$2x^{99}+2x^{98}+\ldots+2x^2$$
and a remainder of $2x^2-3x+4=(x-1)(2x-1)+3$.
Answer: The remainder theorem says the remainder of $f(x)$ when divided by $(x-a)$ is $f(a)$ so the answer would be: $2\times1^{100}-3x+4=3$.
If instead you wanted to work out the quotient that is a bit harder. If you let $t=x-1$ then you can rewrite it as:
$$\frac{2(t+1)^{100}-3(t+1)+4}{t}=\frac{2\left(\sum_{n=0}^{100}{100\choose n}t^n\right)-3t+1}{t}$$
$$=2\left(\sum_{n=1}^{100}{100\choose n}t^{n-1}\right)-3+\frac{3}{t}$$
Substituting back for $x$ will then give:
$$=2\left(\sum_{n=1}^{100}{100\choose n}(x-1)^{n-1}\right)-3+\frac{3}{x-1}$$
$$=2\left(\sum_{n=1}^{100}{100\choose n}\sum_{i=0}^{n-1}(-1)^ix^{i}\right)-3+\frac{3}{x-1}$$
$$=2\sum_{n=0}^{99}x^n-3+\frac{3}{x-1}$$
$$=2\sum_{n=1}^{99}x^n-1+\frac{3}{x-1}$$


What type of unsolvable theory is Elementary Function Arithmetic ($EFA$)?

Question: It is known that Robinson Arithmetic ($Q$) is essentially undecidable.  Is Elementary Function Arithmetic ($EFA$) also essentially undecidable, and what is the Turing degree of its decision problem?
Answer: Since $\mathsf{EFA}$ is a consistent computably axiomatizable theory interpreting $\mathsf{Q}$, it is also essentially undecidable and its decision problem also has Turing degree ${\bf 0'}$. Same for Peano arithmetic, $\mathsf{ZFC}$, etc.
Broadly speaking, computability-theoretic complexity is an extremely coarse invariant. Another instance of this general theme is the result that, for example, the following are equivalent for a Turing degree ${\bf d}$:

${\bf d}$ computes a consistent completion of $\mathsf{Q}$ (usually "$\mathsf{PA}$" is quoted here instead of $\mathsf{Q}$, yielding e.g. the term "$\mathsf{PA}$ degree," but the result holds for $\mathsf{Q}$ too).

For every consistent computably axiomatizable theory $T$, ${\bf d}$ computes a consistent completion of $T$.

(In my opinion this equivalence is demystified when we add a third equivalent condition: "${\bf d}$ computes separating sets for every pair of disjoint c.e. sets." But that's just me.)
More fine-grained computability-theoretic distinctions can be found if we bring some semantics into play. For example, $\mathsf{Q}$ has computable nonstandard models but $\mathsf{PA}$ doesn't, and I'm not sure what the situation for $\mathsf{EFA}$ is (but I suspect it lies on the "$\mathsf{PA}$-like" side). But at least for the specific questions you've asked, all the "vaguely foundational" theories look the same.
Comment: @NoahSchwebet:  Thanks, this is helpful.
Comment: Correction:  Noah Schweber.