Limit of Integral of Difference Quotients of Measurable/Bounded $f$ Being $0$ Implies $f$ is Constant

Question: Assume $f$ is Lebesgue measurable and bounded on $[0,1]$ and that
$$\int_{0}^{1}\frac{|f(x+h)-f(x)|}{h}\;dx\to0\;\text{as}\;h\to0.$$
Show that $f$ is constant for almost every $x$ in $[0,1]$.
My question relates to my proposed proof below.  At no point did I rely on the boundedness of $f$ on $[0,1]$, only its measurability and so I suspect my reasoning is faulty and would appreciate somebody that could (in their answer) scrutinize and correct my proof.
(Proposed) Proof. Assume first that $h\to0^{+}$ and suppose that we may interchange the two limits.  Then since the difference quotients are non-negative, we conclude $f'(x)$ exists and is equal to $0$ for almost every $x$ in $[0,1]$, and the claim follows. (As pointed out, we don't necessarily know the limit of the integrands exists even when we assume the interchange is valid, although this is probably not difficult to reason one's way out of -- more damning is below.)
The goal quickly turns to justifying this interchange.  To that end, the presumed existence of the above limit implies that for any $0<M<\infty$ there is some positive real number $h(M)$ such that for any $h<h(M)$ we have
$$\left|\int_{0}^{1}\frac{|f(x+h)-f(x)|}{h}\;dx\right|<M.$$
Since $m([0,1])=1$ (in particular, we are integrating over a set of finite measure) and the difference quotients are non-negative, we conclude that
$$\frac{|f(x+h)-f(x)|}{h}<M\;\text{a.e.}\;x.$$
Since this bound is independent of $h$ once $h<h(M)$, it follows that at some point along the sequence each of the difference quotients is pointwise a.e. dominated by $M$, which is integrable on any set of finite measure.  Hence the interchange of limits discussed above is valid, and with the case of $h\to0^{-}$ being handled similarly, the claim is proved.
(As the comment points out, we cannot conclude anything about the upper (or lower) bound of a function based off the value of its integral, even if the integration is taken over a set of finite measure and the integrand in question is nonnegative; approximations to the identity serve or otherwise spikey functions on sets of small measure as counter-examples.)

Edit. Fatou's lemma implies
$$\int_{0}^{1}\liminf_{h\to0}\frac{|f(x+h)-f(x)|}{h}\;dx\leq\lim_{h\to0}\int_{0}^{1}\frac{|f(x+h)-f(x)|}{h}\;dx=0.$$  Hence
$$\liminf_{h\to0}\frac{|f(x+h)-f(x)|}{h}=0\;\text{a.e.}\;x.$$
(The $\liminf$ of course exists without further justification.)
We now need a way to obtain the same for $\limsup_{h\to0}\frac{|f(x+h)-f(x)|}{h}.$  This could be accomplished by showing the limit exists under the assumptions given, in which case the $\liminf$ is equal to the $\limsup$.  Any ideas how to execute this, or otherwise approach the problem?
I'm wondering too if my original argument above could be modified by taking into account the assumed boundedness of $f$ in order to exclude the possibility that its difference quotients form a "spikey" sequence of integrands.

Edit. Here is another approach I am considering by posting this question Counter-Example (or Proof) to $\int_{0}^{1}f_{n}\;dx\to0$ Implies $f_{n}\to0$ a.e. $x$ Whenever $f_{n}\geq0$.
Peter Tamaroff mentioned the type-writer sequence being a counter-example to the post linked.
Comment: http://www.math.ucla.edu/grad/handbook/hbquals.shtml -- See problem #1 from Analysis Spring 2013.  I don't understand your point though; there are no singularities or otherwise obstructions to speak of that would prevent us from integrating along $[0,1]$...
Comment: Regarding the posing of the question, the original takes $f$ which is defined on $\mathbb{R}$, which solves the problem. However, note that $\int_E gd\muM\})=0$.
Comment: Isn't this true though when $g\geq0$?  How can you have $\int_{0}^{1}g(x)\;dxM$ on a set of positive measure?
Comment: Thank you for making me realize my naivety.  Approximations to the identity much... (:
Comment: Sure thing; sometimes outside perspective is the only way to avoid these things. Another thing that's bothering me is that you're implicitly assuming the existence of a pointwise limit (a.e.), so that we can contend ourselves to trying to switch the order.
Comment: @Jonathan I incorporated your comments in the most recent edit.
Answer: If one is allowed to use Lebesgue's differentiation theorem, one can prove the result as follows.
Since the integrand is nonnegative, we have $\lim_{h\to 0^+} \int_0^\alpha \frac{\vert f(x+h)-f(x)\vert}{h}\, dx=0$ for every $\alpha\in[0,1)$, and hence
$\lim_{h\to 0^+} \int_0^\alpha \frac{f(x+h)-f(x)}{h}\, dx=0$.
Putting $F(u):=\int_0^u f(x)dx$, one may write
\begin{eqnarray}\int_0^\alpha (f(x+h)-f(x))\, dx&=&\int_h^{\alpha+h} f(u)du-\int_0^\alpha f(x)dx\\&=&F(\alpha+h)-F(\alpha)-F(h)\, .
\end{eqnarray}
So the above limit becomes
$$\lim_{h\to 0^+}\left(\frac{F(\alpha+h)-F(\alpha)}{h}-\frac{F(h)}h\right)=0\, . \tag{$*$}$$
Now, since $f$ is integrable on $[0,1]$ (being bounded), we know from Lebesgue's differentiation theorem that $\lim_{h\to 0} \frac{F(\alpha+h)-F(\alpha)}{h}=f(\alpha)$ for almost every $\alpha\in [0,1)$. By $(*)$, it follows that $l=\lim_{h\to 0^+} \frac{F(h)}h$ exists, and that $f(\alpha)=l$ almost everywhere. Hence, $f$ is a.e. constant.
Comment: I think it was "clear" from the beginning that Lebesgue's differentiation theorem should be helpful, because of the combination "integral+difference quotient+almost everywhere". So it was natural to introduce the function $F$.
Comment: Can I ask what motivated this proof for you?  In other words, what trial and error did you go through before you thought of attacking the problem by defining such $F$?


Show the name of hit gameObject

Question: I'm creating a project for my school and it was going pretty good until now. I've searched for an answer for nearly an hour and still couldn't find anything (wrong tags?).
The thing is that I want to show the name of the item that player is hitting with raycast. I tried this but sadly it's not working:
#pragma strict

var rayLength : int = 10;

private var inventory : Inventory;

private var guiShow : boolean = false;

var bush : GameObject;
var player : GameObject;

function Start()
{
    inventory = GameObject.Find("First Person Controller").GetComponent(Inventory);
}

function Update()
{
    var hit : RaycastHit;

    var forward = transform.TransformDirection(Vector3.forward);

    if(Physics.Raycast(transform.position, forward, hit, rayLength))
    {
        if(hit.collider.gameObject.tag == "Wood")
        {
            guiShow = true;

            if(Input.GetKeyDown("e"))
            {
                inventory.wood++;
                Destroy(hit.collider.gameObject);
                guiShow = false;
            }
        }
        else if(hit.collider.gameObject.tag == "Sticks")
        {
            guiShow = true;

            if(Input.GetKeyDown("e"))
            {
                inventory.stick++;
                Destroy(hit.collider.gameObject);
                guiShow = false;
            }
        }
        else if(hit.collider.gameObject.tag == "BushFull")
        {
            guiShow = true;
            bush = (hit.collider.gameObject);

            if(Input.GetKeyDown("e"))
            {
                inventory.berry += 5;
                bush.GetComponent(BushController).berriesTaken = true;
                guiShow = false;
            }
        }
        else
        {
            guiShow = false;
        }
    }
    else
    {
        guiShow = false;
    }
}

function OnGUI()
{
    if(guiShow == true)
    {
        GUI.Box(Rect(Screen.width / 2, Screen.height / 2, 100, 25), "Pick up" + hit.collider.gameObject);
    }
}

If anyone knows answer - please help me. Thanks in advance!
Comment: please don't add tags in the title, and Unity's "JavaScript" isn't actually JavaScript but UnityScript
Comment: Oh, ok. Sorry - won't happen again.
Answer: Just use hit.collider.name to retrieve the gameObject's name. If that doesn't work (which I'm 99% sure it will), use hit.collider.gameObject.name
Answer: Your code is a little tricky because maybe it would be a greater idea not to use the OnGUI() method. It's easier to call a custom method from update when the raycast hit the player.
One example of an easier implementation is the following:
function Update()
{
    var hit : RaycastHit;

    var forward = transform.TransformDirection(Vector3.forward);

    if(Physics.Raycast(transform.position, forward, hit, rayLength))
    {
        Debug.Log (hit.collider.gameObject.name); //Shows the hittenGo in the console

        drawColliderName(hit.collider.gameObject.name);

        if (hit.collider.gameObject.tag == "Woods")
        {
            //do Woods tuff
        }
        else if (hit.collider.gameObject.tag == "Sticks")
        {
            //do Sticks stuff
        }
        else if (hit.collider.gameObject.tag == "BushFull")
        {
            //do BushFull stuff
        }
   }
}

Of course you have to implement the method drawColliderName where you must draw the Collider name on the GUI.
If you just want your code to work, in the OnGUI() you have to call name variable, like in the Debug.Log call of my code, this is just calling hit.collider.gameObject.name instead of hit.collider.gameObject

Show the name of hit gameObject


Unresolved, non-dominant sevenths in SATB chorale harmony

Question: I'm working on taking some chorales and their soprano lines out of Bach, and making my own harmonizations/compositions — somewhat more elaborate ones than the typical, straight quarter note exercise.
I came up with this for the third phrase of a chorale from the St. John Passion:

(BWV 245.3, ver. 1: http://www.bach-chorales.com/BWV0245_3.htm. Haven't looked much at what the great man himself did with it yet; leaving that for last is part of the fun.)
Now, I'm kind of wedded to the stately, descending/ascending-by-step-progression eighth note figure going on in the bass, over the last and the first half of bars two and three, respectively. Only I'm somewhat troubled by the fact that the F taken by the bass here — bass goes G to F on the fourth beat of the first full measure — happens to be the seventh of the prevailing chord (tonic, G minor), unresolved, even if I only want it to be an "escape tone". How unorthodox would this be? Say, is it liable to upset college professors everywhere, and also not find any equivalent in a catalogue of "things Bach sometimes did anyway"? (Or only the first?)
I suppose I could emphasize it as a non-harmonic tone by sharpening the F, but then there's an unresolved leading tone.
There's an underlying question here, then, of whether sevenths of chords, particularly non-dominant chords, "have" to be sevenths (with their usual requirements for downward resolution), even if you have a plan for treating them differently — as this relates to this historical style in particular.
As the line stands, I like how the figure is corroborated by sequence right afterwards — I guess that could help.
Comment: Separate from my answer below, consider altering the alto voice in the first Gm chord to be eighth notes G-F (natural). Purely an aesthetic comment; I happen to like the effect and suggest it in case you like it, too.
Comment: Yes, I can get behind that, I think. I notice at times that I quite like the effect produced in simple scale singing exercises, of juxtaposed variants of the minor scale. (Singing in "dorian" in one direction, natural minor in the other, etc.)
Comment: Could you mark or describe clearly which chord/notes in which measure are you asking about?
Answer: This is a transferred resolution. The seventh does resolve, but in a different voice — the soprano.
This is discussed in Aldwell and Schachter's "Harmony and Voice Leading" (2nd ed., 1989, pp. 385-87). They give an example from the recitative in Bach's Cantata 18, measures 7-9.
The image below shows measures 6–11. Note in measure 9 that the B♭ in the bass, the seventh, is resolved by the A in the voice.

(SOURCE: IMSLP)
The resolution occurring in a prominent (i.e., outer) voice is helpful — a point on which Aldwell and Schachter comment. They also make an important distinction:

Do not confuse the transferred resolution of the 7th with the much more frequent and simpler technique of transferring the 7th itself from one voice to another. [emphasis original]

In the specific example of the OP, it is also helped by the presence of a pattern — the descending eighth notes — that draws the ear sufficiently to mitigate the "missing" resolution.


c# web browser click on a button with a class name

Question: I need help on clicking a button with a class name.
I want to click this button bellow.
checkout now

I tried this but the button does not click.
HtmlElementCollection classButton = webBrowser1.Document.All;
            foreach (HtmlElement element in classButton)
            {
                if (element.GetAttribute("button checkout") == "button")
                {
                    element.InvokeMember("click");
                }
            }

Comment: You're probably supposed to get the `"class"` attribute
Answer: You are looking for an attribute called "button checkout" instead of class. You should probably use .Contains as well so if there are several classes then it doesn't miss them:
HtmlElementCollection classButton = webBrowser1.Document.All;
foreach (HtmlElement element in classButton)
{
    if (element.GetAttribute("class").Contains("button"))
    {
        element.InvokeMember("click");
    }
}

If you want to make sure you are finding "button" and not something like "redbutton" then change to this:
HtmlElementCollection classButton = webBrowser1.Document.All;
foreach (HtmlElement element in classButton)
{
    if (Regex.IsMatch(element.GetAttribute("class"), @"\bbutton\b"))
    {
        element.InvokeMember("click");
    }
}

You could maybe streamline using LINQ as well:
webBrowser1.Document.All.Where(
     element => element.GetAttribute("class").Contains("button"))/*OR regex in example 2*/
    .ToList().ForEach(element => element.InvokeMember("click"))


Identifying the finite symmetric groups

Question: Is there a single first-order sentence $\varphi$ in the language of groups such that for every finite $\mathfrak{A}$ we have $$\mathfrak{A}\models\varphi\quad\iff\quad\mathfrak{A}\cong S_n\mbox{ for some finite $n$}?$$
Clearly this can be done with a first-order theory in place of a single sentence: if for each $n$ we let $\varphi_n$ be the sentence asserting "Either the structure is isomorphic to $S_m$ for some $m\le n$, or the structure has $>n!$ elements," then the finite models of $\{\varphi_n:n\in\mathbb{N}\}$ are exactly the finite symmetric groups. Similarly, a single second-order sentence can do the job. However, I don't see how to do the job with a single first-order sentence.
Comment: [This paper](https://www.cambridge.org/core/journals/journal-of-the-london-mathematical-society/article/abs/finite-axiomatization-of-finite-soluble-groups/6AD1C30746B67D47ECAED9E821F32F7F) mentions near the beginning that the non-abelian simple groups are characterized amongst finite groups by a first-order sentence. Since you can remove the sporadic groups by hand, if you could show that the groups of Lie type and the alternating groups are separated by a first-order sentence (which seems plausible), then you'd have that the alternating groups can be characterized by a first-order sentence.
Comment: You might be able to then leverage this into a sentence for the symmetric groups if the alternating groups are uniformly definable in the symmetric groups. You would also need to show that there is a sentence that separates symmetric groups from other index 2 extensions of alternating groups.
Comment: @AtticusStonestrom  Unless I'm missing something you can show via Ehrenfeucht-Fraisse games that for every $n$ there is a non-cyclic finite group $G$ which is $n$-equivalent to some cyclic group; this rules out a one-sentence axiomatization. Unfortunately, cyclicity - and in particular, *guaranteeing non-cyclicity* - is simpler than symmetricitude, so I don't see how to run the analogous argument for the symmetric groups.
Comment: @JamesHanson That'd be a *delightful* application of the CFSG!
Comment: Incidentally, note that the first-order-theory argument above shows that **any class** of finite structures (in a finite language) can be pinned down (within the class of finite structures in that language) by a first-order theory. The nontrivial aspect is then the *complexity* of the theory in question, e.g. computably axiomatizable or not.
Comment: I already +1'd this question, but I wish I could +1 again for "symmetricitude"
Comment: perhaps a silly question, but can this be done for the finite cyclic groups? (+1)
Comment: @JamesHanson Looks like we'll have to wait for a necessary use of CFSG along these lines, sadly. :P
Answer: Yes. The key observation is that the symmetric groups $S_n$ (at least for $n>6$) uniformly interpret their action by permutations on the set $[n] = \{1,\dots,n\}$. The interpretation is explained in this answer by Itai Bar-Natan, but I'll repeat it here for completeness.

For $n>6$, $\sigma\in S_n$ is a transposition if and only if $\sigma$ has order $2$ and for every conjugate $\sigma' = \rho\sigma\rho^{-1}$, $\sigma\sigma'$ has order $1$, $2$, or $3$. So the set $T$ of transpositions is uniformly definable. In another answer to the same question, Noam Elkies points out that when $n=6$, $T$ is not even definable, since the outer automorphism of $S_6$ maps $T$ to the set $T_3$ of products of three disjoint transpositions.
The set $X = \{(\tau_1,\tau_2)\in T^2\mid \tau_1\neq \tau_2\text{ and }\tau_1\tau_2\text{ has order }3\}$ is also uniformly definable. Note that a pair $(\tau_1,\tau_2)$ is in $X$ if and only if $\tau_1$ and $\tau_2$ are distinct transpositions which are not disjoint, i.e., there is a unique element $k\in [n]$ such that $\tau_1$ and $\tau_2$ both move $k$. We think of the pair $(\tau_1,\tau_2)$ as identifying the element $k$.
The equivalence relation $\sim$ on $X$ given by $(\tau_1,\tau_2)\sim (\tau_1',\tau_2')$ if and only if the pairs $(\tau_1,\tau_2)$ and $(\tau_1',\tau_2')$ both identify the same element $k$ is uniformly definable by the formula asserting that for all $i,j\in \{1,2\}$, $\tau_i = \tau_j'$ or $(\tau_i,\tau_j')\in X$. Note $X/{\sim}$ is in natural bijection with $[n]$.
Finally, the induced action of $S_n$ on $X/{\sim}$ is uniformly definable by conjugation. Note that if $(\tau_1,\tau_2)\in X$ and identifies the element $k\in [n]$, say $\tau_1 = (k\, i)$ and $\tau_2 = (k\, j)$, then for any $\sigma\in S_n$, $\sigma\tau_1\sigma^{-1} = (\sigma(k)\,\sigma(i))$ and $\sigma\tau_2\sigma^{-1} = (\sigma(k)\,\sigma(j))$. So $(\sigma\tau_1\sigma^{-1},\sigma\tau_2\sigma^{-1})\in X$ and identifies the element $\sigma(k)$. It follows that this action of $S_n$ on $X$ respects the equivalence relation $\sim$.

Given all this, we can identify the symmetric groups by the following sentence: (1) $G\cong S_n$ for some $n\leq 6$, or (2) (a) the formula defining $\sim$ defines an equivalence relation on the definable set $X\subseteq G^2$ and (b) conjugation defines a group action of $G$ on $X/{\sim}$ (in particular it respects $\sim$) and (c) this action is faithful and (d) for any pair of distinct elements of $X/{\sim}$, there is an element of $G$ which transposes them and fixes the rest of the elements of $X/{\sim}$.
The finite symmetric groups certainly satisfy this sentence. And if a finite group $G$ satisfies this sentence, then the action of $G$ on $X/{\sim}$ gives a homomorphism $G\to S_{X/{\sim}}$ which is injective (because the action is faithful) and surjective (because the symmetric group on the finite set $X/{\sim}$ is generated by transpositions). So $G$ is isomorphic to $S_{X/{\sim}}$.
Comment: Lovely! I'm quite surprised by this.
Comment: @ThomasForster I see - unfortunately I know basically nothing about the complete theories of infinite symmetric groups. You're probably aware that Shelah has some papers on the topic?
Comment: wow!!! I find this truly remarkable (+1)
Comment: Wow!  Thank you!  What about infinite models of this theory?
Comment: @ThomasForster Every infinite model of this theory interprets a faithful action on an infinite set which includes all finite support permutations. But for an infinite set, there's a lot of room between the group of finite support permutations and the full symmetric group. It's not clear to me which grouos in between are models.
Comment: Alex,  I barged into this thread beco's i am interested in the various 1st-order theories of symmetric groups on infinite sets.  Apparently they come in a wide variety.  I can see that the symmetric group on an uncountable set satisfies ``every element commutes with at least one involution'' whereas this does not hold in the symm grp on a ctble set. Apparently not all symm grps on uncountble sets are elem equiv, and i would like to understand this better.  I have my own nefarious reasons for interest in this which i won't bore you with unless asked.   Somthng to do w strongly typed set theory.
Comment: Yes i am.   They are extremely scary, and also off limits (for me) beco's they concern infinite wellordered sets only, and i am interested in (for example) beth numbers without any use of AC.choice.

Identifying the finite symmetric groups


Model validation with GEE-GLM

Question: I am trying to find some resources on model validation for GEE-GLMs. Unfortunately I can't afford to purchase expensive textbooks and many of the books address GEEs using other software such as Stata.
Does anyone have good resources on the model validation process of GEE-GLMS particularly with respect to R packages that can be used?
The Zuur textbook mentions that "The graphical validation uses Pearson residuals and follows the model validation steps of GLM." O know for GLMs we use residuals vs. fitted to check for homogeneity and a Q-Q plot of residuals to check for normality, but do we assess these same things in a GEE-GLM or are the assumptions different?
I haven't found R packages yet for how I would check the homogeneity and normality of residuals, and also how to plot the predictions of a GEE-GLM. Any help with this would be much appreciated!
Answer: The Generalized Estimation Equations (GEEs) are a semi-parametric approach that does not make any particular assumption for the distribution of your outcome variable. Also, the correlation structure you assume is a working correlation that is also not assumed to be correctly specified. The sandwich estimator takes care of this. Moreover, GEEs automatically also allow for over-dispersion.
You only need to appropriately specify the mean of your data by suitably specifying the link function and allowing for some flexibility in the functional form of the covariates, e.g., consider potential nonlinear terms.
Note, however, that the simple GEEs will only provide valid inferences under the missing completely at random assumption for any missing data you may have.

Model validation with GEE-GLM


Which approach based on the LASSO yields more biologically relevant results for gene data-sets?

Question: I have a data-set with a continuous outcome variable and some confounding variables (like age, gender, ...) and many gene expressions (more than samples). The goal is to find relevant genes in association with the outcome.
Now the first idea was to use the LASSO (Tibshirani 1996). Some questions arose regarding the whole procedure.

Does one include the confounding variables in the variable selection stage and keep them in the model without regularization? I have seen that including such fixed variables changes the selected genes.
In order to only select stable genes I used the stability selection procedure (Meinshausen and Bühlmann 2010). Does one need confidence intervals in this procedure or only in the basic LASSO?
Would it also make sense to use some LASSO generalization (like group LASSO or newer ideas) to look for relevant networks/groups of genes instead of single genes? Or could one look for associated genes with the selected genes from LASSO, in order for the results to be more interpretable (e.g. clustering by correlation, nodewise regression, group LASSO with groups based on correlation...)? Can this be done on the same data-set or are new measurements needed?
Can the residuals of the LASSO model be analysed? Or does one construct an ordinary regression with the selected variables and look at that model? Or what is the procedure here?
Which other approach would you suggest?
Comment: For stability selection, you just need to know how often would each variable be selected under resampling, no CI needed. You don't even need LASSO for that, any feature selection method is allowed. I don't known answers to other questions
Comment: ah yes, stability selection has some family wise error control
Comment: that's the basically only reason why you would be using it
Answer:
Since you're only interested in the influence of the genes, you should "force keep" the non-gene variables in the model (for example in R with glmnet package and option penalty.factor equal to zero for the corresponding variables). Or you could first do a model with the confounding variables only and identify the ones that have a significant influence on the outcome and then force-keep these along with the genes in the second full model. Another approach would be to stratify your data such that you're doing different lasso models for subgroups (given that you have enough observations), e.g. which genes are chosen for females/age 18-49 compared to males/age 18-49 etc.
Confidence intervals aren't needed, as pointed out by rep_ho in the comment to the question.
You CAN use group lasso or sparse-group lasso if you have pathway/subnetwork information on the genes available. Be aware that vanilla lasso has an undesirable property: if some features are correlated, it tends to choose one of them and disregards the other ones in the remainder. This translates to group lasso but on the group level (out of some correlated groups it chooses only one group) and to sparse-group lasso as well (but here for correlations on between- and within-group levels). It depends on the original scientific question (respectively, what your outcome is) if you're more interested in specific genes or specific pathways. Additionally, stability selection is already a good idea to deal with correlated variables. Furthermore, you might want to take a look into elastic net regression, which is basically a mixture of lasso and ridge regression and has been shown to handle correlated variables better than lasso.
I'm not sure what you're referring to. I hope you're doing cross-validation, then you're actually assessing the residuals to find the best $\lambda$ value and as such the corresponding regression coefficients that best describe your outcome and avoid overfitting. You shouldn't do an additonal model with the chosen features, instead analyse the model chosen by cross-validation.
Lasso is fine. Elastic net might be worth a look. Some Support Vector Machine models (e.g. SVEN) are shown to be similar to lasso methods, and there's Bayesian alternatives to the different lasso methods as well which might be more precise than lasso ("spike-and-slab", for an overview and slow implementations based on Gibbs sampling see here, and more efficient implementations: simple spike-and-slab, grouped spike-and-slab, and sparse-group spike-and-slab). (Disclaimer: the last reference is a paper by me.)
Comment: Just to clarify for #1, if one wants to understand the effects of X variables on Y, between young and older adults, that it would be appropriate /logical to create two age-separated lasso models?


Simplex: duplicate constraints

Question: I'm trying to understand how the two-phase simplex algorithm works, this site explains it using a simple example: http://optlab.mcmaster.ca/feng/4O03/Two.Phase.Simplex.pdf
I've tried to come up with some edge cases myself, and I'm stuck on this one, what am I doing wrong?

Minimize $x$ where $x \ge 1000$ and $x \ge 1000$

Obviously this is a dumb example, but the same issue arises when some constraints are linear combinations of each other.
Phase 1
We rewrite this linear program as a system of equations, where $s_1$, $s_2$ are the surplus variables and $a_1$ and $a_2$ are the artificial variables:
$\left\{
\begin{array}{c}
x - s_1 +a_1=1000\\
x - s_2 +a_2=1000
\end{array}
\right.$
We start by minimizing $a_1 + a_2$, so maximize $p = -a_1 - a_2 = (x - s_1 - 1000) + (x - s_2 - 1000) = 2x - s_1 - s_2 - 2000$
$\iff -2x - s_1 - s_2 + p = -2000$
This gives our starting tableau:
$$
\begin{array}{c|cccccc|c}
&x&s_1&s_2&a_1&a_2&p&A\\
\hline
a_1&1&-1&0&1&0&0&1000\\
a_2&1&0&-1&0&1&0&1000\\
\hline
p&-2&1&1&0&0&1&-2000
\end{array}
$$
After pivoting around column $1$, row $1$:
$$
\begin{array}{c|cccccc|c}
&x&s_1&s_2&a_1&a_2&p&A\\
\hline
x&1&-1&0&1&0&0&1000\\
a_2&0&1&-1&-1&1&0&0\\
\hline
p&0&-1&1&2&0&1&0
\end{array}
$$
The next column to pivot around is row $2$, but there's no row that works! There isn't a positive $\frac{A}{pivot}$ ratio:
$\frac{1000}{-1} = -1000 \le 0$
$\frac{0}{1} = 0 \le 0$
It seems like every explanation of the algorithm assumes there will always be a row with a positive ratio. It looks like the algorithm got stuck, we didn't even get to Phase 2, but the program definitely has a valid solution. What went wrong?
I'm looking for an answer that works in every case, not just this trival example. Just removing one of the constraints isn't a real solution.
Answer: The salient point is that the entries of the RHS have to be non-negative. You  calculate the minimum of the fractions. Only the entries in the matrix  has to be positive. The short notation is
$\min\bigg\{\frac{b_i}{a_{ij^*}}|a_{ij^*}>0\bigg\}  $
where $b_{i}\geq 0$
In your case $\min\bigg\{\frac{b_2}{a_{22^*}}\bigg\}= \min\bigg\{\frac{0}{1}\bigg\}= 0 \quad \color{green} \checkmark $
Thus the final simlex tableau is
$$
\begin{array}{c|cccccc|c}
&x&s_1&s_2&a_1&a_2&p&RHS\\
\hline
x&1&0&-1&-1&1&0&1000\\
s_2&0&1&-1&-1&1&0&0\\
\hline
p&0&0&0&1&1&1&0
\end{array}
$$

Simplex: duplicate constraints


Problem on EU commission

Question: Consider the following problem.
A collection of $n$ countries $C_1, \dots, C_n$ sit on an EU commission. Each country $C_i$ is assigned a voting weight $c_i$. A resolution passes if it has the support of a proportion of the panel of at least $A$, taking into account voting weights. Each country $C_i$ has a probability $p_i$ of voting for the resolution, and each country acts independently of the others.
The problem is to assign the voting weights so as to maximize the probability that any given resolution will pass. I am interested in answering the question asymptotically under something like the following assumptions.

The number of countries $n$ is very large. (Perhaps the EU's $n = 28$ is already not so far from this!)
The proportion of votes held by any one country is bounded above by $M/n$, for some fixed reasonable number $M$.
$p_i > A$ for all $i$.
The probabilities $p_i$ are bounded away from $1$.

Perhaps some of these conditions can be relaxed, or perhaps additional assumptions are needed, but these are the ones that seem to be needed for my arguments below.
I have tried to answer the question in an approximate and non-rigorous way as follows.
Let $X_i$ be the random variable equal to $1$ when country $C_i$ votes for the resolution, and $0$ otherwise. Now let $V = \sum c_i X_i$. By a suitably general version of the central limit theorem (the Berry-Esseen inequality?), $V$ follows approximately a normal distribution with mean $\sum c_i p_i$ and variance $\sum c_i^2 p_i(1-p_i)$. The probability that we would like to maximize is
$$P\left( V \geq A\sum c_i \right).$$
If we let $F(z)$ be the cumulative distribution function for the standard normal distribution, this probability can be approximated by $F(z)$ where
$$z = \frac{\sum c_i(p_i - A)}{\left[\sum c_i^2 p_i (1-p_i) \right]^{1/2}}. $$
Considering the gradient of the function $z = z(c_1,\dots,c_n)$ shows that $z$ is maximal when the weights $c_i$ are proportional to the numbers
$$\gamma_i = \frac{p_i - A}{p_i(1-p_i)}.$$
I conclude that it is plausible that the weights $c_i = \gamma_i$ are close to being optimal.
My questions, in descending order of importance, are:

Has anything significant been written on this problem, or an equivalent one?
Is my "theorem" correct?
What would a rigorous formulation of the "theorem" look like?

EDIT: I've simulated the problem for $A = 0.5$ with 1867 countries with a 50.17% chance of voting in favour and 637 countries with a probability of 50.5%. I gave weight $1$ to each of the first group of countries and weight $c$ to the second. In the graph below, the horizontal axis is for $c$, and the vertical axis for the probability of passing the resolution. The blue curve represents the theoretical probability we would have if the normal approximation worked perfectly, and the red curve experimental data based on 5 million repetitions of the experiment. The maximum for the red graph is not too far from the conjectured optimal value of $\gamma = 2.94$.

EDIT: In response to a comment, here are some additional details on the maximization of $z$ above. By homogeneity, it makes no difference whether or not we constrain the $c_i$'s to have sum $1$. But if we do, then a compactness argument shows that $z$ must attain a maximum at some point.
Now return to unconstrained $c_i$'s. $\partial z/\partial c_i$ has the same sign as
$$\frac{\sum c_j^2 p_j (1 - p_j)}{\sum c_j (p_j - A)} \gamma_i - c_i.$$
This shows that where the maximum occurs, all the $c_i$'s must be proportional to $\gamma_i$.
Comment: You set all pi > A, so resolutions should pass more often than not, if not always. Consequently, the rest of the problem is nearly meaningless. I may try to come back with a reformulation of a more realistic and interesting version of the problem. And why do you want all resolutions to pass? Is A just for show, seeming to keep in line with democratic principles, but you want to circumvent it to set up a dictatorship?
Comment: Paul, I made it an EU commission because the voting weights reminded me of the Nice Treaty: http://en.wikipedia.org/wiki/Treaty_of_Nice The basic idea is one of a collection of independent deciders trying to get something "right" collectively. Perhaps passing a resolution isn't the best example. It is true that resolutions will pass "more often than not" - I don't think that makes the problem meaningless. If you look at the example I gave, there is a maximal probability of about 61% of a resolution passing. In any case, maximizing a probability that might even be 99.999999% or more (1/2)
Comment: isn't necessarily meaningless. People involved in nuclear safety are always talking about chances of one in a trillion and the like (not that I think they're necessarily immune to overconfidence). The reason I had $p_i >A$ is because if some countries had $p_i < A$, I believe it would most likely be optimal to set their weights equal to zero (at least this is so if the normal approximation is valid) and then they can simply be removed from consideration. It wouldn't hurt to include these countries in the problem, but I chose to simplify things a bit in that way. (2/2)
Comment: It took me a while, but I am now convinced your $\max F(z)$ and my $\max 1-\phi(-z)$ objectives are identical (assuming $\sum c_i=1$). Exposition could be clearer at this point. ;) But then you look at the gradient and determine the weights - how exactly? $F(z)$ is not strictly concave, so the first order approach to determine the max need not be valid. Is $z$ always strictly concave, as your graph seems to suggest? One example of mine seems to suggest that isn't always so. Then we might have a nasty case of convex optimization. Otherwise your theorem seems to be correct.
Comment: Here the example; $z$ isn't strictly concave, but at the maximum it is. http://www.wolframalpha.com/input/?i=plot+%280.52-0.5%2Bx*%280.53-0.5%29%29%2F%280.52*0.48%2Bx^2*0.53*0.47%29^%281%2F2%29+for+x%3D[0%2C5]
Comment: Nameless, I've added details on optimizing $z$ above. I don't see how $F(z)$'s concavity is significant. All that matters is that it's an increasing function. Also, I'm not getting anything meaningful with that link to Wolfram Alpha, just a straight line.
Comment: Regarding nuclear safety, politics seems to trump science. We worry about the risk or the cost of doing X. That view is the basis of expensive NEPA studies. Such studies leave out the cost of not doing X. Not doing something can be very costly. The studies become political, and the risks, costs, etc., are inflated and often only loosely attached to actual scientific studies with confirmed findings. The only reason we are having a discussion of this type is because we are affluent and can afford to do so. When a population is struggling to survive, the "nice" concerns go out the window.
Answer: This is a very interesting problem! On your theorem: I don't understand why you maximize $z$, which is just a density (up to that point everything seems fine). You want to maximize $P(V\ge A)$. You assume for sufficiently many countries that this can be approximated by a normal distribution, invoking some version of the CLT. Thus,
$$P(V\ge A)\approx \int^\infty_A \phi\left(\frac{x-\sum c_ip_i}{\sqrt{\sum c_i^2 p_i(1-p_i})}\right) dx=1-\Phi\left(\frac{A-\sum c_ip_i}{\sqrt{\sum c_i^2 p_i(1-p_i)}}\right).$$
How to maximize this? I am not entirely sure. I remember that the normal distribution is log-concave, and the CDF of log-concave functions is log-concave. So if $log(\Phi(x))$ is concave, then $-log(\Phi(x))$ is convex. But that doesn't help us here..
A few more suggestions:

On assumption 2): Why do you need $M$ if you defined weights $c_i$ already?
In your formulation, you could constrain the weights to $\sum_i c_i=1$, then the condition is $V\ge A$, looks nicer but is not necessary.
On assumption 3): I agree it doesn't make the problem meaningless, but it seems unnecessary - it doesn't change the maximization problem. It just implies that, say, even an equal voting weight distribution would lead to more passes than failures of resolutions. But the problem of $p_i<A$ for some (or even all) countries would still be interesting. Given the normal approximation, there is still a positive probability for the resolution to pass whenever $p_i>0$ for all $i$, but it would be harder. This way you could model "harder resultions".
On assumption 1) and 3): if $n\to\infty$, then assumption 3 guarantees that the resolution passes, as long as you have positive weight $c_i$ on all countries. Because the expected voteshare is above $A$, and asymptotically the expected vote share realizes with probability 1 (some strong law of large numbers). Interesting: if some countries have $p_i>A$ (a positive mass, to be exact) and some $p_i<A$, then as $n\to\infty$ you can guarantee passing of the resolution by giving positive weights to all with $p_i>A$ and none to the others.
Given the previous point, it seems dangerous to talk about "asymptotics" - you just want finitely but many countries so that you can approximate with a normal distribution, but you don't actually want $n\to\infty$ as the problem then is trivial given assumption 3). Maybe this is what the commenter above meant.
Where can you find something similar? I think your best bet might be the finance literature, where you compute the probability that your portfolio investment return is above some threshold $A$. There are some assets which have a similar structure as these votes (e.g., bonds): either the asset pays a positive dividend or the issuer goes bankrupt and the return is zero - just like your random variable $X_i$. Same for a loan portfolio.
Your comments about "getting a decision right" reminded me of the Condorcet jury theorems. The setting is a special case of yours, where every member has the same voting weight and the majority threshold is $A=1/2$
It also reminded me of the Feddersen Pesendorfer game theoretic analysis of unanimity voting rules. Neither of the two are directly related to your problem though. Again, finance seems to be your best bet.
Comment: $A$ was the *proportion* of the votes necessary for a resolution to pass, so the condition is $V \geq A \sum c_i$. I want to maximize $z$ because $F(z)$ is an increasing function, so maximizing $z$ is equivalent to maximizing $F(z)$. The reason I set this condition on $M$ was because I thought this would guarantee that some form of the central limit theorem would be applicable. If some countries have too large a share of the votes, it won't be. As for what happens when $n \to +\infty$: I am interested in maximizing the probability of the resolution passing even when this probability (1/2)
Comment: may be quite close to 1. So I don't believe the problem becomes trivial in this case. If a rigorous statement of the theorem involves some limit statement when $n \to +\infty$ rather than an inequality, that might well be acceptable. Thank you for mentioning the Condorcet jury theorem, as I think that may well be related and I hadn't heard of it. (2/2)
Answer: http://en.m.wikipedia.org/wiki/Roy's_safety-first_criterion
(About related finance problems).
trying to chose a portfolio that maximizes the probability of meeting a threshold is probably close to the problem you're mentioning here.
As for the EU, their goal when they set up the system was not too far from what you're describing. The idea was also to prevent the formation of coalitions against France and Germany (if those 2 agree on something, it's very difficult to block it, and inversely, it's very difficult to pass a law without them agreeing).
Comment: Thanks for this answer. Unfortunately, I haven't been able to find a clear statement of Roy's criterion on the internet so far, so I may have to go look at his original paper at some point.
Answer: Forgive me if this solution may appear to be too "simplistic", maybe I misunderstood something in your original question, but what I gathered is that you have to set the various votes of countries in a manner that you maximize the probability of a resolution passing.
Strangely enough for all the assumptions you mentioned, 3 of them did not matter in my solution and only number 2 had a meaning.
I did add one additional assumption though. All countries are "sorted" by decreasing probability of passing the resolution, that means:
$$ p_n \le p_{n-1} \le ... \le p_2 \le p_1$$
It should not affect generality too much, since the probability is data (from what I understand).
Let w be the relative weight of votes:
$$ w_i = {c_i \over \sum c_i}$$
It follows that:
$$ \sum w_i = 1 $$
Also let m be the bound for the proportion of votes:
$$ m = {M \over n} $$
Consider that m is less than 1 so we can write the following:
$$ {1 \over m}  = k + \eta$$
Where k is an integer and eta is a real number higher than or equal to 0 but lower than 1.
This is useful for telling how many countries can have an assigned weight of m, and, in fact we're gonna assign m to exactly the K countries with the highest probability. (the first K)
$$ w_1 = ... = w_k = m $$
Country K + 1 will get the "leftover" (note that if eta is zero, this country gets zero votes):
$$ w_{k+1} = 1 - m \cdot k $$
Everyone else gets zero votes:
$$ w_{k+2} = ... = w_n = 0 $$
Note that this values are weights, to go from weights to actual votes you simply have to multiply all weights for the same arbitrary constant.
Again, since this appears to be too "simplistic", it's very likely that I missed something in your original question or misunderstood it entirely. If that's the case, please tell me and I will deleted this answer.

Problem on EU commission


IllegalAccessException ao ler valores com reflection

Question: Não consigo ler os valores dos atributos da classe com reflection:
    ContentValues values = new ContentValues();

    Field[] fields = this.getClass().getDeclaredFields();

    for (Field field: fields ) {
        field.setAccessible(true);
        values.put(field.getName(), field.get(this.getClass()));
    }

Tenho a exceção: IllegalAccessException  no método get: field.get(this.getClass())
Também tentei field.get(this) e ainda passando a instância do objeto field.get(model)
Os atributos do objeto model não são privados. Se não usar o metodo field.setAccessible(true); a exceção é a mesma.
A pedido do amigo Ramaral, segue a classe toda:
public class GenericModel {

    public Long id;

    public ContentValues GetContentValues()
    {
        ContentValues values = new ContentValues();

        Field[] fields = this.getClass().getDeclaredFields();

        for (Field field: fields ) {
            field.setAccessible(true);

            try {
                values.put(field.getName(), field.get(this.getClass()));
            } catch (IllegalAccessException e) {

            }
        }

        return values;
    }
}

Comment: Esse código nem sequer compila.
Comment: Não manjo muito de reflection, mas acho que precisa previnir exception com try nos métodos dinâmicos, assim compila, mas não executa de acordo. Se tiver sugestão com outros métodos ou pattern
Comment: Sim tem de colocar o try/catch mas a linha `values.put(field.getName(), field.get(this.getClass()));` continuará a dar erro. Só por si `field.get(this.getClass())` não deveria dar erro. Edite a pergunta e coloque os atributos da classe.
Answer: Tem 3 coisas erradas no seu código:

O método Field#get() retorna um objecto, é necessário fazer o cast para um tipo que o ContentValues#put() aceite e esse tipo deve ser compatível com o tipo do campo em causa.
(Long)field.get(...)

Ao método Field#get() deve ser passado o objecto que contem o campo representado por este Field e cujo valor se quer obter.
(Long)field.get(this)

O campo id tem de ser inicializado.
public Long id = 3l;

Com as alterações ficará assim:
public class GenericModel {

    public Long id = 3l;

    public ContentValues GetContentValues()
    {
        ContentValues values = new ContentValues();

        Field[] fields = this.getClass().getDeclaredFields();

        for (Field field: fields ) {
            field.setAccessible(true);

            try {
                values.put(field.getName(), (Long)field.get(this));
            } catch (IllegalAccessException e) {
                //Faça algo aqui, nem que seja apenas um log
            }
        }

        return values;
    }
}

Nota:
Se GenericModel tiver mais campos e estes não sejam todos do tipo Long terá de alterar o método GetContentValues() para lidar com essa situação.
Comment: Obrigado pelo empenho e auxilio. Parece funcionar.
Tive que fazer o switch no Type do Field.


Family hitting r-sets

Question: I'll start with a definition.
We say a family $\mathcal{F}\subseteq [n]^{(k)}$ hits every $r$-set for some $r\geq k$ if for each $R\in[n]^{(r)}$, there exists $F\in \mathcal{F}$ such that $F\subseteq R$.
First of all, I am tasked with finding the smallest family of 2-sets which hits all 3-sets in $[7]^{(3)}$.  I've found such a family of size 9, but how do I know it is the smallest?  If it is not the smallest, how do I find the smallest?  I assume it has to do with Turan's theorem, but I'm not sure I understand that well enough.
The method I used was using a greedy algorithm, but I don't think that always gives you the smallest such family.
Answer: You are right about the connection to Turán's theorem.  It might help to consider the problem in a complementary form.
Suppose you have a family of $2$-sets that hits every $r$-set, and consider the complement of your family - that is, the collection of $2$-sets (which we may think of as a graph) that are not in your family.
Given any $r$-set $R$, we know that your family hits it, so there is some $2$-set in your family that is contained in $R$.  That means that $R^{(2)}$ is not contained within the complementary graph.  In other words, the complementary graph does not contain $K_r$.
Since you want the smallest possible hitting family, the complement should be as large as possible.  Hence the complement should be the largest $K_r$-free graph, which is the $(r-1)$-partite Turán graph.
For your particular parameters, the largest $K_3$-free graph on $7$ vertices is $K_{3,4}$, which has $12$ edges.  Hence the smallest hitting family will have size $\binom{7}{2} - 12 = 21 - 12 = 9$, matching your result (it should be a vertex disjoint union of $K_3$ and $K_4$).  Turán's, or indeed Mantel's, Theorem shows that you cannot do better.

Family hitting r-sets


Vuejs com VueTable2

Question: Estou tentando utilizar o VueTable-2 enviando as informações via a props data. Procurei em diversos sites, testei e nada funcionou, inclusive achei este exemplo no formato que preciso, mas também não funciona. O código mais básico, seria o código abaixo, alguém por acaso sabe o porquê disto não funcionar? Ou a maneira correta.
Coloquei para exibir na tela o objeto de teste que a tabela deveria renderizar.

Obs.: Com o tipo de api-mode igual a true funciona perfeitamente, o que preciso, é que funcione com api-mode igual a false.

Vue.use(Vuetable);
new Vue({
  el: '#app',
  data: {
    tableColumns: ['id', 'name'],
    itens: [
        { id: 1, name: "Jogos Vorazes" },
        { id: 2, name: "Todo mundo em Pânico" }
    ],
  }
})
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

Vuejs com VueTable-2

  <vuetable ref="vuetable"
       :api-mode="false"
       :fields="tableColumns"
       :data="itens">
  </vuetable>

{{ itens }}

Editado:
O projeto VueTable-2 na versão 1.6.3 foi marcado como contendo um bug. O link da abertura no Git do issue. Aguardando a correção para fechar o tópico.

Editado (corrigido):

O bug foi corrigido na versão v1.6.5.
  Observação, para quem utilizar a versão 1.6.3 estará com este bug
Comment: Dá-me ideia que esse projeto não está a funcionar bem. Estive a testar e ler a documentação e nada de pôr a funcionar. As tuas props estão consoante a documentação. Parece o mesmo problema que este: https://github.com/ratiw/vuetable-2/issues/176
Comment: @Sergio, o autor do VueTable marcou como Bug. Agora é só aguardar. Obrigado.
Comment: Boa! Pois também me pareceu. Mas há outras vue-table, na volta encontras um projeto mais estável.
Answer:
O bug foi corrigido na versão v1.6.5.
  Observação, para quem utilizar a versão 1.6.3 estará com este bug

Vuejs com VueTable2


How to open the console of a container as a non-root user in LXD 2.0

Question: I'm new to container things and fiddling with LXD-2.0 on an ubuntu-16.04 host with a Alpine3.4 container. Questions:

How to open the console of the container with a non-root user?

<code>lxc exec mycontainer bash
</code>
This land me directly in the container as root. However I want to be a non-root user in the first place when I open the console.

Is it a best practice to run applications as a non-root user inside the container, just as we normally do in a non-container environment? (even the container is launched in "unprivileged" mode).
Answer:
The exec will execute the command as root. But of course since as root you can "login" as any user via the su command, you could exec a su:

lxc exec mycontainer su - mortaluser

Another way could be to install sshd and use the ssh command to log in on the container, as you would any other server.

It's indeed good practice to treat the container as a normal server and only elevate your rights when needed via for instance 'sudo'.


snmp: getting the short interface name instead of long ifDescr (again)

Question: I'm using cricket to do some simple monitoring (including network devices) of my Debian-based servers.
The interfaces are identified by name (e.g. eth0, eth1,...), and cricket maps these names to the proper OIDs by looking them up in IF-MIB::ifDescr:
$ snmpwalk -Os -c public -v 1 wheezy 126.96.36.199.22.214.171.124.1.2
iso.22.214.171.124.184.108.40.206.2.1 = STRING: "lo"
iso.188.8.131.52.188.8.131.52.2.2 = STRING: "eth0"
iso.18.104.22.168.22.214.171.124.2.3 = STRING: "eth1"

Everything worked cool until I upgraded my machine to Debian/jessie today.
Now the reported interface names are a long description of the brand:
$ snmpwalk -Os -c public -v 1 jessie 184.108.40.206.184.108.40.206.1.2
iso.220.127.116.11.188.8.131.52.2.1 = STRING: "lo"
iso.126.96.36.199.184.108.40.206.2.2 = STRING: "Intel Corporation 82576 Gigabit Network Connection"
iso.220.127.116.11.188.8.131.52.2.3 = STRING: "Intel Corporation 82576 Gigabit Network Connection"

While I find the long name annoying enough, it becomes useless as it is no longer unique: since the machine in question has two identical network cards built in, I just get the same name twice.
Is there a way to make snmpd report the short interface names?
Answer: It seems that using IF-MIB::ifDescr for the interface name is simply wrong.
As the name of the OID implies, this is meant to be a (verbose) description ofthe interface, rather than a (unique) name.
The proper OID to use is IF-MIB::ifName
$ snmpwalk -Os -c public -v 1 wheezy 184.108.40.206.184.108.40.206.1.1.1
iso.188.8.131.52.18.104.22.168.1.1.1 = STRING: "lo"
iso.22.214.171.124.184.108.40.206.1.1.2 = STRING: "eth0"
iso.188.8.131.52.220.127.116.11.1.1.3 = STRING: "eth1"

$ snmpwalk -Os -c public -v 1 jessie 188.8.131.52.188.8.131.52.1.1.1
iso.18.104.22.168.220.127.116.11.1.1.1 = STRING: "lo"
iso.18.104.22.168.220.127.116.11.1.1.2 = STRING: "eth0"
iso.18.104.22.168.126.96.36.199.1.1.3 = STRING: "eth1"

In the case of cricket this means that i changed the cricket-configuration of the interface-map to:
OID    ifName                 184.108.40.206.188.8.131.52.1.1.1

map interface-name
    base-oid    =   ifName
    match       =   %interface-name%


Como listar dados do mysqli exibindo em DESC mas listando de cima pra baixo?

Question: Vou tentar explicar melhor, tipo assim, ao listar algo do banco com id DESC mostra algo assim:
id:1
id:2
id:3
id:4
id:5

mas eu quero que seja exibido assim:
id:5
id:4
id:3
id:2
id:1

Nesse caso usar ORDER BY id ASC não vai me ajudar porque preciso listar varios dados e com isso, os ultimos id's não vão aparecer caso eu dê um LIMIT!.
Para quem quiser ver um pedaço do codigo:
public function quadroAlunos($id){
    $this->Query = $this->Conexao->prepare("SELECT * FROM quadroAlun ORDER BY ? DESC");
    $this->Query->bind_param("s",$id);
    $this->Query->execute();
    $this->ResultadoUser = $this->Query->get_result();
    while($this->Listar = $this->ResultadoUser->fetch_assoc()):

    echo "".$this->Listar["nick"].":"; //Recupera nick
    echo "".$this->Listar["mensagem"].""; //Recupera Mensagem
    echo "".$this->Listar["data"].""; //Recupera hora da postagem
    echo "

"; //Quebra de linhas

    endwhile;
}

Comment: Estão de baixo pra cima pq esse order aí está completamente sem sentido. Você tem que por o nome da coluna no order, e não passar um valor pra ela. Esse binding aí não funciona como você está imaginando. Ponha ORDER BY id DESC que funciona (e tire esse binding daí, que não está te ajudando em nada).
Comment: Tem um problema no seu código, você está passando um valor onde deveria ser um nome de coluna. Com essa ? aí não vai funcionar nunca o ORDER. Você está ordenando com um valor fixo. (o ID passado será sempre o mesmo)
Comment: Se precisar mudar a coluna que está ordenando, precisa fazer com strings `"SELECT * FROM quadroAlun ORDER BY $coluna"` - mas tem que tomar cuidado pra não permitir injeção de SQL em $coluna. Ai poderia chamar `quadroAlunos('nome')`, por exemplo, se quiser por nome, e `quadroAlunos('id DESC')` por id e invertido. Mas antes de complicar, termine de fazer funcionar por ID direitinho, pra não fazer confusão.
Comment: Seria bom [edit] a pergunta e por o trecho relevante do código para analisarmos. Explique o resultado que quer obter, que fica mais fácil. E com DESC o resultado não pode ser o que você afirmou, tem coisa errada aí.
Comment: Pronto, editei!
Comment: Tipo assim, os dados estão sendo listados de baixo pra cima, sendo que os de baixo são os ultimos id's e os de cima os primeiros id's, esta listando tipo um chat, o chat você sabe que lista as ultimas mensagens de baixo pra cima, sendo as de baixo as novas mensagens e as de cima as antigas entendeu ? eu quero inverter isso
Comment: deu certo mesmo, vlw, teve uma vez que precisei que listasse igual esta listando agora e não consegui kkkk
Answer: Assim como o Bacco já te explicou, você está utilizando o bind_param de maneira incorreta. Esse método passa uma variável para o comando SQL previamente definido. Se você "printar" tua query com método debugDumpParams, verá que sua query está sendo montada incorretamente, exemplo:
SELECT * FROM quadroAlun ORDER BY 1 DESC

Note que deveria ser ORDER BY id DESC, porém como você está passando o valor da variável $id via bind_param, ela foi substituída no comando SQL.
Se esse seu método quadroAlunos for apenas para lisar TODOS os alunos, o parâmetro id declarado na função é inútil e não tem serventia alguma. Aconselho a revisar o que está tentando implementar.
Dessa forma, seu código ficará algo como:
$this->Query = $this->Conexao->prepare("SELECT * FROM quadroAlun ORDER BY id DESC");
$this->Query->execute();
$this->ResultadoUser = $this->Query->get_result();


How can a 10GB VirutalBox file system store 11GB of data?

Question: I'm really confused by this. To do some experiments with GlusterFS I created two virtual machines with VirtualBox, running Ubuntu 12.04, each with 10GB of storage. I wrote a script that created lots of little files in lots of folders. Each file was 100k of random data generated by:
dd if=/dev/zero of=#{name} bs=1 count=0 seek=100K

When copying the files from one machine to the other, the recipient run out of space. Which should have been impossible, since they are both the same size and I didn't store anything in them. Trying to figure out what was wrong I found a really confusing situation. This is all on the source machine.
According to df, I'm only using 26% of the space:
root@revisionist:~# df -h
Filesystem                    Size  Used Avail Use% Mounted on
/dev/mapper/revisionist-root  9.2G  2.3G  6.5G  26% /
udev                          237M  4.0K  237M   1% /dev
tmpfs                          50M  292K   49M   1% /run
none                          5.0M     0  5.0M   0% /run/lock
none                          246M     0  246M   0% /run/shm
/dev/sda1                     228M   48M  169M  22% /boot

according to du, the whole structure of files I created takes 772M:
root@revisionist:~# du -h files/
...
4.0K    files/3x/ey/hs
8.0K    files/3x/ey
508K    files/3x
772M    files/

which is clearly wrong, as just that folder contains a single 100K file:
root@revisionist:~# ls -lh files/3x/ey/hs
total 0
-rw-r--r-- 1 root root 100K May 19 11:30 3xeyhst4lnkzg5abzeasiw.txt

If I target that directory and file with du, the data is clearly wrong:
root@revisionist:~# du -h files/3x/ey/hs/
4.0K    files/3x/ey/hs/
root@revisionist:~# du -h files/3x/ey/hs/3xeyhst4lnkzg5abzeasiw.txt
0   files/3x/ey/hs/3xeyhst4lnkzg5abzeasiw.txt

This led me to find the option --apparent-size which is documented as:

--apparent-size
print  apparent sizes, rather than disk usage; although the apparent size is usually smaller, it may be larger due to holes in (`sparse') files, internal fragmentation, indirect blocks, and the like

and indeed this looks better:
root@revisionist:~# du -h --apparent-size files/3x/ey/hs/3xeyhst4lnkzg5abzeasiw.txt
100K    files/3x/ey/hs/3xeyhst4lnkzg5abzeasiw.txt
root@revisionist:~# du -h --apparent-size files/3x/ey/hs
104K    files/3x/ey/hs

but when I run it for the whole structure I end up with a surprising result:
root@revisionist:~# du -h --apparent-size files
...
104K    files/3x/ey/hs
108K    files/3x/ey
6.8M    files/3x
11G files

How can it be 11G? What's going on? Just rounding up? but then why does it fail to fit on the other machine?
Comment: Have you taken into account hard links?
Answer: If you're looking for the total size of the directory, you should use -s.
See what du -sh files gives you?
Also, how exactly did you create the files, and do they really have content?  The differences between the reported sizes might mean the files are sparse.
Comment: @J.PabloFernández Right, so those files you created are all [sparse](http://en.wikipedia.org/wiki/Sparse_file), due to `count=0` and `seek=100K`. There's no data in the files; you're not actually reading any input data from `/dev/zero` to be written to the file.  The total apparent size of your directory tree will be the apparent size of all of the sparse files plus the real size of the directories they're in (this is where that extra gig comes from), while the real size on disk of the tree is just the directories; no real space is being used by the files.
Comment: @J.PabloFernández Changing to `/dev/random` alone won't change the results, as you'll need a non-zero `count` for any data to be read or written - keep that in mind!  Also, your `files` directory is massive - by any chance was the script previously dumping all the files in the same directory?  That'll never shrink, delete and re-create it to get that size back down.
Comment: This is how I created each file: dd if=/dev/zero of=#{name} bs=1 count=0 seek=100K
Comment: Ah... right... I was going to use /dev/random and I forgot to change it. Thanks Shane.


Show that $\mathbb R^3$ is the direct sum of two of its subspaces

Question: Let $U$ and $V$ be finite dimensional subspaces of $\mathbb R^3$ such that $\dim (U)=1$ and
$\dim (V)=2$. Want to show that $\mathbb R^3$ is the direct sum of $U$ and $V$.
How can we show that $\dim(U \cap V)=0$?
Answer: You can't because it doesn't have to be true. Suppose that
$$U=\{(x,0,0)\,|\,x\in\mathbb{R}\}$$and that$$W=\{(x,y,0)\,|\,x,y\in\mathbb{R}\}.$$
Comment: so can it be true if $U$ is not a subset of $W$ ?
Comment: @Karen If $\dim U=1$ and $\dim W=2$, then $\dim(U\cap W)=0$ if and only if $U\varsubsetneq W$.


Installing new module

Question: I have downloaded and installed Drupal 8. The first thing I need to ensure when I create articles URL is automatically generated. In Wordpress this comes by default. But it appears not the case for Drupal.
I searched and found Pathauto (https://www.drupal.org/project/pathauto) will do what I want but facing difficult installing it. The page https://www.fastcomet.com/tutorials/drupal8/module-installation shows a tab List with button +Install New Module but on my system when I visit http://localhost/admin/modules I don't see the tab List or +Install New Module.
What could I be missing?
Answer: If you don't have this button, try to enable the module Update manager.
Maybe this makes the button show .. What backend theme are you using ?
Here's the path to the module installation page: http://localhost/admin/modules/install
Comment: :D installing **Update Manager** didn't work but using /admin/modules/install worked. Thanks.
Answer: Pathauto will do what you want. Download the module to /modules, and upload it to your server (FTP or via git).
Note that fastcomet.com is not the official docs.
Here are the official docs. https://www.drupal.org/docs/8/extending-drupal/installing-contributed-modules
The docs say you must have Update Manager installed to see the link. I personally do not do that - but to each his own.
Comment: Installing **Update Manager** didn't resolve. But I followed advice from @rémy to use /admin/modules/install and it worked.
Answer: Go to admin/reports/updates install bootstap theme. Install and set to default. This should enable both the install theme button and the install module button. You can then revert to the Bartik theme or any other theme.

Installing new module


Mac: Rails not working!

Question: When I run the command rails -v the output is: -bash: /usr/bin/rails: /System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/bin/ruby: bad interpreter: No such file or directory I've tried everything. I really need help on this. I'm using Ruby 1.8.7 and I don't have any gems installed.
Comment: can you show us your gem list? `gem list --local` and please your ruby version `ruby -v` which rails are you using? I think rails 3? show us this too `which rails`
Comment: How did you install rails? What do you get when you run `which rails`?
Comment: I get /usr/bin/rails. I had it installed perfectly but I guess something I did broke it. It came with Developers Tools.
Answer: Standard answer:

First thing you should do if you want
  to work with Ruby/Rails -- install RVM

http://rvm.io/
Comment: We can help you to install it :) This is great tool to work with rubies and gems
Comment: I voted this up. even though it is not the answer it is still needed :)
Comment: THis is not a straight answer, but it is a __fundamental answer__ :)
Comment: Although it is a useful tool, it's far easier to stick with the system version of ruby (1.8.7 I believe) to begin with. They can always grab 1.9.2 via RVM later on. Also, this does not answer the question.
Comment: Ok what do I type into terminal
Comment: @robinjam, actually your answer isn't answer too :) Our answers looks more like comments. My apologies to topic author :)
Comment: 1. Install [git](http://git-scm.com/download), 2. run this in Terminal `bash < <( curl http://rvm.beginrescueend.com/releases/rvm-install-head )`
Comment: @robinjam, with rails 3 you can better use 1.9.2 as i had a lot of problems with 1.8.7 + without rvm
Comment: If RVM is installed open in your text editor (or create) file `~/.bash_profile` and add this at the bottom `[[ -s "$HOME/.rvm/scripts/rvm" ]] && . "$HOME/.rvm/scripts/rvm"  # Load RVM into a shell session *as a function*`
Comment: now you can install Ruby 1.8.7 (I prefer Ruby Enterprise Edition {REE}): `rvm install ree`
Comment: Or even 1.9.2. 1.8.7 is the version included with OS X - the version you told him not to use...
Comment: @robinjam I told that? @jmeyer10 with what? What  have you done already?
Comment: I installed everything so now what do I do? Do I try installing rails again?
Comment: He has got problems with entire stack: Ruby, RubyGems. So let's just simplify that job
Comment: Set `rvm --default ree` and then `gem install rails`
Comment: OK I'll try that. It is still installing.
Comment: I think its hanging on: ree-1.8.7-2011.03 - #installing
Comment: thats all. After that you can instal any version you want: `rvm install 1.9.2` for example. then you can switch to each version: `rvm use ree`, `rvm use 1.9.2`. But remember. Each version needs its own gem package. So you will need to install Rails and other gems for each version of Ruby
Comment: you can. what will return: `gem -v`
Comment: Ill be right back in like 7 hours. it's about 3 a.m. in Moscow :)
Comment: It's probably not hanging - it takes a long time to compile ruby, you know.
Comment: installing rails almost worked this time error: ERROR:  While generating documentation for builder-2.1.2
... MESSAGE:   Unhandled special: Special: type=17, text=""
... RDOC args: --ri --op /usr/local/lib/ruby/gems/1.8/doc/builder-2.1.2/ri --title Builder -- Easy XML Building --main README --line-numbers lib CHANGES Rakefile README doc/releases/builder-1.2.4.rdoc doc/releases/builder-2.0.0.rdoc doc/releases/builder-2.1.1.rdoc --title builder-2.1.2 Documentation --quiet
Comment: lets take this into the chat. There is now 30 coments
Comment: `gem install rails --no-ri --no-rdoc`
Answer: "...and I don't have any gems installed."
Rails is a gem. Have you tried sudo gem install rails?
Comment: Try `sudo gem update --system` first to grab the latest version of rubygems. Then do `sudo gem install rails` afterwards to grab the latest version of rails, which is currently 3.0.6. Then try `which rails` and post the output. Also, stop deleting your comments! It's hard to keep up!
Comment: Rubygems can be quite slow. Leave it to do its work, don't Ctrl-C out.
Comment: Thank you. I tried that but I get this error:WARNING:  Invalid .gemspec format in '/usr/local/lib/ruby/gems/1.8/specifications/rubygems-update-1.6.1.gemspec'
Comment: ERROR:  While executing gem ... (Gem::RemoteSourceException)
    HTTP Response 302 fetching http://gems.rubyforge.org/yaml
Comment: Rubygems didn't update then. This is really strange - ruby sort of 'just works' on my computer.

Mac: Rails not working!


Overriding HTTP client config while declaring routes

Question: I have a web application from which I'm calling around 50-60 rest/soap apis. For this, I've created routes in JAVA DSL. Now, to have default application level timeout settings, I've done configuration like this-
public class DefaultHttpClientConfig implements HttpClientConfigurer {   // http4
    @Override
    public void configureHttpClient(HttpClientBuilder clientBuilder) {
            clientBuilder.setDefaultRequestConfig(
                            RequestConfig.custom()
                                    .setConnectTimeout(1000)
                                    .setSocketTimeout(1000).build());
    }
}

and I've set this in camel context like this-
    static CamelContext ctx = new DefaultCamelContext();

    static {
            try {
                    HttpComponent httpComponent = ctx.getComponent("http4", HttpComponent.class);
                    httpComponent.setConnectionTimeToLive(10);
                    httpComponent.setHttpClientConfigurer(new DefaultHttpClientConfig());
                    ctx.addRoutes(new DirectRestRouteBuilder());
                    ctx.start();
            } catch (Exception e) {
                    e.printStackTrace();
            }
    }

Now when creating individual routes, I want to override these configuration, so I'm trying this as shown below-
from("direct:success")
       .to("http4://localhost:8089/mockcarrier/success?httpClient.socketTimeout=8000");

However, it seems that the direct configuration in JAVA DSL is not picked up. Where am I going wrong?
Answer: Add DefaultHttpClientConfig to the Camel registry and set it on the route with the httpClientConfigurer parameter (Camel documentation).
Like this:
.to("http4://localhost:8089/mockcarrier/success?httpClientConfigurer=yourCustomConfigurerNameInTheRegistry");


Marking emails with DKIM - safe?

Question: Im running an email server as part of a research study. We have subjects connecting and sending email from a variety of clients.
One function of this server is to communicate with said subjects - this means sending out regular emails. In the last few weeks it seems that nearly all of these emails are being marked as spam by the big providers (gmail, hotmail, yahoo, etc). As a result I'm looking into how to mark these messages as safe.
One suggestion that comes up from searching is to use DKIM. I can set this up and try it but it certainly won't be in place for all of our existing clients. If I implement it will it block all emails from our server that aren't setup to use it?
FWIW: Postfix, CentOS 6.4 x64
Answer: You can configure DKIM and only sign a subset of your messages. This probably won't help solve your actual problem though.
There is no completely reliable method to ensure your messages are not marked as spam. Every provider has different detection and filtering mechanisms.
There are several things you can do to reduce the chance that your messages will be marked as spam.

Messages should be properly formed. This means that all necessary headers are present and that none of those headers are malformed or contain invalid data.
Systems sending mail should have rDNS configured for the sending IP address.
Properly configured SPF records should be maintained for your domains.
Sign messages with DKIM.
Handle abuse complaints promptly.
Proactively monitor RBLs and resolve any listing issues.
Sanity check destination addresses before sending messages. Prune mailing lists of e-mail addresses that consistently bounce.
Don't actually send unsolicited e-mail. This really could be a separate discussion entirely. Require confirmation of subscription requests. Provide a link to easily unsubscribe within your bulk messages.
Comment: None of these emails are from subscriptions or unsolicited. It's all communications from the study that these people are part of.
Comment: @ethrbunny I wasn't trying to imply that you were sending unsolicited mail. I was simply rounding out the list for the benefit of anyone that comes across this question in the future.
Comment: Absolutely! I appreciate the comprehensive list. I'm just trying to think of what rules I'm breaking.
Comment: @ethrbunny Missing/Incorrect SPF and rDNS are the two most common issues. There are many web-based tools that can check your sending IP address against the most popular RBLs as well.
Answer: If a mail server doesn't support DKIM then it will simply be ignored.

Marking emails with DKIM - safe?


Show that if $C$ is a vertical line segment $c≤y≤d$ and if $F$ is a function of 2 variable defined on $C$ then $∫_CF(x,y) dx=0$

Question: Show that if $C$ is a vertical line segment $c≤y≤d$ and if $F$ is a function of 2 variable defined on $C$ then
$∫_CF(x,y)  dx=0$
I understand that I need to use the definition of line integral to show this is true. When I draw it out I can see that this is a vertical line, so I can't do any projection to the plan parameterized by $f(x,y)$, so the area should be zero. However, I don't know how to use the definition
$$\int_C f(x,y)dx =\int_a^bF(x(t),y(t))||((x'(t),y'(t)) ||$$
to show it formally.
Answer: You need to change from the ds integral to the dx integral. (I'm not exactly sure what tools you're allowed to use in your course, or what your definitions are, so it's hard for me to be more specific.) Then, based on your parametrization, you'll be able to see that a change in s results in no change in x (because x is constant on the curve C), so the dx integral will just be 0.
Comment: From my understanding , if $C$ is just a normal graph, then I can project $C$ onto the plane that parameterized by $f(x,y)$, so i will have a curvy wall, which I can divide into many rectangle with the heigth is the the change in $y$ or I can say $dy$ and the base is the change in $x$ or $dx$, and the line integral is just the sum of area of all these rectangle. In this case since $x$ doesn't change $dx=0$ so the base of the rectangle is zero, thus its area is zero, hence the sum of areas of all these rectangles also zero. Am I correct?


ERROR: npm ERR! code EOVERRIDE npm ERR! Override for axios@^1.2.0 conflicts with direct dependency

Question: I have built an Azure chatbot that works fine in Bot Emulator locally but fails when I upload it to Azure. I get the following error:
npm ERR! code EOVERRIDE
npm ERR! Override for axios@^1.2.0 conflicts with direct dependency
I'm not entirely sure what this means. Does anyone know how to get around this?
I have tried to update the Axios package in both package-lock and package json files and nothing has worked
Comment: Does this answer your question? [Override for react-error-overlay@^6.0.9 conflicts with direct dependency](https://stackoverflow.com/questions/74734456/override-for-react-error-overlay6-0-9-conflicts-with-direct-dependency)
Answer: This error is due to the impact of packages in npm library related to axios package. We need to override the package manually using the below code block.
<code>npm install axios-method-override

import axiosMethodOverride from 'axios-method-override';

axiosMethodOverride(axios);

const instance = axios.create();
axiosMethodOverride(instance);
</code>
we need to use override patch of HTTP, PUT, DELETE in this implementation.


Show that the geometric images of any complex number defined by $cis \theta$ belong to a circumference of radius 1

Question:
Show that the geometric images of any complex number defined by $cis
 \theta$ belong to the circumference centered at the origin with radius
  1.

My book states that this is proven because $|cis \theta|= 1$ . I tried:
$$|cis \theta| = \sqrt{\cos^2\theta+\sin^2\theta\cdot i^2} = \sqrt{\cos^2\theta-\sin^2\theta} = \sqrt{(\cos(2\theta)} = ??$$
What do I do next?
Comment: You got the modulus wrong, $|x+iy| = \sqrt{x^2 \color{red}{+} y^2}\,$.
Comment: @dxiv Alright, thanks.
Answer: The modulus or norm of any complex number $z = a + bi$, $a, b \in \Bbb R$, is given by
$\vert z \vert = \sqrt{a^2 + b^2}; \tag{1}$
using the identity
$x^2 - y^2 = (x + y)(x - y), \tag{2}$
which holds in any field (actually, in any commutative ring), and taking $x = a$, $y = bi$, and recalling that $i^2 = -1$, we find
$a^2 + b^2 = a^2 - (-b^2) = a^2 - (ib)^2 =$
$(a + ib)(a - ib) = z \bar z;  \tag{3}$
this may also be written
$\vert z \vert ^2 = z \bar z.  \tag{4}$
We apply the formula (4) to $cis \theta$:
$cis \theta = \cos \theta + i \sin \theta, \tag{5}$
whence
$\vert cis \theta \vert^2 = cis \theta \overline{cis \theta}= (\cos \theta + i \sin \theta)(\cos \theta - i \sin \theta) = \cos^2 \theta + \sin^2 \theta = 1, \tag{6}$
from which
$\vert cis \theta \vert= 1 \tag{7}$
readily follows.
Answer: First of all, for a complex number;   $$z = x + iy = r(cos\theta + i sin\theta) = r(cis\theta)$$     $$|z| = (\sqrt {x^2 + y^2})= r $$
Now, as your question refers 'geometric images', let me introduce you to the complex plane(2-d for now) also known as the Argand plane, wherein you can imagine the complex number to be plotted just like an implicit function, the only difference being that 'x' in the complex number refers to the x axis and the value with 'iota' i.e. 'y' refers to the y-axis.
Now, the question comes-- Why represent it as $|cis(\theta)| $?
The answer is very simple. If you know a little of vectors and straight lines I suggest you understand this very carefully :-
For the complex number represented as z, |z| is it's distance from the origin.
Simply, from origin, the distance of point (x,y) would be -- $(\sqrt {(x-0)^2 + (y-0)^2}) = (\sqrt {x^2 + y^2})$
which actually is the modulus of the complex number and is also represented as '$r$'. Take a look at this image here.
Now, having this knowledge, coming back to your question; we are given $$|cis\theta| = 1$$
Hence by "things" we have -- modulus i.e. distance from origin of the complex number to be one. God, make it easy...
$$|cis\theta| = 1 \implies r=1 \implies \sqrt{x^2+y^2} = 1 \implies x^2+y^2 =1$$
and voila it's the equation of a circle having it's center at origin and radius as 1.
It can also be looked at geometrically-intuitively (sort of) , as what would you call a variable point that has distance from the center (origin in this case) as  1 units. I suggest you look at the image again . See when we say $cis\theta$ wwe mean the point represented by $cos\theta+sin\theta$. Here modulus is defined as one.
So, when $\theta$ is variable we have a point that traces the locus of a circle (as is represented in the image) whose modulus is one (i.e. the radius).
Also, make a point of visiting WIKI page (Stack exchange doesn't allow me to ppost more than two links :! ).


How to obtain the inverse of the F cumulative distribution based on the F cumulative distribution?

Question: I am currently implementing a application that needs to obtain the inverse of the F (Fisher-Snedecor) cumulative distribution.
I already have a library that contains the F distribution and I can easily obtain the cumulative distribution based on a confidence interval and degrees of freedom.
How can I easly adapt this library to return the INVERSE of the F cumulative distribution?
Comment: Can this library find values of inverse CDFs for beta distributions?  Or can it find values of CDFs for binomial distributions?
Comment: Yes, I've just checked and It can be done for Beta and Binomial distributions.
Comment: Are you familiar with the bisection method?  Could this help you?
Comment: Not really. I solved the problem using the CDF of Beta. I found a simple implementation of the Inverse CDF of Beta through the regular CDF of Beta and, with the formula below, I obtained the Inverse CDF of F.
Comment: #jonas, it would useful if you coul share the simple implementation of the inverse of the CDF of the Beta
Answer: Let $B$ be the inverse CDF of a Beta$(n/2,m/2)$ distribution.  The inverse CDF of an $F(m,n)$ distribution evaluated at $\alpha$ equals
$$\frac{n}{m}\left(\frac{1}{B(1-\alpha)}-1\right).$$

This graphic plots the inverse CDF of an $F(2,3)$ distribution and the graph of the preceding expression.  The curves coincide.
Source: Johnson & Kotz, Continuous Univariate Distributions--2 (1970), chapter 26.2.
Comment: Although I have a Beta function, I don't have its inverse. So I'm stuck on the same problem again. Apparently this library I'm using has a lot of distribution functions, but none of their inverse CDF.
Comment: Apparently, the only inverse available is the Inverse-Gamma.
Comment: Then you will need to find your inverse CDFs by root finding.  Newton's method should work well.
Answer: It is also possible to just pick out the F-value using the F cumulative distribution function. The idea is the following:

Define an initial interval  where the F-value should be, e.g. [0 1000]
Subdivide the interval in smaller intervals, e.g. [0 100], (100 200],...,(900 1000]
Calculate for each interval boundary the corresponding p-values.

[fcdf(0) fcdf(100)], (fcdf(100) fcdf(200)],...,(fcdf(900) fcdf(1000)]
Check which of these intervals contains the input p-value

Then take only the interval containing the input p-value and subdivide again, e.g.
[0 10], (10 20], ...,(90 100]
Repeat the steps 1) to 4) until the required precision is reached.

The intervals should look like this in order to converge fast:
<code>[0 100], (100 200],...,(900 1000]
[0 10], (10 20], ...,(90 100]
[0 1], (1 2], ...,(9 10]
[0 0.1], (0.1 0.2], ...,(0.9 1.0]
[0 0.01], (0.01 0.02], ...,(0.09 0.1]
etc.
</code>
Here is an example Matlab code:
<code>function FValue = GetFcorrespondingToP(PValue, DFNumerator, ...
    DFDenominator, Precision)

PrevFValue = 0;
NextFValue = 1000;
PrevPValue = fcdf(PrevFValue, DFNumerator, DFDenominator);
NextPValue = fcdf(NextFValue, DFNumerator, DFDenominator);
CurrPrecision = 100;
PreviousStep = 100.0;

% Security: Check if the p-value is in the interval.
if(PValue <= NextPValue && PValue >= PrevPValue)

while CurrPrecision > Precision

    % Create vector with the calculation steps.
    StepVector = PrevFValue:PreviousStep:NextFValue;
    NumSteps = length(StepVector);

    % Search for the interval containing the required p-value.
    for i = 1:NumSteps-1

        PrevPValue = fcdf(StepVector(i), DFNumerator, DFDenominator);
        NextPValue = fcdf(StepVector(i+1), DFNumerator, DFDenominator);
        if(PrevPValue <= PValue && NextPValue >= PValue)

            PrevFValue = StepVector(i);
            NextFValue = StepVector(i+1);
            break;

        end

    end

    % Set the new step and the new precision.
    CurrPrecision = CurrPrecision / 10.0;
    PreviousStep = PreviousStep / 10.0;

end

FValue = (PrevFValue + NextFValue) / 2.0;

% In the case that the wanted F-value is outside the interval [0 1000] the
% output is set to 1000. This could happen if the input p-value is e.g. 1.
else

    FValue = NextFValue;

end
</code>


JQuery Cycle 2 Slide exibindo abaixo do alinhamento

Question: Estou usando o plugin Cycle 2 do JQuery.

Eis o link: http://www.dinamicaimoveis.com.br/novo/
Tenho duas div's. Uma flutuando à esquerda e outra à direita.
Em uma tenho um texto e uma imagem.
Na outra, tenho um slideshow.
A div do Slide show flutua à direita. Acontece que acima do slideshow existe um espaço até o topo de uns 20px que não consigo tirar, fazendo com que ela fique esses 20px abaixo do alinhamento da div que flutua á esquerda.
Na verdade o que parece mesmo é que além da área qe se vê o slide show, existe algum elemento invisivel mas que esta ali ocupando espaço.
Eis o código:

  <?php echo $constantes->getCorretor(); ?> - <?php echo $constantes->getCreci(); ?>

  <?php echo $constantes->getEnderecoCompletoSite(); ?>

Brazão Muriaé

Grande Hotel Muriaé

Cristo Redentor Muriaé

Matriz São Paulo

Matriz do Porto

Matriz da Barra

Matriz da Barra

Pedra Santa Maria

Prefeitrura e Rodoviária

Cachoeira do Rio Preto

Horto Florestal

Vista Pnarâmica

Onde estou errando?
Answer: Resolvdo: No css do plugin havia um border 10px auto


Replacing non-diagonal elements in a matrix in R (hopefully a better asked this time)

Question: Okay, I asked this question earlier but I got bashed (deservedly) for not specifying anything and showing no sign of previous attempt. So let me try again..
I'm using R, and I have a 463✕463 matrix. What I would like to do is to replace all elements other than the diagonal ones (X11, X22, X33,...,Xjj) with zero.
E.g. I want:
[1 4 5
 2 3 5
 3 9 8]

to be:
[1 0 0
 0 3 0
 0 0 8]

When I use the diag() function, it simply gives me a column vector of the diagonal values. I imagine I can use the replace() function somehow combined with a "if not diagonal" logic...but I am lost.
And yes, as some here have guessed, I am probably much younger than many people here and am completely new at this...so please put me in the right direction. Really appreciate all your help!
Comment: Be sure to tag your questions with the language that you're using.   After I tagged the other one as r, you got some better answers.
Comment: In situations where [your original question](http://stackoverflow.com/q/16705468/1468366) is ill-written, it is usually better to edit that question in an attempt to improve it, instead of simply starting off with a new question.
Answer: In R, the diag method has two functions.

It returns the diagonal of a matrix. I.e.
m <- matrix(1:9, ncol=3)
m
#      [,1] [,2] [,3]
# [1,]    1    4    7
# [2,]    2    5    8
# [3,]    3    6    9
diag(m)
# [1] 1 5 9

It can construct a diagonal matrix.
diag(1:3)
#      [,1] [,2] [,3]
# [1,]    1    0    0
# [2,]    0    2    0
# [3,]    0    0    3

So in your case, extract the diagonal from your existing matrix and supply it to diag:
diag(diag(m))
#      [,1] [,2] [,3]
# [1,]    1    0    0
# [2,]    0    5    0
# [3,]    0    0    9

Answer: Examples using logical indexing:
# Case 1
m[ col(m)==row(m) ] <- 0  # replaces diagonal elements with 0

# Case 2
m <- matrix(1:9, 3)   # create example
m[ col(m)==row(m) ]   # displaya diagonal elements
#[1] 1 5 9

# Case 3 uses diag(3) to create a logical matrix
 # transparent indexing rule
m <- matrix(1:9, 3)   # create example
m[ !diag(3) ] <- 0  # negation of 1's on diagonal coerces to logical

# Case 4
# more transparently
m <- matrix(1:9, 3)   # create example
m[ col(m)!=row(m) ] <- 0  # set non-diagonal elements to 0
m                      # show results
     [,1] [,2] [,3]
[1,]    1    0    0
[2,]    0    5    0
[3,]    0    0    9

Answer: using outer
You can use the following to compute a logical matrix which describes the non-diagonal entries of a n×n matrix:
outer(1:n, 1:n, function(i,j) i!=j)

Applied to your example:
> m <- matrix(c(1,2,3,4,3,9,5,5,8),ncol=3)
> m
     [,1] [,2] [,3]
[1,]    1    4    5
[2,]    2    3    5
[3,]    3    9    8
> m[outer(1:3, 1:3, function(i,j) i!=j)] <- 0
> m
     [,1] [,2] [,3]
[1,]    1    0    0
[2,]    0    3    0
[3,]    0    0    8

using triangles
A possible alternative would be combining the two triangles on either side of the diagonal. In this case, you use the matrix m itself as input to determine the size.
upper.tri(m) | lower.tri(m)

Applied to your use case:
> m[upper.tri(m) | lower.tri(m)] <- 0

It seems you already got this answer in response to your original post…
Comment: Both methods worked out perfectly! Thank you!!


Show that $\frac{(J-1)!}{2!(J-3)!}= \sum_{h=2}^{J-1}(h-1) $

Question: Could you help me to show that
$$
\frac{(J-1)!}{2!(J-3)!}= \sum_{h=2}^{J-1}(h-1)
$$
where "$!$" denotes the factorial function?
Answer: $$\sum_{h=2}^{J-1} (h-1) = \sum_{h=1}^{J-2} h = \frac{(J-2)(J-1)}{2}= \frac{(J-1)!}{2!(J-3)!}$$


I can authenticate to Github using SSH but I get a permission denied when trying to push to my repo

Question: I am new to using Git and SSH authentication so bear with me.
I set up my repo on github and was pushing to it just fine using username and password. But then I saw that github is deprecating that so I decided to use SSH instead. I found a tutorial on how to create SSH keys and add them to github. I think I must have doe that right because I do the authentication test with github:
ssh -T email@example.com
And I get:
Hi <username>! You've successfully authenticated, but GitHub does not provide shell access.
But then I run:
git push origin
and I get:
firstname.lastname@example.com: Permission denied (publickey).
fatal: Could not read from remote repository.

I would really appreciate any help because this is driving me crazy!
Comment: Probably `origin` is a repo which your key does not have write access to?
Comment: If you are on Windows, see [this question](https://stackoverflow.com/q/67273366/1256452).
Answer: If git remote -v shows you an SSH URL to a repository you have access to (that you have created for instance), try (assuming Linux):
 GIT_SSH_COMMAND='ssh -v' git push

On Windows, in a CMD:
 set "GIT_SSH_COMMAND=ssh -v"
 git push

You will see where Git is looking for SSH keys, and what URL it uses.
It should be: firstname.lastname@example.com:<you>/<yourRepo>
Comment: I am using windows, is there something similar?
Comment: @J-Rome I have edited the answer to add the Windows version of that command.


blank page after dokuwiki upgrade

Question: I tried to upgrade dokuwiki using its upgrade plugin wizard.  Upgrade went fine.  After upgrade when I brows the site, the landing page loads fine but as soon as I click anywhere in the browser, it brings up a black blank page.
I check the apache's error and access log and see nothing wrong there. Set the site's log level to debug. Checked the file permissions and they look ok.  Cleared the cache.
Anyone has any pointers on how and where to look further?
Answer: Solved by performing below steps:
Temporarily disable JavaScript in your browser, then use the extension manager to update all the extensions. Re-enable JavaScript afterwards.
Answer: Just had this issue myself and this answer helped me. Once I disabled javascript I couldn't get to the admin page. I'd add to this answer, after you disable javascript you should be able to get to your admin page at an address similar to:
http://YOUR_DOMAIN_PATH/doku.php?id=start&do=admin&page=extension

blank page after dokuwiki upgrade


SSL: no alternative certificate subject name matches target host name

Question: At one time our company hosted our own blog which we hosted with our wildcard cert for the domain, *.example.com. We moved our company blog to Hubspot and the team at Hubspot setup a second SSL cert for www.example.com for the Hubspot hosted blog (I have no idea why this all happened before I started here).
We are now having an intermittent issue with our apex domain https://example.com. Sometimes it resolves fine but sometimes in Chrome you get the scary "Your connection is not private" warning. Hubspot's response was to have us create a redirect with EasyRedirect, which I have done, but that hasn't resolved it.
If I curl -vL example.com it works fine but curl -vL https://example.com gives me SSL: no alternative certificate subject name matches target host name 'example.com'
Is there something I can do about these competing SSL certs for our apex domain?
Comment: Are you using `example.com` for your AD domain?  If yes, then you are probably getting the wrong IP occasionally, and hitting a DC.  In the domain used for AD, the apex of the zone is owned by the domain.
Comment: Btw, start simple.  Do an `nslookup example.com` is it reporting multiple IPs?
Comment: Can you provide a little bit more about your webserver configuration (nginx, apache, etc.)? you can easily redirect all requests going towards https://example.com to https://www.example.com. Please let me know what webserver you are using and I will provide you.

e.g. in nginx:

```server {
 listen 80 default_server;
 listen [::]:80 default_server;
 server_name example.com www.example.com;
 return 301 https://www.example.com$request_uri;
}
```
Comment: @DmitriyKupch Hubspot hosts one site I don't have any details. The other is on Heroku.
Comment: @Zoredache Yes the `Non-authoritative answer` is reporting 2 IPs
Answer: A site binding can only have 1 SSL certificate assigned to it.  It sounds like Hubspot has the www.example.com certificate bound to your site and that certificate does not have a SAN for example.com.  You should do a couple things here:

Reissue your SSL certificate and include a SAN for example.com
Redirect anyone going to example.com to www.example.com (This will not resolve the "Your connection is not private" message until you do #1.  This is because the SSL connection occurs before the site is displayed and  you will not be able to redirect people until they trust your certificate.

If they were using your wildcard certificate then none of this would matter and both URLs would result in a valid certificate.  Depending on how long you've been at the company it's possible your wildcard certificate is expired and you'd need a new one anyway.  There is probably a way to work with Hubspot to have a CSR generated and go buy your own wildcard certificate if your company wants to go that route.
Comment: Thanks. The wildcard cert has not expired because it was renewed in December. I tried to work with Hubspot's team to explain this but they have not been very helpful. They have made this very clear that it's "my problem". I'll give this a try and report back.


Handle application states (starting/stopping) not activity states

Question: I'm working on my 1st Android app and wondering how to handle activation/deactivation/starting/stopping globally, not on Activity level.
This great article shows states transition for Activities:
http://developer.android.com/reference/android/app/Activity.html#ActivityLifecycle
Is there something similar for Application states?
For example at iOS and Windows Phone app there is clear app states separated from activities (views, controllers, whatever).
I'm asking because I want to perform certain operations only once per app loading/exiting not with every activity starting/stopping
Comment: I don't really know of a built-in way to do that, but if there is one, it would be nice to know.  I believe you will have to create your own class that watches for leaving the application.
Answer: The answer is There is Simply No Direct method to do this
rather than in Application Class you can catch these events
@Override
public void onLowMemory()
{
    super.onLowMemory();
}

@Override
public void onTerminate()
{
    super.onTerminate();
}

So you will have to handle it  in all the Activities you will be having
the following methods

onResume()
onStart()
onRestart()
onPause()
onDestroy()

You will have to implement in all Activity to handle for all application
A suggesstion
You can have some Variable in Application class to save application state
say create a variable like
public static boolean isPaused;

and set it from all activity on state change
Answer: The question you're asking is applicable for iOS and Windows but not really for Android.
Android doesn't really have a concept of an application as an object, although there's an Application class. Instead, an app is a loose collection of Activities. There are many good reasons for this state of affairs; for example, it supports fast app switching and easy interaction between Activities of different apps.
The best way to coordinate your "app" so that one Activity doesn't try to do something that's already been done is to use SharedPreferences to store app state. Nearly every other way of doing it is less preferred. Even if the system kills off your entire app, SharedPreferences will maintain the current state. The Application object won't.
Also, Android is based on pausing and resuming. An Activity or activities are created, pause, and resume. They may be destroyed, but that's an extreme case. A corollary to this is that apps should not have an exit button; there's no need for one. I sometimes see apps that have one, but what they're really trying to do is shut down a background Service or process. The best way to do that is to have an affordance that says "Sleep" or similar.
Answer: Have all activities inherit from the same hierarchy and put whatever you want in OnCreate, OnPause, OnResume, OnStop, OnDestroy and call the super where applicable.
Example
Parent
IamTheParentActivity : Activity

protected void onCreate()
{
setApplicationState(ApplicationState.Running);
}

protected void onPause()
{
setApplicationState(ApplicationState.Paused);
}

private void setApplicationState(Enum ApplicationState)
{
//Some Application Level Variable
Application.State = ApplicationState
}

Children
IamTheChild : IamTheParentActivity

protected void override onCreate()
{
base.OnCreate;
do other stuff
}

Comment: thanks, I want to load app state whenever application is activated(resumed). If I put this login in super class it will be called every time I navigating to new Activity. Otherwise if I put this logic for the first Activity I could lose some date when user reactivates my app on say the second Activity.
Comment: I am unclear about your statement. If you want your logic to be called every time you app resumes put the state logic in onresume of the super class and update the application level variable holding state. If there are circumstances ie a second activity in which you dont want to change state just use some logic to determine that within your application state handling method.