$s_{2^{n+1}-1}\leq t_n$ for all $n\geq 0$.

Question: Suppose $\sum a_n$ is a series with decreasing, nonnegative terms. Define $$s_n = \sum_{k=1}^n a_k = a_1+\cdots +a_n $$ and $$t_n = \sum _{k=0}^n 2^ka_{2^k} = a_1+2a_2+4a_4+\cdots +2^na_{2^n}.$$
Also,  $s_n$ is defined for all $n\geq 1$ whereas $t_n$ is defined for all $n\geq 0$. I need to prove that $s_{2^{n+1}-1}\leq t_n$ for all $n\geq 0$.
My thinking is to use the fact that $a_n \geq 0$ and that $a_n$ is decreasing. How can I use grouping to compare and make this proof?
Comment: thanks for the edit everyone, any idea how to work through this proof?
Comment: Hey, could you remind me of the proof of how $\sum \frac{1}{n}$ doesn't converge?
Comment: harmonic series
Comment: Take a look at the proof for why the Harmonic series does not converge.
Answer: HINT Compare $2a_2$ to $a_2 + a_3.$ Compare $4a_4$ to $a_4+a_5+a_6+a_7,$ etc.
Comment: so $2a_2>a_2+a_3$ and $2^na_2^{n}>a_2^{n}+...a_2^{n+1}-1$ ??
Comment: @hburt Yeah, that's the idea, I think, modulo some tex rendering issues
Comment: but from here how do I prove the rest?
Comment: @hburt Isn't that kind of the nature of a hint? Write out both expressions and compare $t_k$ to the corresponding $2^{k-1}$ in $a$..
Comment: $$t_n = \sum _{k=0}^n 2^ka_{2^k} = a_1+2a_2+4a_4+\cdots +2^na_{2^n}.$$ and $$s_n = \sum_{k=1}^n a_k = a_1+\cdots +a_n $$  So since $a_n$ is decreasing then $2a_2>a_2+a_3$ and $4a_4 > a_4+a_5+a_6+a_7$ and so on, so $2^na{_2^n}> a_2^n+...a_2^{n+1}-1$ so therefore $s_{2^{n+1}-1}\leq t_n$ for all $n\geq 0$.
Comment: how does that look?
Comment: @hburt Good. You might want to make sure that the last term lines up right when you write down $s_{2^{n+2}-2}$ and $t_n$ for a given $n$. (Or use Open Ball's induction approach where you only need to compare the last term).
Answer: Use induction.
$$s_{2^{n+1} - 1} = s_{2^n - 1} + \sum_{k=2^n}^{2^{n+1} - 1} a_k \le t_{n-1} + (2^{n+1} - 1 - 2^n + 1)a_{2^{n}} = t_n $$
Comment: does this show $s_{2^{n+1}-1}\leq t_n$ for all $n\geq 0$.


Finding other eigenvector and matrix $A$ given eigenvalues

Question: I want to find a symmetric matrix $A$, whose eigenvalues are $4$ and $-1$. One of the eigenvectors corresponding to the eigenvalue $4$ is $(2,3)$. I want to find an eigenvector corresponding to the eigenvalue $-1$ and then find the matrix $A$.
Comment: What do you know about the eigenspaces of a real symmetric matrix?
Answer: Consider  general form
$$\begin{bmatrix} x & d \\ d & y \end{bmatrix}=
\begin{bmatrix}  2/\sqrt{13} & a \\ 3/\sqrt{13} & b \end{bmatrix}
\begin{bmatrix} 4 & 0 \\ 0 & -1  \end{bmatrix}
\begin{bmatrix} 2/\sqrt{13} & a \\ 3/\sqrt{13} & b      \end{bmatrix}^T $$
Additionally vector $v=\begin{bmatrix}  a \\  b      \end{bmatrix} $ can be normalized to unit length  (as  $[2 \ \ 3]^T$ was normalized)   and it is orthogonal to $w=[2 \ \ 3]^T  $ i.e. $w^Tv=0$.
Answer: HINT
Pick your favorite eigenvector , say $(1, 0)^T$ and remember that the diagonalized form of $A$ looks like $A= V^{-1}DV$ for special $D$ and $V$. Can you reconstruct $A$?
Comment: 'symmetric matrix'.
Answer: Recall that the eigenspaces of a symmetric matrix are mutually orthogonal. Thus, all eigenvectors with eigenvalue $-1$ are orthogonal to all eigenvectors with eigenvalue $4$. Can you come up with a nonzero vector that's orthogonal to $(2,3)$? Once you've done that, you have a basis of $\mathbb R^2$ that consists of eigenvectors of $A$, therefore $A$ is diagonalizable. Can you construct $A$ from its diagonalization?


Inverted Circle?

Question: The equation I have is
$$\Large x^{\frac23} + y^{\frac23} = 3^{\frac23} $$
I know what the graph looks like, but I don't know how I would find points other than the intercepts mathematically. How would I do that?
Comment: I personally don't understand what it is you're asking - please clarify.
Comment: If vyou are curious about the $y$'s that correxpond to a particular value of $x$, such as $x=0.4$, plug in and solve for $y$. You might be interested also in a question like when is $y=x$, i.e. where does the curve meet the line $y=x$. One can calculate, just put $y=x$ and solve.
Comment: I think Kekker's problem lies in the understanding of [fractional exponents.](http://www.purplemath.com/modules/exponent5.htm)
Comment: This is an [astroid](http://en.wikipedia.org/wiki/Astroid), a special case of a [superellipse](http://en.wikipedia.org/wiki/Superellipse).
Comment: I understand what fractional exponents are, and I know the shape of the graph. I just don't understand how to undo a fractional exponent in this equation so as to get an answer.

For example, I plug in 1 for x, so I can find the y coordinate for x=1 for my graph.
$$\Large 1^{\frac23} + y^{\frac23} = 3^{\frac23} $$

That I can simplify to
$$\Large 1 + y^{\frac23} = 3^{\frac23} $$

How would I simplify that further?
Answer: Try $\begin{cases}
x=3\cos^3\theta\\
y=3\sin^3\theta\\
\end{cases}$     or, for rational solutions, $\begin{cases}
x=3\left({{2t}\over{t^2+1}}\right)^3\\
y=3\left({{t^2-1}\over{t^2+1}}\right)^3\\
\end{cases}$
Comment: Perhaps this would lead to a rational parametrization of the curve, using the Weierstrass substitution. (+1)
Comment: I like your second formulation because it allows quick and easy hand computation of loads of rational points.

Inverted Circle?


accessing userControl value in winform c# using Model

Question: I'm working in a smal project where I'm using userControl displayed within the main form. I'm using a Model class which allow access to database look like:
<code>    public void InsertRoute(Route route)
    {
        string routecode = route.RouteCode.ToString();
        string vehiclecode = route.VehicleCode.ToString();
        string firsstudentname = route.FirstStudentName.ToString();

        using (SqlCommand cmd = new SqlCommand("InsertRoute2", conn))
        {
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.Parameters.Add(new SqlParameter("@RouteCode", routecode));
            cmd.Parameters.Add(new SqlParameter("@VehicleCode", vehiclecode));
            cmd.Parameters.Add(new SqlParameter("@FirstStudentName", firsstudentname));

            conn.Open();
            cmd.ExecuteNonQuery();
            conn.Close();
        }
    }
</code>
then i have a user control called UCCreateRotue which has several textboxes and  Button click Event handler :
<code>   private void btnCreateRoute_Click_1(object sender, EventArgs e)
    {
        UCRouteCreate form = new UCRouteCreate();
        //DialogResult dialog = form.ShowDialog();

        //if (dialog == DialogResult.OK)
        //{
            Route route = controller.CreateMovieFromText(form);
            controller.InsertRoute(route);
            //RefreshTable();
        //}

    }
</code>
then i have a Class called route as follow
<code>       class Route
{

    private   GlobalReach.UserControls.UCRouteCreate usrCon;
    public string RouteCode
    {
        get { return usrCon.txtRouteCode.Text ;}
        set { usrCon.txtRouteCode.Text = value ; }

    }
</code>
}
then i have a method in controller as follow to perform the insert which is done through sproc
<code>        public Route CreateRouteFromText(UCRouteCreate form)
    {

        string routecode =form.txtRouteCode.Text.ToString();
        string vehiclecode = form.txtVehicleCode.Text.ToString();
        string firststudentname = form.txtFStudent.Text.ToString();

        Route route = new Route();
        return route;
    }
</code>
my problem is when i click on the button click the code is working as i do have new rows inserted into my table but with empty value i.e the values are entered as nothing (if that make any sense) and the field that i dd not choose to fill entered as NULL value..?
could you please advise on why when i enter values in my usrControl TextBox the value is not captured through my code..
thank you in advance
Answer: button click event creates an empty form, you've commented out the show dialog lines, so the inputs will still be empty (unless you have them initialize to anything, but even then).  In CreateRouteFromText, you assign the form values to local variables, and then create an empty Route object and pass that back to the insert method. so no surprise that you have empty rows.
should at least set the Route objects to what the form has:
<code>public Route CreateRouteFromText(UCRouteCreate form)
{
    return new Route()
    {
        RouteCode = form.txtRouteCode.Text,
        VehicleCode = form.txtVehicleCode.Text,
        FirstStudentName = form.txtFStudent.Text
    }
}
</code>
Comment: Hi rangarok56 i commented the showdialog as it seems not to work in a user control as my user control are not showing within a form!


Martingale Difference Sequence Definition

Question: My definition of a Martingale Difference Sequence (MDS) is: A sequence $(Y_n)_{n \geq 1}$ of integrable random variables, adapted to the filtration $(\mathcal{F}_n)_{n \geq 1}$, is an MDS w.r.t $(\mathcal{F}_n)_{n \geq 1}$ if $\mathbb{E}[Y_{n+1}|\mathcal{F}_n] = 0$ a.s.
I am stuck showing the following statement, which it seems should be trivial but for some reason I can't figure out.
$(X_n)_{n \geq 0}$ is a martingale w.r.t $(\mathcal{F}_n)_{n \geq 0}$ iff $X_0$ is integrable and $\mathcal{F}_0$-measurable, and $(X_n - X_{n-1})_{n \geq 1}$ is a MDS w.r.t $(\mathcal{F}_n)$.
Right now I have:
$\mathbb{E}[X_{n+1} - X_n | \mathcal{F}_n] = \mathbb{E}[X_{n+1}| \mathcal{F}_n] - \mathbb{E}[X_{n}| \mathcal{F}_n] = \mathbb{E}[X_{n+1}] - X_n = \mathbb{E}[X_n]-X_n$.
I'm not sure how to get this expression to equal $0$ as required.
For the reverse direction I'm trying to use the fact that $X_{n} = X_0 + \sum_{i=1}^n (X_{i}-X_{i-1})$. I get
$\mathbb{E}[X_{n+1}|\mathcal{F}_n] = \mathbb{E}[X_0 + \sum_{i=1}^{n+1}(X_i - X_{i-1})|\mathcal{F_n}] = \mathbb{E}[X_0|\mathcal{F}_n] + \sum_{i=1}^{n+1}\mathbb{E}[X_i - X_{i-1}|\mathcal{F_n}] = \mathbb{E}[X_0|\mathcal{F}_n] + \sum_{i=1}^{n}\mathbb{E}[X_i - X_{i-1}|\mathcal{F_n}] + \mathbb{E}[X_{n+1}-X_n|\mathcal{F_n}] = \mathbb{E}[X_0|\mathcal{F}_n] + \sum_{i=1}^{n}\mathbb{E}[X_i - X_{i-1}|\mathcal{F_n}] = \mathbb{E}[X_n|\mathcal{F}_n]$
But again I'm not sure how to finish this. We know that $(X_n - X_{n-1})_{n \geq 1}$ is adapted to the filtration. But to complete this proof I need $X_n$ to be $\mathcal{F}_n$-measurable.
Thanks
Comment: In the first part you got the definition of a martingale wrong.
Comment: @geetha290krm Which bit is wrong. I have $\mathbb{E}[X_{n+1}|\mathcal{F}_n] = \mathbb{E}[X_{n+1}]$ since $X_{n+1}$ is independent of $\mathcal{F}_n$. And then $\mathbb{E}[X_n |\mathcal{F}_n] = X_n$ since $X_n$ is $\mathcal{F}_n$-measurable. I presume one of those is wrong?
Comment: What makes you think $X_{n+1}$ is independent of $\mathcal F_n$? $\mathbb{E}X_{n+1}=X_n$ be definition of a martingale.
Comment: @geetha290krm Oh right we dont know that it is. We just know that $X_{n+1}$ is not $\mathcal{F}_n$ measurable. But if $\mathcal{F}_n$ was actually the natural filtration then they would be independent right?
Comment: No, there is no such independence here.
Comment: We don't even know that $X_{n+1}$ is not $\mathcal F_n$ measurable: It's possible that $X_{n+1}=X_n$.  For example, in a constant sequence.  The definition of a martingale is that $\mathbb{E}[X_{n+1}|\mathcal F_n] = X_n$.  It is not possible for $X_{n+1}$ to be independent of $\mathcal F_n$ unless $X_n$ is deterministic.
Answer: Why would you think that $X_{n+1}$ is independent of $\mathcal{F}_{n}=\sigma(X_{n},X_{n-1},..,X_{1})$? It's just that $X_{n+1}$ is not "necessarily" measurable wrt $\mathcal{F}_{n}$. For example, take $S_{n}$ to be the simple symmetric random walk on $\Bbb{Z}$ . Then $S_{n}$ is a martingale. Does that mean that $S_{n+1}$ which is the ($n+1$ -th state) independent of the $n$-th state?. No, ofcourse not. It just means that we have don't have a full idea(we do have some idea) about what the $n+1$-th state will be. That's what measurability means. Intuitively, $X$ is $\mathcal{F}$ measurable should mean to you that if all information of $\mathcal{F}$ is known then $X$ is known.
Now, as far as the problem is concerned, first let $X_{n}$ be a martingale.
Then $E(X_{n+1}-X_{n}|\mathcal{F}_{n})=E(X_{n+1}|\mathcal{F}_{n})-E(X_{n}|\mathcal{F}_{n})=E(X_{n+1}|\mathcal{F}_{n})-X_{n}$  which is $0$ as by definition of martingale $E(X_{n+1}|\mathcal{F}_{n})=X_{n}$ for each $n$. So $(X_{n+1}-X_{n})_{n}$ is a martingale difference sequence. (Sometimes also called "fair sequence"). Also, by definition of martingales, $X_{0}$ is $\mathcal{F}_{0}$ measurable as $(X_{n})$ is an adapted sequence.
Conversely le $(Y_{n})_{n}=(X_{n}-X_{n-1})_{n}$ be a martingale difference sequence. Then $Y_{n}$ is $\mathcal{F}_{n}$ measurable and by definition $E(Y_{n}|\mathcal{F}_{n})=0$
Then $\sum_{k=1}^{n}Y_{n}=X_{n}-X_{0}$ is $\mathcal{F_{n}}$ measurable. As $X_{0}$ is $\mathcal{F}_{0}$ measurable and $\mathcal{F}_{0}\subseteq \mathcal{F}_{n}$ for all $n\geq 1$, we have $X_{n}=X_{n}-X_{0}+X_{0}$ is $\mathcal{F}_{n}$ measurable.
Then \begin{align}E(X_{n}|\mathcal{F}_{n-1})&
=E(\sum_{k=1}^{n}Y_{n}+X_{0}|\mathcal{F}_{n-1})\\
&=E(\sum_{k=1}^{n-1}Y_{k}|\mathcal{F_{n-1}})+E(X_{0}|\mathcal{F}_{n-1})+E(Y_{n}|\mathcal{F}_{n-1})\\
&=E(X_{n-1}-X_{0}|\mathcal{F}_{n-1})+E(X_{0}|\mathcal{F}_{n-1})+E(Y_{n+1}|\mathcal{F}_{n-1})\\
&=E(X_{n-1}|\mathcal{F}_{n-1})+E(Y_{n}|\mathcal{F}_{n-1})\\
&=X_{n-1}
\end{align}
for each $n\geq 1$. This shows that $X_{n}$ is a martingale sequence.


How could the Greek (Pythagoras et al.) measure the frequencies - as they didn't have a mobile app?

Question: How could the Greek (Pythagoras et al.) measure the frequencies - as they didn't have a mobile app?
They didn't have a tuning fork or any other standardized measure. But even without standards they were able to find out the ratios: by measuring strings or weigh pieces of iron. But how could they count the frequencies?
Or - with other words - when was the first tune pitch  defined as something about  Hertz >400 and <450?
I am suspicious that they were really able to define the wavelength and frequencies and that the also could define the pitch of the tone G. But the longer I think about it the more I believe they had the abilities.
I will try out some tests myself and when I'll find the results I'll tell you here the answer.
Comment: This can't be a serious question.
Comment: My question may be related to this one: https://music.stackexchange.com/questions/66957/how-did-pythagoras-and-ptolemy-measure-the-relative-pitch-of-musical-notes
Comment: Why restrict it to just the Greeks?  No-one had a mobile app for this until about 15 years ago!
Comment: But  we didn't find wires of telephone lines  on the archaeological excavations. So they might have had already wireless transmission, don't you think?
Comment: The first definition of  "A" as being in that range was rather a couple thousand years after Pythagoras.
Comment: @jjmusicnotes: this question is meant quite seriously (apart oft mobile joke! - that's only mentioned  to make it more interesting and attraktive to the younger generation.
Comment: ok, phoog, I have to admit there it is much different, but meanwhile I've been thinking a lot what I would have done if I had been an ancient Greek and I've also learnt more about the measures of time and length in China, Egypt, Greek and Roman.
Comment: Perhaps then you can share what you know about measurement if time, particularly with regard to precision.  As far as I can see it was not possible between the middle ages and the invention of the pendulum to measure time precisely enough to have numerical measurement of frequency.  I doubt ancient technology allowed sufficiently precise measurement of time, while precise measurement of length is relatively simple.
Comment: This probably is better suited to hsm.SE (history of science and math)
Comment: I don't see how this question is appreciably different from the one you link to in a comment, and I would answer this one with the same [answer](https://music.stackexchange.com/a/90042/2257) I wrote for [History of standardization of pitch and tuning: measuring waves](https://music.stackexchange.com/q/90025/2257).  Why shouldn't this be closed as a duplicate of either?  What distinguishes it from them?
Comment: I've been thinking a lot about this problem. I agree that it was not necessary to define the pitch as 440 or to count the vibrations. But I had even ideas how they could have defined minutes and seconds ... if they had wanted... but this is not a question I meant to discuss here.  Now I'm  pretty sure that the tone C and a tone  that we call as such today was possible. Of course not in Hertz.

The logical question to my answer I would give will be: Were the ancient Greek the able to tune their instruments near +/- 10 Hertz of the pitch in the middle age or today?
Answer: There is no historical evidence that the ancient Greeks ever measured the frequencies of sounds. They developed their theories of intervals using the relative lengths of strings or pipes, which are an equivalent way to relate intervals to geometrical ratios of lengths.
There is no obvious reason why the Greeks could not have invented the siren (see below), and by 300BC they already had reasonably accurate water-driven clocks, but in general they were more interested in philosophical discussion about how things ought to work, rather than scientific experimentation to find out how they actually worked.
The method of sound frequency measurement in Hz used by Helmholtz in "The Sensations of Tone" (first published 1863) was a siren, which is basically a rotating disk with a pattern of holes through which air is blown. It is easy to measure the rotational speed using a clock, and hence know the fundamental frequency of the sound produced.
I remember seeing a demonstration of exactly the same measurement system in high-school-level physics, back in the 1960s. Of course electronic frequency measurement was possible at that time, but (like modern tuning apps) it was a "magic black box" compared with a mechanical system whose working could be understood.
Helmholtz's other experimental method was to use sympathetic resonance to demonstrate the existence of a particular overtone in a sound, but that does not measure the frequency in Hz except by an independent calibration of the resonator itself.
Before Helmholtz, pitch standards (pipes, bells, tuning forks, etc) were simply compared with each other, and not with any absolute measurement. As a result, almost every geographical area in Europe had is own local pitch standard, though travelling professional musicians, and the practical range of human voices, tended to keep them more or less aligned with each other.
A mechanical strobe tuner is not a practical method of tuning musical instruments. The tuning fork was invented in 1711, and before that time the usual pitch standards were bells or reed pipes.
For church music, pipe organs provided a "standard" simply because they were impossible to retune quickly. Ironically the pitch of organ flue pipes (similar to a flute or recorder) is temperature dependent while the pitch of reed pipes is not, but in practice the reed pipes were (and still are) retuned to match the flues to compensate for temperature changes, because that is more practical.
Comment: Ummm, what do you mean  'a mechanical strobe tuner is not practical' ?  Strobe usually implies strobed light, and the StroboConn was the tuning device in every school in the 60s and 70s.
Comment: @CarlWitthoft Likely means "was", else the sentence doesn't really have anything to do with the question.
Answer: The earliest mechanisms which indicated or measured seconds weren't constructed until the mid 1500's.  And, of course, they were not accurate until the discoveries and inventions of Galileo and Huygens (et.al.) in the next century.  So there were no measurements or frequencies in anything per second (such as Hz) till after that.  Before that, relative audio frequency tuning was done either by ear, or by sympathetic resonance against some other instrument or resonant tuning device in the local community.  e.g. different places made instruments tuned to different local standards.
Various Western orchestras were tuning at a local frequency somewhere around 425 to 475 Hz in the 1800's. (Possibly earlier to make it easier on traveling composers and musicians.) (And likely measured using mechanical strobe tuners.) According to Wikipedia, 440 wasn't standardized in the U.S. until 1936. This was so that fixed tuning instrument makers didn't need to make slightly different instruments for different major Western orchestras around the world.
Strobe tuners don't count sound cycles directly.  They use a clockwork-like mechanism capable of counting revolutions per second.  And the tuner looks for synchronizing some visible display of the sound waveform against the revolving mechanical reference.  (Or these days, a computer simulation of the same.)
Comment: Did you mean 1836?  Helmholtz notes that the 440 Hz standard was established by a German standards body in the early 19th century, but I do not remember the exact year.  Of course, it was not widely adopted until later, and I don't think it was ever universal.
Comment: Different European countries and cities used different tuning "standards" in the 1800's.
Comment: So what precisely happened in 1936?  Was it the first time an international standards body recognized the 440 Hz standard?  Different orchestras use different pitch standards even today.  Why does the adoption of a German national standard 100 years earlier not count as standardization?  Can you link to the Wikipedia article that is the source of your claim, or at least identify it?
Comment: If you're talking about the article [440 Hz](https://en.wikipedia.org/wiki/A440_(pitch_standard)), it appears that the 1936 event was the adoption of 440 Hz by an American standards body.  That has no more authority than the 1834 adoption by the German standards body, except inasmuch as it contributes to an increased consensus of national standards bodies.  It's also unclear why you put "standards" in quotes.  A national standard established in the nineteenth century is still a genuine standard.
Comment: Regarding your edit, why would standardization "in the US" contribute to "fixed tuning instrument makers [not needing] to make slightly different instruments for different major Western orchestras around the world"?  I'm not being nitpicky for its own sake.  Rather, I think this could be a great answer but in its current state it is not.
Comment: A good separate question would be where and when did mass production of musical instruments for International distribution and sale scale up.


Bass scale length pros and cons

Question: For the last two years I've been seriously learning the guitar as my second instrument. I also bought a used low quality bass that I have been playing for the last 6 months or so. I am really enjoying playing the bass and want to upgrade to a nicer quality bass that plays better.
I went to the local shop and played a bunch of basses to see what feels good and I played a used 63 Hofner that was well out of my price range. I really like the way it feels but it has a short scale length (30" I think).
This led me to look at other 30" basses and before I purchase one I want to know what the pros and cons are.
I know it will have a different tone and obviously it will play easier in some respects. I also read that the strings will be a little looser.
Before I buy one based on how I, a rather new bassist, thinks it plays, I want to know if there are cons to having a shorter scale length that will make me regret it as I get better.
Also what benefits might a shorter neck provide.
Comment: Possible duplicate of [What are the disadvantages of buying a short-scale bass guitar](https://music.stackexchange.com/questions/4212/what-are-the-disadvantages-of-buying-a-short-scale-bass-guitar), although that might not cover the advantages very well.
Comment: Duplicate of 'What are the diadvantages of buying a short scae bass guitar'? Don't go away with the idea that a bass guitar is a different version of a standard guitar. They're different beasts, and are played differently. Lots of pros for short-scale, but if you ever have to play a borrowed bass, it'll be a full scale. String tension is sorted with string gauge. go for the 'proper job', and never regret it. I haven't!
Comment: @Tim it's not so much the lower tension on a shorty that makes it easier to play (for me) but the tighter fret spacing. There are a lot of fingerings I can do on a short scale that are out of the question on my standard 34" P.
Comment: I wonder if I've got over that sort of problem by using a 5 string, and playing further up the neck. Although playing on the first five frets is never a problem, and I have small hands.
Comment: Have a gander at SGC Nanyo Bass Collection. I use them all the time. Full scale though..!
Answer: Very briefly: I reckon a shorty is way easier to play for those without huge hands, often lighter which is a bonus if you have long sets, and a well-chosen one can sound absolutely fine in most styles of music (if a tiny bit rubbery compared to most 34" instruments).
Full-length (34/35") instruments usually sound a little more satisfying / versatile, and tend to be better for slap/pop IMO. You also have a lot more choice of instruments. Re-stringing to BEAD is a more realistic option too.
I probably sound better playing on a short-scale, to be honest. I tend to play through an effect like a bass driver which evens out some of the differences anyway.
I guess the only real drawback is that you might get so used to 30" that moving to a longer-scale instrument - should you wish to do so - may entail an degree of re-learning.

Bass scale length pros and cons


Getting the error message ServletActionRedirectResult incompatible with ServletDispatcherResult

Question: I have upgraded my Struts 2.0 application to Struts 220.127.116.11. The application is working fine. But I see few messages in system out log.
com.opensymphony.xwork2.util.logging.commons.CommonsLogger error Exception occurred
  during processing request: org.apache.struts2.dispatcher.ServletActionRedirectResult
  incompatible with org.apache.struts2.dispatcher.ServletDispatcherResult

What causes this error?
Comment: If you're redirecting during the execution of an action's code, are you then returning from the method? I know in Struts 1 you get warning/error messages if you redirect, then try to return a forward, from the same action.
Comment: share your pom or set of libraries you're using ?
Comment: Yeah, I do redirect during the execution of an action'scode and then returning from the method. In Java class, I have included the code dispatcherResult = (ServletDispatcherResult) invocation.getResult(); where I am getting the exception
Comment: Here is my sample code in XML
/login.jsp
searchStmtAll

recentActivityConfirm
Y

login
Comment: @Prashanth Do not add information in comments; edit it into the question. It's completely illegible here.
Answer: In the configuration you didn't use result type dispatcher which is a default result type. The instance of ServletActionRedirectResult is returned from action invocation. If you want to get a type of the result you could check that instance
Result result = invocation.getResult();
if (result instanceof ServletDispatcherResult){
  ServletDispatcherResult dispatcherResult = (ServletDispatcherResult )result;
  ...
}


Problem with adding checkbox to a view of flags with webform view

Question: So, I've been trying to implement a 'sample request' type webform using Flag, Webform, and Webform Views. The idea is to have a webform with a select list made from a view of Flags as implemented here through a custom moduleProgrammatic Sample Request, Drupal Steve.
The issue I'm having is that I can't seem to get a checkbox to show up in the view. I have followed the instructions at the webform views documentationWebform Views Docs by creating a boolean field with a checkbox widget. I'm Flagging Commerce products.  I have even tried to add a boolean on Flags and add that into the view, but that didn't work either.  Not sure is this is a Flags, Commerce, or Webform Views issue, but I wanted to report this here and see if anyone had any ideas.
Answer: Using drupal commerce (irrelevant), session_api, flags, views, webform4, custom content type (product display in my example), custom module.
Works even under anonymouse user
I think it's in select field settings.
Called "Multiple":

webform_flags.module:
<code>    <?php
 /**
 * Implements hook_webform_select_options_info().
 */
 function webform_flags_webform_select_options_info() {
    $items = array();
     if (function_exists('webform_flags_user_flag_sample_requests')) {
         $items['webform_flags_user_flag_sample_requests'] = array(
         'title' => t("User's flagged products"),
         'options callback' => 'webform_flags_user_flag_sample_requests',
         );
     }

    return $items;
 }

 function webform_flags_user_flag_sample_requests() {
     $view = views_get_view('user_flagged_products', TRUE);
     $options = array();
     if(isset($view)){
         $view->set_display('webform_options');
         $view->execute();

         if ($view->result) {
             //$row_class = $view->style_options['row_class'];
             //$attributes = $row_class ? " class='$row_class'" : '';
             foreach($view->result as $item) {
                //dpm($item->field_field_image);
                $options[$item->nid] = '<a>' . render($item->field_field_image[0]['rendered']) . $item->node_title .  '</a>';
         }
         }
         else {
            $options[0] = t("Nothing");
         }
     }

    return $options;
 }
</code>
View's settings:
Comment: See [result](http://i.imgur.com/MgyBc8b.png). Can't post more than 2 links in post. =)
Comment: This is a well-documents and thorough, answer!


Qual o melhor jeito de se obter o RadioButton que foi escolhido pelo usuário?

Question: Meu programa tem 5 RadioButton em um dos Panel que eu não renomeei e assim ficou Panel1, então só um pode ser escolhido.
Eu criei uma lista com todos os RadioButtons, depois de clicado em um botão eu tentei usar o código abaixo para iterar a propriedade Tag item do marcado:
// this.ListaRadios é minha lista de RadioButtons

var variacao = from item in this.ListaRadios //Esta parte dá erro:

// Could not find an implementation of the query pattern for source type
// 'System.Collections.Generic.List<System.Windows.Forms.RadioButton>'.
// 'Where' not found.  Are you missing a reference or a using directive
// for 'System.Linq'?

               where item.Checked = true
               select (string)item.Tag;

Além do erro que está dando, tem jeito mais eficiente de se fazer isso?
Como seria um Linq pra iterar somente os RadioButtons de um Panel e em seguida o único marcado?
Comment: Em relação ao erro verifique se tem a referência ao *System.Core assembly* e se indicou o *Namespace* com `using System.Linq;`
Answer:     var resultado = "";

    foreach (Control control in this.Panel1.Controls)
    {
        if (control is RadioButton)
        {
            RadioButton radio = control as RadioButton;

            if (radio.Checked)
            {
                resultado = radio.Text; //Text ou qualquer outra propriedade
            }
        }
    }


Rails 4, Simple form: custom url not finding user by id properly

Question: I have a bsic question regarfing a simple_form I have
Here is the form
  <%= simple_form_for(current_user, :url =>  nation_user_path(current_user), :method => :post) do |f| %>
        <%= f.input :selected_country, collection: @user_country_array, label: "Select a country to view data on (only countries represented are listed)", class: 'form-control' %>
        <%= f.submit "Submit", class: "btn btn-primary" %>

  <% end %>

routes.rb
resources :users do
   member do
     get :network
     post :nation
   end
end

user_controller
before_action :set_user, only: [:show, :edit, :update, :destroy, :nation]

 def nation
    @country = User.find(params[:user][:selected_country])
    @user_country_array = Array.new
    @user_country_array = User.all.map {|user| user.country }.reject{ |country| country.nil? }.uniq.sort
    @user_count = User.all.select { |u| u.user_complete == true }.count
    @user_json = User.all.group_by(&:iso).map{|k,v| [k, v.count, k.to_s.downcase]}.map {|c, v | ["code" => c, "value" => v, "flag" => c.to_s.downcase]}.flatten.to_json
    @sectiona =  User.all.group('practice').count.map { |k,v| [ "name" => k, "y" => v] unless k.nil?}.reject { |a| a.blank? }.flatten.to_json
    render 'country'
 end

def set_user
  @user = User.find(params[:id])
end

# Never trust parameters from the scary internet, only allow the white list through.
def user_params
  params.require(:user).permit(:experience,
                               :kind,
                               :selected_country,
                             ])
end

And user.rb
  attr_accessor :selected_country

When I submit the form with a country I get...
  Couldn't find User with 'id'=American Samoa

I am struggling to see why the before action isn't setting the suer correctly and defaulting (it seems) to the value in the select box
Any suggestions on this....
Comment: Do you read the documentation for the [`find`](http://apidock.com/rails/ActiveRecord/FinderMethods/find) method ? Maybe you should use [`find_by`](http://apidock.com/rails/ActiveRecord/FinderMethods/find_by) in `@country = User.find_by(country: params[:user][:selected_country])`
Answer: The problem you have is that you're trying to find the User using the selected_country attribute:
@country = User.find(params[:user][:selected_country])

Because you're setting this as a pure string, it will attempt to look up your User with the country you selected.
If you want to look up a value with a string, you'd be best using the find_by method:
@country = User.find_by country: params[:user][:selected_country]

--
To be honest, your whole nation method is really bad (multiple heavy db calls etc). I would do the following:
 def nation
    @country = User.find_by country_params[:selected_country]
    @user_country_array = User.select(:country).distinct
    @user_count = User.where(user_complete: true).count
    @user_json = User.all.group_by(&:iso).map{|k,v| [k, v.count, k.to_s.downcase]}.map {|c, v | ["code" => c, "value" => v, "flag" => c.to_s.downcase]}.flatten.to_json #-> this needs to improve
    @sectiona =  User.all.group('practice').count.map { |k,v| [ "name" => k, "y" => v] unless k.nil?}.reject { |a| a.blank? }.flatten.to_json #-> this also needs to improve
    render :country
 end

 private

 def country_params
    params.require(:user).permit(:selected_country)
 end


How do I pass the UID in URL to embedded View?

Question: Probably a stupid question, but I'm stumped... I have a simple View which lists all terms from a Taxonomy. Within this is a Global Field Type of "View" which is trying to list any content related to the Term, and authored by the UID present in the URL. However I am unable to pass the parameter from the URL to the View using standard Replacement Patterns. I can pass the Term using [!name] but not a parameter from the URL.
So parent view URL is /report
This is called with the UID appeded, e.g.: /report/34
How do I get 34 passed to the embedded view as contextual filter?
Many thanks for any help on this seemingly simple use case!
****** ANSWERED ********
Check Alfred's answer below, but also make sure the order of your Contextual Filters is correct. In this case, I was passing a blank value, rather than NULL value, as the first parameter from the parent view.
Swapping the order of the Contextual Filters over mean't I could pass a NULL value from the parent view (i.e. just the first one). Hope this makes sense.
Answer: In an embedded view you typically use the "When the filter value is not available" option for the contextual filter to achieve this.
Select "provide default value" then choose "raw value from URL" and set the path component to be 1.
You should also set validation criteria and select what should happen when the value is missing or incorrect.
Comment: OK, so I had two Contextual Filters in the embedded view and the first one was the UID, which was looking for the raw value [2] from the URL if not provided. The second contextual filter was getting the value from the parent view as the second parameter...
Comment: I had to change the order of the contextual filters in the embedded view, so the UID filter became the second in the list.

Then I could provide the first contextual filter in the parent view as the first and only parameter.

Before this, the parent view was passing the UID filter first, which was blank, which makes sense. It wasn't even getting as far as looking in the URL. Blank isn't null, now, is it?

Silly user.
Comment: That's exactly what I've tried, Alfred. But the embedded view is returning no items. Does it matter what type of display I use? Tried with Master, Page, Pane, and Block.
Comment: Maybe there's something else such as the set up of the contextual filter. Perhaps you are filtering the wrong thing.


OpenGL - Show Texture Only

Question: I'm working on a 2D isometric game, using pygame and pyopengl.
I'm drawing sprites as quads, with a texture. I managed to get the alpha transparency to work for the texture, but the quad itself is still filled in a solid color (whatever colour gl pipeline is set with at the time).
How do I hide the quad shape, and just show the texture?
Here is a pic showing the problem (gl pipeline set to pink/purple color):

The code is a bit messy, and I've been blindly copy 'n pasting gl calls hoping it solves the problem so there are bound to be quite a few calls in the wrong place or duplicated (or both).
GL Setup code (called once at start of script)
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)
glLoadIdentity()
glViewport(0, 0, screen_size[0], screen_size[1])
glMatrixMode(GL_PROJECTION)
glLoadIdentity()
glOrtho(0.0, screen_size[0], 0.0, screen_size[1], 0.0, 1.0)
glMatrixMode(GL_MODELVIEW)
glLoadIdentity()
glDisable(GL_LIGHTING)
glEnable(GL_TEXTURE_2D)
glEnable(GL_BLEND)
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA)

Drawing setup code (called once at the start of each frame)
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)
glLoadIdentity()
glViewport(0, 0, screen_size[0], screen_size[1])
glMatrixMode(GL_PROJECTION)
glLoadIdentity()
glOrtho(0.0, screen_size[0], 0.0, screen_size[1], 0.0, 1.0)
glMatrixMode(GL_MODELVIEW)
glLoadIdentity()
glDisable(GL_LIGHTING)
glEnable(GL_TEXTURE_2D)
glEnable(GL_BLEND)
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA)

Quad draw code (called for every sprite draw call):
glEnable(GL_BLEND)
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA)
glEnable(GL_TEXTURE_2D)
glEnable(GL_ALPHA_TEST)
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST)
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST)
glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_DECAL)

# Start new transformation matrix
glPushMatrix()

# Apply translation
glTranslatef(self.rect.centerx, self.rect.centery, 0.0)

# Start gl drawing cursor
glColor4f(1.0, 0.0, 1.0, 1.0)

# Bind the texture to this draw session
glBindTexture(GL_TEXTURE_2D, self.texture.id)

# Start drawing a quad
glBegin(GL_QUADS)

# Grab new copy of rect, and move to the origin
r = self.rect.copy()
r.center = (0, 0)

# Draw top left point
glTexCoord2f(1.0, 0.0)
glVertex2f(*r.topleft)

# Draw top right point
glTexCoord2f(0.0, 0.0)
glVertex2f(*r.topright)

# Draw bottom right point
glTexCoord2f(0.0, 1.0)
glVertex2f(*r.bottomright)

# Draw bottom left point
glTexCoord2f(1.0, 1.0)
glVertex2f(*r.bottomleft)

# End quad
glEnd()

# Apply transformation matrix
glPopMatrix()

Answer: Well, either use blending, so that the alpha value actually has effect on opacity. Or use alpha testing, so that incoming fragments with an alpha below/above a certain threshold are discarded.
Blending requires to sort geometry back to front. And given what you want to do alpha testing may be the easier, more straightforward solution.
Update:
Either way it's imperative that the texture's alpha value makes it through to the fragment. If you were using shaders this would be as simple as making sure that the fragment output alpha would receive its value from the texture. But you're using the fixed function pipeline and the mess that's the texture environment state machine.
Using only a single texture your best bet would be a GL_REPLACE texture mode (completely ignores the vertex color). Or GL_MODULATE that takes the vertex color into account. Right now you're assumingly using GL_DECAL mode.
My suggestion: Drop the fixed function pipeline and use shaders. Much easier to get things related to texturing working. Also you'll hard pressed to find hardware that's not using shaders anyway (unless you're planning to run your program on stuff that's been built before 2004).
Comment: I thought the glEnable (BLEND) calls were enabling alpha blending. What am I missing?
Comment: @Oliver: Damn, I missed, that. My bad.
Comment: Can you recommend any tutorials on the shader method for 2d stuff? All the stuff I've found and read so far has been using the old method, especially for 2D.
Comment: @Oliver: There's no conceptual difference between 2D and 3D in OpenGL. Technically it always boils down to drawing points, lines or triangles, one at a time on a 2D framebuffer. And what makes the whole thing "3D" is, how the position of the vertices on the 2D framebuffer are determined from coordinates in a higher dimensional space. For what's it worth any tutorial regarding 3D graphics and shaders will do for you and the only thing you have to keep in your mind, that one of the coordinates (which one is your choice) is constant for all operations.
Answer: The colored background behind your tiles is probably due to this line when you set up your texture:
glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_DECAL)

Just remove this as the default texture environment settings are probably fine for standard tile rendering. As an example of what messing with these parameters can do, if you wanted glColor calls to "tint" your texture instead, then replace GL_DECAL with GL_BLEND.
There is no need for any of those lighting calls included in your code as far as I can tell unless you are working with 3d models and ancient per-vertex lighting (I assume you are not since this is a 2d isometric game). Also you only need blending for this, no need for alpha testing. Assuming you are working with images with alpha (RGBA format), here is a simple demo that displays two tiles with a transparent background (supply your own image of course instead of ./images/grass.png):
import pygame
from pygame.locals import *
from OpenGL.GL import *
import sys

class Sprite(object):
    def __init__(self):
        self.x = 0
        self.y = 0
        self.width = 0
        self.height = 0
        self.texture = glGenTextures(1)

    def load_texture(self, texture_url):
        tex = pygame.image.load(texture_url)
        tex_surface = pygame.image.tostring(tex, 'RGBA')
        tex_width, tex_height = tex.get_size()
        glBindTexture(GL_TEXTURE_2D, self.texture)
        glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR)
        glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR)
        glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, tex_width, tex_height, 0, GL_RGBA, GL_UNSIGNED_BYTE, tex_surface)
        glBindTexture(GL_TEXTURE_2D, 0)
        self.width = tex_width
        self.height = tex_height

    def set_position(self, x, y):
        self.x = x
        self.y = y

    def render(self):
        #glColor(1, 1, 1, 1)
        glEnable(GL_BLEND)
        glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA)
        glBindTexture(GL_TEXTURE_2D, self.texture)
        glBegin(GL_QUADS)
        glTexCoord(0, 0)
        glVertex(self.x, self.y, 0)
        glTexCoord(0, 1)
        glVertex(self.x, self.y + self.height, 0)
        glTexCoord(1, 1)
        glVertex(self.x + self.width, self.y + self.height, 0)
        glTexCoord(1, 0)
        glVertex(self.x + self.width, self.y, 0)
        glEnd()
        glBindTexture(GL_TEXTURE_2D, 0)

def init_gl():
    window_size = width, height = (550, 400)
    pygame.init()
    pygame.display.set_mode(window_size, OPENGL | DOUBLEBUF)
    glEnable(GL_TEXTURE_2D)
    glMatrixMode(GL_PROJECTION)
    glOrtho(0, width, height, 0, -1, 1)
    glMatrixMode(GL_MODELVIEW)
    glLoadIdentity()

if __name__ == "__main__":
    init_gl()
    tile1 = Sprite()
    tile1.load_texture("./images/grass.png")
    tile1.set_position(50, 100)
    tile2 = Sprite()
    tile2.load_texture("./images/grass.png")
    tile2.set_position(80, 130)
    tiles = [tile1, tile2]

    while True:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                sys.exit()

        glClear(GL_COLOR_BUFFER_BIT)
        glColor(1, 0, 0, 1)
        for tile in tiles:
            tile.render()
        pygame.display.flip()

Let me know if this helps!
Comment: I would try out the advice over [here](http://gamedev.stackexchange.com/a/30365/78005). As stated in that answer, one simple starting improvement would be to reduce texture switching as much as possible (i.e. minimize calling glBindTexture by ordering the list of tiles). The most important fix, however, is to group all of your tiles into a vertex buffer object (VBO) and render it with a single draw call. Rendering quads one by one is extremely slow and uses the old immediate mode.
Comment: Thanks for the help. I managed to get it working properly. Only thing now (although this was always a problem) is the performance is slow. I was hoping moving from SDL based to opengl would give me a boost, but its not really much different. I have about 1000 64x64 tile sprites on a 1280x960 screen I redraw constantly and I get around 17fps. Is there something major I'm doing wrong, or do I just need to move away from the pipeline method?

OpenGL - Show Texture Only


Binomial proportion confidence interval with known distribution of the proportion

Question: If I have a coin that produces head with probability p, I know there are several methods to estimate a confidence interval for p with a given confidence level.
If I also know that the coin was randomly selected from a set of coins whose distribution of p is known, I think that it is possible to improve the quality of the estimation.
I tried to find if this is a known problem and if there are known solutions, but I found nothing.
Is there anyone who knows if this is a studied problem or has any idea on how it could be possible to leverage the known distribution of p in order to improve its estimation?
Comment: what you describe is a mixed Binomial distribution:  it is like a two step approach: (1) you daw a $p$ from a distribution and then (2) given the drawn value you draw from a Binomial with that success probability. You should google for mixed binomial or for lexian distribution.
Comment: Tim,  that's true, but I don't know p, I can just toss the coin and make observations in order to estimate p.
fcop, thanks for the tip. I think I have found what I need thanks to your comment: https://www.jstor.org/stable/2984516?seq=1#page_scan_tab_contents.
jds, thanks for the observation.
Comment: @Tim everything except the particular value of $p$ that was drawn when you started observing heads....
Comment: If you know p, then you don't need to estimate it and you don't noted confidence intervals for it.
Comment: It very much depends on what your distribution for $p$ is. Note that in general having variability in $p$ will likely lead to wider confidence intervals or less certainty (in a bayesian framework).
Comment: So what do you mean by knowing the distribution of p? If you know the distribution, you know everything: mean, mode, variance, quantiles etc.
Answer: I don't think either of the comments under the question quite get at what's going on here.
My understanding of it is this (and please correct me if I am wrong): a specific value for $p$ is drawn from a known distribution, but we don't observe that $p$. Instead we observe a binomial random variable with that $p$. You want to use both the information in the known distribution for $p$ as well as in the likelihood to make some inference about $p$.
On that understanding:
A random $p$ obtained from a known distribution plus some information about that specific draw of $p$ from a sample is naturally answered with  Bayesian approach; the known distribution of $p$ is the prior, which you then update via the sample (specifically the posterior is proportional to the product of the likelihood and the prior).
$$f(p|X)\,\propto\, f(X|p)\,f(p)$$
For example, if the prior were beta, the posterior would also be beta (since the
beta is conjugate for a binomial likelihood).
If the prior were symmetric triangular, the posterior would be piecewise beta (with two continuous pieces).
More generally we could use a variety of techniques to obtain the updated information about $p$. On this simple problem - assuming a prior that didn't work nicely with the likelihood - one option would use numerical integration to scale the product of the prior and the likelihood to a density.
Comment: @Kodi You're correct that a credible interval for $p$ is not a confidence interval; I wasn't assuming the OP was absolutely fixed on having an interval with exactly the properties of a confidence interval (like the coverage guarantee) but I should still have mentioned the difference.
Comment: I don't think the question is trying to get at bayesian posteriors. I think @maxvv is trying to ask about hierarchical/compound distributions. This can be very similar to the answer you provided but could also be a frequentist question. In either way, unless $f(p)$ has a specific form, simulation may be his best bet.
Comment: How are you going to get a confidence interval for $p$ out of an estimate of the posterior distribution of $p$? You can get a credible interval, to be sure, but that's a different animal.
Comment: Thanks Glen, I was suspecting that the Bayesian approach was the way to follow, but I am not very familiar with statistics. I have +1 you answer, but I am not reputable enough to have my vote displayed. :)
Comment: @jds the answers could be quite different so I think it's important to try to figure out what problem is being solved. If the question were about the distribution of the number of heads, then it would be a problem of compound distributions, as you say. But the question is about inference on $p$. I don't quite see how looking at that compound distribution for the number of heads gets you to inference on $p$. If you can clarify for me how you see that working, I'd be interested to see if I could improve this answer
Answer: Thanks everybody for the help.
I am indeed in an easy situation, where I can approximate my prior distribution with a beta distribution
Beta($\alpha_0$ ,$\beta_0$).
Therefore, the posterior distribution is
Beta($\alpha_0$ + observed_heads , $\beta_0$ + observed_tails).
I found an answer to another question that uses a very nice example that can be applied to my case: https://stats.stackexchange.com/a/47782/44624


Poisson Distribution of Students in a Class

Question: I know that Poisson distributions generally count the number of occurrences of something over a period of time. However, in my experiment, I am counting the number of non-white students per class in International Baccalaureate classes and non-IB classes. Would I still be able to use a Poisson distribution where the mean would be the amount of non-white students per class, even if I'm counting the number of occurrences per class instead of the number of occurrences per unit of time?
Thanks!
Comment: You should as a minimum link to your related question https://stats.stackexchange.com/questions/633561/poisson-distribution-from-samples-of-varying-sizes, preferably  aybe just edit that one! But, for this application Poisson distribution does not seem to fit. For a class with total $N$ students, you could use a binomial distribution $\mathcal{binom}(N, p)$, and thus a logistic regression ...
Comment: Hi Kjetil, sorry about that. How would I model a logistic regression if I would be comparing the success (probability of a student being non-white) to a binary factor (whether a class is IB or non-IB)?
Answer: You could just a poisson regression in this case.  Let $Y_i$ be the count of non-white identifying students in the $i^{th}$ class of size $N_i\geq Y_i$, and let $x_i$ be an indicator for if the class is an IB class.  You can model the scenario the data as
$$ Y_i \sim \operatorname{Poisson}(\lambda_i(x)) $$
$$ \log(\lambda_i(x)) = \beta_0 + \beta_1x_i + \log(N_i) $$
Here, we have included the class size as an offset term.  This will model the rate of non-white identifying students in each type of class.  The rate in IB classes would be $\exp(\beta_0)\exp(\beta_1)$ and the rate in non-IB classes would be $\exp(\beta_0)$.  The quantity $\exp(\beta_1)$ is then the multiplicative factor describing how the rate changes between classes.
Comment: @kjetilbhalvorsen The main difference is in the estimand, but logistic regression is fine here as well. Here OP asked for Poisson regression and so I answered thusly.
Comment: How would this differ from an binomial logistic regression?
Answer: You can use a logistic regression, which I think here is a more direct and more directly interpretable solution. The size of class $i$, $N_i$, is not in itself informative about proportion from different ethnic groups. At least not when $x_i$, the number of non-white students, is known. So by conditioning on $N_i$ we can assume that $x_i \mid N_i \sim \mathcal{Binom}(N_i, p_i)$  is binomial.
Now you can model $p_i$ as depending on covariates, in your case the type of school, IB or non-IB. That can be represented as a factor variable with two levels. Using R this could be coded as
mod0 <- glm( cbind(x, Y-x) ~ IB, data=yourdataframe, family=binomial)

Here we assume the data frame has one row for each school class. If you have more covariates the model can be extended. For instance, if you have multiple classes within schools, you can use lme4 with mixed models to extend this to a multilevel model. One thing to be aware of is that in this binomial case there might be overdispersion, so maybe try family=quasibinomial.
Another advantage with binomial regression in this case is that you can extend it (with multinomial logistic regression) to diversity with more than two ethnic groups.
A completely different way to attack your problem, it to measure diversity  directly. You can check the tag diversity
Comment: FWIW people sometimes use "logistic regression" only to refer to the binary-outcome case, calling this case *binomial regression*.


Scraping HTML table with Ruby and Nokogiri

Question: so I'm working on a project that scrapes data from a website that has gun accident/death data. Here's what the website looks like: http://www.gunviolencearchive.org/officer-involved-shootings
I'm trying to grab each table row and make an object(instance?, sorry I'm new to ruby) with the data from that row and print it out into the console. Right now, the @occurances array returns an array of the same data 26 times. Clearly it is overwriting with the first row. How would you suggest that I store each of these instances?
Here is my code, the (choice) is the website address.
 def self.data_from_choice(choice)
        doc = Nokogiri::HTML(open(choice))
        @occurances = []
        doc.xpath("//tr").each do |x|
          date = doc.css("td")[0].text
          state = doc.css("td")[1].text
          city = doc.css("td")[2].text
          deaths = doc.css("td")[4].text
          injured = doc.css("td")[5].text
          source = doc.search(".links li.last a").attr("href").value
          @occurances << {:date => date, :state => state, :city => city, :deaths => deaths, :injured => injured, :source => source}
        end
        puts @occurances
      end

Comment: That's a very important subject. What's your app doing with this data? #peace
Comment: Welcome to SO. Please read "[mcve]". It's important that your question contain enough so people can run it without having to rewrite your code or write a wrapper for it.
Comment: @maxpleaner right now it's just a project so I can learn scraping well, but I'd like to do more with the data later!
Answer: In the loop for each row you are calling doc.css(...). This causes a search from the top of the document each time (i.e. from doc). What I think you want is to make the search relative to the row, which you have in the x variable.
So change this:
date = doc.css("td")[0].text

to this
date = x.css("td")[0].text

and similarly for state, city etc.
Comment: Thank you Matt, that makes sense now!


How to download all documents from OWASP (github)?

Question: I wanted to download all the documents from OWASP repository in github:
https://github.com/OWASP/DevGuide/find/dc5a2977a4797d9b98486417a5527b9f15d8a251
I haven't found an action button where I can download all documents in just one click (I need to enter each page to download).
Answer: Why don't you use the zip archive? https://github.com/OWASP/DevGuide/archive/2.0.1.zip .
By default, the page of a repository will give the link to download the zipped master branch, clicking on "Download ZIP" (on the right column). If you select the appropriate branch, in your case, the 2.0.1 branch, you can use the same "Download ZIP" which will targets the selected branch.
In a general way, in Github, you can download the content of a repository in the following way:
https://github.com/user_or_organization/repository/archive/branch.zip
Comment: Try this https://github.com/OWASP/DevGuide/archive/2.0.1.zip ``2.0.1`` is the github branch where the docs files are listed. Once you unzip the file, the docs files should be in the ``DevGuide2.0.1`` directory
Comment: i've updated my answer above, i gave you some explanations where to download the zipped branch, and how the url is built.
Comment: Download the zip, and unzip it, you will get a local copy of all the content of the repository, there you will have all documents in .doc format.
Comment: But your zip contains only .md files, not .doc ones... What's the zip link for https://github.com/OWASP/DevGuide/find/dc5a2977a4797d9b98486417a5527b9f15d8a251 ?
Comment: But I didn't understand how do you know the links, because I don't see it on the page.
Answer: Downloading the zip archive is probably best for your purposes (see @eblondel's answer) but if you have git on your system you could also just clone the archive:
> git clone https://github.com/OWASP/DevGuide.git
> git checkout 2.0.1

Then look in the 'DevGuide 2.0' directory of the resulting folder.


How to sort a view using values not stored in the database

Question: I'm using a view where elements are sorted by price values,
under certain conditions the price values are rewritten on the display (if there are offers) but not in the database. The problem is that I need the results to be ordered by the rewritten price.
I can reorder the results returned by the query using a views_pre_render hook:
https://stackoverflow.com/questions/2471361/how-to-sort-view-results-programmatically
but it only affects the current page so elements are not properly ordered within the elements not shown in the current page.
Other option would be to order the view altering the query itself but since the right price values don't actually exist in the database I don't know how this could be done.
Is there a way to order the results of a the whole view when paginator exists?
I've thought about not using pagination and requesting all the elements of the view so I can create my own paginator once I've ordered the results but I'm not sure how would it affect the speed of the page.
Comment: Forget Drupal for a minute and think it through - how would you implement this in any system? Drupal is just a layer over PHP and a database, if you can come up with a method that would allow you to use external data to sort a paged sql query, you'll be able to solve this with Views :)
Comment: I ended up solving it by retrieving all the view results, modifying the values and using multisort. Then I had to create my own pagination system. I'll post the solution later. It works fast and I can't perceive any delay, but I think this solution is not scalable for very big queries.
Comment: Yes, for solving it in any system it would require to alter the query that returns the results using the values I need which are not stored in the database. This could be done, maybe, using a temporary database in the query where i would store the values for which I want the results to be ordered by, but I don't know how this could be done.
Comment: That's definitely the right approach - getting Views to do that might be tricky though, I can't recall coming across anything that would help with that. Here's hoping there's something out there already written
Comment: hmmm, have you tried using [Views PHP](https://www.drupal.org/project/views_php) and then [use Global php](https://www.drupal.org/node/1178170#comment-6032566) as your sort?
Comment: Views PHP would basically request all data and sort it with PHP, yet preserving pagination (last paragraph of the OP). If performance is an issue, this might not be the solution.
Comment: performance IS an issue here. I'm still looking to solve it altering the query even if it's not the easyest solution.
Comment: If not in the database, where are the values coming from?  Is it a computation?  Or a call to an external API?  If the former, SQL can certainly order by a computed value.  If the latter, then yes, you would seem to need a temporary table of some sort, although creating and populating the table may not be quick either if you can't cache it in some manner.
Comment: The modified values come from an external API,
Comment: External data sources for Views are feasible, give a look at this http://colans.net/blog/integrating-remote-data-drupal-7-and-exposing-it-views or this https://www.drupal.org/node/1126578 or this http://barcelona2012.drupaldays.org/sessions/displaying-external-data-fly-views-and-ctools
Comment: For what I've seen It creates new whole entities with external data and use them for the views. It's not the use i need, but still pretty interesting.
Answer: I used a view pre render hook to alter the order of the returned rows (I had to disable pagination and create my own pagination system). Here's an example of the function:
function your_theme_or_module_views_pre_render(&$view) {
  if ('your_view' == $view->name && 'your_display' == $view->current_display ) {
    if(isset($_GET['sort_order'])){
      if($_GET['sort_order'] == 'ASC'){
        $sortorder = SORT_ASC;
      }else{
        $sortorder = SORT_DESC;
      }
      if($_GET['sort_by'] == 'field_price_value'){
        $byprice = true;
      }else{
        $byprice = false;
      }
    }else{
      $byprice = true;
      $sortorder = SORT_ASC;
    }
    $order = array();
    foreach ($view->result as $key => $row){
    /* Here you can modify the values you want to show
    and put them in an order array */
      $row->field_field_price[0]['rendered']['#markup'] = $thenewprice[$index]."€";
      $row->field_field_price[0]['raw']['value'] = $thenewprice[$index];
      $order[$key] = $thenewprice[$index]; // we will use this array for multisorting
    }

    //this will be used for pagination In my case I'll show 8 results per page
    $numpages = ceil(count($view->result)/8);
    if($byprice){
      /* we only change the rows order if we are sorting by the
      modified field, otherwise the order returned by the view is fine */
      array_multisort($order, $sortorder, $view->result);
    }

Now we create the pagination system you can use this as an example
    if(!isset($_GET['page'])){
      $view->result = array_slice($view->result, 0, 8);
    }else{
      $sumando = ((int)$_GET['page']*8);
      $view->result = array_slice($view->result, $sumando, 8);
    }
    $links = array();
    if(isset($_GET['page'])){
      $page = $_GET['page'];
      $absolute_url = full_url( $_SERVER );
      for($i=0;$i<$numpages;$i++){
        if($page == $i){
          $active = " active";
        }else{
          $active = "";
        }
        $urlconpage = str_replace("page=".$page,"page=".$i,$absolute_url);
        $links[] = "".$i."";
      }
    }else{
      $absolute_url = full_url( $_SERVER );
      $countarray = explode("?",$absolute_url);
      if(count($countarray)>1){
        for($i=0;$i<$numpages;$i++){
          if(0 == $i){
            $active = " active";
          }else{
            $active = "";
          }
          $urlconpage = $absolute_url."&page=".$i;
          $links[] = "".$i."";
        }
      }else{
        for($i=0;$i<$numpages;$i++){
          if(0 == $i){
            $active = " active";
          }else{
            $active = "";
          }
          $urlconpage = $absolute_url."?page=".$i;
          $links[] = "".$i."";
        }
      }
    }
    $_SESSION['links'] = $links;
  }

Most of the code in the paginator is just to keep unchanged the parameters in the url, essentials for the view returning the right results. The function full_url that I call in the code is an adaptation of the function described in:
https://stackoverflow.com/questions/6768793/get-the-full-url-in-php
Using the SESSION variable You can print the links where you prefere, For example in a global textarea in the view footer, inside an

 structure.


Linear algebra: Find || || u || v ||

Question: Let u = (2, 4, 1) and v = (-3, 5, -1).
The question asks me to find <code>|| ||u||v||</code> but I don't know exactly what that means as I've never seen something written like this (other than guessing that it's a question about parallels). I've searched everywhere for a question similar to this but I couldn't find anything. Any help would be appreciated. Thanks!
Answer: Hint: Probably $\lVert \mathbf{x}\rVert$ signifies the (Euclidean) norm of the vector $\mathbf{x}$, so
$\lVert (x_1,x_2,x_3) \rVert = \sqrt{x_1^2+x_2^2+x_3^2}$.
You probably have a typo and mean $\lVert \mathbf{u}\rVert \lVert \mathbf{v}\rVert$, the product of $\lVert \mathbf{u}\rVert$ and $\lVert \mathbf{v}\rVert$.
Or, possibly you mean $\Big\lVert \underbrace{\lVert \mathbf{u}\rVert \mathbf{v}}_\textrm{scalar times vector} \Big\rVert$ (as @Chessanator suggests)? Your notation is difficult to understand without using MathJax.
Answer: The notation of those double-bars refers to the norm on the vector space (usually the euclidean norm $||x||=\sqrt{x_1^2+x_2^2+x_3^2}$). Knowing this, we can see how the expression in your question was constructed:

Start with the vector $u$ and take its norm $||u||$.
$||u||$ is a real number - a scalar - so we can take any other vector $v$ and multiply it by that scalar to get $||u||v$.
$||u||v$ is a vector. Therefore, we can take its norm $||(||u||v)||$.

This is subtly different to the expression $||u||.||v||$ mentioned by Jagol95 in the comment. However, knowing the properties of norms it turns out that the two expressions are actually equal. I wouldn't be surprised if your teacher follows up by getting you to confirm this for the specific example (You should probably attempt this even if they don't).

Linear algebra: Find || || u || v ||


Replace string within a list that's NOT equal to a value in Python

Question: I have a list contains different names:
list = ['Tom', 'Mary', 'Robin', 'Tom']

What I want to do, is to replace 'Tom' with 'MESSAGE' and everyone else as 'RESPONSE'.
Like below:
list = ['MESSAGE', 'RESPONSE', 'RESPONSE', 'MESSAGE']
Is there a way to do it? Preferably using only one line of code.
Answer: It's a simple list comprehension:
["MESSAGE" if name == "Tom" else "RESPONSE" for name in list]

As a side note, do not use built-ins such as list to name your variables.
Answer: Its a try, and its in a single Line. If the list contains only 2 unique values, then
replacedList = ['MESSAGE' if item == 'Tom' else 'RESPONSE' for item in list]

reference from here
Answer: You can try using list comprehension:
list = ["MESSAGE" if item == "Tom" else "RESPONSE" for item in list]


Starting iaxmodem and faxmodem with upstart

Question: How can I use Upstart to start iaxmodem and faxgetty when I have multiple modems? Centos 6.4 has a nice warning as listed below which incites me to believe the standard inittab lines will not work.
# inittab is only used by upstart for the default runlevel.
#
# ADDING OTHER CONFIGURATION HERE WILL HAVE NO EFFECT ON YOUR SYSTEM.

where I would normally put
IAX:2345:respawn:/path/to/iaxmodem ttyIAX

Answer: Use a task which is started on change of runlevel to start a job for each IAXModem you want to start.  Then use a task to start a faxgetty for each started iaxmodem job.
IE:
init 3 -> start-iaxmodem ---> iaxmodem(ttyIAX0) -> start-faxgetty(ttyIAX0) -> faxgetty(ttyIAX0)
                          \-> iaxmodem(ttyIAX1) -> start-faxgetty(ttyIAX1) -> faxgetty(ttyIAX1)

/etc/init/start-iaxmodems.conf:
# This service starts the configured number of gettys.
start on stopped rc RUNLEVEL=[2345]

task

script
    for ttyIAX in /etc/iaxmodem/* ; do
        start iaxmodem TTY=`basename $ttyIAX`
    done
end script

/etc/init/iaxmodem.conf:
# This service maintains an iaxmodem on the sepcified device.
stop on runlevel [016]

respawn
instance $TTY
exec /usr/sbin/iaxmodem $TTY

/etc/init/start-faxgettys.conf:
# This service starts the configured number of faxgettys.
start on started iaxmodem
# this will run once per triggering iaxmodem instance
instance $INSTANCE

task

script
    # give it time to at least create the device
    /bin/sleep 1s
    start faxgetty TTY=$INSTANCE
end script

/etc/init/faxgetty.conf:
# This service maintains a faxgetty on the sepcified device.
# only stop when the stopping iaxmodem is this TTY
stop on stopping iaxmodem INSTANCE=$TTY

respawn
instance $TTY

exec /usr/sbin/faxgetty $TTY


How do I limit access to a custom field type I have created so that it can only be attached to certain bundles of content?

Question: I have a custom field class. I would like to limit it to specific content types and bundles that I will choose when my custom module is installed and as other content types meet certain criteria. I don't want it to be available at /admin/structure/types/manage/article/fields/add-field
Is hook_form_alter on the add-field page form my only option or is there an Annotation or API I can use to mark my field as "not available to this content" similar to the way FieldWidgets can be marked as applicable to only certain field types?
Note: I was also planning to add a ConstraintValidator to the field so that it won't validate if added to the wrong content.
Answer: It is not possible to define field types which are only applicable to certain bundles. I think you need hook_form_alter for the form where the fields are chosen for a bundle to achieve that.
Answer: After some further research I will answer with what I found:
In order to make a field type be unavailable on the manage fields page there is an option in the FieldType annotion plugin called $no_ui which must be set to TRUE as documented here.
Then the field can still be added to specific content types using BaseFieldDefinition::create() in hook_entity_base_field_info or to bundles using the less common hook_entity_bundle_field_info plus hook_entity_field_storage_info.


PCA variance is sum of eigenvalues?

Question: Earlier today in a lecture we were shown some slides that showed that the variance of k is equal to the sum of the first k eigenvalues.
There was a bit where I got totally lost

Can someone explain what's happening here? How do we get from the LHS to the RHS? I've searched online but haven't been able to find anything relevant.
Update: This is the entire slide:
Comment: What are $m$, $k$, $u_j$ and $x^{(i)}$?
Comment: I would feel dishonest if I did not mention: if this is in the context of regression, using the percentage of variance retained to determine which principal components to use in a regression is often given, but quite poor, advice.
Answer: Presumably the variables have been centered already, which explains the second-to-last equality in the slide.
$$\frac{1}{m} \sum_{i=1}^m (u_j^\top x^{(i)})^2
= \frac{1}{m} \sum_{i=1}^m u_j^\top x^{(i)} (x^{(i)})^\top u_j
= u_j^\top \left(\frac{1}{m} X^\top X\right) u_j
= \lambda_j,$$
since $u_j$ was presumably defined to be a unit eigenvector of $\frac{1}{m} X^\top X$ corresponding to eigenvalue $\lambda_j$.

PCA variance is sum of eigenvalues?


Better way to use or condition in js

Question: When I write this, my or condition works
const role = "admin"
if (role === "user" || role === "admin") {

}

But why my or condition does not work this way
if (role === "user" || "admin") {

}

If I write this it works
if (role === "admin" || "user") {

}

I want to make my if condition true both the times but in second it does not work.
Comment: `||` is an operator, and both your samples are *syntactically* correct but they *mean* significantly different things. It's not clear what your question is however.
Comment: You can always use RegExp.test() `/^(user|admin)$/.test(role)` if you like that syntax more
Comment: The second way does not work because it doesn't mean what you think it does. It "works" but what it does is different that the first code sample.
Comment: `['user', 'admin'].includes(role)`
Comment: @Pointy Sorry I was not clear. I want to make my if condition truthfully both the times but in second it does not work.
Comment: I believe I am not the first who has this doubt. Do you have any duplicate link which can give me an answer? @Pointy
Answer: The equal-operator has a higher binding as the or-operator, so first is tested role === "user". If this is false because role it is not "user" this will be false. But this doesn't matter because on the other hand "admin" is truethy and truthy or false is true.
Here the 3 cases from the OP:
1.
const role = "admin";
if (role === "user" || role === "admin") { ... }

role === "user" is false,
role === "admin" is true
=> (role === "user" || role === "admin") is true.
2.
const role = "xxx";
if (role === "user" || "admin") { ... }

role === "user" is false,
"admin" is true
=> (role === "user" || "admin") is true.
3.
 if (role === "user" || "admin") { ... }

Error because role is not defined. If you instantiated it with any value you will have case 2.

Explanation
Here is for better understanding a list of examples for truethy in JS (they will be executed):

if (true)
if ({})
if ([])
if (42)
if ("foo")
if (new Date())
if (-42)
if (3.14)
if (-3.14)
if (Infinity)
if (-Infinity)

And here is a list of examples for falsy in JS (they will NOT executed):

if (false)
if (null)
if (undefined)
if (0)
if (0n)
if (NaN)
if ('')
if ("")
if (``)
if (document.all)
Comment: Could you pls check the above question and give your answer based on all the three cases
Answer: Because that's not how or works. It evaluates the condition on the left for truthiness, then returns with that if it is truthy, otherwise it returns the right side. Any non empty string is truthy, so what you've written is if (role === /*some truthy value*/ || /*doesn't matter, the first value is truthy*/) You need to use the first snippet. That's how or is supposed to work.
Alternatively, you could do if(["user", "admin"].includes(role))
Comment: "If neither side is truthy, it returns false" — no, that is incorrect. If neither value is truthy, the right-hand value is the result, not `false`.
Comment: Oops. I've been in other programming languages recently. Thanks for the correction.

Better way to use or condition in js


QThread::start(priority) vs Linux

Question: I am using some QThread based worker threads in KDE Neon 18.04 (based on Ubuntu 18.04, Kernel 4.15.0-46-generic). The worker threads interfered with my desktop applications so I decided to reduce their priority.
The Qt documentation of QThread::start(priority) says:

The effect of the priority parameter is dependent on the operating
  system's scheduling policy. In particular, the priority will be
  ignored on  systems that do not support thread priorities (such as on
  Linux, see  http://linux.die.net/man/2/sched_setscheduler for more
  details).

After reading the above documentation I expected priorities would have no effect on my Linux system. Still I gave it a try. And guess what - it worked perfectly.
So, why does the Qt documentation state there would be no thread priorities on Linux? And why does it work anyway?
Answer: Depending on which flavour of Linux/Unix/*Nix you use the scheduler may or may not support it. As far as I'm aware the majority of Qt's priority levels are supported on most Linux systems now, but not all of the priority levels. I suspect the documentation says it's unsupported so they don't need to list every combination of OS variant and scheduler variant that do support priority levels and which levels are supported.
You can validate it has created it with the correct priority by using htop or top and processing with awk: https://unix.stackexchange.com/questions/19301/what-is-a-command-to-find-priority-of-process-in-linux
Comment: Linux and other Unix will almost always let you use lower priorities, but higher is not allowed without special permission. It is unlikely that `QThread::TimeCriticalPriority` will work, for example.

QThread::start(priority) vs Linux


setting up Ubuntu 10.10 as paravirtualized guest in Xen on RHEL5 host - what kernel?

Question: I've discovered the tool ubuntu-vm-builder, which I've installed and then invoked on an Ubuntu workstation as:
sudo vmbuilder xen ubuntu --suite maverick --flavour virtual --arch amd64 --mem=512 --rootsize 8192

This workstation is not the intended target host of the virtual machine, however; I would like to host the guest on a Red Hat Enterprise Linux 5 machine that is running Xen 3.0.3.
The output of this command appears to be a folder named ubuntu-xen containing three files:

tmpXXXXXX, a very large file which I assume is the root partition image
tmpYYYYYY, a somewhat large file which I assume is the swap partition image
xen.conf, a text file

I have copied the xen.conf file to the RHEL server's /etc/xen directory under the new name newvm, adjusting the paths of tempXXXXXX and tempYYYYYYin the file after also copying them from my local workstation to the RHEL server.  When I launch the Virtual Machine Manager virt-manager, I can see the newvm virtual machine listed underneath the Dom0 machine.
When I try to start newvm, I get the error:
Error starting domain: virDomainCreate() failed POST operation failed: (xend.err 'Error creating domain: Kernel image does not exist: None')

Indeed, there exists an entry kernel = 'None' in the xen.conf file.  How do I find out what the path of the kernel should be?  Is this path supposed to be to a kernel stored on the local filesystem of the RHEL5 host, or is it supposed to be a path inside the guest image?
I see that the vmbuilder command provides for a --xen-kernel option, along with a --xen-ramdisk option, but I'm not sure what to use for either.
I think I should be able to get this to work, since Ubuntu is said to be supported as a Xen guest, even though the Xen 4.0.1 docs state support for only a limited set of distributions, Ubuntu excluded.

Update 1
When running vmbuilder on my local workstation, I did observe an output line saying:
Calling hook: install_kernel

and later, output lines saying:
update-initramfs: Generating /boot/initrd.img-2.6.35-23-virtual
[...]
run-parts: executing /etc/kernel/postinst.d/initramfs-tools 2.6.35-23-virtual /boot/vmlinuz-2.6.35-23-virtual

So in the xen.conf file, I tried setting the lines:
kernel = '/boot/vmlinuz-2.6.35-23-virtual'
ramdisk = '/boot/initrd.img-2.6.35-23-virtual'

When trying to start the VM, I got an error similar to last time:
Error starting domain: virDomainCreate() failed POST operation failed: (xend.err 'Error creating domain: Kernel image does not exist: /boot/vmlinuz-2.6.35-23-virtual')

This makes me think that the RHEL5 machine is looking for local files, rather than a file within the binary guest disk image.
After running sudo updatedb on my workstation, neither of those files were found.  If the vmbuilder tool had tried to install them, it must have failed.

Update 2
I was able to extract the kernel and initrd images from the guest disk binary by mounting it:
mkdir mnt_tmp
sudo mount ubuntu-xen/tmpXXXXXX mnt_tmp/ -o loop
cp mnt_tmp/boot/vmlinuz-2.6.35-23-virtual virtual_kernel_ubuntu
cp mnt_tmp/boot/initrd.img-2.6.35-23-virtual virtual_initrd_ubuntu

These two files I copied to the RHEL5 server, and edited the xen.conf file to point to them as kernel and ramdisk.
With this done, I could "run" the newvm virtual machine from within virt-manager, but was met with the message
Console Not Configured For Guest

when I double clicked the entry to open the Virtual Machine Console.  As suggested by a forum, I then added the line
vfb = [ 'type=vnc' ]

to the configuration file, recreated the virtual machine (a ~10 min process), and this time got the message:
Connecting to console for guest

This remained indefinitely; after selecting View -> Serial Console, I found a kernel panic:
[5442621.272173] Kernel panic - not syncing: Attempted to kill the idle task!
[5442621.272179] Pid: 0, comm: swapper Tainted: G      D     2.6.35-23-virtual #41-Ubuntu
[5442621.272184] Call Trace:
[5442621.272191]  [<ffffffff815a1b81>] panic+0x90/0x111
[5442621.272199]  [<ffffffff810652ee>] do_exit+0x3be/0x3f0
[5442621.272204]  [<ffffffff815a5e20>] oops_end+0xb0/0xf0
[5442621.272211]  [<ffffffff8100ddeb>] die+0x5b/0x90
[5442621.272216]  [<ffffffff815a56c4>] do_trap+0xc4/0x170
[5442621.272221]  [<ffffffff8100ba35>] do_invalid_op+0x95/0xb0
[5442621.272227]  [<ffffffff8130851c>] ? intel_idle+0xac/0x180
[5442621.272232]  [<ffffffff810072bf>] ? xen_restore_fl_direct_end+0x0/0x1
[5442621.272239]  [<ffffffff815a48fe>] ? _raw_spin_unlock_irqrestore+0x1e/0x30
[5442621.272247]  [<ffffffff8108dfb7>] ? tick_broadcast_oneshot_control+0xc7/0x120
[5442621.272253]  [<ffffffff8100ad5b>] invalid_op+0x1b/0x20
[5442621.272259]  [<ffffffff8130851c>] ? intel_idle+0xac/0x180
[5442621.272264]  [<ffffffff813084e0>] ? intel_idle+0x70/0x180
[5442621.272269]  [<ffffffff810072bf>] ? xen_restore_fl_direct_end+0x0/0x1
[5442621.272275]  [<ffffffff8148a147>] cpuidle_idle_call+0xa7/0x140
[5442621.272281]  [<ffffffff81008d93>] cpu_idle+0xb3/0x110
[5442621.272286]  [<ffffffff815873aa>] rest_init+0x8a/0x90
[5442621.272291]  [<ffffffff81b04c9d>] start_kernel+0x387/0x390
[5442621.272297]  [<ffffffff81b04341>] x86_64_start_reservations+0x12c/0x130
[5442621.272303]  [<ffffffff81b08002>] xen_start_kernel+0x55d/0x561

Update 3
I tried an i386 architecture instead of amd64, but got the same kernel panic.
Also, it seems the Virtual Machine Manager pays attention to the format of the filename of the kernel; for the same kernel binary, I tried simply naming it vmlinuz-virtual, which threw out an error box about an invalid kernel.  When I named it vmlinuz-2.6.35-23-virtual, it did not throw the error, but it did still result in the kernel panic shortly thereafter.
Comment: @pepoluan, because the question was asked in 2010?
Comment: @psusi drats! I must've been drunk to not notice the date... :-P
Comment: I'm curious... any reason for not using Ubuntu 12.04 instead?
Answer: You might want to look into the xen-tools package which if you specify --pygrub on the xen-create-image command it will embed the kernel/initrd within the guest disk image which may make it easier for you to transfer guest images between systems.
Answer: you might want to consider upgrading your xen infrastructure, xen 3.x does have limitations to which guests it supports. Have a look at the following, http://www.redhat.com/resourcelibrary/articles/enterprise-linux-virtualization-support
Have you tried an older ubuntu version?
Answer: You should use (have used?) the linux-image-virtual kernels provided by Ubuntu, and a newer Xen hypervisor (possibly with pygrub or similar).
But your question is old, nowadays you wouldn't use Ubuntu-10.10 and on newer ones you use the same kernel under Xen (both hvm and paravirt) and on bare metal.


Maximum ratio of the shorter to the longer leg in a Pythagorean triangle

Question: Problem
I was reading the question Why is the smallest Pythagorean triple $(x,y,z)=(3,4,5)$ not close (in ratio $x/y$) to any other small triple?.
I came up with this question:

Let $(a, b, c)$ be a Pythagorean tuple where $a < b < c$.  What is the
  maximum possible value of $a / b$?

(A triple $(a, b, c)$ is a Pythagorean triple if $a, b, c \in \mathbb{Z}^+$ and $a^2 + b^2 = c^2$)

My attempt
I am aware of Euclid's formula$^1$
$$ a = 2mn, \qquad b = m^2 - n^2, \qquad c = m^2 + n^2. \qquad (m,n \in \mathbb{Z}^+, m > n)$$
Therefore,
$$ \frac{a}{b} = \frac{2mn}{m^2 - n^2}. $$
Now, how can I maximize it?  I can't see a lot of connection between the numerator and the denominator.

$^1$ It turns out that this step is wrong — it fails to consider the case where $2mn > m^2 - n^2$.
Answer: There are infinitely many Pythagorean triples $(a, b, c)$ with $b=a+1$, see for example

Wikipedia: Pythagorean triple:

Choosing m and n from certain integer sequences gives interesting results. For example, if m and n are consecutive Pell numbers, a and b will differ by 1

The Proof of Infinitude of Pythagorean Triples $(x,x+1,z)$

An infinite set of positive integers is necessarily unbounded, therefore
$$
 \frac{a}{b} = 1 - \frac{1}{a+1}
$$
can be arbitrarily close to one for these triples.
Answer: We will show that the maximum ratio of the short leg to the long leg is $3/4$ by contrasting it with the ratio of the long leg to the short leg.
For Pythagorean triples (if we insist that side-A is odd) it is not always the case that $A<B<C$. For example $(15,8,17)\quad (35,12,27)\quad (63,16,65)...\quad$
If in Euclid's formula $ (A=m^2-k^2,\quad B=2mk,\quad C=m^2+k^2)$  we let $(m,k)$  be $(2n-1+k,k)$ and let $k=1$ we arrive at a formula that makes it easy to see how $A/B$ can be maximized.
$$A=4n^2-1\quad B=4n\quad C=4n^2+1\implies R=\frac{A}{B}=f(n)=\frac{4n^2-1}{4n}$$
Here are examples of $F(n)\rightarrow (A,B)$ represented as $n(A,B)$
$$1(3,4)\quad 2(15,8)\quad 3(35,12)\quad 4(63,16)\quad  ...\quad 25(2499,100):(R=24.99)$$
We can see by this progression that the ratio $RnA/B$ can grow indefinitely with $n$.
$$\lim_{n\rightarrow\infty} \bigg(\frac{4n^2-1}{4n}\bigg)=\infty$$
As an alternative, if we let $(m,k)$  be $(2n-1+k,k)$ and $n=1$ we find that $B/A$ grows faster.
$$A=2k+1\quad B=2 k^2 + 2 k\quad C=2 k^2 + 2 k + 1
 \implies R=\frac{B}{A}=f(k)= \frac{2 k^2 + 2 k}{2k+1}$$
where
$$1(3,4)\quad 2(5,12)\quad 3(7.4)\quad 4(9,40)\quad ...\quad 25(51,1300) :(R\approx 25.49)$$
$$\lim_{k\rightarrow\infty} \bigg(\frac{2 k^2 + 2 k}{2k+1}\bigg)=\infty$$
All other combinations of $(n,k)$ are slower to grow but all Ratios approach infinity. In any case, the first triple in any series has the largest ratio of short leg to long leg. $$\therefore R_{max}=\frac{3}{4}$$


How can I automatically flag new comments?

Question: I have a Drupal 8 site with Flag and Rules modules. How to flag a new comment ?
I want that when a user creates a comment, the comment should be automatically flagged.
I created a type of Flag on the comments and I created a rule with the event "When a new comment is posted".
What should I put in action ?
Answer: Flag ID should be the ID of the flag being set. If you go to /admin/structure/flags, and Edit the flag, the machine name/ID of the flag will be at the end of the URL -- so /admin/structure/flags/manage/{flag_id}.
I've not used Rules on D8, but for Entity ID, if you click "switch to data selection" and then click the field, I think it should give you some autocomplete options to help select the data you want. You'll likely end up with something like "comment:id".
Comment: I just tested but it doesn't work https://ibb.co/bWbJ00g
Comment: Does it let you drill down any further? Seems like that isn't grabbing the actual value of the cid for whatever reason. Also...anything useful in the Provided Variables fieldset below?
Comment: I don't know how to use c module, because it is not as simple as in drupal 7
Comment: Not sure what you mean by "c module". You may want to look at https://www.drupal.org/project/rules/issues/2920651#comment-12328109 and https://www.drupal.org/project/rules/issues/2763945#comment-12358180 for info on how the data selector works. It might be as simple as using `comment.cid.value`. Past that I think we'll need to wait for somebody with more D8 Rules experience to drop in for guidance.


Exchange DAG 2013 force node to keep mounted database

Question: Please do help us with this critical issue.
We have 2 node DAG, one of the MB server has issues on the physical host itself and keeps hanging. All the databases has copies on 2 MB servers. But when this MB2 server gets hanged the database shows dismounted. It doesn't switch over to MB1 which should be happening. We have to restart the MB2 to get the database up and running or wait for long time to move to MB1.
We currently have plans to built another node and gradually remove the faulty MB2.
Please instruct us on how to prevent the current databases which is on MB1 not to move to MB2 and stay in MB1 itself
Awaiting kind response on this regard
Thanks in Advance
-Sanjai
Comment: Depending on the amount of data being replicated from MB1 to MB2 the process might be still on-going when the MB2 fails. Did you have a look at the Exchange logs? Windows Logs?
Answer: I would prefer if you set the "ActivationPreference" correctly and point them to the "healthy" server. Exchange 2013 shouldn´t do an automatically "rebalance" as Exchange 2016 do (see here). Then an issue related to the "faulty" server shouldn´t cause any issues (disconnect) for your users.

The Activation preference number Displays the activation preference
  number. This is used as part of Active Manager's best copy selection
  process, and it is used to balance the DAG by redistributing active
  mailbox databases throughout the DAG via the DAG's
  PreferenceMoveFrequency property. This property defines the frequency
  (measured in time) when the Microsoft Exchange Replication service
  rebalances database copies by performing a lossless switchover that
  activates the copy with an activation preference number of 1. The
  value for activation preference is a number equal to or greater than
  1, where 1 is at the top of the preference order. The number can't be
  larger than the number of copies of the mailbox database.

For more see here or here.
However having a faulty Exchange Mailbox (MB) server in your DAG might cause corruptions and I would quickly fix that.


zf2 doctrine 2 - Output OnetoOne Unidirectional

Question: After annotating an OneToOne Unidirectional, i want to output the joined column, without using a form.
One People Entity has got a column to store the id of Country Entity.
What i can do: I can store the id of the country into the People Entity using a form with a dropdown select, which is bound to the Country Entity.
Problem: I can not enter the value country of the, hopefully correct, joined table.
People Entity:
<?php
namespace People\Entity;

use Doctrine\ORM\Mapping as ORM;
// ...

/**
* A people entity.
*
* @ORM\Entity
* @ORM\Table(name="icd_people")
* @property int $id
// ...
* @property string $ic_hq_country
*/
class People implements InputFilterAwareInterface
{
protected $inputFilter;

/**
* @ORM\Id
* @ORM\Column(type="integer");
*/
protected $id;

/**
* @ORM\Column(type="integer")
* @ORM\OneToOne(targetEntity="Country")
* @ORM\JoinColumn(name="ic_hq_country", referencedColumnName="id")
*/
protected $ic_hq_country;

// getter and setter
}

The Country Entity:
<?php
namespace People\Entity;

use Doctrine\ORM\Mapping as ORM;
//...

/**
* A Country entity.
*
* @ORM\Entity
* @ORM\Table(name="pre_country")
* @property int $id
* @property string $country
*/
class Country implements InputFilterAwareInterface
{
protected $inputFilter;

 /**
 * @ORM\Id
 * @ORM\Column(type="integer");
 */
protected $id;

/**
* @ORM\Column(type="string")
*/
protected $country;

/**
 * Get id
 *
 * @return integer
 */
public function getId()
{
    return $this->id;
}

/**
 * Set country
 *
 * @param string $country
 * @return Country
 */
public function setCountry($country)
{
    $this->country = $country;

    return $this;
}

/**
 * Get country
 *
 * @return string
 */
public function getCountry()
{
    return $this->country;
}

/**
* Convert the object to an array.
*
* @return array
*/
public function getArrayCopy()
{
    return get_object_vars($this);
}

public function setInputFilter(InputFilterInterface $inputFilter)
{
    throw new \Exception("Not used");
}

public function getInputFilter()
{
    throw new \Exception("Not used");
}
}

The Controller Action:
public function indexAction()
{

    $userid =  $this->zfcUserAuthentication()->getIdentity()->getId();

     return new ViewModel(array(
        'pea' => $this->getEntityManager()->find('People\Entity\People', $userid),
));
}

The View giving the id of the country, but not the name:
<?php echo $this->escapeHtml($pea->ic_hq_country);?>
I actually expected something like this being possible, to output the country name and not the id:
<?php echo $this->escapeHtml($pea->country);?>
Thank you for reading, and for any help, which could lead me into the right direction!
Comment: did you take a look at my answer?
Comment: I am sorry! quite busy, i thougth that i get a message from stackoverflow with an anotation, that somebody answered. thank you very much for ur answer, it did help me out !
Answer: You should not use the @Column anotation in the $ic_hq_country field of the Peopleentity.
/**
* @ORM\OneToOne(targetEntity="Country")
* @ORM\JoinColumn(name="ic_hq_country", referencedColumnName="id")
*/
protected $ic_hq_country;

like this, hopefully ic_hq_country will be a proxy to the entity instead of the id.
so in your view you can use:
<?php echo $pea->ic_hq_country->getId();?>

and also
<?php echo $this->escapeHtml($pea->ic_hq_country->getCountry());?>

Comment: Sorry for not recognizing!


Error while writing to file with multiprocessing

Question: I am working on html parser, it uses Python multiprocessing Pool, because it runs through huge number of pages. The output from every page is saved to a separate CSV file. The problem is sometimes I get unexpected error and whole program crashes and I have errors handling almost everywhere - reading pages, parsing pages, even writing files. Moreover it looks like the script crashes after it finishes writing a batch of files, so it shouldn't be anything to crush on. Thus after whole day of debugging I am left clueless.
Error:
multiprocessing.pool.RemoteTraceback:
"""
Traceback (most recent call last):
  File "D:\Programy\Python36-32\lib\multiprocessing\pool.py", line 119, in worker
    result = (True, func(*args, **kwds))
  File "D:\Programy\Python36-32\lib\multiprocessing\pool.py", line 44, in mapstar
    return list(map(*args))
  File "D:\ppp\Python\parser\run.py", line 244, in media_process
    save_media_product(DIRECTORY, category, media_data)
  File "D:\ppp\Python\parser\manage_output.py", line 180, in save_media_product
    _file_manager(target_file, temp, temp2)
  File "D:\ppp\Python\store_parser\manage_output.py", line 214, in _file_manager
    file_to_write.close()
UnboundLocalError: local variable 'file_to_write' referenced before assignment
"""

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "D:\ppp\Python\store_parser\run.py", line 356, in <module>
    main()
  File "D:\Rzeczy Mariusza\Python\store_parser\run.py", line 318, in main
    process.map(media_process, batch)
  File "D:\Programy\Python36-32\lib\multiprocessing\pool.py", line 266, in map
    return self._map_async(func, iterable, mapstar, chunksize).get()
  File "D:\Programy\Python36-32\lib\multiprocessing\pool.py", line 644, in get
    raise self._value
UnboundLocalError: local variable 'file_to_write' referenced before assignment

It look like, there is an error with variable assignment, but it is not:
try:
    file_to_write = open(target_file, 'w')
except OSError:
    message = 'OSError while writing file name - {}'.format(target_file)
    log_error(message)
except UnboundLocalError:
    message = 'UnboundLocalError while writing file name - {}'.format(target_file)
    log_error(message)
except Exception as e:
    message = 'Total failure "{}" while writing file name - {}'.format(e, target_file)
    log_error(message)
else:
    file_to_write.write(temp)
    file_to_write.write(temp2)
finally:
    file_to_write.close()

Line - except Exception as e:, does not help with anything, the whole thing still crashes. So far i have excluded only Out Of Memory scenario, because this script is designed to be handled on low spec VPS, but in testing stage I run it in environment with 8 GB of ram. So if You have any theories please share.
Comment: I'm not intimately familiar with Python, but in every language that I know, equivalent code would crash in the `finally` block if the `open` call fails.
Comment: Which line throws the exception?
Comment: I do not know, but the `try except` is basically in its own function, so there is not possible to reference `file_to_write` before assignment.
Comment: It did not crash with `OSError while writing file name`, so it looks like when error is caught there is not problem. This is a clue, that the script crashes due to error which is not in any of those exceptions.
Answer: The exception really says what is happening.
This part is telling you obvious issue:
UnboundLocalError: local variable 'file_to_write' referenced before assignment

Even you have try/except blocks that catches various exceptions, else/finally doesn't.
More specifically in finally block you reference variable that might not exist since exception with doing: file_to_write = open(target_file, 'w') is being handled by at least last except Exception as e block, but then finally is run too.
Since exception happened as a result of not being able to open target file, you do not have anything assigned to file_to_write and that variable doesn't exist after exception is handled. That is why finally block crashes.
Comment: I have ran some test, and it looks like this is it. Thanks.