Volume of solid $W$ delimited by $z=x^2+3y^2$ and $z=8-x^2-y^2$.

Question: Volume of solid $W$ delimited by $z=x^2+3y^2$ and $z=8-x^2-y^2$.
I need to solve this with triple integrals, however I'm having a lot of problems. Anyone knows how to solve?
Answer: The hard part of such problems is to imagine the volume enclosed by the surfaces and describing the points inside the volume in a mathematical language so that you can determine the limits of integration.
It seems that the two surfaces are some parabolic surfaces facing toward each other. You may imagine some picture in your mind like the figure below
$\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,$
So, first we find the intersection of the two surfaces as it bounds the variation of $x$ and $y$ coordinates of the points inside this volume. Hence, consider the following
$$\eqalign{
  & {x^2} + 3{y^2} = 8 - {x^2} - {y^2}  \cr
  & 2{x^2} + 4{y^2} = 8  \cr
  & {{{x^2}} \over 4} + {{{y^2}} \over 2} = 1  \cr
  & {\left( {{x \over 2}} \right)^2} + {\left( {{y \over {\sqrt 2 }}} \right)^2} = 1 \cr} $$
and hence all points $(x,y,z)$ which lie on both surfaces satisfy
$$\matrix{
   {\left\{ \matrix{
  {\left( {{x \over 2}} \right)^2} + {\left( {{y \over {\sqrt 2 }}} \right)^2} = 1 \hfill \cr
  z = {x^2} + 3{y^2} \hfill \cr}  \right.\,\,\,\,\,or\,\,} & {\left\{ \matrix{
  {\left( {{x \over 2}} \right)^2} + {\left( {{y \over {\sqrt 2 }}} \right)^2} = 1 \hfill \cr
  z = 8 - {x^2} - {y^2} \hfill \cr}  \right.}  \cr
 } $$
which are two different equations of the same intersection curve. Now, we are ready to describe the coordinates of the points inside the volume in some mathematical language
$$\Omega  = \left\{ {\left( {x,y,z} \right)| - 2 \le x \le 2, - \sqrt {2 - {1 \over 2}{x^2}}  \le y \le \sqrt {2 - {1 \over 2}{x^2}} ,{x^2} + 3{y^2} \le z \le 8 - {x^2} - {y^2}} \right\}$$
and hence your triple integral will be
$$\eqalign{
  & \mathop{\int\!\!\!\int\!\!\!\int}\limits_{\kern-5.5pt \Omega }
 {dV}  = \int\limits_{x =  - 2}^2 {dx\int\limits_{y =  - \sqrt {2 - 0.5{x^2}} }^{\sqrt {2 - 0.5{x^2}} } {dy\int\limits_{z = {x^2} + 3{y^2}}^{8 - {x^2} - {y^2}} {dz} } }  = \int\limits_{x =  - 2}^2 {\int\limits_{y =  - \sqrt {2 - 0.5{x^2}} }^{\sqrt {2 - 0.5{x^2}} } {\int\limits_{z = {x^2} + 3{y^2}}^{8 - {x^2} - {y^2}} {dzdydx} } }   \cr
  & \,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\, = \int\limits_{x =  - 2}^2 {\int\limits_{y =  - \sqrt {2 - 0.5{x^2}} }^{\sqrt {2 - 0.5{x^2}} } {\left[ {\left( {8 - {x^2} - {y^2}} \right) - \left( {{x^2} + 3{y^2}} \right)} \right]} } dydx  \cr
  & \,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\, = \int\limits_{x =  - 2}^2 {\int\limits_{y =  - \sqrt {2 - 0.5{x^2}} }^{\sqrt {2 - 0.5{x^2}} } {\left( {8 - 2{x^2} - 4{y^2}} \right)dydx} }   \cr
  & \,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\, = 4\int\limits_{x =  - 2}^2 {\int\limits_{y = 0}^{\sqrt {2 - 0.5{x^2}} } {\left( {4 - {x^2} - 2{y^2}} \right)dydx} }   \cr
  & \,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\, = 4\int\limits_{x =  - 2}^2 {\left[ {\left( {4 - {x^2}} \right)y - {2 \over 3}{y^3}} \right]} _0^{\sqrt {2 - 0.5{x^2}} }dx = 4\int\limits_{x =  - 2}^2 {\left[ {\left( {\left( {4 - {x^2}} \right) - {2 \over 3}{y^2}} \right)y} \right]} _0^{\sqrt {2 - 0.5{x^2}} }dx  \cr
  & \,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\, = 4\int\limits_{x =  - 2}^2 {\left[ {\left( {{8 \over 3} - {2 \over 3}{x^2}} \right)\sqrt {2 - 0.5{x^2}} } \right]dx}   \cr
  & \,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\, = {{32} \over 3}\int\limits_{x = 0}^2 {\left[ {\left( {2 - 0.5{x^2}} \right)\sqrt {2 - 0.5{x^2}} } \right]dx}   \cr
  & \,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\, = {{32} \over 3}\left( {{{3\sqrt 2 \pi } \over 4}} \right) = 8\sqrt 2 \pi  \cr} $$
Comment: Nice visual  representation
Comment: @EmirŠemšić: Thanks. :)
Answer: Let's first find the boundary of the integration region, that is, where both surfaces intersect:
$z=x^2+3y^2=8-x^2-y^2$ thus $2x^2+4y^2=8$ thus it's the ellipse $\frac{x^2}{2^2}+\frac{y^2}{\sqrt 2^2}=1$ in the $xy$ plane.
Now let $E$ be the plane region bounded by that ellipse. The volume of $W$ is then $\displaystyle\iint_E\left(8-x^2-y^2-(x^2+3y^2)\right)\,dx\,dy=\iint_E\left(8-2 x^2-4 y^2\right)\,dx\,dy$.
In order to define the integration limits one should change coordinates as follows: $x=2\,r\cos\theta$, $y=\sqrt2\,r\sin\theta$, so that the bounding ellipse is simply $r=1$, $0\leq\theta\leq2\pi$ in the new coordinates. Now let's calculate the Jacobian:
$\displaystyle J=\begin{vmatrix}\frac{\partial x}{\partial r}&\frac{\partial x}{\partial \theta}\\\frac{\partial y}{\partial r}&\frac{\partial y}{\partial \theta}\end{vmatrix}=\begin{vmatrix}2\cos\theta&-2\,r\sin\theta\\\sqrt2\sin\theta&\sqrt2\,r\cos\theta\end{vmatrix}=2\sqrt2\,r$.
Therefore, the volume is
$\displaystyle\iint_E\left(8-2 x^2-4 y^2\right)\,dx\,dy=\int_0^1\int_0^{2\pi}\left(8-2\cdot4r^2\cos^2\theta-4\cdot2r^2\sin^2\theta\right)2\sqrt2\,r\,d\theta\,dr=8\cdot2\sqrt2\int_0^1(1-r^2)r\,dr\int_0^{2\pi}d\theta=8\cdot2\sqrt2\frac14\cdot2\pi=8\sqrt2\pi$.


Android REST with Spring handle too long request

Question: I am building a REST App with Spring. I am doing it the POJO way. Now I want to handle a GET Request that takes too long (lets say because the user has a very bad connection). What can I do to handle this (in Spring), maybe by canceling the request after 5000ms?
My approach:
So I guess there is a need for some kind of timeout. On my google-tour I found that there is a HttpComponentsClientHttpRequestFactory and a so called setConnectTimeout() Function. I tested that but I can't handle the thrown Exception because its "to deep inside" and it gets passed out as a Fatal Exception of the AsyncTask. So I failed.
Whats the best practice? Any Idea?
edit:
Spring is set, so please only Spring solutions.
edit:
According to my research its not possible. Even @ Spring Forums is no answer yet: http://forum.springsource.org/showthread.php?135656-How-can-I-handle-GET-requests-that-are-taking-to-long
Answer: First of all, don't use an AsyncTask to perform network request because if you change the orientation of your device, Activity is destroyed and after recreated but the AsyncTask keep a reference on the destroyed Activity and cause some memory leaks.
Use Service instead. I suggest you to use RoboSpice. It's a library to easily make REST request with POJO and Spring.
If you're interesting in automatic local & remote data persistency management, you can use RestDroid to handle that (also with POJO).
Both library use RequestListeners to manage the case you're talking about. When your request failed, the UI is notify.
Answer: Why not taking a simpler approach,
try this code and you'll get a more explicit exception:
<code>HttpParams httpParameters = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParameters, 5000);
HttpConnectionParams.setSoTimeout(httpParameters, 10000);

HttpClient client = new DefaultHttpClient(httpParameters);
HttpGet request = new HttpGet(url);

HttpResponse response = client.execute(request);
</code>
Comment: Nope, it's Android's client side.


A Question About Little-O Notation

Question:
How could the following be interpreted:
  $$ h(t)=\dfrac{1+o(1)}{(2 \pi)^{3/2}\sqrt{t}} \; \; \; \text{as} \; t\downarrow0 \tag{1} $$
  Where $o(1)$ is the little-o notation.

From my understanding, if we say that $$f(x)=o(g(x)) \; \; \text{as} \; t \downarrow 0$$ then this means that $$\dfrac{f(x)}{g(x)} \to 0 \; \; \text{as} \; t\downarrow0$$
Now from (1) am I allowed to say that
$$ (2 \pi)^{3/2}\sqrt{t}\cdot h(t) -1 =o(1) \; \; \text{as} \; t\downarrow 0 \tag{2}$$
And then by applying the definition of little-o notation to (2), we see that
$$ (2 \pi)^{3/2}\sqrt{t}\cdot h(t) -1 \to 0 \; \; \text{as} \; t \downarrow 0 $$
Or should I interpret (1) in a different way?
Answer: What you said is correct, and you can also think of it as saying there exists $f$ in $o(1)$ as $t\to0$ such that
$$h(t) = \frac{1+f(t)}{(2\pi)^{3/2}\sqrt{t}}$$
Answer: I would write
$h(t)=\dfrac{1+o(1)}{(2 \pi)^{3/2}\sqrt{t}}
$
as
$h(t)=\dfrac{1}{(2 \pi)^{3/2}\sqrt{t}}
+o(\dfrac1{\sqrt{t}})
$
so that
$h(t)-\dfrac{1}{(2 \pi)^{3/2}\sqrt{t}}
=o(\dfrac1{\sqrt{t}})
$
or
$\sqrt{t}(h(t)-\dfrac{1}{(2 \pi)^{3/2}\sqrt{t}})
\to 0
$
or
$\sqrt{t}h(t)-\dfrac{1}{(2 \pi)^{3/2}}
\to 0
$
or
$\sqrt{t}h(t)\to\dfrac{1}{(2 \pi)^{3/2}}
$.
Comment: Why does $$\dfrac{1+o(1)}{(2 \pi)^{3/2}\sqrt{t}} =\dfrac{1}{(2 \pi)^{3/2}\sqrt{t}}
+o(\dfrac1{\sqrt{t}})$$
Comment: Because you split the added terms and big-oh and little-oh allow you to ignore constant multipliers.

A Question About Little-O Notation


Default Gateway in a VLAN

Question: Could I have a router/firewall device providing WAN connectivity, part of a VLAN on a switch?
For example:
2, L3 Switches. 2 VLANs
DefaultVLAN  10.1.1.0/24
VLAN100      192.168.1.0/24

Two Internet lines - irrelevant what they are. Both controlled by two Firewalls. I need all VLAN traffic for DefaultVLAN down one WAN, thus one firewall, and the other VLAN100 down the other.
DHCP:
Two ranges, 10.1.1.0/24 and 192.168.1.0/24 handing out as the DG, the IP of the switches respectively. In this instance, the 10.1.1.0 range gives out the IP for SW02 as the DG for clients. And the 192.168.1.0/24 range gives out the IP of SW01 for clients.
Switches:
SW01, IP's - Default VLAN IP: 10.1.1.10 - VLAN100 IP: 192.168.1.10
SW02, IP's - Default VLAN IP: 10.1.1.11 - VLAN100 IP: 192.168.1.11

Firewalls:
FW01: 192.168.1.1
FW02: ? (Please read on)

Switches:
SW01, Default Gateway of Switch set to: 192.168.1.1
SW02, Default Gateway of Switch set to: ?

So now how do I separate it, I want the 10.1.1.0/24 clients VLAN to have the other FW02 as their default gateway?
Comment: You don't need two firewalls for starters... but typically you'd create a VLAN interface on your layer 3 for each VLAN; this becomes the default gateway for that VLAN.  Create a small /29 network (or /24, but you don't need all those IPs) between the L3 switch and the firewall, add your policy routes (based on source subnet) on your firewall, add both your WAN connections to said firewall... done. EDIT: putting in answer.
Answer: You don't need two firewalls (unless they support failover/high availability) for starters.
Get a decent business class firewall.  Cisco ASA 5500 series, Sonicwall TZ 105, pfSense, etc.
Add both WAN connections to the one firewall; I'd probably set them up in at least a failover configuration, but whatever.  Your call.
Assuming we're dealing with one L3 switch you've already bought, you can create a VLAN interface for your two VLANs (VLAN 1: 192.168.1.0/24, VLAN interface: 192.168.1.1; VLAN 100: 10.1.1.0/24 VLAN interface: 10.1.1.1).  These become the default gateway for the nodes on each VLAN respectively.  Whether that's DHCP or not, out of scope for this question.
Create another VLAN, say VLAN 10.  172.16.0.0/29.  Set the LAN interface of your firewall to an IP on this subnet (172.16.0.1/29) and create a VLAN interface on same subnet (172.16.0.2/29).  Assign a port to this VLAN and uplink into your firewall from that port.  You should be able to ping the firewall's LAN interface from within the console of the L3 switch.
Update/create the default route on the L3 switch like so 0.0.0.0 0.0.0.0 gw 172.16.0.1 (pseudo-syntax as obviously it will vary depending on switch make/model, but we want to create a default route to the firewall's LAN interface).
On the firewall, create a route back to your VLAN subnets like so (192.168.1.0 255.255.255.0 gw 172.16.0.2 and then 10.1.1.0 255.255.255.0 gw 172.16.0.2).
On the firewall, you'll want to look at policy based routing, policy routing, source based routing, etc. (depends on what you get but any half decent router/firewall should support this) but basically you'll want to add a routing rule/policy that looks at the source subnet and assigns a WAN gateway accordingly.
If you don't have a L3 and you're not anticipating a lot of interVLAN routing (i.e. 100s of workstations talking to dozens of servers on different VLANs), don't waste your money on one.  Any decent firewall's going to have several physical interfaces (or even one will work with router on a stick, but again, depends on traffic requirements, etc.) and these can take the place of the VLAN interfaces: just carve up a L2 switch into two VLANs like we discussed already, but instead of assigning interfaces (which you likely can't) to the VLAN virtual interfaces, you'll be uplinking into interface LAN1 and LAN2 (or whatever) on the firewall and let it to do the interVLAN routing and/or Internet routing.
Unless you're talking about several switches trunked/tagged together, carrying VLANs from multiple locations, I wouldn't even bother with L2 switches: you could easily accomplish this with just two unmanaged switches, one for each firewall interface.  I do prefer L2 switches as there's way more flexibility and management/monitoring options and are reasonably priced typically.

Default Gateway in a VLAN


Extract Date from HTML page using regex in R language

Question: How do I extract just the date in title="11:53 AM - 27 May 2018" using REGEX.
FYI this is from a HTML page. I want to extract all such matches to a list using R language.
My output should be  27 May 2018.
Thanks in advance for your time :)
Comment: I think you should be using a DOM parser to extract the `title` attribute.  After this, you might also use a regex.
Answer: Figured it out:
rawHTML <- paste(readLines("D:\\practicum\\CSK.html"), collapse="\n")

b<-unlist(str_match_all(rawHTML, '\\d{2} \\w+ 2018'))

Answer: Considering you have HTML code of the page in which you want to find the date, the simplest way will be to use regex to find all parts of the code that look like
title="11:53 AM - 27 May 2018"
Then you can simply again use regex to extract the date from the string.
I have written a basic code, you can modify it and use it according to your nee.
first_match <- regexpr(pattern='title\\s*=\\s*"\\d\\d:\\d\\d\\s*(AM|PM)\\s*-\\s*\\d\\d\\s[a-zA-Z]{3}\\s\\d{4}"', str)`
match_str <- regmatches(str,m)
date_exp <- regexpr(pattern='\\d\\d\\s[a-zA-Z]{3}\\s\\d{4}', match_str)
date <- regmatches(match_str, date_exp)

date is your required output and str is the code as string.
Comment: `sub(".*-","",your_string)` is what you are looking for


Number of samples needed for the empirical (discrete) distribution to converge to the underlying distribution

Question: My apologies if this is something standard in statistics.
My problem is as follows:
I have a discrete population distribution with finite support and I would like to use observed samples to obtain the empirical distribution function. How can I determine the required number of samples, $n$, such that the empirical distribution function, $\hat{p}_n$, approximates the population distribution function, $\hat{p}$, with some certainty?
i.e. what is the minimum $n$ such that $Pr\{|\hat{p}_n - p| \leq \epsilon \} \geq 1 - \delta$ for some $\delta$, e.g. 0.05? In my case, I do not have a specific parametric form of the distribution.
Answer: In general, what you want is the Dvoretzky–Kiefer–Wolfowitz inequality.
It it stated in the form:
$P(\text{sup}_{x \in \mathbb{R}}|F_n(x)- F(x)|>  \epsilon)\leq 2 \exp(-2n\epsilon^2)$.
This seems to be more or less what you want, even though your difference between $p_n$ and $p$ is not really defined. I suspect you mean the supremum.
There probably is some version specifically for your case.
Comment: Thank you a lot for this, I guess that the supremum should be a sufficient measure, I am not a statistician.


Proving the following sequence is bounded (Proof Verification)

Question: I want to prove that the following sequence is bounded,
$a_{n+1}=\sqrt{2+a_n}$, $a_1=\sqrt{2}.$
We can prove that it is monotonically increasing by induction. (I'll skip this part and treat it as an assumption.)
Assume $\exists m \in \mathbb{N}$ such that $M\leq a_m < M^2-2$ for $M>2$, the second inequality gives $a_{m+1}<M$ (contradiction because the sequence is increasing.) Then assume $\exists m \in \mathbb{N}$ such that $M^2-2\leq a_m < (M^2-2)^2-2.$ This gives $a_{m+1}<M^2-2$ (also a contradiction.) Repeating the procedure over and over we find that there is no $a_m$ starting from $M$ up to infinity.
Therefore the sequence is bounded.
Is the logic sound? Also is there a better way to write the proof?
Comment: @DavidC.Ullrich Sorry I forgot to add that $a_1=\sqrt{2}.$
Comment: I don't understand the logic here at all. Note it's easy to simply show that $a_n<2$.
Comment: $a_{n+1}>a_n$ if $-2 < a_n<2$. You did not prove $(a_n)$ fits in the interval $(-2,2)$ so you can't assume the sequence is increasing. So you have no starting point for your proof.
Comment: @DavidC.Ullrich The idea is to divide $\mathbb{R}$ into intervals: $(M,M^2-2),(M^2-2,(M^2-2)^2-2)$ and so on. And proving that there doesn't exist any $a_m$ in any of these intervals.
Comment: @CiaPan Can we prove it by induction? $a_2>a_1$ and $a_{n+2}\geq a_{n+1} \implies a_{n+1}\geq a_{n}$. Does that still require that we prove $a_n \in (-1,2)$? Also the interval should be $(-1,2)$, right?
Comment: Yes, you possibly _can_ prove it by induction (with some additional assumptions), but you did not do that.
Comment: Just test: what is the value of $\sqrt{2+a}$ for $a=-1$...? And for $a=-1.9$?
Comment: @CiaPan Yes I skipped proving the monotonic increasing part. This is not my question.
Comment: @MostafaAlkady, Do you understand how my proof proves convergence?
Answer: The hypothesis $$(\exists m\in \Bbb N ) : M\le a_m<M^2-2$$
implies a contradiction $(a_{m+1}<a_m)$, hence, this hypothesis is false.
An other way :
The sequence is increasing and if it converges to $ L $, then
$L=\sqrt{L+2} \; or \; L=2 $ and $$(\forall n\in \Bbb N)\; a_n<2$$
this can be proven easily by induction :
$$a_{n+1}<\sqrt{2+2}=2$$
Answer: All of your numbers ($M$, $M^2-2$, $\left(M^2-2\right)^2-2$, …) are greater than $2$. So, you have not considered all possible cases.
Note that, of $f(x)=\sqrt{2+x}$ and if $0<x<2$, then$$f(x)-x=\sqrt{2+x}-x=\frac{2+x-x^2}{\sqrt{2+x}+x}=\frac{(x+1)(2-x)}{\sqrt{2+x}+x}>0$$and that therefore $f(x)>x$. Also, $f(x)<2$, since$$2-f(x)=2-\sqrt{2+x}=\frac{2-x}{2+\sqrt{2+x}}$$and therefore $2>f(x)$. So, since $a_1=\sqrt2$, $a_1<a_2<2$. Since, $a_2<2$, $a_2<a_3<2$ and so on…
Comment: Since $M>2$, I proved that there can't be any $a_n>2.$ Therefore 2 is an upper bound. I'm not trying to find the least upper bound. So what is wrong with starting the intervals from 2?
Answer: Taking nested roots of positive numbers leads one to think that $0$ is a lower bound for $(a_{n})$ so we do the following:
Since $a_{1} > 0$, suppose $a_{n} > 0$ for some $n$.
Then $a_{n+1} = \sqrt{(2+a_{n})} > 0$. By induction, $a_{n} > 0$ for all $n$. I assumed a limit existed and saw that it would be $2$ if it did. This made me consider $2$ being an upper bound.
Since $a_{1} < 2$, suppose $a_{n} < 2$ for some $n$.
Then $a_{n+1} = \sqrt{(2+a_{n}}) < \sqrt{(2+2})=\sqrt 4 = 2$. By induction, $a_{n} < 2$ for all $n$.
Hence $0<a_{n}<2$ for all $n$ and $(a_{n})$ is bounded.
To prove monotonicity, check $a_{1}$ and $a_{2}$, and we see it is the case that $a_{1} \leq a_{2}$.
Suppose for some $n$ that $a_{n} \leq a_{n+1}$.
Then we must show that $a_{n+1} \leq a_{n+2}$.
That is, $a_{n+1} \leq a_{n+2} \Longleftrightarrow\sqrt{2+a_{n}} \leq \sqrt{2+a_{n+1}} \Longleftrightarrow 2+a_{n} \leq 2+ a_{n+1} \Longleftrightarrow
a_{n} \leq a_{n+1}$
Since $(a_{n})$ is bounded and monotonic, the sequence converges.
Comment: You never claimed in your question that the goal was to prove that there is no $n\in\Bbb N$ such that $a_n>2$.
Comment: I'm trying to prove the convergence of the sequence eventually, therefore I can't assume the limit exists. (Sorry if this was not clear).
Comment: @MostafaAlkady, I have edited my answer.
Comment: @DerekLuna Great but the choice of 2 was obvious because we know the sequence is actually convergent to 2. But in general, how should one go about proving it's bounded?
Comment: We didn't know the sequence converged to 2 until I proved the sequence was monotonic as well. I had my reason for choosing 2 that I wrote up above for you. You can see clearly it grows very slowly since we are nesting into a square root from the start. You could have chosen $10$ and it would have been good enough to bound it.
Comment: You said you want proof verification, then you say you want bound, then you say prove convergence, then you say the bound was obvious since we know it is convergent. Why are you the way that you are?
Comment: We've shown it is increasing so now suppose a limit $L$ exists and since the sequence is represented by a recurrence relation, take $n$ approaches $ \infty $ so that $ a_{n+1} = \sqrt{2+a_{n}} \implies L = \sqrt{2+L}$ so that $L^{2} = 2+ L$, and by the quadratic formula or by inspection we get that $L = 2$. Using all this information, it makes perfect sense to check for an upper bound of $2$.
Answer: Your proof uses the phrase "Repeating the procedure over and over". This is not a finite proof, thus not valid. Also you seem to use proof by contradiction where I don't see necessary.
Here's my proof which uses induction:
We will show that the sequence $(a_n)$ is bounded by $2$. It is easy to see that $(a_n)$ is a sequence of positive reals, so we instead check, by induction, if  $a_n<2$ for all $n\in\mathbb{N}$. The basis step is easy, since $a_1=\sqrt{2}<2$. Now let $n\in\mathbb{N}$ and assume $a_n<2$. Consider $$a_{n+1}=\sqrt{2+a_n}<\sqrt{2+2}=\sqrt{4}=2.$$ Thus, the inductive step is proved. By Principle of Mathematical Induction, we have that $a_n<2$ for all $n\in\mathbb{N}$. Thus, the sequence is bounded.
Comment: Proof is a finite sequence of propositions. So your proof statement must be finite. However, "repeating this forever"-type of proof, even though it looks life finite, but if you expand it out it is indeed an infinite sequence of steps. This is not allowed. You need induction to convert your "repeating this" type of argument into a finite deduction.
Comment: In the informal situation, the idea suffices. But in the formal situation, one shouldn't attempt this. Nevertheless, I sometimes do not adhere to this advice because at some point writing down a perfect proof become rather cumbersome.
Comment: Nice! I'm just not sure what is meant by "finite proof". I'm self-learning analysis so I tend to add statements such as this because I'm not used so much to the way proofs are written.
Comment: Great. Is this type of proofs always not valid? Because this trend of observing patterns carrying out to infinity is almost ubiquitous. Do I always have to resort to induction?
Answer: Nope. The logic is flawed, because you start from an unjustified assumption that your sequence is increasing.
It actually is increasing, but in some interval only, and you didn't show what the interval is nor the starting point belongs to the interval.
The interval is $(-2,2)$ and the starting point does belong to it, hence the sequence is increasing and, as a result, it is bounded – but your reasoning does not prove it.


Passing a variable produces error code "ByRef argument type mismatch" for "..."

Question: I am trying to create a personalized mass email and get the error code

"ByRef argument type mismatch" for "mail_body_message"

in line mail_body_message.

Sub SendEmail(what_address As String, subject_line As String, mail_body As String)

    Dim olApp As Outlook.Application
    Set olApp = CreateObject("Outlook.Application")
    Dim olMail As Outlook.MailItem
    Set olMail = olApp.CreateItem(olMailItem)

    olMail.To = what_address
    olMail.Subject = subject_line
    olMail.Body = mail_body
    olMail.Send

End Sub

Sub SendMassEmail()

    row_number = 1

    Do
        DoEvents
        row_number = row_number + 1
        Dim mail_body As String
        Dim full_name As String
        Dim promo_code As String
        mail_body_message = Sheet1.Range("J2")
        full_name = Sheet1.Range("B" & row_number) & " " & Sheet1.Range("C" & row_number)
        promo_code = Sheet1.Range("D" & row_number)
        mail_body_message = Replace(mail_body_message, "replace_name_here", full_name)
        mail_body_message = Replace(mail_body_message, "promo_code_replace", promo_code)
        MsgBox mail_body_message
        Call SendEmail(Sheet1.Range("A" & row_number), "This is a test e-mail", mail_body_message)
   Loop Until row_number = 6

   MsgBox "complete"

End Sub

Comment: First step: add `Option Explicit` to the top of the module and declare all variables.
Comment: try `Sheet1.Range("A" & row_number).value`
Answer: As mentioned by @BigBen, add Option Explicit at the top of the code. That will force you to declare the variables.
Imp Note: Just declaring them will not solve your issue. You need to declare them as the Right Type.
In Sub SendEmail(), the parameter mail_body is declared as String. So in simple language, you need to declare a variable as String before you pass it through. These two example will make it clear for you.
SAMPLE A
Option Explicit

Sub Sample()
    Dim mail_body_message

    mail_body_message = "Blah"

    SendEmail mail_body_message
End Sub

Sub SendEmail(mail_body As String)
    MsgBox mail_body
End Sub

SAMPLE B
Option Explicit

Sub Sample()
    Dim mail_body_message As String '<~~ Declaring it as the RIGHT TYPE

    mail_body_message = "Blah"

    SendEmail mail_body_message
End Sub

Sub SendEmail(mail_body As String)
    MsgBox mail_body
End Sub

You may also want to read up on this error ByRef argument type mismatch


Php Pregmatch on youtube video download link

Question: I found a youtube video download link generator... My script is http://www.paylash.biz/admin/youtube/index.php?id=[YOUTUBE ID]
For example: http://www.paylash.biz/admin/youtube/index.php?id=cKWqawoJPnw
But it will give me:
        Array
(
    [0] => Array
        (
            [ext] => 3gp
            [type] => Medium Quality - 176x144
            [url] => http://r8---sn-mv-q4fl.c.youtube.com/videoplayback?sparams=algorithm%2Cburst%2Ccp%2Cfactor%2Cgcr%2Cid%2Cip%2Cipbits%2Citag%2Csource%2Cupn%2Cexpire&fexp=904825%2C916807%2C929202%2C916612%2C932000%2C932004%2C906383%2C906387%2C904479%2C904482%2C902000%2C901208%2C929903%2C925714%2C929119%2C931202%2C900821%2C900823%2C912518%2C911416%2C904476%2C908529%2C904830%2C930807%2C919373%2C906836%2C929602%2C930101%2C900824%2C912711%2C910075&upn=2VY3aGvOZVE&ip=22.214.171.124&algorithm=throttle-factor&burst=40&expire=1367365132&mv=u&sver=3&mt=1367342103&ipbits=8&ms=au&gcr=us&source=youtube&key=yt1&factor=1.25&cp=U0hVTFNRU19ITENONV9LS1dCOjZQTENFSURXdmJx&id=70a5aa6b0a093e7c&newshard=yes&itag=17&signature=8864B62808466461882F04386057218EABF28F.81B02252560BDAB893AE6C55753D64D30DF3BAD0
        )

    [1] => Array
        (
            [ext] => 3gp
            [type] => High Quality - 320x240
            [url] => http://r8---sn-mv-q4fl.c.youtube.com/videoplayback?sparams=algorithm%2Cburst%2Ccp%2Cfactor%2Cgcr%2Cid%2Cip%2Cipbits%2Citag%2Csource%2Cupn%2Cexpire&fexp=904825%2C916807%2C929202%2C916612%2C932000%2C932004%2C906383%2C906387%2C904479%2C904482%2C902000%2C901208%2C929903%2C925714%2C929119%2C931202%2C900821%2C900823%2C912518%2C911416%2C904476%2C908529%2C904830%2C930807%2C919373%2C906836%2C929602%2C930101%2C900824%2C912711%2C910075&upn=2VY3aGvOZVE&ip=188.8.131.52&algorithm=throttle-factor&burst=40&expire=1367365132&mv=u&sver=3&mt=1367342103&ipbits=8&ms=au&gcr=us&source=youtube&key=yt1&factor=1.25&cp=U0hVTFNRU19ITENONV9LS1dCOjZQTENFSURXdmJx&id=70a5aa6b0a093e7c&newshard=yes&itag=36&signature=6B94E19AE88E2E1FBE8CFE3A57CFF3EC3D68CE00.5399A38CA9B8F3302E0298F180CBEEA4D8810CAF
        )

    [2] => Array
        (
            [ext] => flv
            [type] => Low Quality - 400x226
            [url] => http://r8---sn-mv-q4fl.c.youtube.com/videoplayback?sparams=algorithm%2Cburst%2Ccp%2Cfactor%2Cgcr%2Cid%2Cip%2Cipbits%2Citag%2Csource%2Cupn%2Cexpire&fexp=904825%2C916807%2C929202%2C916612%2C932000%2C932004%2C906383%2C906387%2C904479%2C904482%2C902000%2C901208%2C929903%2C925714%2C929119%2C931202%2C900821%2C900823%2C912518%2C911416%2C904476%2C908529%2C904830%2C930807%2C919373%2C906836%2C929602%2C930101%2C900824%2C912711%2C910075&upn=2VY3aGvOZVE&ip=220.127.116.11&algorithm=throttle-factor&burst=40&expire=1367365132&mv=u&sver=3&mt=1367342103&ipbits=8&ms=au&gcr=us&source=youtube&key=yt1&factor=1.25&cp=U0hVTFNRU19ITENONV9LS1dCOjZQTENFSURXdmJx&id=70a5aa6b0a093e7c&newshard=yes&itag=5&signature=681047019412022702DC977F6EAA3D8728A8F8C2.49267286178E66D24ED370C7F6C895E47C85F18B
        )

    [3] => Array
        (
            [ext] => flv
            [type] => Medium Quality - 640x360
            [url] => http://r8---sn-mv-q4fl.c.youtube.com/videoplayback?sparams=algorithm%2Cburst%2Ccp%2Cfactor%2Cgcr%2Cid%2Cip%2Cipbits%2Citag%2Csource%2Cupn%2Cexpire&fexp=904825%2C916807%2C929202%2C916612%2C932000%2C932004%2C906383%2C906387%2C904479%2C904482%2C902000%2C901208%2C929903%2C925714%2C929119%2C931202%2C900821%2C900823%2C912518%2C911416%2C904476%2C908529%2C904830%2C930807%2C919373%2C906836%2C929602%2C930101%2C900824%2C912711%2C910075&upn=2VY3aGvOZVE&ip=22.214.171.124&algorithm=throttle-factor&burst=40&expire=1367365132&mv=u&sver=3&mt=1367342103&ipbits=8&ms=au&gcr=us&source=youtube&key=yt1&factor=1.25&cp=U0hVTFNRU19ITENONV9LS1dCOjZQTENFSURXdmJx&id=70a5aa6b0a093e7c&newshard=yes&itag=34&signature=4B7A96C7F0E5FA796B8D1429382041D518CB1639.B9BF0A636366448189A9A297582F48FF1C347871
        )

    [4] => Array
        (
            [ext] => flv
            [type] => High Quality - 854x480
            [url] => http://r8---sn-mv-q4fl.c.youtube.com/videoplayback?sparams=algorithm%2Cburst%2Ccp%2Cfactor%2Cgcr%2Cid%2Cip%2Cipbits%2Citag%2Csource%2Cupn%2Cexpire&fexp=904825%2C916807%2C929202%2C916612%2C932000%2C932004%2C906383%2C906387%2C904479%2C904482%2C902000%2C901208%2C929903%2C925714%2C929119%2C931202%2C900821%2C900823%2C912518%2C911416%2C904476%2C908529%2C904830%2C930807%2C919373%2C906836%2C929602%2C930101%2C900824%2C912711%2C910075&upn=2VY3aGvOZVE&ip=220.127.116.11&algorithm=throttle-factor&burst=40&expire=1367365132&mv=u&sver=3&mt=1367342103&ipbits=8&ms=au&gcr=us&source=youtube&key=yt1&factor=1.25&cp=U0hVTFNRU19ITENONV9LS1dCOjZQTENFSURXdmJx&id=70a5aa6b0a093e7c&newshard=yes&itag=35&signature=CBA74C27EA4442E2A170218DE750D7129A6CF767.1D4EA626FBDEE5340523606A9AD811E26D8E264B
        )

    [5] => Array
        (
            [ext] => webm
            [type] => Low Quality - 640x360
            [url] => http://r8---sn-mv-q4fl.c.youtube.com/videoplayback?sparams=cp%2Cgcr%2Cid%2Cip%2Cipbits%2Citag%2Cratebypass%2Csource%2Cupn%2Cexpire&fexp=904825%2C916807%2C929202%2C916612%2C932000%2C932004%2C906383%2C906387%2C904479%2C904482%2C902000%2C901208%2C929903%2C925714%2C929119%2C931202%2C900821%2C900823%2C912518%2C911416%2C904476%2C908529%2C904830%2C930807%2C919373%2C906836%2C929602%2C930101%2C900824%2C912711%2C910075&upn=2VY3aGvOZVE&ip=18.104.22.168&mt=1367342103&itag=43&expire=1367365132&mv=u&ipbits=8&sver=3&ms=au&gcr=us&ratebypass=yes&source=youtube&key=yt1&cp=U0hVTFNRU19ITENONV9LS1dCOjZQTENFSURXdmJx&newshard=yes&id=70a5aa6b0a093e7c&signature=4B0E84BF1BBF632D81CFCC4A615CF31A4F4D9FB3.43A54E50CC78A26DFA4C22154C9E2FB999376CDC
        )

    [6] => Array
        (
            [ext] => webm
            [type] => Medium Quality - 854x480
            [url] => http://r8---sn-mv-q4fl.c.youtube.com/videoplayback?sparams=cp%2Cgcr%2Cid%2Cip%2Cipbits%2Citag%2Cratebypass%2Csource%2Cupn%2Cexpire&fexp=904825%2C916807%2C929202%2C916612%2C932000%2C932004%2C906383%2C906387%2C904479%2C904482%2C902000%2C901208%2C929903%2C925714%2C929119%2C931202%2C900821%2C900823%2C912518%2C911416%2C904476%2C908529%2C904830%2C930807%2C919373%2C906836%2C929602%2C930101%2C900824%2C912711%2C910075&upn=2VY3aGvOZVE&ip=188.8.131.52&mt=1367342103&itag=44&expire=1367365132&mv=u&ipbits=8&sver=3&ms=au&gcr=us&ratebypass=yes&source=youtube&key=yt1&cp=U0hVTFNRU19ITENONV9LS1dCOjZQTENFSURXdmJx&newshard=yes&id=70a5aa6b0a093e7c&signature=6C5E15D7A7AD84AB86C24655AF404348B2FC28AA.6645A6127C5FBC1923CB6E0A3EBAFC72A92B769F
        )

    [7] => Array
        (
            [ext] => mp4
            [type] => Medium Quality - 480x360
            [url] => http://r8---sn-mv-q4fl.c.youtube.com/videoplayback?sparams=cp%2Cgcr%2Cid%2Cip%2Cipbits%2Citag%2Cratebypass%2Csource%2Cupn%2Cexpire&fexp=904825%2C916807%2C929202%2C916612%2C932000%2C932004%2C906383%2C906387%2C904479%2C904482%2C902000%2C901208%2C929903%2C925714%2C929119%2C931202%2C900821%2C900823%2C912518%2C911416%2C904476%2C908529%2C904830%2C930807%2C919373%2C906836%2C929602%2C930101%2C900824%2C912711%2C910075&upn=2VY3aGvOZVE&ip=126.96.36.199&mt=1367342103&itag=18&expire=1367365132&mv=u&ipbits=8&sver=3&ms=au&gcr=us&ratebypass=yes&source=youtube&key=yt1&cp=U0hVTFNRU19ITENONV9LS1dCOjZQTENFSURXdmJx&newshard=yes&id=70a5aa6b0a093e7c&signature=8B1FDA0DD8D992B56B8693F42476E2D952012E31.7B9D1A89C70A3A72D17A7C377747BFB204824CCD
        )

)

But I want to give me only mp4 part. How can I do it?
Comment: Sometimes this link http://www.paylash.biz/admin/youtube/index.php?id=cKWqawoJPnw opens a whitepage. If this happens please reload the page again
Comment: my code is my secret :)
Answer: Like this:
foreach ($yourArray as &$value) {
    if ($value['ext'] != 'mp4') unset($value);
}
print_r($yourArray);

or like this if you want to preserve the original array:
foreach ($yourArray as &$value) {
    if ($value['ext'] == 'mp4') $result[]=$value;
}
print_r($result);


Pearson chi squared test vs deviance test in GLM

Question: From my understanding, both Pearson chi squared test and deviance test can be used to assess the goodness of fit for GLM, but they have different alternative hypotheses. For the Pearson chi-squared test, the null hypothesis suggests that the true model is the estimated model, while the alternative hypothesis indicates that the true model differs from the estimated model.
On the other hand, the null hypothesis from the deviance test (also known as residual deviance) assumes that the true model is the estimated model, but the alternative hypothesis states that the true model is the saturated model, where each observation can have its own parameter. In R, the summary output of the GLM includes both null deviance and residual deviance. The null deviance tests the hypothesis that the true model is the intercept-only model, while the residual deviance is similar to the deviance test.
Given that null and residual deviance already assess whether less or more parsimonious models might be better, I wonder if there are scenarios where using the Pearson chi-squared test would be more appropriate or insightful. Can someone clarify such scenarios and explain the advantages of using the Pearson chi-squared test over the deviance test in specific situations?
Comment: Might help a bit https://stats.stackexchange.com/q/166585/3277
Answer: Generally, the G-test is useful in case of categorical data, but when we see the concept of "Goodness of fit", the more powerful test is chi-square test as compared to the LRT.
Also I would like to add one more thing, LRT is considered more effective in case when some of the values in contingency table have less than 5 observed or expected frequencies.
Reference: Journal of Applied Sciences Research 1(2): 242-244, 2005
© 2005, INSInet Publication


External o365 Mail-Users Receive plaintext

Question: In my Office365 I have an Office365 Group.  Whenever I add a Mail-User (external) to the group they receive the welcome message from the group, but it is in plaintext, complete with image file attachments and winmail.dat.
The message comes across like this:

Welcome to the Roadkill Cafe group.
[cid:office365_icon_orange]
[cid:group_photo.jpg] Roadkill Cafe Welcome to the Roadkill Cafe
  group.
Roadkill Cafe group
[cid:welcome_onenote_icon]https://email@example.com/groupsubscription.ashx?realm=roadkillcafe.com&source=WelcomeEmail&action=onenote
  Share
  noteshttps://email@example.com/groupsubscription.ashx?realm=roadkillcafe.com&source=WelcomeEmail&action=onenote
Capture ideas and images in OneNote.
[cid:document_icon]https://email@example.com/groupsubscription.ashx?realm=roadkillcafe.com&source=WelcomeEmail&action=files
  View and share
  fileshttps://firstname.lastname@example.com/groupsubscription.ashx?realm=roadkillcafe.com&source=WelcomeEmail&action=files
View, share, and collaborate on content using SharePoint.

I have tested this with my local email server and with Yahoo.
However, if I add one of the non-external users (licensed o365 user), the message is sent in html.  Or, if in OWA, if I add a "guest" to the group who has a yahoo.com address, that person is also sent a normal html email like it should.  I have also tested this with a gmail account.
So I added a remote domain under Exchange > mail flow > remote domains and configured that domain for Always use rich-text format (it was default set to follow user settings) and I changed the character sets to Western European.
But this had no effect.
This MS help document says to make an adjustment that will force the message into plaintext and eliminate the winmamil.dat file altogether.  However, I want the message to be in html, not plaintext.  And besides that, none the three settings (Use rich-text format: Always, Never, Follow user settings) have any effect on the message at all.
How can I fix this?
[update]
Apparently, the mail-user receives ALL email correspondence in plaintext, not just the welcome message.  This happens when you post anything in "conversation" in the group itself.
However, if I send an email to that same group, it is received as html!  Go figure that.  Post to the group directly and it sends plaintext; send an email to it and it sends html.
[update]
So I tried using powershell against the mail-user object like this, but this also did not change the welcome message to html:
set-mailuser -identity email@example.com -messageformat mime -messagebodyformat html

Answer: Well!  I ended up making a Support Request through the Office365 interface.  The Folks over there at the MS Service Center told me that they were able to reproduce the problem.
Their solution?  It seems that my tentant's server is one update-patch behind and that perhaps when that patch is applied (no idea of when) it might solve the problem.  Or, if enough other people have the same complaint they will look into it more deeply.
Such wonderful promises they make to me!  In the meantime, I have decided to avoid adding mail-users to Office365 groups using the Office Admin web GUI.  I shall have to do it in powershell and script out my own welcome email.
Answer: This fixed it:
Set-RemoteDomain Default -TNEFEnabled $false

Details: How to Fix Winmail Dat Attachment Issue
The post is old, but I still got the same issue in 2020, and it is not well-explained by MS, hope my reply makes life easier for someone.


How to visualize what ANOVA does?

Question: What way (ways?) is there to visually explain what is ANOVA?
Any references, link(s) (R packages?) will be welcomed.
Comment: In his blog 'A psychologist's endeavors in statistical programming' Kristoffer Magnusson gives a great example of one-way anova visualization using D3.js http://rpsychologist.com/d3-one-way-anova/#comment-1891
Comment: I have found this nice visualisation of what analysis of variance is.
It not as precise as previous answers, but you can interactively play with the visualisation. Found it pretty intersting : http://students.brown.edu/seeing-theory/regression/index.html#third
Answer: Personally, I like introducing linear regression and ANOVA by showing that it is all the same and that linear models amount to partition the total variance: We have some kind of variance in the outcome that can be explained by the factors of interest, plus the unexplained part (called the 'residual'). I generally use the following illustration (gray line for total variability, black lines for group or individual specific variability) :

I also like the heplots R package, from Michael Friendly and John Fox, but see also Visual Hypothesis Tests in Multivariate Linear Models: The heplots Package for R.
Standard ways to explain what ANOVA actually does, especially in the Linear Model framework, are really well explained in Plane answers to complex questions, by Christensen, but there are very few illustrations. Saville and Wood's Statistical methods: The geometric approach has some examples, but mainly on regression. In Montgomery's Design and Analysis of Experiments, which mostly focused on DoE, there are illustrations that I like, but see below

(these are mine :-)
But I think you have to look for textbooks on Linear Models if you want to see how sum of squares, errors, etc. translates into a vector space, as shown on Wikipedia. Estimation and Inference in Econometrics, by Davidson and MacKinnon, seems to have nice illustrations (the 1st chapter actually covers OLS geometry) but I only browse the French translation (available here). The Geometry of Linear Regression has also some good illustrations.
Edit:
Ah, and I just remember this article by Robert Pruzek, A new graphic for one-way ANOVA.
Edit 2
And now, the granova package (mentioned by @gd047 and associated to the above paper) has been ported to ggplot, see granovaGG with an illustration for one-way ANOVA below.
Comment: @gd047 All right, as usual it's always when we look for old code that we cannot found it (despite my best effort with grep/find), so I rewrote a quick (still ugly) [R script](https://gist.github.com/736212) for that. I've also put an example of the [MP code](https://gist.github.com/736216).
Comment: Is the first illustration produced using R?
Comment: @gd047 Yes. Should have the ugly source code somewhere if you want. The second one is done in Metapost.
Comment: [The geometry of linear regression](http://www.ceseephd.net/wp-content/uploads/2011/12/Projection1.pdf) link seems to have rotted, sadly.
Answer: How about something like this?

Following Crawley (2005). Statistics. An introduction using R: Wiley.
Comment: (+1) I remind me of `plot.design()` (but yours in an enhanced version :-)
Comment: This is the best.
Answer: Thank you for your great answer so far.  While they where very enlightening, I felt that using them for the course I am currently teaching (well, TA'ing) will be too much for my students. (I help teach the course BioStatistics for students from advanced degrees in medicine sciences)
Therefore, I ended up creating two images (Both are simulation based) which I think are useful example for explaining ANOVA.
I would be happy to read comments or suggestions for improving them.
The first image shows a simulation of 30 data points, separated to 3 plots (showing how the MST=Var is separated to the data that creates MSB and MSW:

The left plot shows a scatter plot of the data per group.
The middle one shows how the data we are going to use for MSB looks like.
The right image shows how the data we are going to use for MSW looks like.

The second image shows 4 plots, each one for a different combination of variance and expectancy for the groups while

The first row of plots is for low variance, while the second row is for high(er) variance.
The first column of plots is for equal expectancy between the groups, while the second column shows groups with (very) different expectancies.
Comment: (+1) I always think that the takeaway messages when teaching ANOVA is: (1) we have an F-ratio which reflects the relative importance of the variance accounted for by our factor of interest wrt. total variance (or MSB/MSW where MSW=MST-MSB), (2) the differences between the group means is a variance, and (3) we explicitly test $H_0:~\mu_1=\mu_2=\ldots=\mu_k$ *vs.* $H_1:~\exists\ i,j~|~\mu_i\neq\mu_j$ ($H_1\equiv\neg~H_0$). If you're able to convey those ideas into a graphical display--which seems to be the case here--, then I think you're almost done.
Comment: Yep, sorry I wrote quickly. I meant: Consider the model $y_{ij}=\mu + \alpha_i + \varepsilon_{ij}$ or $y_{ij}=\mu_i + \varepsilon_{ij}$ and highlight graphically the following decomposition: $y_{ij}=\bar{y_i}+\varepsilon_{ij}=\bar{y}+(\bar{y}_i-\bar{y})+(y_{ij}-\bar{y}_i)$, that is obs. are expressed as deviations from the grand mean + group mean + fluctuations around group mean. Then, we have $(y_{ij}-\bar{y})=(\bar{y}_i-\bar{y})+(y_{ij}-\bar{y}_i)$ or total variation = between-group variation + within-group variation (which is basically your first picture).
Comment: Hi chl, thank you for the positive feedback (and for your previous detailed answer)! I think some of the biggest take home massages I got from preparing the material for this class are:  1) How to describe the transformation of the original data so to get te MSB and MSW variances measures.  2) How the test statistic of the MSB/MSW is actually a one sided (not a two sided) test where the H0 is that MSB<=MSW. Lastly, I just thought to note that it is true that SSW=SST-SSB (but I don't see how it's true for MSW=MST-MSB).
Answer: Since we gather certain types of nice graphs in this post, here is another one that I recently found and may help you understand how ANOVA works and how the F statistic is generated. The graphic was created using the granova package in R.
Comment: (+1) I gave a link to Robert Pruzek's article, but I didn't know it was available in R.
Answer: Check out Hadley Wickham's presentation (pdf, mirror) on ggplot.
Starting on pages 23-40 of this document he describes an interesting approach to visualizing ANOVAs.
*Link taken from: http://had.co.nz/ggplot2/
Answer: Great question. You know, I've struggled myself with wrapping my head around ANOVA for a very long time.  I always find myself going back to the "between versus within" intuition, and I've always tried to imagine what this would look like in my head.  I'm glad this question came up, and I've been amazed by the varied approaches to this in the answers above.
Anyway, for a long time (years, even) I've been wanting to collect several plots in one place where I could see what was happening simultaneously from a lot of different directions:  1) how far apart the populations are, 2) how far apart the data are, 3) how big's the between compared to the within, and 4) how do the central versus noncentral F distributions compare?
In a truly great world, I could even play with sliders to see how sample size changes things.
So I've been playing with the manipulate command in RStudio, and holy cow, it works!  Here is one of the plots, a snapshot, really:

If you have RStudio you can get the code for making the above plot (sliders and all)! on Github here.
After playing with this for awhile, I am surprised at how well the F statistic distinguishes the groups, even for moderately small sample sizes.  When I look at the populations, they really aren't that far apart (to my eye), yet, the "within" bar is consistently dwarfed by the "between" bar.  Learn something every day, I guess.
Answer: Here are some representations of situations in which an ANOVA will conclude to different level of fit between $Y$ and $X$.
Comment: what a impressive visualization!
May I know if there is any link or example code show how to plot it?
The anova  concept of F value, p_vale, group, df is too difficult to busines people, I think you plot may help them to understand how different factor could be influent target.  Most importantly, using visualization way,
looking forward you feedback.
Comment: These two SVGs is all I've been able to recover in my archive (the download link won't probably survive very long): https://we.tl/t-fElYVO7hX3
Answer: To illustrate what is going on with one-way ANOVA I have sometimes used an applet offered by the authors of "Introduction to the Practice of Statistics", which allows the students to play with within and between variances and observe their effect on the F statistic. Here is the link (the applet is the last one on the page).  Sample screen shot:

The user controls the top slider, varying the vertical spreads of the three groups of data.  The red dot at the bottom moves along the plot of p-values while the F-statistic shown beneath is updated.
Answer: It seems the ship has already sailed in terms of an answer, but I think that if this is an introductory course that most of the displays offered here are going to be too difficult to grasp for introductory students... or at the very least too difficult to grasp without an introductory display which provides a very simplified explanation of partitioning variance.  Show them how SST total increases with the number of subjects.  Then after showing it inflate for several subjects (maybe adding one in each group several times), explain that SST = SSB + SSW (though I prefer to call it SSE from the outset because it avoids confusion when you go to the within subjects test IMO).  Then show them a visual representation of the variance partitioning, e.g. a big square color coded such that you can see how SST is made of SSB and SSW.  Then, graphs similar to Tals or EDi may become useful, but I agree with EDi that the scale should be SS rather than MS for pedagogical purposes when first explaining things.

How to visualize what ANOVA does?


Disable cache for specific blocks

Question: I would like to let pages continue to benefit from Drupal 8 caching mechanism for anonymous users, except for a specific blocks which should update on every page refresh knowing that they are generated from Views.
Is it technically possible? How?
Comment: As MPD noted, use the max-age setting. Also you can do this via UI on block edit form too.
Comment: I have this issue too - it is annoying Drupal doesn't deal with this automatically. Caching is good, but Drupal is supposed to be for dynamic websites...
Answer: If this is a custom block, then you can use the Cache API, and set the cache max age to 0, eg
<code>$build = [
 // ...
 '#cache' => [
   'max-age' => 0,
 ],
];
</code>
If it is an existing block, then you can alter it to add this into the render array.
Comment: Unfortunately, this doesn't work anyway (tried it). Seems like the page is delivered from pagecache and contains the outdated block. But I am still investigating.
Comment: As explained in the question, my block is a Views block. I think it's too complicated to interfere with at php/module layer.
Answer: What does that views block show?
D8 has cache tags and contexts that will automatically invalidate the block if something changes.
So if you have a list of nodes, every time a node is added or updated, that block will be updated, but until then, the cached version is used. Which is much better than rebuilding on every page.
It also works with the page cache, those pages will be updated automatically as well.
Many, many things just work with caching out of the box, without the need for any manual configurations.
Edit (responding to comment):
Random with the random sort plugin? That should automatically mark that block as non-cacheable. That however does not affect the page cache module. There is now a new smartcache/dynamic page cache module but it will only be in the next beta (or RC!). That will eventually allow to cache the rest of the page and just build that part.
But a case like this is probably best implemented by using some javascript. If there only a few nodes you could display them all, hidden by default and just randomly make one of them visible. Or request a URL with javascript that returns a random Ad or even better visit a random of N URL's that each returns an ad (e.g. by returning a list of URL's and then picking one of them. You could even do that directly for the image URL.
Comment: The views returns a random node in order to vary the ads bloc.
Comment: I will wait for the next release for the clean solution so :)
Comment: Yes, the random is from the Views Random Sort plugin. I agree, it's possible to generate a javascript block content which put in a list the entities and then decide at browser layer with some random or circular function to pick and ajax one of them. However, I will have more than one block like this in some pages and a server side solution will fit best.

Disable cache for specific blocks


WKWebView Dark and Light Mode with dynamic URL in Swift 5

Question: I created WKWebView that doesn't have one url. User use this WKWebView as Safari means user can search anything on WKWebView. I am facing one issue when I change dark and light mode my web view will show me only white(Light) mode. My app is working on both mode all things working fine except WKWebView.
Already search on SO not find any related question on this.
how to use iOS 13 darkmode for wkwebview
I refer this blog but it's static url so it will not help me out
https://useyourloaf.com/blog/using-dynamic-type-with-web-views/
Also checked opaque and background property but not working for me!
IMPORTANT
User can search anything like google.com, photos or any surfing etc.
class DownloadViewController: UIViewController {

    @IBOutlet weak var webView: WKWebView!

    override func viewDidLoad() {
        super.viewDidLoad()
        webView.uiDelegate = self
        webView.navigationDelegate = self
        webView.load(URLRequest(url: URL(string: "https://www.google.com")!))
        webView.allowsBackForwardNavigationGestures = true
        webView.allowsLinkPreview = true
    }

}

First I am loading Google site then depend on user(Totally dynamic not one url here).
Please suggest me! Thank you.
Answer: You can use injecting CSS technic to add Light/Dark feature to your loaded web pages e.g:
// Load a web page
webView?.load(URLRequest(url: URL(string: "https://google.com")!))

// Inject Light/Dark CSS

let lightDarkCSS = ":root { color-scheme: light dark; }"
let base64 = lightDarkCSS.data(using: .utf8)!.base64EncodedString()

let script = """
    javascript:(function() {
        var parent = document.getElementsByTagName('head').item(0);
        var style = document.createElement('style');
        style.type = 'text/css';
        style.innerHTML = window.atob('\(base64)');
        parent.appendChild(style);
    })()
"""

let cssScript = WKUserScript(source: script, injectionTime: .atDocumentEnd, forMainFrameOnly: false)
webView?.configuration.userContentController.addUserScript(cssScript)

Result:

To support page changing you can move insertion code to didCommitNavigation notification:
func webView(_ webView: WKWebView, didCommit navigation: WKNavigation!) {
    ...
    // Inject CSS here
}

NOTE: It doesn't work with any web page in general because some of web sites can hardcode colors of background, fonts etc. but you can tune specific pages as well by overriding its CSS.
Comment: It's only working with google. so which approach would be correct if I want to do for any web page Inject or interfaceStyle?
Comment: @YogeshPatel it can work with web pages that doesn't have hardcoded colors for backgrounds etc. but you can inject CSS dynamically and override known styles  for certain web sites only so there is no a general solution as I mention above.
Comment: okay understood!
Comment: Why is the base64 encoding/decoding required? I see that it doesn't work without it, but it doesn't make sense to me.
Answer:
Already search on SO not find any related question on this.

Interesting that you mention this, as this has been a question addressed quite a few times already. A quick search will show many good answers and threads, for example: this one.
That being said, the quick answer is:
WKWebView can adopt light and dark mode, like any other UIView/NSView. You can manually set the interfaceStyle on the appearance, or it will inherit it. More details here overrideUserInterfaceStyle.
But
Probably the problem you are facing is that even though the WKWebView is using the dark interfaceStyle, websites still show on light mode. That is because those websites (google and any other website/URL) are independent and handle their style on their own. Some of them adjust to match your device's interface style, but not all. In short, even if WKWebView is on dark mode, Google will load a white background if they want to do it.
As mentioned by others, you can change this behaviour by manually injecting CSS, please check those answers if that is what you want to do, check also the link I posted at the beginning of this answer where they discuss that approach.
Comment: I checked but its not working
https://stackoverflow.com/questions/57203909/how-to-use-ios-13-darkmode-for-wkwebview
Comment: @YogeshPatel you need to manually inject CSS, probably via JavaScript. Every website is different so it might work for some but not others, it is not really straightforward and there can be many different approaches.

Difficult to tell what exactly is not working for you, please post your Swift code, your JavaScript code, your CSS code, and the website that you are trying to modify with that code. With the code posted so far you have not even started to try to inject anything.
Comment: I tried many css code but it's not working so haven't mentioned that code because it's not working google site to @iuril code is only work for google. so Which approach would be correct if I want to do for any web page Inject or interfaceStyle?
Answer: As in android web views(force_darkmode), Apple has not provided support for dark mode web-views yet.  you can explore safari with a few reputed websites, even though they don't convert to dark mode.
so we should wait for Webkit dark mode support till then. These CSS injections are not the best practice or robust solution.


Transfer fieldgroups through features

Question: I need transfer fieldgroup through features, but always when I add field group into feature I see status "overriden". How I can add fieldgroup into features correctly?
This fieldgroup added for taxonomy vocabulary.
This problem described in this topic http://drupal.org/node/1619154 but it not works for me :(
I use Drupal 7.14, field_group 7.x-1.1, features 7.x-1.0, CTools 7.x-1.0
Answer: I found problem - features is not paste this line include_once('my_feature.features.inc'); into my_feature.module

Transfer fieldgroups through features


Re-mount USB device after removal on Windows

Question: From time to time I eject a USB device, generally a memory stick or external HDD, when I think I have finished transferring data only to realise there's something else I need to do with it. Normally this involves nothing more than unplugging the device and plugging it back in. What about if I'm doing the work from remote? Is there a command I can run that will have Windows re-detect and mount the device?
Update:
Thanks to all who responded.
Although some of the suggested methods will work they also cause problems if another device is connected via the same hub. Others, such as devcon, may well work for others but failed for me, although I don't know why not and won't be investigating it any further.
I would have preferred not to have to rely on a commercial product but Safelyremove, suggested in the accepted answer, worked so well in my tests I consider it a keeper.
Comment: so you are "soft-ejecting" the USB device remotely?
Comment: Either by selecting "eject" from Explorer or using "safely remove..." in the system tray. I generally use the latter because the eject option is less than reliable.
Answer: When you've click the eject/safely remove, go into device manager (Control panel -> System -> Hardware Tab).
Under USB, you should see the device with a (!) icon.  If you view the device, it will say something like:

Windows cannot use this hardware   device because its been prepared for "safe removal".

Change the view of Device manager using the View Menu to "Devices by connection".  Find the parent USB hub.  Right click it and disable the hub, then right click and enable the hub.
Answer: When you "safely remove" a USB HDD - it stops spinning. I believe there's a USB command to turn the device off (sleep mode, actually). So the thing you need is how to turn the device back on.
The application Safelyremove has a command-line tool that is capable of returning the device back: "Returning just stopped device back!".
It is shareware, but it works :)
Comment: http://superuser.com/questions/731404/detect-usb-after-safely-remove-usb

You saved my USB and my Laptop.
Comment: @MariaMeh, hehe, good luck in your development! :)
Answer: Command line mountvol or mount. Type in mountvol in command prompt to see your options. It explains all of the options in there. Then create a batch file. You can access the batch file from the remote desktop. Be sure to enable permissions in remote desktop. Try it out.
Comment: I'll give you an upvote for the effort but in reality mountvol is not really viable. Because the target machine and USB port are variables I could have traveled to the remote location and just used the normal GUI method by the time I work out the absurdly cryptic command parameters required. This is an area where Windows could and should have had a simple command but the developers just got plain lazy.
Comment: 1. To list the currently attached volume names, issue:
**mountvol**
2. To mount a USB to D: drive:
`mountvol D: \\?\Volume{4fad0fe5-35f7-11ee-93dc-0010f3895094}\` (obtained from step 1)
Answer: I just tested this out and was able to verify this works in Windows Vista and also verified it works in Windows XP. Disabling and re-enabling the USB device directly did not reinitialize it. The steps below did.
After the device has been "safely removed" go into Device Manager.
Find the USB Mass Storage Device, right-click on it, and select uninstall.
Next, one at at time, disable, and re-enable the USB Host controllers. Take your time with this step, as one of the controllers will reinitialize the USB device.
None of this required a reboot, so it should meet your needs. Ignore any prompts for a reboot.
Answer: I was also going to suggest devcon, however in addition, there are a few GUI tricks you can use.
If you use eject instead of safely remove, it unmaps the drive and kills all open handles (and displays the popup saying it is safe to remove), however the device is still present. You can then go to Device Manager and disable followed by enable the flash drive, and it should remap itself.
I can not guarantee, but I assume the same should work for safely remove - however if it does actually remove the device, you should be able to readd it by going to Device Manager, right clicking on the computer object and click scan for new hardware.
Answer: Try Microsoft's devcon command line utility.
Comment: I've tried devcon but it hasn't worked on any of the machines I tested it on.


Mapping roles to users while migrating

Question: Following [this][1], I have  done migration for users from Drupal 7 to Drupal 8, but I got stuck with assigning roles to the specified users.
In user.php file, my code for mapping roles to assigned users is the following.
public function prepareRow(Row $row) {
    $uid = $row->getSourceProperty('uid');
    // user_role

    $result = $this->getDatabase()->query('
      SELECT
        r.rid, r.name, ur.uid
      FROM
        {role} r, {users_roles} ur
      WHERE
        r.rid = ur.rid
      AND
        ur.uid = :uid
    ', array(':uid' => $uid));
    foreach ($result as $record) {
      $row->setSourceProperty('roles', $record->name );
    }

    // local_market field of type entity_reference
    $result = $this->getDatabase()->query('
      SELECT
        fld.field_local_market_target_id
      FROM
        {field_data_field_local_market} fld
      WHERE
        fld.entity_id = :uid
    ', array(':uid' => $uid));
    foreach ($result as $record) {
      if (!is_null($record->tids)) {
        $row->setSourceProperty('local_market', explode(',', $record->tids) );
      }
    }

    return parent::prepareRow($row);
  }

Except roles and custom field, field_local_market, all users migrated from Drupal 7 to Drupal 8.
destination:
  plugin: entity:user

process:
  uid: uid
  name: name
  pass: pass
  mail: mail
  status: status
  created: created
  changed: changed
  access: access
  login: login
  timezone: timezone
  langcode: language
  preferred_langcode: language
  preferred_admin_langcode: language
  init: init
  field_local_market: local_market
  field_user_role: user_role

What's the right way to assign roles to the users?
Migration of roles is done from Drupal 7 to Drupal 8 by using drush migrate_upgrade; the only task left is assigning/mapping these roles to certain UIDs or users.
Answer: You can migrate users with roles without migrating roles using migrate static_map
In migrate set
  process:
  uid: null
  name: name
  pass: pass
  mail: mail
  status: status
  created: created
  access: access
  login: login
  roles:
    plugin: static_map
    bypass: true
    source: roles
    map:
      5: new_role_name
      3: editor

and in the source plugin you have to set the roles in prepareRow
  /**
   * {@inheritdoc}
   */
  public function prepareRow(Row $row) {
    $uid = $row->getSourceProperty('uid');

    $query = $this->select('users_roles', 'r');
    $query->fields('r', ['rid']);
    $query->condition('r.uid', $uid, '=');
    $record = $query->execute()->fetchAllKeyed();
    $row->setSourceProperty('roles', array_keys($record));

    return parent::prepareRow($row);
  }

Answer: Few things you can try:
1) You need to pass the Role ID instead of the Role name.
2) Ensure you're passing an array and you actually have results in the query result:
$roleIds = array_map(function ($record){
  return $record->rid;
}, $result);

// Make sure $roleIds is an array.
$row->setSourceProperty('roles', $roleIds);

3) As your roles are migrated in another migration, the mapping should be done by using a special plugin "migration". E.g:
roles:
  plugin: migration
  source: roles
  migration: the_migration_name_which_migrated_user_roles

Mapping roles to users while migrating


Does this accidental before an acciaccatura also apply to the main note?

Question: This is the climax from John Kember's "Happy Feet" for solo piano (annotations are mine):

On the final beat of this excerpt, there's an octave interval (#2, #3) in the right hand, with an acciaccatura (#1) before the lower note.
Both the acciaccatura (#1) and the upper note of the octave (#3) are B flat. My question is: does the flat accidental before the acciaccatura (#1) also apply to the main note (#2)? In other words: is the main note (#2) played as B flat or as B natural?
Arguments in favor of B flat (i. e., the accidental applies to the main note as well, the interval is a perfect octave):

Normally, accidentals remain in effect for the remainder of the measure.
B natural isn't part of the indicated chord, D7/♭9/♭11/♭13, whereas B flat is the ♭13 of D.

Arguments in favor of B natural (i. e., the accidental does not apply to the main note, the interval is a diminished octave):

An acciaccatura is normally a tone or semitone above or below the main note.
If it was also a B flat, what would the acciaccatura even indicate? It could be an arpeggio, but then I would have expected it to be written with a wavy vertical line instead.

This answer says that an accidental on an ornament (like on a regular note) remains in effect for the remainder of that measure; but the ornament in question is an appoggiatura, not an acciaccatura (also written as a grace note, but without the oblique stroke through the stem), and the answer doesn't make it explicit whether it applies to "all appoggiaturas" or "all ornaments, regardless of their type".
In addition to an answer to the question which of the options is correct, it would also be interesting to understand why the arguments in favor of the other option do not apply.
Comment: @Martin It doesn't matter that the ornament is an appoggiatura, and acciaccatura, or any other kind of ornament. The rule is general: an accidental in the staff before any type of ornament carries through the bar.
Comment: @AAron it doesn't - this is the question I linked to in the second-to-last paragraph of my question.
Comment: Another argument in favor of B♭: If the composer had desired a semitone acciaccatura into the lower note of a major seventh dyad, the lower note of the dyad should have been written as a C♭ (or perhaps the B♭ should have been written as A♯, although that conflicts with the spelling of the chord as including a ♭13; but anyway this chord is confusing since it contains both an F♯ and a G♭ -- this makes me think the composer doesn't know what he's doing).
Comment: @Aaron thanks for the clarification. I wasn't sure if the statement "the accidental always remains in effect" on the other answer applied to all appoggiaturas (as that's what had been asked about) or to all ornaments regardless of their type. Your comment, as well as the other replies to this question, make it clear that it's the latter.
Comment: Having now listened to it, I do think it should be A♯; it sounds like an unresolved leading tone to B.
Comment: @phoog by "I do think it should be A♯", do you mean that the "little note" should be A♯ instead of B♭, and the main note should be B natural (essentially my second interpretation), or do you mean something else?
Comment: @Martin I mean that I think the chord is misspelled: all the B flats should be A sharps.  That pitch sounds to me like it ought to resolve to the B natural that is the third of the G major tonic chord (although the resolution is not in fact realized).  I would spell it as B flat if it sounded like a blue note, which (to me) it does not.  Rather, it evokes the sort of chromaticism one hears in late 19th and early 20th century popular music.  This spelling would also avoid the truly weird circumstance that the chord contains both an F sharp and a G flat.
Answer: I've often wondered why this causes confusion.  If the accidental was on a note other than a grace note or an ornament you would not think twice would you;  you would know that it still applies.  However because its on an ornament a doubt arises.
I think that this is because we tend to view ornaments and grace notes as less significant because they are written smaller.  But that does not alter the fact that they are just as valid as all the other notes (or should be) and the smaller font is just "how they are written".
So the answer to your question is yes, it applies.
Comment: @Martin It's because accidentals apply to lines (and spaces,) not to notes. Which obviously sounds a bit confusing since the essentials in a key signature ARE applied to notes, not lines and spaces :0 It sounds confusing, but I do think it makes sense, when reading, since they represent different concepts too.
Comment: Less significant as they're supposed to take up as little time as possible - particularly acciaccaturas.
Comment: On the other hand, a similar thing could be said about the same note in a different octave - and in this case, the accidental does _not_ apply. In the same manner, it would have been plausible for grace notes to be "separate" from regular notes. Apparently they aren't - and arguably, it's better for readability that way - but this isn't obvious.
Answer: Great question! Whilst an acciaccatura generally plays a note a semitone higher/lower than the target note, that would sound odd here, if the target was in fact B♮. Making the final 'chord' B♮ with B♭. As you say, B♮ isn't part of the designated chord, so odd it would be.
Th slur (or is it in fact a tie?) is often (but not always) part of the sign, but here, I guess it'll signify that unlike a normal acciaccatura, where the grace note is let go as the target is played, the writer wants both B♭s to be held, along with the other notes in the 2nd half of that bar. (It's all pedalled).
A wavy line, showing a 'mini-arp.' would have been more clear, and would end up sounding the same.
Can't for the life of me understand why ♭11 (G♭) is there. What's wrong with leaving the M3 (F♯) that's in the D7 triad anyway? And - ♭13 is the B♭ - with B♮ as well, that chord name and spelling wouldn't be accurate. Maybe another question...
Comment: I'd call it a tie.  I'd also find a wavy arpeggio line for a two-note "chord" to be a bit weird.
Comment: @Martin - the little one gets played on beat 4, with the upper Bb very slightly after, while holding on to the first is how I'd do it. But virtually together.
Comment: @phoog - so probably the way it's written would be the most accurate? Although the little line often associated with acciaccaturas must be seen as a slur, I guess.
Comment: So the way to play this would be the lower B♭ slightly before the beat and the upper B♭ on the beat?
Comment: Regarding the "sounds odd" aspect of B♮, I think it works pretty well in context (in fact, I prefer it that way). Dissonant, sure, but I think it makes a nice climax, and it is resolved in the next measure. The way I used to play it is like a "normal" acciaccatura (from A♯ to B♮), with the A♯ _on_ the beat (simultaneously with the upper B♭).
Comment: @Martin yes.  Tim: as far as I see it, the curvy line is a tie if the pitches are the same and a slur if not.  The only exception I can think of is portato or similar rearticulation of the same pitch.
Comment: @Martin - acciaccaturas are crushed in, so the little note is played on the beat, with the main note following a.s.a.p., thus losing the minimal amount of its own length. Both within the 4th beat, not taking anything from beat 3. (Although pausing past the end of beat 4...)
Comment: @phoog - are you sure you mean yes to Martin's 1st question?
Comment: @Tim would I then be playing the _upper_ B♭ (#3) slightly _after_ beat 4? If I play the little note as B♭ on the beat, and that is tied to the (lower) main B♭ (so nothing happens here), and I also play the upper B♭ _on_ the beat, then it seems like it would just be a regular perfect octave without any ornamentation at all (and it would surely have been written as such).
Comment: Tim yes, I would play the lower note slightly before the beat, but as we're under _molto rall._ in addition to a fermata on the previous beat, it probably doesn't make much difference what goes on in the performer's mind.
Comment: The Wikipedia entry on "Acciaccatura" states that "Whether the note should be played before or on the beat is largely a question of taste and performance practice.", so both interpretations seem to be valid. The German-language Wikipedia adds that the former is more common in classical music, whereas the latter is more common in baroque music and jazz.


Generalized Derangement Problem with $k$ unchanged elements

Question: I am seeking a formula which answers this question:

If we have a set with $n_1$ elements $X_1$, $n_2$ elements $X_2$, $\ldots$, and $n_r$ elements $X_r$, what is the number of ways we can reorder this set so that $k$ elements are in their original position?

If we set $k=0$, the answer would be (Derangements and Laguerre Polynomials)
$$P_{n_1, \ldots, n_r} = (-1)^{n_1 + \cdots + n_r} \int^{\infty}_{0} dx\, e^{-x} \prod_{i=1}^{r} L_{n_i}(x),$$
where $L_{n}(x)$ is the $n$th Laguerre polynomial.
Such a formula would give the number of ways we can reshuffle an initially ordered deck of $52$ cards, so that $10$ cards are in places where their rank (but not necessarily their suit) match the respectively ordered card in the original deck.
Also, there should be a way to use the obtained formula in a summation identity so that the final result is equal to the multinomial coefficient
$$ \frac{(n_1 + \cdots +n_{r})!}{n_1!\times  \cdots \times n_{r}!},$$
i.e., the total number of ways to reorder a set with $n_1$ elements $X_1$, $n_2$ elements $X_2$, $\ldots$, and $n_r$ elements $X_r$.
Answer: After some thought, you can reason that if we have a list with $n_1$
 elements $X_1$, $n_2$ elements $X_2$,... and $n_r$ elements $X_r$, the
 number of ways we can reorder this list so that only $k$ elements
 remain in their original position is

$$ \Omega^{k}_{\,\,n_1, \ldots, n_r} = \sum_{j_1=0}^{n_1} \cdots
 \sum_{j_r = 0}^{n_r} \binom{n_1}{j_1} \cdots \binom{n_r}{j_r} P_{j_1,
 \ldots, j_r} \delta_{N-k,\, j_1 + \cdots +j_r}, $$ where $N \equiv n_1
 + \cdots + n_r$, $\delta_{i, j}$ is the Kronecker delta, and $P_{j_1, \ldots, j_r}$ is defined as it is in the prompt.

Normalization Check
We can check this result by summing over all possible values of $k$ and ensuring we get the multinomial coefficient in return. Namely, checking that
$$
\frac{(n_1+\cdots + n_r)!}{n_1! \cdots n_r!} = \sum_{k=0}^{n_1 + \cdots + n_r} \Omega^{k}_{\,\,n_1, \ldots, n_r},
$$
is satisfied.
Performing the outer sum first eliminates the Kronecker delta and we obtain
\begin{align}
\sum_{k=0}^{n_1 + \cdots + n_r} \Omega^{k}_{\,\,n_1, \ldots, n_r} & = \sum_{j_1=0}^{n_1} \cdots \sum_{j_r = 0}^{n_r} \binom{n_1}{j_1} \cdots \binom{n_r}{j_r} P_{j_1, \ldots, j_r} \\
& = \int^{\infty}_{0} dx \, e^{-x} \prod_{k=1}^{r}\left[ \sum_{j_k=0}^{n_k} (-1)^{j_k} \binom{n_k}{j_k}\,L_{j_k}(x)\right],
\end{align}
where $L_{j_k}(x)$ is the $j_k$th Laguerre polynomial.
Using the identity
$$ \sum_{\ell=0}^{m} u^{\ell} \binom{m}{\ell} L_{\ell}(x) = (1+u)^{m} L_{m}\left( \frac{u x}{1+u}\right) $$
and the limit
$$ \lim_{\alpha\to 0}\, \alpha^{m} L_{m}\left(\frac{x}{\alpha}\right) = (-1)^m\frac{\alpha^m}{m!},$$
both of which are provable by referring to the series definition of the Laguerre polynomial, we find
\begin{align}
\sum_{j_k=0}^{n_k} (-1)^{j_k} \binom{n_k}{j_k}\,L_{j_k}(x) & = \frac{x^{n_k}}{n_k!},
\end{align}
and so we obtain
\begin{align}
\sum_{k=0}^{n_1 + \cdots + n_r} \Omega^{k}_{\,\,n_1, \ldots, n_r} & = \int^{\infty}_{0} dx \, e^{-x} \prod_{k=1}^{r}\left[ \frac{x^{n_k}}{n_k!} \right]\\
& = \frac{1}{n_1! \cdots n_r!} \int^{\infty}_{0} dx\, e^{-x} \, x^{n_1 + \cdots n_r}\\
& = \frac{(n_1+\cdots + n_r)!}{n_1! \cdots n_r!},
\end{align}
as expected. Thus the stated equation satisfies the desired consistency requirement.


Boost Cache helps some pages, hurts others?

Question: I'm working on fixing some performance issues of a Drupal 6 site. Very new to Drupal, been figuring things out as I go, so please bear with me here.
My client has a rather busy site and uses Boost cache. On pages where Boost cache is applicable -- their home page, reviews pages, etc,... -- it works great. Pages are fast, load testing shows that they can take whatever's thrown at them. I just discovered that with Boost enabled, pages that are not eligible for its caching, such as pages with polls that need to pull from the DB each time, they are significantly slower to load then when Boost is disabled entirely.
For instance, here are the Loader.io results of a page in question. The instances where it completed successfully were with Boost disabled, instances where it failed were with Boost enabled. Ignore that 100% error rate test that's second from the top, MySQL actually crashed after the previous test and I forgot to restart it before running again.

All I know for sure is that the errors are caused by MySQL. It appears that Boost adds database overhead, maybe it has to check for information about cached pages and then it has to do a second query to draw the page if it doesn't find the cached information? I'd love any insight anyone can provide!
Edit: Screenshot of Boost expiration settings
Comment: Boost module is created by a performance Guru(mickeytown2). It however has a somewhat complex configuration that can lead to some problems on certain configurations. Check the boost settings page to make sure it does not clear every caches on a page *write*. It's difficult to guess the exact configuration but I think there has to be some configuration that caused it.
Comment: Also, if your pages are interactive for anonymous users, I would not use Boost. Investigate why you needed boost in first place, and try to optimize the bottom first.
Comment: It does clear certain caches on certain write or update operations. I'll update the question with a screenshot in case something jumps out at you. As for whether or not to use Boost, it does feel like the best way to do the majority of the site. There are only a few pages with interactive elements for anonymous users. I'm working on optimizing queries, that's how I discovered this issue in the first place! :-)
Comment: If you have access to the database, convert the boost_cache table to innodb. That should solve a lot of the issues you're seeing.
Comment: @mikeytown2 Did that, unfortunately didn't fix the issue. Same symptoms. Anything else I should check out?
Answer: There is an option in boost that let you count the number of hits even of cached pages. That version hits your database on each page hit. It's fairly small, but it still loads all the modules as it has to go through the standard Drupal initialization.
Make sure you turn that off if it is on to ease the load on the DB.


OpenGLEs doen't color my point well

Question: I want to color my figure of red. With using GL10 to draw element there aren't problem but now using GLES20 the figure is black colored instead red.
Here there is my code:
To set color float array and buffer:
for (int i=0;i<colors.length;i++)
        {
            colors[i]=1f;
            colors[++i]=0f;
            colors[++i]=0f;
            colors[++i]=1f;
        }
byteBuffer=ByteBuffer.allocateDirect(4*colors.length);
        byteBuffer.order(ByteOrder.nativeOrder());

        colors_buff=byteBuffer.asFloatBuffer();
        colors_buff.put(colors);
        colors_buff.position(0);

My Vertex and Fragment shaders:
 private String v_shader="" +
        "attribute vec4 verte;" +
        "attribute vec4 colors;" +
        "varying vec4 vcolor;" +
        "void main(){" +
        "gl_Position=verte;" +
        "vcolor=colors;" +
        "}";

private String c_shader="" +
        "precision mediump float;" +
        "varying vec4 vcolor;" +
        "void main(){" +
        "gl_FragColor=vcolor;" +
        "}";

My function to draw elements:
 public void DrawShader(){
        GLES20.glUseProgram(progra);

        int v_handler=GLES20.glGetAttribLocation(progra,"verte");
        int f_handler=GLES20.glGetUniformLocation(progra,"colors");

        GLES20.glEnableVertexAttribArray(v_handler);
        GLES20.glEnableVertexAttribArray(f_handler);

        GLES20.glVertexAttribPointer(v_handler,3,GLES20.GL_FLOAT,false,12,vertexbuffer);
        GLES20.glVertexAttribPointer(f_handler,4,GLES20.GL_FLOAT,false,16,colors_buff);

        GLES20.glDrawElements(GLES20.GL_LINES,indicies.length,GLES20.GL_UNSIGNED_SHORT,indicies_buff);

        GLES20.glDisableVertexAttribArray(v_handler);
        GLES20.glDisableVertexAttribArray(f_handler);
    }

An other question if i change the color array and put it in the buffer when i called drw the color doesn't change while when i used GL10 to draw element it worked.
 Thanks indeead to all.
Answer: You are mixing uniforms and attributes. Decide which one to have.
In the shader you used attribute: attribute vec4 colors;. To change this into the uniform then move it to fragment shader as uniform vec4 uColor;.
When getting a location you are treating it as an uniform: int f_handler=GLES20.glGetUniformLocation(progra,"colors"); to change it into the attribute you should use int f_handler=GLES20.glGetAttribLocation(progra,"colors");. If you use it as uniform then remove the attribute enabling: GLES20.glEnableVertexAttribArray(f_handler);.
You assign the pointer as an attribute GLES20.glVertexAttribPointer(f_handler,4,GLES20.GL_FLOAT,false,16,colors_buff); to use uniform you need to use it as GLES20.glUniform4f(f_handler, 1.0f, .0f, .0f, 1.0f); and you can remove your color buffer.
How to chose between which to use you should look into the definition of the two (uniform and attribute). But to make it very short when you use uniform the value will be set as a constant for the whole draw call. In your case it means your shape will have one color over the whole surface. The attribute is used per vertex and each vertex will have a specific color, the pixels between the vertices then will have interpolated values (gradient) if the values are different.

OpenGLEs doen't color my point well


How to filter entities in View by all of their taxonomy term reference fields?

Question: Let's say I have a custom entity that has two taxonomy reference fields: categories and tags. And I want to display all entities that have taxonomy term with id 1. The term is a dynamic value(contextual filter) so it can be either the category or tag.
How can I do that in Views? Right now I can filter categories or tags separately but I need to filter both of them.
If I use two filters they will cancel each other because each of them have, in my case, "Display contents of "No results found"" set.
Comment: in d7 there is filter for all taxonomy terms associated with a node. though I can'remember it's name, but it's in the core.
Comment: How is this Drupal 8 specific?
Comment: Then it is in D8 as well, as all functionality was moved in.
Comment: Can you make a screenshot? I was not able to find it. I didn't even know it was in D7(since I haven't been using Views for a while) but someone mentioned it on irc so I've looked and it actually is in D7 Views. But not in D8(at leas I haven't found it).
Answer: You can get an argument from url with views.
Use Provide default value in the contextual filter.

Another way (in drupal 7)would be to use this module: https://drupal.org/project/views_url_path_arguments
Comment: You didn't understood my question. I know how to use contextual filters. I'm asking how to use one argument for all taxonomy term reference fields an entity has.
Comment: Ok, so use one argument for multiple filters?
Comment: I can't because if one field won't return results it will hide the whole View.


Predicting which population generated my observation

Question: I am trying to predict which of my two populations generated an observation.
I have two samples from my two populations, and for future observations, I want to decide which population they belong to.
What is the best way to approach this?
Comment: @kjetilbhalvorsen isn't logistic regression for estimating a dependent variable given a set of independent variables? I want to estimate the class of a variable based on it's value alone
Comment: Look into logistic regression, search this site.
Answer: You can think of this as a binary classification problem; there are a number of different algorithms you can use. @kjetilbhalvorsen points out a commonly used one, logistic regression. Logistic regression need not be used purely for parameter estimation, as you seem to think; any fitted model can be used for prediction. In this case, a fitted logistic regression model can be used to predict the probability of belonging to either class/population.
Aside from logistic regression, you could use decision trees, random forests, support vector machines, or neural networks, among others.


I can't seem to concatenate two strings together in the append() method

Question:

$('resultsBlue').append('
Verschil: ' + (randomNumber1 - randomNumber) / 1000 + ' Seconden
');
#resultsBlue {
  background-color: #6699ff;
  border-radius: 7px;
}

.resultDiv {
  height: 200px;
  width: 300px;
  display: inline-block;
}

Blauw

That's a snippet of all of the code that has to do with this issue
As you can see in the snippet, I'm trying to append multiple data types but it just doesn't seem to work. How do I get it to do what I want? Thank you in advance
Answer: You forgot to put # in the selector.
$('#resultsBlue').append('
Verschil: ' + (randomNumber1 - randomNumber) / 1000 + ' Seconden
');
Comment: O.O.... I have been trying to solve it for three hours now. Thank you anyway haha.
Comment: @Jojo, sometime we face this kind of situation. Please don't forget to accept the answer if it helps----Thanks
Answer: You need to prepend an # for the id.
I think
$('resultsBlue').append('
Verschil: ' + (20 - 10) / 1000 + ' Seconden
');
should be
$('#resultsBlue').append('
Verschil: ' + (20 - 10) / 1000 + ' Seconden
');
Answer: Try $('#resultsBlue') since you're selecting an element which has an id property.


Falha de segmentação durante conversão de imagem para tons de cinza

Question: Estou escrevendo código que deve receber um arquivo de imagem em colorido (Formato PPM) e transformá-lo em tons de cinza (formato PGM no código ASC II) Após ter feito funções para ler, converter as cores e salvar o arquivo, o  código está retornando um erro de segmentation fault logo no início da execução do main. Vocês poderiam me ajudar a identificar o erro?
Esse é o código:
# include <stdlib.h>
# include <stdio.h>
# define MAX 500
typedef struct {
int r, g, b;
} pixel;

void ler_ascii(pixel imagem[MAX][MAX], char *code, int *max, int *coluna, int *linha);
void salvar_ascii(pixel imagem[MAX][MAX], char *code, int max, int coluna, int linha);
void gray_scale(pixel imagem[MAX][MAX], int coluna, int linha);

 int main(int argc, char** argv) {

     pixel imagem[MAX][MAX]; //cria uma matriz de pixeis para armazenar a imagem
     char code[3]; // codigo que identifica se a imagem é ascii ou binária
     int max; //o valor máximo de tonalidade de cada pixel
     int larg, alt; // largura e altura da imagem em pixeis

     ler_ascii(imagem, code, &max, &larg, &alt);
     gray_scale(imagem, larg, alt);
     salvar_ascii(imagem, code, max, larg, alt);

return 0;
}

void ler_ascii(pixel imagem[MAX][MAX], char *code, int *max, int *coluna, int *linha) {
int i, j;
FILE *arquivo;

char nome_arq[50];
printf("entre com o nome do arquivo: \n");
scanf("%s", nome_arq);

if ((arquivo = fopen(nome_arq, "r")) == NULL) {
    printf("Erro ao abrir o arquivo %s\n", nome_arq);
    exit(1);
}

fscanf(arquivo, "%s", code);
fscanf(arquivo, "%d", coluna);
fscanf(arquivo, "%d", linha);
fscanf(arquivo, "%d", max);

for (i = 0; i < *linha; i++) {
    for (j = 0; j < *coluna; j++) {
        fscanf(arquivo, "%d", &imagem[i][j].r);
        fscanf(arquivo, "%d", &imagem[i][j].g);
        fscanf(arquivo, "%d", &imagem[i][j].b);
    }
}

fclose(arquivo);
}

void salvar_ascii(pixel imagem[MAX][MAX], char *code, int max, int coluna, int linha) {
int i, j;
FILE *arquivo;

char nome_arq[50];
printf("entre com o nome que deseja salvar: \n");
scanf("%s", nome_arq);

arquivo = fopen(nome_arq, "w");

fprintf(arquivo, "P3\n");
fprintf(arquivo, "%d\n ", coluna);
fprintf(arquivo, "%d\n", linha);
fprintf(arquivo, "%d\n", max);

for (i = 0; i < linha; i++) {
    for (j = 0; j < coluna; j++) {
        fprintf(arquivo, "%d ", imagem[i][j].r);
        fprintf(arquivo, "%d ", imagem[i][j].g);
        fprintf(arquivo, "%d\n", imagem[i][j].b);
    }
}

fclose(arquivo);
}

void gray_scale(pixel imagem[MAX][MAX], int coluna, int linha) {
int i, j;
for (i = 0; i < linha; i++) {
    for (j = 0; j < coluna; j++) {
        imagem[i][j].r = (int) ((0.299 * imagem[i][j].r) + (0.587 * imagem[i][j].g) + (0.144 * imagem[i][j].b)); //calcula o valor para conversão
        imagem[i][j].g = imagem[i][j].r; //copia o valor para
        imagem[i][j].b = imagem[i][j].r; //todas componentes

        //testa o valor para ver se o mesmo não passou de 255
        if (imagem[i][j].r > 255) {
            imagem[i][j].r = 255;
            imagem[i][j].g = 255;
            imagem[i][j].b = 255;

        }

    }
}
}´

Obrigado
Comment: Você sabe usar um debugador, como o ddd ou gdb? Ajuda muitissimo a descobrir a causa de falhas de segmentação.
Comment: Em outras palavras, você saberia ao menos indicar mais ou menos a linha onde o erro de segmentação está ocorrendo? O seu código tem algum potencial para falha em alguns lugares. Por exemplo, a leitura do "código" (na linha com `fscanf(arquivo, "%s", code);`) pode produzir invasão de memória se a string de código lida tiver mais do que os 3 bytes alocados na variável `code`.
Answer: Você está tentando alocar 250.000 pixels (500 * 500) na pilha (que é 3 MB se cada int ocupa 4 bytes), e depois você passa essa matriz enorme para outras funções. Acredito que isso estoura a pilha, então a solução é alocar a matriz de pixels dinamicamente, pois assim a pilha só guarda um apontador.
Troque:
void ler_ascii(pixel imagem[MAX][MAX], char *code, int *max, int *coluna, int *linha);
void salvar_ascii(pixel imagem[MAX][MAX], char *code, int max, int coluna, int linha);
void gray_scale(pixel imagem[MAX][MAX], int coluna, int linha);

por:
void ler_ascii(pixel **imagem, char *code, int *max, int *coluna, int *linha);
void salvar_ascii(pixel **imagem, char *code, int max, int coluna, int linha);
void gray_scale(pixel **imagem, int coluna, int linha);

Atualize as definições das funções para que sejam compatíveis com os novos protótipos mostrados acima.
Assim, em vez de as funções receberem a matriz inteira, elas recebem apenas o apontador para a primeira coluna da primeira linha da matriz. Com isso a pilha não estoura.
Troque (na função main):
pixel imagem[MAX][MAX]; //cria uma matriz de pixeis para armazenar a imagem

por:
pixel **imagem = (pixel**)malloc(MAX * sizeof(pixel*));
for (int i = 0; i < MAX; ++i)
     imagem[i] = (pixel*)malloc(MAX * sizeof(pixel));

Assim, você aloca um arranjo de apontadores, em que cada posição desse arranjo é um arranjo de pixels.
Como você simplesmente usa a matriz em 3 funções seguidas e depois o programa termina, não há muita necessidade de liberar o espaço que foi alocado para a imagem, mas é boa prática fazer isso mesmo assim, pois mais tarde você pode querer acrescentar mais funcionalidade ao seu programa e nesse caso pode surgir a necessidade de liberar a memória alocada, então é bom que o código que libera a memória já esteja presente.
Acrescente isso logo depois de chamar salvar_ascii e antes do return 0;:
for (int i = 0; i < MAX; ++i)
     free(imagem[i]);
 free(imagem);

Assim, cada arranjo de pixels em imagem é liberado e depois o arrranjo imagem é liberado.
Após realizar essas mudanças, o programa deve funcionar.
Comment: Vetores não são copiados na passagem por parâmetro.


If $y=\frac{x^2+1}{2x+3}$, evaluate $\frac{dy}{dx}$

Question: Solving it would give
$$\frac{(2x-3)(2x)-(x^2+1)(2)}{(2x+3)^2}$$
$$=\frac{2x^2-6x-2}{(2x+3)^2}$$
I don't think it's possible to move ahead from here. The answer is $$\frac{6x-2}{(2x+3)^2}$$
I have serious doubts that the answer given is wrong, but I would like to verify it here nonetheless. Thanks a lot as always.
Comment: wrong sign on the first term of the numerator: should be $2x + 3$ and not $2x - 3$
Comment: Your recent edit made my answer pointless. Please refrain from editing a question once an answer is posted.
Comment: Yes, I was being dumb. Thanks for the help.
Comment: Of course. It was a typo, so I figured I would correct it. I will cancel the edit if you want it.
Comment: I have already done that
Comment: Yeah, no problem.
Answer: $$y'=\frac{(2x\color{red}+3)(2x)-(x^2+1)(2)}{(2x+3)^2}=\frac{2(x^2+3x-1)}{(2x+3)^2}$$
Comment: The book's answer is wrong!
Comment: @Aditya you may verify [here](https://www.derivative-calculator.net/#expr=%28x%5E2%2B1%29%2F%282x%2B3%29)
Comment: But that still does not give he right answer


jQuery — Nested Sortables Plugin — Disabling sortability between parents

Question: I've got a question that I think is simple but I've not been able to figure it out.
This is in regard to this plugin: http://mjsarfatti.com/sandbox/nestedSortable/
Essentially, I want to disable the ability to sort children outside of their parents.
So, I've got this:
<code>CATEGORY 1
      ITEM 1.1
      ITEM 1.2
      ITEM 1.3

CATEGORY 2
      ITEM 2.1
      ITEM 2.2
      ITEM 2.3
</code>
So, I'd like to provide the ability for users to sort the children within their category, and the ability to sort the categories themselves. But I want to disable the ability to move a child to another parent. (e.g. ITEM 1.1 cannot be moved to CATEGORY 2). And also I would like to disable the abilty to nest any parents in any children.
I tried setting it so that the 'nestedSortable' function is called for every new OL but that simple disables sorting for everything entirely.
Thanks for any help.
Answer: Just answered what is essentially an identical question here:
jQuery UI: Only allow sortable within its own parent level, and not above or below
Comment: Holy Shazbots. Thank you schizo. So simple. I was using the NestedSortable plugin when I didn't even need to. Thanks again, I was pulling my hair out trying to get this to work.