Linear combinations of sine and cosine

Question: If you take a linear combination of the cosine and sine function, then the result is again a sinusoid, but with a new amplitude and phase shift.
$$a \cos(\theta) + b \sin(\theta) = A \cos(\theta + \theta_0)$$
This is one of those facts which I've always felt should be more obvious to me than it is. I can't help feeling that I might be missing out on some good "conceptual reason" for this to be true. I did a bit of thinking about it today and I came up with the following explanation which I'm not particularly satisfied with. I feel like there should be some perspective on this which renders the fact obvious.

Multiplying the polar equation $r = 2a \cos(\theta) + 2b \sin(\theta)$ by $r$ yields $x^2+y^2 = 2a x + 2by$. Rearranging terms and adding $a^2 + b^2$ to both sides gives $x^2 - 2ax + a^2 +y^2 -2by + b^2 = a^2 + b^2$ which is identical to
  $$(x-a)^2 + (y-b)^2 = a^2 + b^2$$
  which we recognize as the equation for the circle with centre at $(a,b)$ and passing through the origin. This hints that $r = 2a \cos(\theta) + 2b \sin(\theta)$ should define a parametrization of this circle and, indeed, this holds. This circle can be rotated about the origin so as to have its centre on the $x$-axis. Such a circle will have the simpler equation
  $$r = D \cos(\theta) $$
  where $D=2(a^2+b^2)$ is the diameter of the circle. In polar coordinates, performing this rotation amounts to introducing a phase $\theta_0$. In fact $\theta_0$ is an argument for the point $(a,b)$.

Note I'm not really looking for rigorous proofs of this fact, more like interpretations, really.
Answer: Geometric
Here is a geometric illustration:

Start with two circles around the origin $O$, one with radius $OA=a$, the other with radius $OB=b$. Choose $A$ so its angle is $\theta$ (marked in cyan). Then projecting that onto the $x$ axis will give $OC=a\cos\theta$. Construct a line perpendicular to $OA$ and intersect it with the other circle to obtain $B$. Make sure to choose the right point of intersection: $B$ should be $90°$ behind $A$ in terms of angle, since $\sin$ is $90°$ behind $\cos$. Projecting $B$ onto the $x$ axis gives $OS=b\sin\theta$. Now you could add these projections, but you could also add the original vectors $OA$ and $OB$ to obtain $OD$ and then project the result $D$ to get $OE=a\cos\theta+b\sin\theta$.
Now as you rotate $A$, $B$ and $D$ will rotate along with it. So you can see that as $D$ moves at the same speed but on a larger circle, its projection $E$ will follow a cosine function so you have $OE=d\cos(\theta+\theta_0)$. You can use the Pythagorean theorem to find that $d^2=a^2+b^2$. You can also see that angle $\theta_0$, marked in orange and negative in my case. It's the angle between ray $OA$ and $OD$, and is defined by $\tan\theta_0=-\frac ba$ unless I got a knot in my thoughts with the sign. As usual when using a tangens to compute an angle from a fraction, make sure you end up in the correct quadrant, perhaps use an atan2 function if available.
Complex numbers
Since others answers brought up complex numbers, here is what you get if you do all of this in complex numbers:
\begin{align*}
A &= ae^{i\theta}=a\cos\theta+ai\sin\theta \\
B &= -bie^{i\theta}=b\sin\theta-bi\cos\theta \\
C &= \operatorname{Re}A = a\cos\theta \\
S &= \operatorname{Re}B = b\sin\theta \\
D &= A+B = (a-bi)e^{i\theta} = (de^{i\theta_0})e^{i\theta}
= de^{i(\theta+\theta_0)}\\
E &= \operatorname{Re}D = a\cos\theta+b\sin\theta = d\cos(\theta+\theta_0)
\end{align*}
So the core aspect here is the conversion from the Cartesian coordinates $a-bi$ to the polar coordinates $de^{i\theta_0}$. Which again can be characterized by $d^2=a^2+b^2$ and $\tan\theta_0=-\frac ba$. To avoid confusion: $a,b,d,\theta_0$ are all real numbers here.
Answer: Every sinusoid (of unit angular frequency) is the real part of $Ae^{i\theta}$ for some complex number $A$. But $A_1e^{i\theta}+A_2e^{i\theta}=(A_1+A_2)e^{i\theta}$, so the sum of two sinusoids is again a sinusoid!
Comment: I was confused until I noticed $A$ is allowed to be complex. This is nice, thanks!
Answer: The complex representation (or rotational matrix representation) gives a nice way of visualizing without actually saying we are using complex numbers. Cosine and sine are position of a point that started at the x axis and was rotated by angle $\theta$. $a\cos\theta$ is the segment on the $x$ axis at distance $a$, while $b\sin\theta$ has to start with a phase shift of quarter circle. Adding them means fixing the second circle to the point of the first circle.
Because both rotate by the same angle, we can just add (a,0)+(0,-b) in unrotated frame and rotate both by $\theta$. The resulting $x$ segment is your cosine with a phase shift.

This method also works if the LHS already contains phase shifts.
Answer: Perhaps a better way:
Start with the sum of angles formula for cosine.
$$ A \cos(\theta + \theta_0) = A \cos\theta \cos\theta_0 - A \sin\theta \sin\theta_0$$
Observe that $\frac{A \sin\theta_0}{A \cos\theta_0} = \tan\theta_0$, which can be any real number as $\theta_0$ ranges over $(-\pi/2, \pi/2)$.  In fact, it can be $-b/a$: $\frac{A \sin\theta_0}{A \cos\theta_0} = \frac{-b}{a}$, so that $$A \cos(\theta + \theta_0) =a \cos \theta + b \sin \theta $$
For pictures of what's going on see this page.

Linear combinations of sine and cosine


Does a 150ms latency is good enough to launch a product (USA hosted in Europe)?

Question:
Possible Duplicate:
Can you help me with my capacity planning?

Having worked for weeks on a new mobile app product, we are finally preparing a public launch in the coming weeks. However we wonder if our Europe based servers will be good enough (latency, etc.) for american users. Tested on dotcom-monitor.com and we got around 150ms for CA. Is it good enough?
We are exploring EC2 options but it is way more costly than local dedicated hosting, and I've been told that you should not care / work that much on scalability at early stages.
Considering the time&cost it would take to go to a replicated EC2 worldwide setup, we are not sure wether we want to commit on this too soon.

More info about the BW usage :

On startup, the app performs 3 ajax request to our API (1 login + info & 2 indexes). Typical bw usage would be around 5k (gziped). From europe the biggest request takes 62ms connecting (34ms ssl) & 140ms processing. After that, the app is 100% usable, it will only perform one request at a time on user interaction / push.
Comment: How could anybody here know an answer to your question? We don't know your product, we don't know your requirements.
Comment: Do you have documentation for your internal use that outlines what is and what is not acceptable performance for this app? I'd suggest that rather than looking at numbers, you need a real-world test of how well your app performs under those conditions.
Comment: Just edited to be more specific about the BW usage.
Comment: Besides what has already been said, mobile users tend to have much higher tolerances for latency due to 3G (waiting until the train moves to a better area, low signal, tunnels, etc) and less CPU / RAM available in their devices. Personally, I usually wait 10 - 20 seconds before trying an action again when I'm commuting.
Answer: I'm not sure what you app does, but if it can be proxied the charles might be able to simulator latency and see if you application 'feels' usable with varying amount of 'lag'.
http://www.charlesproxy.com/documentation/proxying/throttling/
If that's not suitable, other network test tools are available.
Comment: Thanks for the tip. Exactly what i should have looked for ;-).
Answer:
PS> ping stackoverflow.com

Pinging stackoverflow.com [22.214.171.124] with 32 bytes of data:
Reply from 220.127.116.11: bytes=32 time=221ms TTL=56
Reply from 220.127.116.11: bytes=32 time=227ms TTL=56
Reply from 18.104.22.168: bytes=32 time=223ms TTL=56
Reply from 22.214.171.124: bytes=32 time=227ms TTL=56

Ping statistics for 220.127.116.11:
    Packets: Sent = 4, Received = 4, Lost = 0 (0% loss),
Approximate round trip times in milli-seconds:
    Minimum = 221ms, Maximum = 227ms, Average = 224ms

150ms is normal for many services on the internet when going across an ocean.
Unless your application is inherently particularly sensitive to latency, 150ms shouldn't be a problem.
(Note, there are plenty of parts of the world where 500ms would be a typical latency.)
Comment: Wow, thats some sick latencies you are talking about. Personally, when it gets over 100ms I begin to worry. Although 150 shouldnt be that much of an issue - but it also depends on the requesters internet connection.
Comment: @FrederikNielsen Not currently helped by doing a download (so looks bad currently). But the point is really in the final two paragraphs (I suspect the OP is based in North America, and assumes what is true in the US in the norm elsewhere.)


Commerce Extra Pane wont drag in checkout UI

Question: I have created a Drupal Commerce pane using the Commerce Extra Panes module. I created a group and field and they show up on the UI. However, its listed in the Disabled section. I tried to drag it into the Checkout pane and when I save it reverts back to the Disabled section.
When I look in the database it does list it correctly in the Checkout pane, but it doesn't actually appear on any page pane.
What is happening here and what can I do to debug more?
Answer: It looks a bit odd, but the only thing I can come up without more information is that you might have the node disabled in the commerce extra panes tab:

If that's not the case, try also to disable the js in the checkout configuration form, click on "show row weights" so you can select the page for each pane without dragging and dropping.


stochastic process with random variable as time, measurable

Question: i have a problem with the following exercise:
Let $X$ be an measurable $\mathbb{R}^d$ valued stochastic process on $(\Omega,\mathcal{F},\mathbb{P})$ and $T$ a finite $T : \Omega\to \big[ 0, +\infty \big)$ random time.
. Show that $X_T$ is $\mathcal{F}$-measurable.
I know how to show $\{\omega\in \Omega|{X_{T(\omega)}(\omega)}\in B\} \in  \mathcal{F}$, but only if T would take values in $\mathbb{N}$.
I have no clue how to show it for a real valued random time.
thank you
edit:Yes $X$ is measurable on the space $(\Omega \times [ 0, +\infty),\mathcal{F}\otimes \mathcal{B}([0,\infty))$
Comment: My answer here may help: http://math.stackexchange.com/questions/190220/the-strong-markov-property-with-an-uncountable-index-set
Comment: Does measurable mean that the mapping $(\omega,t)\mapsto X_t(\omega)$ is measurable with respect to the sigma-algebra $\mathcal{F}\otimes \mathcal{B}([0,\infty))$ on $\Omega\times [0,\infty)$?
Comment: I added the information to the Question. yes measurable was ment like you wrote
Answer: Thank you Bryon Schmuland, the answer of "The strong Markov property with an uncountable index set" does answer my question too.
I was first put off why $T$ should be finite, but since then $\{T<\infty \}=\Omega, X_T$ is well defined for every $\omega$ without having to look at the Limits.
Comment: Can you please explain a bit more about why T should be finite?


What does it mean for a vector function to be $C^k$?

Question: So, I know for a function $f :\mathbb{R}^m\to\mathbb{R}^n$, $f$ is differentiable on $U\subset\mathbb{R}^m$ iff for every point $a\in U$ there exists a linear transformation, call it $Df(a)$ such that
$$
\lim_{\vec{h}\to 0}\frac{\|f(a + \vec{h}) - f(a) - Df(a)\vec{h}\|}{\|\vec{h}\|} = 0
$$
You can determine from this that if $f$ is differentiable then all the partial derivatives of $f$ exist on $U$ and $Df(a)$ is the Jacobian of $f$. We write $f\in C^1(U)$ to say it is once-differentiable on $U$.
So, what exactly does it mean to say $f\in C^k(U)$ for $U\subset\mathbb{R}^m$, and $k>1$? My only thought is that it requires all the partial derivatives of order $k$ to exist, but this is not enough information for the $C^1$ case since not only must the partials exist, but the above limit with $Df(a)$ equal to the Jacobian must also be zero (which are not necessarily always simultaneously true). My second thought was that, at least for the $k = 2$, the Hessian of $f$ must exist, and some limit involving the Hessian must go to zero, but I can't figure out what it is.
There really is, as far as I can tell, no reasonable idea of the "second-derivative" of a vector function exists. The "derivative" of a vector function, as I understand it, is $Df(a)$, which is a function that maps a vector $a$ to a matrix. So if we were to take the derivative of this, the "second" derivative, what kind of object would it be? Would it be a tensor?
Comment: If all partial derivatives of $f:\mathbb{R^m}\longrightarrow\mathbb{R}$ exist and are continuous in some neighborhood $U$, then $f$ is $C^1$ on $U$. One can use this notion to extend the idea of differentiability classes for vector functions and for values other than $k=1$
Comment: @Fimpellizieri I've only ever seen the theorem that $f$ is differentiable (that is, there exists a linear operator such that the limit I wrote goes to zero) **iff** all the partial derivatives exist *and* the limit I wrote, with $Df(a)$ replaced by the Jacobian, goes to zero. This doesn't require any notion of continuity of the partial derivatives. How do you use continuity?
Comment: I have posted a proof.
Answer: Well, that's pretty simple if you take the abstract point of view: as you mention it, the differential of a  map $f\colon U\subset \mathbf R^m\longrightarrow \mathbf R^n$ at a point $a\in\mathbf R^m$ is a linear map map $Df(a)\in \mathcal L(\mathbf R^m,\mathbf R^n)$ which is tangent to $f$ at $a$.
Now, if $f$ is differentiable at every point of $U$, you define a (first order) differential map
\begin{align}
Df\colon U\subset\mathbf R^m & \longrightarrow \mathcal L(\mathbf R^m,\mathbf R^n),\\
a & \longmapsto Df(a).
\end{align}
This differential map $Df$ may in turn be differentiable at a point $a\in U$. You then obtain a second order differential $D^2f(a)$, which is a linear map in $\;\mathcal L\bigl(\mathbf R^m,\mathcal L(\mathbf R^m,\mathbf R^n)\bigr)$, tangent to $Df$ at $a$.
As we have a canonical isomorphism $\;\mathcal L\bigl(\mathbf R^m,\mathcal L(\mathbf R^m,\mathbf R^n)\bigr)\simeq\mathcal L^2(\mathbf R^m,\mathbf R^n)$ (the set of bilinear maps from $\mathbf R^m$ to $\mathbf R^n$, we identify $D^2f(a)$ with the corresponding bilinear map, which is represented by the Jacobian matrix once a basis has been chosen.
Comment: Ok, so my idea of it being a "tensor" was somewhat in the right direction. Can I ask, does this notion of higher order derivatives of vector functions lend itself easily to other generalizations of facts of higher order derivatives of scalar valued functions? For example, how is your second derivative related to the partial derivatives of $f$? What norm do you use in the limit definition of $D^2f(a)$, the Frobenius norm for matrices? If a function is $k$-differentiable in the sense you give, does it have an $k$th order approximation by Taylor polynomials?
Comment: The questions I asked above are more-or-less rhetorical (especially the one on Taylor polynomials, but I would be interested in the relationship to partial derivatives if you have time), I really just want to know if your $D^2f(a)$ is the "right" notion of the second derivative to work with generalizations of theorems of calculus on $\mathbb{R}$.
Comment: The norm in use is the usual norm for linear maps (which does not depend on any matrix representation), and, yes, you obtain a Taylor's formula. My reference would be Henri Cartan's *Differential Calculus*. For your information, Henri Cartan was one of French mathematicians who founded the *Bourbaki* group, towards 1935.
Comment: This book? https://www.amazon.ca/Differential-Calculus-Henri-Cartan/dp/0901665053/ref=sr_1_8?ie=UTF8&qid=1511543604&sr=8-8&keywords=henri+cartan+differential+calculus
Comment: I guess so – I used the French version when  I was a student.
Answer:
Thoerem: Let $U\subset \mathbb{R}^m$ be open and let $f:U\longrightarrow \mathbb{R}$ be such that, for each $i\in\{1,\dots,m\}$, the partial derivative $f_i=\frac\partial{\partial x_i}f$ exists and is continuous throughout $U$.
  Then $f\in C^1(U)$.

Proof: For each $x\in U$, $i\in\{1,\dots,m\}$ and $h_i\in\mathbb{R}$ such that $x+h_ie_i \in U$, we have that
$$f(x+h_ie_i)=f(x)+h_if_i(x)+h_i\epsilon_{i}(h_i;x), \tag{1}$$
where $\epsilon_{i}$ satisfies $\lim_{t\to0}\epsilon_{i}(t;x)=0$ for all $x$. This limit condition implies that
$$\lim_{h_i\to0}\frac{f(x+h_ie_i)-f(x)}{h_i}-f_i(x)=\lim_{h_i\to0}\epsilon_i(h_i;x)=0$$
and hence that $f_i(x)=\lim_{h_i\to0}\frac{f(x+h_ie_i)-f(x)}{h_i}$.
Notice that because $U$ is open, there is always a neighborhood of $0$ in $\mathbb{R}$ of valid $h_i$.
The value of $\epsilon_i$ when $h_i=0$ does not change the validity of equation $(1)$, so we set $\epsilon_i(0,x)=0$ for all $x$. It then follows that $\epsilon_i(\cdot\,; x)$ is continuous in $h_i$ for all $x$, and that $\epsilon_i(0\,;\, \cdot)$ is continuous in $x$.
Moreover, it follows from the continuity of $f_i$ that $\epsilon_{i}(h_i\,;\,\cdot)$ is continuous in $x$ for all $h_i\neq 0$, and hence for all $h_i$.
Thus, $\epsilon_{i}$ is continuous and $\epsilon_{i}(0;x)=0$ for all $x$.
Now, let $a\in U$ and $h=(h_1,\dots,h_m)\in\mathbb{R}^m$ be such that $a+h\in U$. Then:
\begin{align}
f(a+h)-f(a)
=f\left(a+\sum_{i=1}^mh_ie_i\right)-f(a)
=\sum_{k=1}^m\,f\left(a+\sum_{i=1}^{k}h_ie_i\right)-f\left(a+\sum_{i=1}^{k-1}h_ie_i\right),
\end{align}
where the sum $\sum_{i=1}^{-1}$ is taken to be the empty sum, $0$.
We may then rewrite it as
\begin{align}
f(a+h)-f(a)&=\sum_{k=1}^m\,f\left(\left(a+\sum_{i=1}^{k-1}h_ie_i\right)+h_ke_k\right)-f\left(a+\sum_{i=1}^{k-1}h_ie_i\right)\\
&=\sum_{k=1}^m\,h_k\cdot f_k\left(a+\sum_{i=1}^{k-1}h_ie_i\right) + h_k\epsilon_{k}\left(h_k;a+\sum_{i=1}^{k-1}h_ie_i\right)
\end{align}
Consider $\nabla f:U\longrightarrow \mathbb{R}^m$ the gradient of $f$, that is, $\nabla f(x)=(f_1(x),\dots,f_m(x))$.
We define $Df(a)h=\langle\nabla f(a), h\rangle=\sum_{i=1}^m\,h_if_i(a)$.
Then:
\begin{align}
f(a+h)-f(a)-Df(a)h
&=\sum_{k=1}^m\,h_k\cdot \left(f_k\left(a+\sum_{i=1}^{k-1}h_ie_i\right) -f_k(a)\right)
+ h_k\epsilon_{k}\left(h_k;a+\sum_{i=1}^{k-1}h_ie_i\right)
\end{align}
Now, as $h\to 0$, we have that
$$f_k\left(a+\sum_{i=1}^{k-1}h_ie_i\right) -f_k(a)\longrightarrow 0$$
because the $f_k$ are continuous.
Moreover, $|h_k|\leq \lVert h\rVert$, so $\frac{h_k}{\lVert h \rVert}$ remains bounded as $h\to 0$ and hence $\frac{h_k}{\lVert h \rVert}\cdot \left(f_k\left(a+\sum_{i=1}^{k-1}h_ie_i\right) -f_k(a)\right)$ vanishes as $h\to 0$.
Finally, in a similar fashion we have that $\epsilon_{k}\left(h_k;a+\sum_{i=1}^{k-1}h_ie_i\right) \to 0$ as $h\to0$, because $\epsilon_{k}$ is continuous and it vanishes whenever the first argument is $0$.
Since $\frac{h_k}{\lVert h \rVert}$ remains bounded as $h\to 0$, once again the product $\frac{h_k}{\lVert h \rVert}\cdot \epsilon_{k}\left(h_k;a+\sum_{i=1}^{k-1}h_ie_i\right)$ vanishes as $h\to 0$.
It follows that the limit $\lim_{h\to0}\frac{f(a+h)-f(a)-Df(a)h}{\lVert h \rVert}$ exists and is $0$, that is, $f$ is differentiable at $a$ and $Df(a)=\langle\nabla f(a),\cdot\rangle$.
Since $a$ was arbitrary, we have that $Df$ is given by $x\mapsto \langle \nabla f(x),\cdot\rangle$.
Finally, because the $f_i$ are continuous, $Df$ itself is continuous, which concludes the proof. $\square$


Non-participation bias: weighting for the inverse of the sampling fraction

Question: This and other studies, where only a proportion of people return a completed questionnaire, suffer from non-participation bias. I have previously just compared participants with non-participants to see if there are any systematic differences and comment on them. However, the study in the link uses "weighting for the inverse of the sampling fraction" which I am not familiar with. Can anyone share any wisdom?
Answer: Suppose your information suggests that $50\%$ of men complete the survey and $80\%$ of women complete the survey.
Then you might weight the actual responses by men by $\frac{1}{0.5}=2$ and the responses by women by $\frac{1}{0.8}= 1.25$
Comment: Thank you @Henry. Suppose the responders are 80% male but the total sample has 50% males? Or, more complex still, suppose responders have a mean age of 30 but the total sample mean age is 20? How would one approach these scenarios?
Comment: The natural approach would be to try to get the weighted samples to reflect the population distribution as far as possible on things that matter (which may be age and gender).  A risk is that you end up with small sub-samples in particular categories, so the only teenage boy who could be bothered to fill up the form might get heavily overweighted despite being unusual


Do I have to re-install the DNS server after I switch to FIOS router?

Question: HP ML350e - Windows server 2008 r2 - Active directory
I have put the FIOS router on the network to replace the Road runner router.
I have also restarted all the network equipments and server, but I can't access the internet.
All the computers under this domain can access the server but not internet.
Do I have to update any data on the DNS server?
Thank you.
Comment: Did lan IP address of then new router change?
Comment: They are the same, 192.168.0.1 is the gateway, 255.255.255.0 is the subnet.
Answer: Something changed between the router swap, possibly the internal/local IP of the router as Danila mentioned. If possible compare the configuration on the two routers to verify the internal addressing settings are the same as before (external IP settings will likely be the same unless you also changed ISPs). There should be a console or intranet web interface on both routers to see detailed information such as internal IP address, subnet mask, and default gateway. Try plugging a laptop directly into the routers to get Internet working on the laptop, then change settings on the FIOS router to work with your existing internal network. You may need to contact your FIOS provider to see or change settings on their device.
Comment: Thanks for the suggestion, but I have already compared both of the router setting, the settings are the same. I found it is funny that, it would work after I ping yahoo.com... does it make any sense that if I have the primary DNS as 192.168.0.100(the server itself, it is the AD, DNS, and file sharing server, only server) and secondary as 184.108.40.206?
Comment: does it make any sense that if I have the primary DNS as 192.168.0.100(the server itself, it is the AD, DNS, and file sharing server, only server) and secondary as 22.214.171.124? - > That is fine, only 22.214.171.124 DNS will not be able resolve local addresses if 192.168.0.100 is down.
Comment: I found the problem, it is because the forwarders still has the old DNS servers from Road Runner. I have entered the Google public dns and everything is working fine now. But am I suppose to leave the forwarders empty? Again, thanks for your help.
Comment: For any AD environment, leave the public DNS servers out of the picture with the exception of root hints. Let AD and domain controllers do all your internal DNS resolution. You only need forwarders for rare circumstances such as a DNS zone that is not known by public DNS servers. For example, if you have a persistent VPN tunnel to a vendor and in order to use a service of theirs you have to direct DNS clients to a DNS server on the other side of the tunnel. You would say for all 'vendor.zone' requests, use DNS server [vendor DNS server IP].


JavaScript foreach sends everything at the same time

Question: I'm new in javascript programming so i experienced a problem while i was trying to make a script.
I have an textarea and a button that calls the function " test() "
In the textarea, I'm going to insert Links and I am going to use AJAX to post each link and get a response from the callback.
I can do all this no problem, by using jquery  function .each or for(i=0;i

function test() {
    document.getElementById("qitu").innerHTML = 'Checking Started...';
    var mylines = $("#ti").val().split("\n");

    for(i=0;i<mylines.length;i++) {
        if(mylines[i] != "") {
            $.ajax({
                type:       "POST",
                url:        "callback.php",
                data: { checklink : mylines[i] },
                 beforeSend: function() {
                    document.getElementById("qitu").innerHTML = 'Checking ' + mylines[i];
                 },
                 success: function(data) {
                    var result = JSON.parse(data);
                    i++;
                    if(result.status == 'invalid') {

                    } else {

                    }
                 },

                 complete: function() {
                    document.getElementById("qitu").innerHTML = 'Checking is done';
                 }
            });
        }

    }
}

So is there any recommendations ?
Comment: Ajax is **asynchronous**. It takes almost no time to *start* a request, but they take some time to complete.
Comment: @Fokker then you have to start the second request in the "success" or "complete" callback from the first one.
Comment: I can recommend using the async library for tasks like this: https://github.com/caolan/async. Promises might also be worth looking into.
Comment: @Pointy  thats what i want, i dont want the second request to start without the last one being completed ?
Comment: @David Would there be any other way without having to install that ?
Comment: oh, good idea, so i would just remove the for() fucntion and start from line 0 which is the first line and then i would increase it everytime in the success or complete, thanks I hope this works.
Answer: Okay i fixed this by calling the function on complete and proceeding with the next line by keeping record of the number of lines after each error or success
function other(n,b,g) {

document.getElementById("qitu").innerHTML = 'Checking Started...';
var mylines = $("#ti").val().split("\n");
var good = 0;
var bad = 0;
var i = 0;
var remaining = mylines.length;
    if(mylines[n] != "") {
        $.ajax({
            type:       "POST",
            url:        "class.uploader.php",
            data: { mydata : mylines[n] },
             beforeSend: function() {
                // my loading function
             },
             success: function(data) {
                var result = JSON.parse(data);
                if(result.status == 'invalid') {
                    b++;
                    document.getElementById("bad").innerHTML = b;

                } else {
                    g++;
                    document.getElementById("good").innerHTML = g;
                    document.getElementById("mythings").innerHTML += '
' + result.thing + '	' + result.code + '
';
                }
             },
             complete: function() {
                 n++;
                 if(n < mylines.length) {
                    other(n,b,g);
                 }
                 remaining -= n;
                 document.getElementById("remaining").innerHTML = remaining;
                if(remaining == 0) {
                    document.getElementById("qitu").innerHTML = 'Checking is done';
                }

             }
        });
    }

}
I got the idea from a guy who commented on this page and i hope this helped someone.


Is there a way to load content of each tab in the view using AJAX?

Question: I've created View to display my content and I'm using Quicktabs module https://drupal.org/project/quicktabs to format the output of this view into the tabs.

Is there a way to load content of each tab in the view using AJAX? I can't see any option.
Comment: Have you checked the "use ajax" setting in Advanced-Tab inside Views settings? http://i.stack.imgur.com/a8uGJ.png
Comment: Yes. But it has no effect on AJAX tabs. Did you try it with this quicktabs module in views?
Comment: No, i use this module only to create quicktabs-blocks where i reference my views. I didn't try it the other way round, sorry, i think i misinterpreted your question.
Answer: I had a similar problem. The following code worked perfectly for me.
<code>jQuery(".quicktabs-wrapper ul a").click(function(e) {
    e.preventDefault();
    jQuery(this).parents('.quicktabs-wrapper').find('.quicktabs_main  .quicktabs-tabpage').addClass('quicktabs-hide');
    showId = jQuery(this).attr('id').replace("-tab-", "-tabpage-");
    jQuery('#' + showId).removeClass('quicktabs-hide');
    jQuery(this).parent().siblings('li').removeClass('active');
    jQuery(this).parent().addClass('active');
  });
</code>


Where does Gradle log to in context of TestKit's GradleRunner?

Question: My Spock specification starts the Gradle build with the option --debug using the TestKit's GradleRunner like this:
GradleRunner.create()
            .withProjectDir(testProjectDir.root)
            .withPluginClasspath(pluginClasspath)
            .withArguments('myCustomTask', '--debug', '--stacktrace').build()

But I can't find Gradle's output anywhere. Neither on the console nor in JUnit's output under the build directory nor in the temporary directory used by the GradleRunner.
Gradle Version is 4.9, JUnit Version 4.12.
Answer: GradleRunner buffers the output of the launched Gradle build internally in memory. You can access it with getOutput() of BuildResult returned by GradleRunner.build(). Alternatively, you can call GradleRunner.forwardOutput() which duplicates the output to System.out of GradleRunner.


Error 401: Invalid Client. Google API with Postman

Question: My company's client organization would like us to do data pulls on their campaign data using AWS Lambda so that our digital marketing analysts can analyze the data and use predictive modeling (data is stored in AWS data lake). However, I'd like to pre-test API calls  using Postman. We will be using the Google Campaign Manager API (GCM 360).

When I try to generate a New Access token in Postman, I get this Error No OAuth Client was found. I made sure that the client secret values,scope, token URL,Auth URL, and callback url were correct and their values matched Google API Playground.
I then looked at the Postman log trace and I am seeing an incorrect
Client ID that does not match what's Postman nor the CGM 360 API
credentials.  Here are the screen scrapes and not the client ID in the
postman trace log does not match what's defined in GCM360's OAuth
credentials page. Are these 2 completely different client IDs?
See screen scrapes of the GCM360 API's credentials page, Postman Authorization page, and the error message below.
Thanks:
Answer: When encountering an "Error: No OAuth Client was found" message in Postman while trying to generate a new access token, there are a few potential reasons for this issue:

Incorrect Client ID or Client Secret

Double-check that the Client ID and Client Secret values entered in Postman match the credentials provided by the Google Campaign Manager API. Any mismatch in these values can result in authentication errors.

Authorization Configuration:

Ensure that the authorization configuration in Postman is correctly set up. Verify that the token URL, authorization URL, and callback URL are accurate and aligned with the Google Campaign Manager API's requirements.

Scope:

Confirm that the scope you're requesting in Postman matches the scope defined in the Google Campaign Manager API credentials. The scope determines the access permissions granted by the access token.
It's important to cross-check all the details, such as Client ID, Client Secret, URLs, and scope, between the Google Campaign Manager API credentials and your Postman configuration. Any discrepancies can lead to authentication failures.
Comment: This looks like ChatGPT
Comment: When I ran this using Postman Web version, I got a 401 and later an access block because of one of my scops which was invalid. Here is the message the popup error dialog gave me: Some requested scopes were invalid. {valid=[https://www.googleapis.com/auth/dfareporting, https://www.googleapis.com/auth/ddmconversions], invalid=[https://www.googleapis.com/auth/dfatraffiking]} Learn more about this error. So I had to removing the DFA traffiking scope. I wonder if this needs readonly permissions? I will try to add that.
Comment: Thanks @Mohsin, there was one main issue that I had which was  that I in attempting to access the 3 scopes for GCM 360, somehow authorization didn't like the scope: https://www.googleapis.com/auth/dfatrafficking. When I removed that form the list of scopes it worked. No more 401 Error.


The path admin/content/files is missing in Drupal 8.5

Question: I have installed Drupal 8.5 and today I realised that the tab admin/content/files is missing. Thanks to my backups I realized that this tab link is already missing since the 14th of March. Prior to the disappearance on the link I did not install any module. How can I solve this issue?
Comment: we will need more information before we can help you solve this ... but you can setup both in different location and probably compare them.  See if they have different enabled modules `drush pm-list --type=module --status=enabled`.  Are there any file related modules that might interfere ?
Answer: I had the same problem and was because the route that creates the page (view.files.page_1) was not recognized by Drupal. Why? I don't know, but I reinstalled the Views UI and the Views module and the problem was solved.
You can read about this problem in Add Item for Files under Content Menu and this is why we added in the Admin Toolbar module a validation for the route. The file module can be installed and the route can be missed from the site.
Answer: By mistake I've disabled the View that generates the page, and the only thing I needed was to enable it again, and the tab reappeared. Thanks for the support.
Comment: Maybe was the same problem for me :-)


EM algorithm: Why do we compute the expectation with respect to the conditional distribution?

Question: I am trying to understand the EM algorithm, and I see that in the expectation step,we need to compute $E_{Z|X} {\log p(X,Z)} = \sum_{Z} {p(Z|X) \log p(X,Z)}$ where $Z$ is the hidden variable and $X$ is the observed variable. I am understanding that we need to compute the expected value of $\log p(X,Z)$ since we cannot compute the exact value of $\log p(X,Z)$ due to the variable $Z$ whose value we are not aware of. But I have 2 separate confusions here:

Why don't we do, say, a block coordinate descent instead? That is, why don't we compute $Z$ and the parameters of the model (say $\theta$) iteratively such that we compute $Z$ in one step using the current value of $\theta$ and $\theta$ in the other step using the current value of $Z$?

Let's say I understood that we cannot do block coordinate descent but we need to compute that expectation of $\log p(X,Z)$. Then why don't we compute $E_Z {\log p(X,Z)} = \sum_{Z} {p(Z) \log p(X,Z)}$ but we compute $E_{Z|X} {\log p(X,Z)}$? What does it mean (intuitively, or in words) to compute an expected value with respect to a conditional probability?
Comment: I think in one of my unanswered question you may find your answer.
Comment: Here is my question https://stats.stackexchange.com/questions/277073/question-about-e-step-in-em-algorithm-a-challenge-part-any-help-please please read through the posted photo.
Comment: I think the first two paragraphs are belong to your second question. I really confused about it, but may it will be clear for you.
Answer: For your first question: in EM you are alternating between updating $Z$ and updating $\theta$. (Note however that $Z$ is commonly a set of categorical variables, i.e. labels, in EM applications, so it is not exactly a "gradient descent" per se.)
For the second question, the most common example of a conditional expectation is probably the standard regression problem, i.e.
$$y=f(x)+\epsilon\,,\,\mathbb{E}\big[\epsilon\big]=0\implies\mathbb{E}\big[y\mid{x}\big]=f(x)$$

With regards to the first question, I would recommend checking out the Wikipedia description. You could "update $Z$" based on the current $\theta$ (called hard EM), but in general you can update the entire posterior $p\big[Z\mid{X,\theta}\big]$ (note that the observed data $X$ is fixed throughout, see also here). For a concrete example of the difference, see here.
With regards to the requested clarification on the second question: Imagine you want to do standard MLE for $\theta$ based on the data $\hat{X}$. But the data $\hat{X}$ is not fully observed, that is, $\hat{X}=[X,Z]$ but $Z$ is unknown. As noted in Wikipedia, a natural approach would be to maximize the marginal likelihood
$$p\big[X\mid{\theta}\big]=\sum_Zp\big[\hat{X}\mid{\theta}\big]$$
over possible $Z$ values. Since $X$ is known and fixed, EM proceeds by taking the expected value of the likelihood over possible $Z$ values, conditioned on $X$ and $\theta$.
Note that $p\big[Z\big]=\int{p}\big[Z\mid{X}\big]p\big[X\big]dX$. But since $X$ is known and fixed, we don't care what the likelihood of $Z$ is given some other hypothetical value of $X$. (For simplicity I omit the $p\big[\ldots\mid{\theta}\big]$ in the above.)
Comment: Thanks, but I am confused. Followup questions: 1) We are not updating the value of $Z$ at all, right? We are just updating the expected value of log likelihood $E(\log p(Z,X))$. Do we need to recompute $P(Z|X)$ in the next expectation step to recompute $E(\log P(Z,X))$? Even if we do that, we are not updating the actual value of $Z$ in the expectation step. 2) I can't see the relation of this example to $E_{Z|X}{\log p(Z,X)}$. The condition is not a subscript in your example, right? And the main point of my question is why don't we compute $E_Z{\log p(Z,X)}$ instead of $E_{Z|X}{\log p(Z,X)}$.
Comment: You want to get the value of Z using your data.


What does a number inside a parentheses in a chord name mean? Example: B(7)#9b9

Question: What does a number inside a parentheses in a chord name mean? Here are some examples I have found: B(7)#9b9 no 5, Ab(7) #9#11 no R, A(7)b9sus no b7 .
For context, I found them on this James Hober paper, starting at page 6: The 43 Four-Note Qualities
Answer: It's normal to write altered chord extensions, and to some degree altered chord notes, in parentheses. The (minor or major) sevenths though, are normally never parenthesized.
However James Hober uses some unusual notation. This is a consequence of that there are some unusual chords or chord voicings that he is trying to represent.
If you look carefully you will find that the only figure that is parenthesized in his list is the 7. Further you will find that in all instances of chord voicing names that has this parenthesized 7 it is also stated that it is omitted ("no b7").
(Example: "B(7)#9b9sus+ no R, b7" meaning the chord B-E-G-A-C-D with the root 'B' and the b7 'A' omitted, leaving the notes C-D-E-G. (I would like to see the functional analysis that would arrive at calling this voicing by this name rather than just Cadd9 or perhaps G6sus4...))
Why then does he list the 7 in parentheses when it also says it is omitted? It's perhaps because he has interpreted that the additional chord extension notes are to be seen as extensions to a dominant chord, and perhaps also that calling most of them added tones would be quite unorthodox.
So the parenthesized sevens you see in James Hober's list are merely an indication that the chord can be considered a dominant chord, but that is missing the dominant seventh.
Comment: Note: For normal notation of chords the parentheses around chord extensions are merely there for improved readability and does **not** signify lesser importance, and certainly not that they are to be omitted. Omitting extension notes or other notes could however be done by the discretion of the performer.
Comment: Yes, in my experience, chords that tell you to omit a note are usually in an "analysis" context where you try to be as exact as possible. If you were to give that instruction to an improviser, they would most likely just ignore it unless the chord by nature was extremely limiting and specific (i.e. a heavily modified pentatonic scale or something). But even then, chords are guidelines to an improviser, a skilled one can make any consonance/dissonance work for them.
Answer: The number in a parenthesis isn't strictly equated to a Dominant seven per se. When music is written by hand, the use of parenthesis is used just to make groups of notes and "alterations" more clear to the reader, so it's a matter of preference. Unlike in computer science where syntax is non-negotiable, there are many ways to convey formal concepts in music, especially when referring to music theory and chord alternations.
There is a common convention though in music that if you just list a 7, you're implying a dominant seven (flatted 7). You would have to specify "Major 7" or "Maj7" or "M7" or the triangle Aebersold notation used in the paper itself depending on your notation preference to get an unaltered "Major 7".
So to use your first example:

B(7)#9b9 no 5

This is a B major, dominant 7, with a sharp 9, a flat 9, and omit the 5th.
I personally would have written it like this (on a computer)

B7(#9,b9, no 5)

Because B dominant 7 is a very common chord, so it is in a sense, the "core" of the cord. Then alterations would follow after.
If written by hand I might have made the 7 a subscript, and the alterations in parenthesis as a superscript to increase the clarity, similar to this:

B7(#9,b9, no 5)
Answer: The reason for parenthesis is clearly to denominate options (ad libitum) that dont go thru the whole measure:

D(m) is d - g with ad libitum alternating f/f♯
Dm2 is d - e - a
Dm(2) is d - f - a with ad libitum alternating e/f
Dm4 is d - g - a
Dm(4) is d - f - a with ad libitum alternating f/g
Dm(2/4) is d - f - a with ad libitum alternating e/f/g
Dm2(4) is d - e - a with ad libitum alternating e/g
Dm9(4) is d - e - f - a with ad libitum alternating f/g
Dm9(4) is d - e - f - a with ad libitum alternating f/g
Dm11(2) is d - f - g - a with ad libitum alternating e/f
Dm11(9) is d - f - g - a with ad libitum added e

So yes, there is a defined System, but it might be that few really understand it. You can do that for any modificator to denominate a modification that depends on the melodical structure of the part you want to key with the chord, so instead of writing:
| C | C ; C7 | G |
you just trust the musicians experience (and the perhaps already given melodic notes below) and just write:
| C | C(7) | G |
…while…
| C | C7 | G |
would really mean: if someone filling it with strings on the keyboard, please fill with c-e-g-b♭ for the whole measure.
Answer: I believe it means a dominant chord with its alterations. Dominant meaning the 7th degree is flat.


Limit which ports a user can bind

Question: I'm working on a setup for a Linux based system in which user applications are executed in Linux Containers to provide confinement and limited capabilities. Each application is launched under in a container with a specific user ID.
Now, given that some of these applications are going to have server roles, I would like to be able to control which ports a specific user can bind (both TCP and UDP). One solution is manually polling <code>/proc/net/(tcp|udp)6</code>? but this is very inefficient for obvious reasons. So, I was wondering if there is a better way to do this?
Comment: By "Linux Containers" do you mean [LXC](http://lxc.sourceforge.net/)?
Comment: Yep, but that is somewhat besides the point, as LXC simply relies on kernel modules. I'm investigating GRSecurity as a possiblity.
Answer: AppArmor and SELinux can be used to restrict network access by processes.
Comment: AppArmor turned out to be the good solution. Thanks ;)
Answer: There is also iptables user match.
Comment: an example would be nice :)
Comment: The iptables user match only works for OUTPUT chain so I don't think it's a good solution. Your app will be able to open the port and receive data but NOT sending. It really depends on the protocol you use through this port (http, ...). If the protocol you use needs negociation/exchange before being able to be used, you can use this...

Limit which ports a user can bind


Displaying a large collection in a DataGrid

Question: The amount of items in collection: ~100k
The amount of field displayed in columns: 4-10
The problem itself - the collection is taken from a database using EntityFramework. It takes about 10-12s on dev computers to load and materialize all the required data. Yet another thing that comes up is that the same collection can be bound to several controls, and, therefore, they must be filtered separately (= not setting the default collection view filters). Currently, I set the binding as follows:
Binding b = new Binding();
b.Source = new CollectionViewSource() { Source = MyLargeCollection }.View;
MyDataGrid.SetBinding(DataGrid.ItemsSourceProperty, b);

Creating a new CollectionViewSource greatly increases the time it takes to initialize - several minutes (and I suspect that it is enumerating the 100k collection for some reason). I mean that if I just set:
b.Source = MyLargeCollection;

It will just take those 10-12 seconds to load and materialize data from the database.
The question - is there some problem with my code? If not - what would be the right approach for binding the same large collection to different items controls but with different collection views?
Answer: Just use Linq to Entities to load the entities with its specified filter to make sure you don't load all 10k records because no user is interested in a grid with 10k records.
Example of binding to a query:
grid1.DataContext = (from i in context.MyItems
                    where i.MyPropertyToFilter == "myFilter"
                    select i).ToList();

grid2.DataContext = (from i in context.MyItems
                    where i.MyOtherPropertyToFilter == "myOhterFilter"
                    select i).ToList();

In this way you only load the records needed for your controls
Comment: Well, this only solves the problem partially. I understand that this is a neat way to filter and sort the resultset.

Consider a case when you need to have something like 100k entries in one control (== or create a 'feeling' for the user that there are 100k entries there). What is the best way to optimize it? First thought - just query the needed data => data virtualization. Yet this will raise problems with such methods as IndexOf in the underlying collection and such.
Comment: If you need such a functionality you will need to implement an own class that wraps your full collection that is not yet initialized and create custom implementations of Count, IndexOf, Indexer, ... A good suggestion is to implement IList. Hope this helps you
Comment: Well, I ended up querying partial data that does not get materialized and tracked by entity framework. At the same time I use SelectedValuePath=Id to select entities by id. This way the memory consumption is minimal. The time to load such a collection varies on my machine from 0.2 to 0.5 second for a set of 100k entities. The memory consumption is at approx 20-30 mb for two nvarchar(255) columns. This is just my case, not a benchmark.
Comment: Implementing IList was an option, yet when you do a partial select (with some WHERE params) you still have a problem with IndexOf as it requires at least one more query to the database and EF does not actually support selecting the row number in the resultset. Thanks for the answer though. It got me going. :)


Is it possible to tell which cpus are hyperthreads of the same core?

Question: I have a server that is a quad-core i-7 with hyperthreading enabled. The kernel recognises this as 8 cpus, as it should. I want to create a couple virtual hosts running on this machine. virt-manager lets me select which cpus are used on which machine. I want to configure this so that I assign both cpus in a hyperthreaded pair to the same virtual machine. This way one machine under heavy load will not effect another virtual machine by sharing a single core due to the hyperthreading. But I do want hyperthreading available to each vm because I am running tasks that involve heavy parallelization.
So, how can I tell which cpus the kernel recognizes are a pair? I would suspect cpu 0 and cpu 1 make a pair, then cpu 2 and cpu 3, and so on, but I am not sure how to test/confirm.
Answer: This link describes how to match physical id, core id, and sibling count to identify which entries in /proc/cpuinfo are on the same core, but I can make no claims as to its accuracy.  It also looks similar to [this question][2].
Note: the link referred to now seems to be a spam site, it was:   http ://www.linuxforums.org/articles/finding-server-is-multi-processor-multi-core-or-hyperthreading-is-enabled-or-not-_856.html
[2]: https://stackoverflow.com/questions/3019129
Comment: Is there a cleaner way to determine which cores are which for CPU affinity purposes?
Answer: <code>cat /sys/devices/system/cpu/cpu0/topology/thread_siblings_list
</code>
will print comma-separated list of sibling cores for a particular physical CPU/core.
I used cpu0 (first core) as example.
The same information can be extracted from "core id" fields in /proc/cpuinfo (thanks user61849).


Primefaces 4.0 resource compression

Question: I have Primefaces 4.0 running on top of JBoss 7.1.1.Final. I am using google webutilities (https://code.google.com/p/webutilities/) to compress and combine my javascript and CSS files. When I run PageSpeed insights on my page all my custom css and js files seem to be compressed and do not output any problems on the page. But then again all Primefaces resources seem to skip all the filters. Here is my webutilities configuration:

<filter>
    <filter-name>characterEncodingFilter</filter-name>
    <filter-class>com.googlecode.webutilities.filters.CharacterEncodingFilter</filter-class>

    <init-param>
        <param-name>encoding</param-name>
        <param-value>UTF-8</param-value>
    </init-param>
    <init-param>
        <param-name>force</param-name>
        <param-value>true</param-value>
    </init-param>
    <init-param>
        <param-name>ignoreURLPattern</param-name>
        <param-value>.*\.(png|gif|jpg|tiff|bmp|mpg|jpeg)</param-value>
    </init-param>
</filter>
<filter-mapping>
    <filter-name>characterEncodingFilter</filter-name>
    <url-pattern>*</url-pattern>
</filter-mapping>

<filter>
    <filter-name>responseCacheFilter</filter-name>
    <filter-class>com.googlecode.webutilities.filters.ResponseCacheFilter</filter-class>
    <init-param>
        <param-name>acceptMIMEPattern</param-name>
        <param-value>text/javascript,application/javascript,text/css</param-value>
    </init-param>
    <init-param>
        <param-name>acceptURLPattern</param-name>
        <param-value>.*\.(js|json|css).*</param-value>
    </init-param>
</filter>
<filter-mapping>
    <filter-name>responseCacheFilter</filter-name>
    <url-pattern>*.js</url-pattern>
    <url-pattern>*.json</url-pattern>
    <url-pattern>*.css</url-pattern>
</filter-mapping>

<filter>
    <filter-name>compressionFilter</filter-name>
    <filter-class>com.googlecode.webutilities.filters.CompressionFilter</filter-class>
    <init-param>
        <param-name>compressionThreshold</param-name>
        <param-value>512</param-value>
    </init-param>
    <init-param>
        <param-name>ignoreURLPattern</param-name>
        <param-value>.*\.(png|gif|jpg|tiff|bmp|mpg|jpeg).*</param-value>
    </init-param>
    <init-param>
        <param-name>ignoreMimes</param-name>
        <param-value>images/*,video/*, multipart/x-gzip</param-value>
    </init-param>
    <init-param>
        <param-name>ignoreUserAgentsPattern</param-name>
        <param-value>.*MSIE.*</param-value>
    </init-param>
</filter>
<filter-mapping>
    <filter-name>compressionFilter</filter-name>
    <url-pattern>*</url-pattern>
</filter-mapping>

<filter>
    <filter-name>yuiMinFilter</filter-name>
    <filter-class>com.googlecode.webutilities.filters.YUIMinFilter</filter-class>
    <init-param>
        <param-name>lineBreak</param-name>
        <param-value>8000</param-value>
    </init-param>
    <init-param>
        <param-name>acceptMIMEPattern</param-name>
        <param-value>text/javascript,application/javascript,text/css</param-value>
    </init-param>
    <init-param>
        <param-name>acceptURLPattern</param-name>
        <param-value>.*\.(js|json|css).*</param-value>
    </init-param>
</filter>
<filter-mapping>
    <filter-name>yuiMinFilter</filter-name>
    <url-pattern>*.js</url-pattern>
    <url-pattern>*.json</url-pattern>
    <url-pattern>*.css</url-pattern>
</filter-mapping>

Also I have tried to set the following parameters to web.xml:
<context-param>
    <param-name>org.primefaces.extensions.DELIVER_UNCOMPRESSED_RESOURCES</param-name>
    <param-value>false</param-value>
</context-param>
<context-param>
    <param-name>javax.faces.PROJECT_STAGE</param-name>
    <param-value>Production</param-value>
</context-param>

But still the output of the PageSpeed gives me the following how to get the page performance better:
**Enable compression for the following resources to reduce their transfer size by 567.5KiB (75% reduction).**
Compressing http://localhost:8888/.../primefaces.js.xhtml?... could save 213.8KiB (79% reduction).
Compressing http://localhost:8888/.../jquery-plugins.js.xhtml?... could save 156.1KiB (72% reduction).
Compressing http://localhost:8888/.../jsf.js.xhtml?... could save 84.3KiB (78% reduction).
Compressing http://localhost:8888/.../jquery.js.xhtml?... could save 67.1KiB (65% reduction).
Compressing http://localhost:8888/.../primefaces.css.xhtml?... could save 42.3KiB (81% reduction).
Compressing http://localhost:8888/.../watermark.js.xhtml?... could save 3.3KiB (63% reduction).
Compressing http://localhost:8888/.../hotkey.js.xhtml?... could save 660B (45% reduction).

**Minify JavaScript for the following resources to reduce their size by 84.4KiB (20% reduction).**
Minifying http://localhost:8888/.../jsf.js.xhtml?... could save 78.4KiB (72% reduction). See optimized content
Minifying http://localhost:8888/.../jquery-plugins.js.xhtml?... could save 3.6KiB (2% reduction). See optimized content
Minifying http://localhost:8888/.../jquery.js.xhtml?... could save 551B (1% reduction). See optimized content

**Minify CSS for the following resources to reduce their size by 4.1KiB (8% reduction).**
Minifying http://localhost:8888/.../primefaces.css.xhtml?... could save 2.7KiB (6% reduction). See optimized content
Minifying http://localhost:8888/.../theme.css.xhtml?... could save 1.4KiB (24% reduction) after compression. See optimized content

**605.3KiB of JavaScript is parsed during initial page load. Defer parsing JavaScript to reduce blocking of page rendering.**
http://localhost:8888/.../primefaces.js.xhtml?... (219.5KiB)
http://localhost:8888/.../jquery-plugins.js.xhtml?... (191.8KiB)
http://localhost:8888/.../jquery.js.xhtml?... (95.3KiB)
http://localhost:8888/.../tooltip.js.xhtml?... (34.5KiB)
http://localhost:8888/.../jsf.js.xhtml?... (25.4KiB)
http://localhost:8888/.../primefaces-extensions.js.xhtml?... (19.7KiB)
http://localhost:8888/page/my/toolbox/ (13.2KiB of inline JavaScript)
http://localhost:8888/.../watermark.js.xhtml?... (4.7KiB)
http://localhost:8888/.../hotkey.js.xhtml?... (1.2KiB)

For me it seems like lots of overhead with Primefaces + Primefaces extensions resources. Any idea how I could get these resources to go through WebUtilities filters or at least enable the compression for these files? Thanks for help!
Answer: After some playing around I figured out this was not showing as minified since it was pulling the files from the browser cache. Try clearing the cache by right clicking a resource in the network tab. Once you refresh the page you should see the compressed files get pulled from the server with a response status of 200 (OK) instead of 304 (Not modified).
Edit: You may also have to comment out the 'Response cache filter' in web.xml until you see the files are being compressed.

Primefaces 4.0 resource compression


Geometric explanation for the convergence of $\sum_{n = 1}^{\infty} (1/a)^n$ when $1<a<2$

Question: I'm studying some series and I'm trying to see them in a more geometric way, thinking of integrals or parts of something big (you will know what i mean). But I can't find a geometric way to see why those should converge!
Being a bit more precise, what I want is:

Let $S = \sum_{n = 1}^{\infty} (1/a)^n$ be a series with $a > 1$. Then, $S < \infty$.

If $a = 2$, using the "part of a hole" idea works, because we can think of the circle with radius $1$ and then the sum $1/2 + 1/4 + \cdots + 1/\infty$ is just filling this circle by painting half of it, then taking the rest and painting half of it, doing this recursively.
Then, if $a > 2$, obviously the series will converge because $(1/a)^n \leq (1/2)^n$ and so the sum will never get to fill the circle, hence it must be finite.

Now, the problem lies in $2 > a > 1$. Is there a geometric argument that is somehow intuitive for why this should converge?
Comment: The last example at https://sites.google.com/site/butwhymath/m/geometric-series-visually may help you (but you should read the whole thing, not just skip down to the bottom, I think).
Comment: For $a=2$ just consider a rectangle of lengths $2$ and $1$ on its sides. Then the sumation adds up to half a portion of the remainder at every step. This is a nice simple way to see that on the limit the sum is $1$. Every other case is analogous to this one.
Answer: Note that $$\sum_{n=1}^\infty \left(\frac{1}{a} \right)^n=\frac{1}{a-1}$$
For $a=2$, the sum converges to $1$, so we can easily visualize the sum as a progressive filling of fractions of a circle. For $a>2$, the evidence that $(1/a)^n<(1/2)^n$  also allows an intuitive visualization of the convergence to a limit $<1$.
For $1<a<2$, since the sum converges to a number that is $>1$, to keep the possibility of easy visualization of the convergence, it is sufficient to rescale the fractions filled in the circle by a factor $a-1$. In this way, our limit is again $1$ as in the case $a=2$.
For example, set $a=3/2$. We know that the sum converges to $1/(3/2-1)=2$. So we must rescale our fractions by a factor $2$. Take the first term of the sum $1/(3/2)=2/3$, divide it by $2$, and we get $1/3$: so we fill $1/3$ of the circle and $ 2/3$ of it remain to be filled. Take the second term of the sum $1/(3/2)^2=4/9$, divide it by $2$, and we get $2/9$: so we fill other $2/9$ of the circle, arriving to a total filled portion of $5/9$ of the circle, and $ 4/9$ of it remain to be filled. Continuing in this way, the proportion that remains to to be filled is $8/27$ in the third term, $8/81$ in the fourth, and so on.
In general, after summing $m$ terms for a given $a$, the proportion remaining to be filled is $$\left(\frac{1}{a}\right)^m$$
which can be easily visualized from a geometric point of view.
Comment: Ok so now you're basically the god that I'll pray every morning to, this is BEAUTIFUL, thanks a lot
Answer: Consider the following continuous function:
$$f(s) = \frac{1}{a^s}$$
Compare this to the left-continuous step function:
$$g(s) = \frac{1}{a^{\lceil s \rceil}}$$
Note that
$$\int_0^n g(s) ds \equiv \sum_{i=1}^{n} \frac{1}{a^i} \quad \forall n \in \mathbb{N}$$
Also note that $\lceil s \rceil \geq s \implies f(s) \geq g(s)\quad\forall s \in \mathbb{R}$.
Therefore, we know
$$\int_0^n f(s) ds \geq \int_0^n g(s) ds \quad \forall n\geq0$$
Geometrically, we can see that the area under the curve for $f(s)$ includes the area under the curve $g(s)$ as a subregion.
We can evaluate the improper integral of $f(s)$ to get a closed-form result:
$$\lim_{b\to\infty}\int_0^b \frac{1}{a^s} ds =\lim_{b\to\infty}\frac{1}{\ln(a)}\left[ 1- a^{-b}\right] = \frac{1}{\ln(a)} \implies \lim_{b\to\infty}\int_0^b g(s) ds < \infty $$
$$\implies \sum_{n=1}^{\infty} \frac{1}{a^n} < \infty$$


Simple open source filter for php mysql

Question: I know I could code what I'm trying to achieve, but I'd like to know if such a plugin exists....
This is what im looking for,
A web page which takes a mysql table structure and accepts user conditions for a select.
For example, if a table consists of age,location, name and email, is there a plugin which once set up shows a page where a user can enter conditions for any of/ some the columns he wants and then run a search which displays the records fromt eh mysql database...
conditions like age between or age>
location in ('..','...')
etc etc...
basically  a simple script to search for a bunch of records based on the users conditions
Answer: I don'y know if i understood you correctly and i don't know if this is what you are looking for exactly but this might do.
http://www.scriptiny.com/2009/03/table-sorter/
Comment: I've seen this before...
Im kind of looking for something which will help a person who doesnt know a word of sql type in values into text boxes and use these to frame the where clause of the query...
It should support ands ors and allow the user to choose which fields he wants to search by etc.
Comment: I am also looking for a more filter based solution. I want it to do and/ors in searches. I do not see that this plugin is able to do that.
Answer: I use phpMyAdmin - you can browse your tables, insert data, run open-ended queries or use a search form to fill in what you're looking for.  Plus loads more.  It's excellent, free and (I believe) open source.
http://www.phpmyadmin.net/
Comment: Yes i know phpmyadmin does the job, but i want to integrate it with my project, and i was looking for a simple plugin.

Simple open source filter for php mysql


Why is the code in the thread executed twice?

Question: As indicated in the title, why is the following code executed twice (2x Test in the console) and how to fix it?
type
  TSelfThread = class(TThread)
    procedure Execute; override;
end;

procedure TSelfThread.Execute;
begin
  Writeln('Test');
end;

var
  SelfThread : TSelfThread;
begin
  try
    SelfThread := TSelfThread.Create(False);
  except
    on E: Exception do
      Writeln('Error');
  end;
end.

Comment: Now it works.. Thank you. But why did it do such unexpected things without it?
Comment: @Nasreddine open a console and execute a process, console doesn't disappear when the process terminates.
Comment: Cannot reproduce. In any case, you do need to wait for the thread to finish. Add a call to `SelfThread.WaitFor`.
Comment: What version of Delphi?  Can't reproduce.
Comment: Delphi 10.3 Community. I recompiled the tool under another name. The first start it prints 2x "Test" and after that no output???? https://prnt.sc/nv00cx
Comment: And what happens when you correct the code by making it wait for the thread to finish?
Comment: Well, you start a thread, and before you are certain that is has finished executing, you end the process. Anything can happen.
Comment: Now my question might be stupid, But how did you see the second Test. The console would blink. I mean did you log the console output or put the readln; before the end of the block?.
Comment: @DavidHeffernan Any thing can happen. But I do not think calling the execute again is something you want to be possible. The rtl should prevent this.
Comment: @Nasreddine Galfout Without the SelfThread.WaitFor; i get 2x "Test" or no ouput. I did not change anything.
Comment: @Nasfeddine How could it do that? And why should it?
Answer: The only possible explanation for this behaviour is the bug in your code where you fail to wait for the thread to complete before terminating the process.
Change the code to be like this:
SelfThread := TSelfThread.Create(False);
SelfThread.WaitFor;


Displaying Taxonomy Term Field for Multiple Entries on a Taxonomy Term List View

Question: I'm using a view to override my taxonomy term pages to display content fields.  One of those fields is another taxonomy term (applicable divisons).  Displaying the titles of terms applied to the content is no problem (multiple field settings).
The problem comes in here.  I need to display icons that represent each of those terms that is an image field in the term itself (division icon).  I added a relationship to the view (Content:Taxonomy Terms on node).  I can then add the field, but it limits it to one of the terms/icons and it doesn't have a "multiple field settings" area.
I've searched for this quite a while and it's probably an obvious answer, but it's one I can't find or figure out.
Answer:
This isn't pretty, but it's getting me the data I want.  It needs to be cleaned up.  Thanks for the help!
<?php
foreach($data->field_field_applicable_divisions as $mydata) {
    if (isset($mydata['raw']['tid'])) {
        $term = taxonomy_term_load($mydata['raw']['tid']);
        echo "
";
        echo "field_division_icon['und'][0]['uri']) . "' title='" . $term->field_division_icon['und'][0]['field_file_image_alt_text']['und'][0]['value'] . "' alt='" . $term->field_division_icon['und'][0]['field_file_image_alt_text']['und'][0]['value'] . "'class='term-image' />";
        echo "
 ";
    }
}
?>

Also, to get a legend in the header or footer:
<?php
foreach(taxonomy_get_tree(7) as $icon) {
    $term = taxonomy_term_load($icon->tid);
    echo "
";
    echo "field_division_icon['und'][0]['uri']) . "' title='" . $term->field_division_icon['und'][0]['field_file_image_alt_text']['und'][0]['value'] . "' alt='" . $term->field_division_icon['und'][0]['field_file_image_alt_text']['und'][0]['value'] . "'class='term-image' /> - " . $term->field_division_icon['und'][0]['field_file_image_alt_text']['und'][0]['value'];
    echo "
 ";
}
?>

Answer: You are going to have to adjust this to your own use case, but the approach I would use is a little different.
First, delete the relationship.
Add (or configure) the term reference field (field_divisions?) in your query. Set it to no label, and exclude from display. Rewrite the output to [field_tags-tid] . This will give you a list of term id's.
Install and enable the Views PHP module.
EDIT:
The $row variable does not play well with multiple values, so we will switch to the $data variable.
In your view, add a Global:PHP field, and in the Output code box enter something like:
<?php
  // Select your field object.
  $obj = $data->_field_data;
  // Then get your field array
  $divisions = $obj->field_divisions[LANGUAGE_NONE]
  foreach($divisions as $division) {
    if ( is_numeric( $division['tid'] ) ) {
      $term = taxonomy_term_load($division['tid']);
      $icons= $icons. "
";

      if (isset($term->division_icon['und'][0]['uri'] )) {
        $icons= $icons. "
division_icon['und'][0]['uri']) . "' class='term-image' />
 ";
      }
      $icons = $icons . "
";
    }
  }
  print $icons;
?>

Make sure the PHP field follows the term reference field so the $row values are available to the PHP field. Then style your icons to display as you wish.
Comment: I've deleted the relationship.  I've changed the output in field_applicable_divisions to the token and modified your code to for the field name.  In the PHP field, field_applicable_divisions shows up in available variables.  I'm getting an "invalid argument supplied to the foreach."  Any specific settings in the field_applicable_divisions that would mess this up?  Multiple field settings perhaps?  Thanks for the help.
Comment: I found the problem. Slightly more involved code, but the above should get you going.


Interpretation of $\Omega_\pm(x^c)$

Question: In an answer regarding the behaviour of two functions, I got the following:
"As in the proof of Theorem 15.2 in Montgomery-Vaughan: Multiplicative number theory I, this eventually yields that $$\pi(x)-\sigma(x)=\Omega_\pm(x^c)\quad\text{for any}\quad c<3/4$$
I would like to check if I interpret correctly the meaning of $\pi(x)-\sigma(x)=\Omega_\pm(x^c)$ for $c=1/2$. Can I interpret that $-\sqrt{x}\leq\pi(x)-\sigma(x)\leq\sqrt{x}$?
I understand that the meaning of $\Omega_\pm(x^c)$ is deeper, as additionally express that the value of $\pi(x)-\sigma(x)$ has infinitely many changes of sign, but I would like to check that $_\pm(x^c)$ work as upper and lower bound for this oscillation, and thus my interpretation is correct.
If that is not the intrepretation, I would appreciate your help for understanding it.
Thanks in advance!
Answer: After searching a bit more, I found this question, and in a comment Peter Humphries explains that "$\Omega_\pm$ is standard notation in analytic number theory. $f(x)=\Omega_\pm{(g(x))}$ means that $\limsup_{x \to \infty} \frac{f(x)}{g(x)} > 0$, while $\liminf_{x \to \infty} \frac{f(x)}{g(x)} < 0$".
From this definition, I conclude that the answer to my question would be NO, as my statement $-\sqrt{x}\leq\pi(x)-\sigma(x)\leq\sqrt{x}$ is stronger than $\pi(x)-\sigma(x)=\Omega_\pm(\sqrt{x})$.

Interpretation of $\Omega_\pm(x^c)$


Problem with Javascript ad code

Question: I am trying to add a Javascript ad code on our Drupal based website through a block and when I do this, the page doesn't display but only ads display. Please see this sample page:
http://circuitdigest.com/forums/circuits-and-projects-help/arduino
I tried adding on different blocks and even added the ad code by directly inserting in the codes but no changes. Other Javascript based ad codes from other ad networks are working fine but only had problem with this one.
Could someone let me know what could be the problem? Here is the ad code.

Comment: where do you put this code? your block contents?
what is your durpal version?
Comment: I have put the code in a block below the content. Drupal version is 7. I have find this code is not working with 'Advanced CSS/JS Aggregation' module. When I am disabling it, the ad code works. So now trying to find a solution how can I get both work together
Comment: check Advanced CSS/JS Aggregation settings, there are some option for inline css and js. I switched to drupal 8 and don't have drupal 7 on my local machine to tell you exactly which options you should change.
Comment: @zhilevan thank you very much. I disabled "Deferred JavaScript Execution" in sub-module 'AdvAgg Modifier' settings and it worked.
Comment: you're welcome I post it as a answer for future guys that have the same problem.
Answer: If you are working on Drupal 8, create a twig like html.html.twig in your themes templates folder and the put your script in there.
<!DOCTYPE html>

    <title>{{ head_title|safe_join(' | ') }}</title>

Answer: Advanced CSS/JS Aggregation Module  has several option for inline CSS and JAVASCRIPTS, you can resolve this problem with  disabling Deferred JavaScript Execution in sub-module 'AdvAgg Modifier' settings.

Problem with Javascript ad code


Mysql blocked my webserver max_connect_error reached

Question: Last week end, one of my two webservers was blocked by mysql server.
The result is all requests on that blocked webserver show a taylored error page.
I'm thinking to implement a script to prevent this issue. but i can't reproduce this error in my test lab.
Mysql doc says that this error is du to network problems and it is a security implementation to bloc attacks.
Do you have ideas about how to reproduce this error?
i tryed to connect to my test server with wrong login/pwd to simulate a brute force attack. Also i executed a complicated queries which took some minutes to get an answer and stopped it in before getting answer  (many time).
I saw variable Aborted_connects increasing but not Aborted_clients and i did't get my host blocked by this test server.
Any idea?
Thank you in advance.
Answer: I know it is old, but i found the way to reproduce it.
First you have to lower down max_connection_error to not repeat yourself:
<code>SET GLOBAL max_connect_errors=2;
</code>
then you can use telnet program to make faulty connections. after command just double press enter:
<code>$ telnet 192.168.128.98 3306

Trying 192.168.128.98...
Connected to 192.168.128.98.
Escape character is '^]'.
a
5.6.14-1+debphp.org~precise+1?"sC1kHf?s,{MO$dK-<(Smysql_native_password
!#08S01Got packets out of orderConnection closed by foreign host.

$ telnet 192.168.128.98 3306

Trying 192.168.128.98...
Connected to 192.168.128.98.
Escape character is '^]'.
a
5.6.14-1+debphp.org~precise+1?"sC1kHf?s,{MO$dK-<(Smysql_native_password

!#08S01Got packets out of orderConnection closed by foreign host.
</code>
then you will see your connection refuse:
<code>$ telnet 192.168.128.98 3306

Trying 192.168.128.98...
Connected to 192.168.128.98.
Escape character is '^]'.
kHost '192.168.128.1' is blocked because of many connection errors; unblock with 'mysqladmin flush-hosts'Connection closed by foreign host.
</code>
Comment: Hi.Thank you for your answer.
I was not able to try the tools suggested above.
+1 for the proposed solution :)
Answer:
If there are more than this number of interrupted connections from a
  host, that host is blocked from further connections. You can unblock
  blocked hosts with the FLUSH HOSTS statement.
  If a connection is established successfully within fewer than max_connect_errors
  attempts after a previous connection was interrupted, the error count for the
  host is cleared to zero. However, once a host is blocked, the FLUSH
  HOSTS statement is the only way to unblock it.

Source: http://dev.mysql.com/doc/refman/5.1/en/server-system-variables.html#sysvar_max_connect_errors
Note that the default value in MySQL 5.1.x is set at 10.
EDIT:
If you want to try crafting invalid TCP packet hoping that it will generate connect errors in mysql you should look at those two tools:

Scapy and this tutorial
Nemesis and this manpage
GSpoof which may be the simplest of all three due to its GUI

I suppose it will generate the error you want but I never tried it.
Comment: Thank you for the replay. I did this when i noticed that my webserver is blocked.  But my question was how to reproduce this issue?  I would like to monitore connection_errors variable in order to avoid a next host blocking. Thank you
Comment: Given what you already tried without success and the doc stating that this error is due to "network problems", you may want to look at crafting your own invalid TCP packets, I'll add details in my question.


Linha horizontal no VSCode

Question: Oi hoje pela noite apareceu uma linha horizontal preta no meu VSCode. Ela aparecia toda vez que eu rolava pra baixo ou para cima. Eu devo ter ativado algo sem querer.Isso tá incomodando. inserir a descrição da imagem aqui
Comment: Por favor, esclareça seu problema ou forneça detalhes adicionais a fim de destacar exatamente o que você precisa. Da forma como está escrito atualmente é difícil dizer com exatidão o que você está perguntando.
Comment: Tem uma imagem no final da dúvida que mostra o problema, alguém respondeu que era só desativar a opção "Stick Scroll" e funcionou, obrigado!
Answer: Você pode clicar com o botão direito do mouse e desativar a opção "sticky scroll"

Linha horizontal no VSCode


Problem 9.7 - Lie Algebras - Humphreys

Question: Let $\alpha,\beta\in\Phi$ span a subspace $E'$ of $E$. Prove that $E'\cap\Phi$ is a root system in $E'$. Prove similarly that $\Phi\cap(\mathbb{Z}\alpha+\mathbb{Z}\beta)$ is a root system in E' (must this coincide with $E'\cap\Phi$?).
More generally, Let $\Phi'$ be a nonempty subset of $\Phi$ such that $\Phi'=-\Phi'$, and such that $\alpha,\beta\in\Phi'$, $\alpha+\beta\in\Phi$ implies $\alpha+\beta\in\Phi'$. Prove that $\Phi'$ is a root system in the subspace of E it spans.
Answer: I hope this could be useful for you and I'm not saying something wrong.
I don't use root systems by a lot of time, then I'm going to recall some of their properties solving you execise.
Definition $\Phi \subset E$ is a root system for $E$ if

$\Phi$ generates $E$ (in our case this is by definition)
$\alpha$ and $-\alpha$ are the only "$\alpha$"-multiples in $\Phi$ (and this is trivial for $\Phi \cap E'$ because $E'$ is a subspace of $E$)
$\forall \gamma, \; \delta \in \Phi$ we have $\langle \gamma, \; \delta  \rangle \in \mathbb{Z} $ (this holds for the elements of our $\Phi$ and then holds for the elements of its subset $\Phi \cap E'$)
If $\gamma \in \Phi$ and $\sigma_{\gamma}$ is the reflection by the iperplane generated by $\gamma$, then $\sigma_{\gamma}(\Phi)=\Phi$

The hardest part of you question is obviously $4.$.
To solve it, we have to ask ourself the following question: How the generic reflection $\sigma_{\gamma}$ acts on the generic root $\delta \in \Phi$?
Well, $\sigma_{\gamma}(\delta)= \delta - \langle \delta, \; \gamma  \rangle \gamma $
I think now is easy to conclude...

Problem 9.7 - Lie Algebras - Humphreys


How to send messages from web-service to Android clients?

Question: I have a PHP web-service, and Android client. I need to make ability to send messages from service for my Android client. How can I make this mechanism?
Comment: [C2DM](http://code.google.com/android/c2dm/) or [Airship](http://urbanairship.com/docs/android-client-push.html)
Answer: Unless you have implemented a push mechanism, or using an external one, such as Google C2DM, which is available for Android (I have not tested it myself, last time I checked it, it was in a beta state), the only way left is use a polling mechanism (ask every so often the web service).


"mount error(13): Permission denied" only in LXC container for CIFS/Samba share

Question: I have a samba share that mounts just fine under the Ubuntu 12.04 host:
root:~# mount -t cifs -o credentials=/var/lib/lxc/vpn/rootfs/etc/samba/desktop.credentials //desktop/Media /media/Media

But when I try to do the same mount in an LXC container, also Ubuntu 12.04, which also has the cifs-utils package installed, I get a permission error:
root:~# mount -t cifs -o credentials=/etc/samba/desktop.credentials //desktop/Media  /media/Media
mount error(13): Permission denied
Refer to the mount.cifs(8) manual page (e.g. man mount.cifs)

Both commands are being run as root.  Why would this be different in the container and is there a way I can get this mount to work under the container.
Answer: Direct mounting is not possible, you should mount the share to the host first and then use lxc.mount.entry configuration directive to bind mount share's mountpoint inside the container (an example of using lxc.mount.entry can be found here). You can also provide the container with an external fstab file as shown here.


How do I do a regex query in reverse in entity query?

Question: I have a config entity with a row of regex strings, and I want to query which one of them matches a provided string; this stackoverflow question (https://stackoverflow.com/questions/12044628/searching-mysql-database-by-a-regex-match-in-reverse) describes how this could be done in mysql. What's the best way to do this using entity query?
Answer: Okay, is seems like this is in fact impossible to do right now with config entities.
If you look at \Drupal\Core\Config\Entity\Query\Condition, and into the function match, it shows what operators are available for config entity queries. REGEXP isn't even an option. Nor is there anyway to query a value against a field, instead of a field against a value.
The only way to really do this seems to be to load all of the config entity records into memory, then do the comparison with php.
Comment: here's an example of how to load the nodes and filter them using regex: https://gist.github.com/mchelen/0d02801e8a6ac0dde13ab9c0e6864caa


Tampering with players

Question: When a team executive apparently influences a player from another team to join them without prior knowledge or permission to that player's current team, it's considered tampering, and teams have been fined for this in the past.
In the most recent cases like Lebron James and Paul George, if an upcoming free agent is contacted by another team to convince the player to sign with them, is this still considered tampering?
Answer: July 1 is when teams can begin negotiating with free agents.
Teams cannot contact a player under contract nor their agent. The player must be a free agent.
Not even supposed to talk to the press about wanting a player.  Forget who it was but I think it was Doc Rivers commented a player was good and would be a good fit on his team.  Not sure if he got fined or the league just told that pushes tampering and don't do it any more.
If a player has a player option but they have not yet declined the player option I am not sure.
Comment: How is it that when it involves executives or other team personnel it's considered tampering but not when players themselves are actively recruiting another player to their team?
Comment: @NoirAntares IANAL  Collective Bargaining Agreement gives players a lot of lattiture.

Tampering with players


Temporary membership to AD group

Question: We restrict the running of exe's across the organization. But based on justifications & approvals we add users to (specific) AD groups for 24 hours.
Currently the process of removing the users from those AD groups after X hours is manual. I am trying to automate it in some fashion. But I was wondering if there is any native way of handling this within AD 2003. Is writing a script (powershell / vbs) the only way of handling this?
Answer: Assuming all your Domain Controllers are Windows Server 2003 or later you can do this with native Active Directory's dynamic objects functionality without any scripting.
Let's say that a user account, "Bob", needs to be in the "Accounting" group for 24 hours.

Create a "Bob in Accounting 24 Hours" group and specify an entry-TTL for 24 hours (the duration you want the group to remain in the Active Directory) at the time of creation.
Add the "Bob in Accounting 24 Hours" as a member of the "Accounting" group
Add the "Bob" user account as a member of the "Bob in Accounting 24 Hours" group

Upon the "Bob" user account's next logon it will be a member of the "Accounting" group through the nested group membership of the "Bob in Accounting 24 Hours" group into the "Accounting" group. At the end of 24 hours all the domain controllers will garbage-collect the "Bob in Accounting 24 Hours" group and "Bob" will no longer be a member of "Accounting".
The trick is that non-dynamic objects cannot be converted to dynamic after their creation. Using group nesting, though, gets you around that limitation in this instance.
You'll need to use a tool other than "Active Directory Users and Computers" to create the group because you'll need to set the entry-TTL at the time of the group's creation. The script in this blog entry might be a starting place (it's built to create User objects) or, alternatively, you could just use ldifde or csvde to do the creation, too.
Comment: http://i.imgur.com/TZX2RbP.jpg
Comment: Holy crap, that is something I did not know about. And it's 10 years old.
Comment: @EvanAnderson You're a badass.
Comment: You're all too kind. There's some really good background on the feature in this blog (*this* guy really is an AD badass-- I just use the product a lot): http://blogs.chrisse.se/2012/11/28/how-the-active-directory-data-store-really-works-inside-ntds.dit-part-4/
Comment: @mfinni - I've never used it in production, ever. It works exactly as-advertised, though. Pretty neat, eh?
Comment: +1 for a cool feature I never knew existed.
Comment: You can bump the TTL over and over again and, so long as it doesn't reach zero, the object will persist. This is definitely a way to make an Active Directory dead-man switch. I cannot confirm or deny that I may have used this feature to automatically take actions if I should die unexpectedly... >smile<
Comment: Just think how much cooler I'd look if I'd gotten to this question 45 seconds after it was posted and put up this answer! >smile<  I don't know why this feature is so obscure, other than it has very few practical uses. It's terrible from an auditing perspective because the objects are *completely* gone after they've been deleted. They don't tombstone-- they actually garbage-collect on all the DCs simultaneously. From a forensics perspective I don't know what they leave laying around in the DIT. If I had some free time I'd love to look into that. They could certainly be used for evil, though!
Comment: If it were possible to favorite answers, I'd favorite this one.
Answer: You could handle this a few ways, none are native to AD:

Write a script and put it in task scheduler. Have it query a text file or CSV somewhere on the network with the current list. Have it remove people not on that list at runtime.
Use something like System Center Orchestrator to create a runbook to add users to the group and to remove them after X hours automatically.
Make an Outlook reminder to take people out manually :)
Comment: You cannot resist the siren song of dynamic objects... Dynamic objects!
Comment: FYI - We use Quest's ActiveRoles server to assist with AD management.  It has the capability built in along with a little workflow tool added to assist.
Comment: I think using option 1 and creating a scheduled PowerShell script with a file of current users is a good way to solve this.

Temporary membership to AD group


Proof that $\binom{n}{\smash{0}}^2+\binom{n}{1}^2+\cdots+\binom{n}{n}^2=\binom{\smash{2}n}{n}$ using a counting argument

Question: Prove the following by way of a counting argument:

$$\binom{n}{0}^2+\binom{n}{1}^2+\cdots+\binom{n}{n}^2=\binom{2n}{n}$$
Comment: Is this is a homework? What did you try? Where did you fail?
Answer: Suppose you have $2n$ items.  Break them into two equal groups of size $n$; fix an integer $k$, $0\le k \le n$.
Take $k$ from the first group and $n-k$ from the second.  There are
$${n\choose k}{n\choose n - k} = {n\choose k}^2$$
ways to do this.
Now if you take a sample of size $n$ from the $2n$, for a unique $k$ you will take $k$ from the first group and $n-k$ from the second.  Sum over all $k$ and you get the result.
Comment: A way to visualize this proof is to have an $n \times n$ grid, and count the number of ways (going either right or up) to get from the bottom left corner to the top right corner. If for each point of the main diagonal (going topleft-bottomright) you count the number of way to get to it from the bottom left vertex, and then multiply that by number of ways to get to the top right, you get this exact identity.
Comment: He guess he means

$$\sum_{k=0}^n{n \choose k}{n\choose n-k}=\sum_{k=0}^n{n \choose k}^2$$
Comment: That's quite cool, Aryabhata.
Comment: I am not sure what you mean by sum all k and get the result. Do you mind to explain some more?
Comment: *I guess he means*
Comment: Correct.  It is what I meant to imply


Equivalence of Tightness of Seqeuence of CDFs

Question: In Durrett, a sequence of cdf $\{F_n\}$ is called tight if for all $\epsilon > 0$< there exists $M_\epsilon$ such that $\limsup 1-F_n(M_\epsilon)+F_n(-M_\epsilon) \leq \epsilon$.
In Rosenthal, a sequence of probability measure is called tight if for all $\epsilon$, there exists $a<b$ both finite such that $\mu_n([a,b]) \geq 1-\epsilon$ for all $n$.

Are these two definitions equivalent?
I can write $\limsup 1-F_n(M_\epsilon)+F_n(-M_\epsilon) \leq \epsilon$ as $\limsup F_n(-M_\epsilon)-F_n(M_\epsilon) \leq \epsilon-1$, which can be writen as $\liminf \mu_n(-M_\epsilon, M_\epsilon])=\liminf F_n(M_\epsilon)-F_n(-M_\epsilon) \geq 1-\epsilon$
From this, it's clear that the definition in Rosenthal implies the definition in Durrett.
However, the converse is not clear to me. Since we can have for all $n$, $\mu((-M_\epsilon, M_\epsilon]) < 1-\epsilon$ while $\liminf \mu((-M_\epsilon, M_\epsilon]) = 1-\epsilon$, in which case the definition in Rosenthal wouldn't hold.
Thank you.
Comment: @whuber but my problem is that even if $\liminf \mu_n([-M,M]) \geq 1-\epsilon$, we may have $\mu_n([-M,M]) < 1-\epsilon$. Does it suffice to get close enough to $1-\epsilon$?
Comment: @whuber got it thanks
Comment: What happens when you take $a = -M_\epsilon-1$ and $b=M_\epsilon+1$?
Comment: Also, Durrett later defines tightness as $\lim\inf \mu_n([-M, M]) \geq 1-\varepsilon.$
Comment: @whuber does that matter? Since we can still have $\mu_n([a,b]) = \mu_n([a-1, b+1])$
Comment: @User1865345 is that one equivalent to one in Rosenthal? I don't see it.
Comment: Draw a picture.  The key idea concerns the distinction between $\Pr(X\lt x)$ and $\Pr(X\le x)$ when expressed in terms of the distribution function of $X.$  Slightly widening the interval overcomes that minor technical point, enabling you to see the sense in which $1-F_n(M_\epsilon) + F_n(-M_\epsilon)$ is essentially expressing the probability of the interval $[-M_\epsilon, M_\epsilon].$
Comment: Apply the assumption to $\epsilon/2$ and use that result to draw your conclusion about $\epsilon.$  This is where the "for all" quantification of $\epsilon$ is helpful.
Answer: Assuming Durrett's definition, choose $M$ so that for all $\liminf \mu_n([-M,M]) \geq \frac{\epsilon}{2}$ for a fixed $\epsilon > 0$.
Then eventually, $a_n = \inf_{m \geq n} \mu_m([-M,M]) \geq 1-\epsilon$ since $\liminf \mu_n([-M,M]) > 1-\epsilon$.
So eventually, $\mu_n([-M,M]) \geq 1-\epsilon$, and this suffices since finite collection of probability measures is tight.


Why NetApp snapshot spill happen?

Question: I am confused about what Snapshot Copy Reserve actually stores. From what I understand, a snapshot copy is a copy of pointers which points to blocks on disk which were occupied by a file at some point in time. File blocks are stored on volume and pointers are stored on Snapshot Copy Reserve. When a file is modified, a new version of data from a modified block is written to another block (in volume). The original block stays in read-only mode for as long as the first snapshot exists. Modified block is also written to volume and the snapshot of the modified file is written to the Snapshot Copy Reserve.
Now, it doesn't make sense to me how and why snapshot spills happen. Shouldn't volume run out of space before snapshot spill in all cases?
Answer: Assume for a moment, a 1TB volume with a 10% Snapshot Copy Reserve, exposed as an NFS export.
The usable space on the volume is now 900GB.  The snapshot reserve is 100GB.  If you were to view the volume on an attached server, you'd see it with 900GB of free space.
What "snapshot spill" is, in NetApp land, is when the size of the snapshot runs over the Snapshot Copy Reserve.  So if you snapshot the volume, then write/change 120GB of data to the volume, the snapshot will hit 120GB of space used.  The Snapshot Copy Reserve does NOT prevent a snapshot from using more space than is allocated to the reserve.  In this instance, if you again looked at the volume from a mounted server, you'd see it with 880GB free.

Why NetApp snapshot spill happen?


R Function To Calculate Accuracy at Threshold

Question: DATA = read.csv("https://stats.idre.ucla.edu/stat/data/binary.csv")
MODEL =  glm(admit ~ gre + gpa + rank, data = DATA, family = "binomial")

ACTUAL = DATA$admit
PRED = predict(MODEL, type = "response")

HAVE = data.frame(ACTUAL = ACTUAL, PRED = PRED)

I fit my model and store the ACTUAL and PRED values in HAVE which gives a data frame containing the real values and also the model prediction values.
To calculate model accuracy I have to convert PRED values into 0 and 1s and I can do that at different levels for example if PRED < .1, then 0 else 1. Then I can compare accuracy. I am wondering, how can I to do this calculation if I wish to transcribe the accuracy at a bunch of levels, say CHECK = seq(0,1,.05) ?
For example I can do this manually but how is there a function and efficient way to do so?
HAVE$PRED05 = with(HAVE, ifelse(PRED < .05,0,1))
with(HAVE, table(ACTUAL,PRED05))

Answer: You can write your own function pretty easily. We can add some checks and vectorize it like this
evaluate <- Vectorize(function(data, cutoff) {
  stopifnot(cutoff >= 0 & cutoff <= 1)
  stopifnot(all(c('ACTUAL','PRED') %in% names(data)))
  pred <- ifelse(data$PRED < cutoff, 0 , 1)
  table(data$ACTUAL, pred, dnn=list("actual", paste0("pred (", cutoff, ")")))
}, "cutoff")

By using Vectorize, we can pass in multiple check values at once. For example
CHECK = seq(0,1,.05)
evaluate(HAVE, CHECK)

will return a list of all the tables.
There are packages that can help with this stuff. For example the ROCR package. You can compare the accuracy for difference cutoff values.
library(ROCR)
pred <- with(HAVE, prediction(PRED, ACTUAL))
plot(performance(pred, "acc"))

See the ?performance help page for a bunch of other metrics you can compare with.


Bug ao tentar usar o PySimpleGUI

Question: Estou aprendendo a usar o SimplePythonGUI, porém estou me deparando com um bug. O problema é o seguinte: ao chegar no if lá em baixo, mesmo que o número random e o escolhido pelo usuário sejam iguais, o programa não dá o print de que o usuário ganhou e sempre vai para o else.
import PySimpleGUI as pg
from random import randint
class telapython:
    def __init__(self):
        #layout
        layout = [
            [pg.Text('Digite um número') , pg.Input(key= 'Pergunta')],
            [pg.Button('Verificar número')],

        ]

        #janela

        janela = pg.Window('Adivinhe o número').layout(layout)

        #extração de dados
        self.button , self.values = janela.Read()

    def iniciar(self):
        random = randint(0, 1)
        pergunta = self.values['Pergunta']
        print(random , pergunta)
        if random == pergunta:
            print('Você venceu')
        else:
            print('Você errou')

tela = telapython()
tela.iniciar()

Answer: Sou avançado na biblioteca TKInter, uma biblioteca similar a pysimpleGUI.
Quando rodo seu codigo só essa parte dá super certo... Parabéns!
    def iniciar(self):
    random = randint(0, 1)
    pergunta = self.values['Pergunta']
    print(random , pergunta)
    if random == pergunta:
        print('Você venceu')
    else:
        print('Você errou')

Parece que pergunta = self.values['Pergunta'] não está pegando o valor que você põe, no TkInter uso o .get(), então por isso que vai direto pro else, mas no pysimpleGUI (uma pesquisa que encontrei) se usa o .read().
Tente usar algo parecido com:
pergunta = self.values['Pergunta'].read()
pergunta = self.values.read(['Pergunta'])
pergunta.read() = self.values['Pergunta']

Espero que tenha ajudado,
Answer: Utilize a conversão para int antes de verificar a igualdade:
if random == int(pergunta):

Answer: Por padrão quando você recebe o Input do PySimpleGUI ele vem com 'str' você tem que transformar em 'int' da seguinte maneira.
_pergunta_ = self.values['Pergunta']
_pergunta_ = int(_pergunta_)

Bug ao tentar usar o PySimpleGUI


Rush hour - Iterative Deepening

Question: I have to solve the "rush hour puzzle" by iterative deepening algorithm. I have read a lot of topics here on stackoverflow and also on the internet. I think that I understand the iterative deepening algorithm. Basically you just go deeper into the tree and try to find the solution.
I figured that I need to create a graph or a tree from the puzzle, but I really don't have an idea how. Also, if I would have the tree, then how would I tell if something is a valid move or a final state?
There were answers that the nodes should be possible moves and the edges are between the nodes that can be reached in one move. I can imagine this, but somehow I'm getting trouble in see how this can be useful or better yet how can this solve the problem.
Please help me, I'm not asking for complete solution or code sample, I just need some easy explanation of the problem.
Answer: There is a reason you need to use the deepening algorithm. Imagine you name each car A, B, C, D... The root node of your tree is the initial board state. Now, move car A. You go down one node in the tree. Move car A back. You are at the initial state, but you made two moves to get here, so you are two nodes down the tree. Repeat over and over. You will never hit a final state.
The root node of your tree is the initial board state. Given that node, add a child node to it for every possible valid move. So, each child node will be what the initial tree looks like after one move. Now, for each of those child nodes, do the same thing: make a child node where each node is one move off the original child node.
Eventually, you will hit a solution to the puzzle. When that happens, you print the moves from the root node to the solution child node and quit. This algorithm ensures that you find a solution with the least number of moves.
Comment: Thanks, so the node would actually represent the whole board? It make sense to me now. This is however very memory consuming, is there any other approach?
Comment: There are two methods. Method 1: Each node is an entire board (you'd make it an object, of course). Method 2: Each node is a move. To see the state of the board at a node, you must start with the initial board and go through the tree to get to the node you are checking since all you have are moves. One takes more memory. One takes more processing time. Which do you want to do?
Comment: I think i will go with more memory. The move method seems a bit complicated

Rush hour - Iterative Deepening


Como garantir que todas as threads executaram?

Question: Como posso garantir que o método get de um FutureTask só será chamado quando todas as threads já tiverem executado?
Eu tenho este método :
for (int j = 0; j < threadNum; j++) {
        FutureTask<Integer> futureTask = taskList.get(j);
        if(!taskList.get(j).isDone()){
            System.out.println("Não terminou: ");
        }
        amount += futureTask.get();

    }

Eu deveria fazer um loop infinito antes deste for para garantir que só chegará aqui quando todas as threads terminarem sua execução ou há uma outra maneira de fazer isso?
Comment: O método `futureTask.get()` espera a thread terminar para obter seu valor. É tipo um "esperar e então obter".
Answer: Usando FutureTask você não precisa de loop para verificar se já terminou. Também não precisa de um método específico para aguardar terminar. O próprio método get faz as duas coisas - espera terminar e então obtém o valor computado.
Seu código ficaria mais ou menos assim:
for (FutureTask<Integer> futureTask : taskList) {
    amount += futureTask.get();
}