Positive integers $d_1$, $d_2$, $\ldots$, $d_n$ divide $1995$. Prove that, for some $i,j$, the numerator of $\dfrac{d_i}{d_j}$ is at least $n$.

Question:
(Probably Correct Statement) Distinct positive integers $d_1$, $d_2$, $\ldots$, $d_n$ divide $1995$. Prove that, for some indices $i,j\in\{1,2,\ldots,n\}$, the numerator of the reduced fraction $\dfrac{d_i}{d_j}$ is at least $n$.

Well, the 16 divisors of 1995 are 1 3 5 7 15 19 21 35 57 95 105 133 285 399 665 1995. So, everything starting from 19/1(or, if you want quotient to be greater than 1, from 95/3) suits. But how to make it more general?
Comment: What did you try?
Comment: I just rolled back an edit because I saw no conceivable justification for the changes that were made. The included image is clear about what the statement of the question is.
Comment: @Famke Your conclusion is true but your assumptions are much stronger than the olympiad problem allowed. You're dealing with a different question.
Comment: @Piquito The quotient is less than $2$, but the ***numerator*** of the quotient is either $15$ or $19$, both of which are greater than $2$.
Comment: Remarks: (1) The notation $d_1\mid d_2\mid \ldots \mid d_n\mid 1995$ means $d_1\mid d_2$, $d_2\mid d_3$, $\ldots$, $d_{n-1}\mid d_n$, and $d_n\mid 1995$.  (2) The problem is not clear.  If the $d_i$'s are allowed to be the same, then the statement is definitely false.  It is perhaps the case that the $d_i$'s must be pairwise distinct (which should have been clearly stated in the problem).
Comment: By "clear," of course, I meant that we can see what it says. It is a bit annoying that we are apparently supposed to implicitly assume the numbers are pairwise distinct--is that true of every list of variables in every Israeli Math Olympiad?
Comment: Supose that $m$ is any arbitrary integer.
Let $ d_1 \mid d_2 \mid ... d_{n-1} \mid d_{n} \mid m $.
If we are allowed to assume $d_i \neq d_j$; then we can deduce that:

 - $n \leq m$.

 - $n \leq d_n$.
Comment: Are we to assume that the $d_i$ are distinct?
Comment: @ThomasAndrews I presume so, because otherwise a string of $1$s satisfies the stronger of the suggested criteria, and evidently fails for $n\gt 1$
Answer: Claim: If $p_1,p_2,\dots,p_m$ are distinct primes with $p_i\geq 2^{i}-1$, then for any set of distinct divisors $d_1<d_2<\dots<d_n$ of $N=p_1p_2\cdots p_m$, there is some fraction $\frac{d_i}{d_j}$ with reduced numerator $\geq n$.
This gives your result since $1995=3\cdot 5\cdot 7\cdot 19$.
Proof:
We will prove by induction on $m$.
If $m=1$, then all divisors are $1,p_1$. Since $p_1\geq 2$ you are done.
If true for $m$, then take $p_1,\dots,p_{m+1}$ with $p_i\geq 2^{i}-1$.
If none of $d_1,\dots,d_n$ are divisible by $p_{m+1}$, then it reduces to the case of $m$.
If all of the $d_i$ are divisible by $p_{m+1}$, then we can take the set of distinct divisors $\frac{d_1}{p_{m+1}},\dots,\frac{d_n}{p_{m+1}}$ of $p_1\cdot p_m$, and reduce to the case of $m$.
If $d_i$ is divisible by $p_{m+1}$ and $d_j$ is not, then $\frac{d_i}{d_j}$ has $p_{m+1}$ as a factor of the numerator. So that handles the cases when $n\leq p_{m+1}$. But if $n> p_{m+1}\geq 2^{m+1}-1$, then, since there are exactly $2^{m+1}$ divisors of $N$, $n=2^{m+1}$ and $d_1,\dots,d_n$ is all of the divisors. In particular, one of the $d_i=1$ and another $d_j=N$, and since $\{d_1,\dots,d_n\}\subseteq \{1,\dots,N\}$, you have $N\geq n$.
Answer: All of the $16$ divisors of $1995$ are of the form $3^{\delta_1}5^{\delta_2}7^{\delta_3}19^{\delta_4}$ where each exponent is equal to $0$ or $1$.
There are $8$ divisors of the form $19\cdot3^{\delta_1}5^{\delta_2}7^{\delta_3}$ and $8$ divisors of the form $3^{\delta_1}5^{\delta_2}7^{\delta_3}$.
►All set of divisors containing $n\ge9$ elements should contain at least one element of each of the two forms in which case we choose as numerator a factor of $19$ and as denominator a divisor coprime with it. This end the proof for $n\ge9$ because $19\gt 16$.
It remains the proof for $n=1,2,3,4,5,6,7,8$.
► For $n=8$ if all the divisors are multiples of $19$ we choose, for example the quotient $\dfrac{19\cdot3\cdot5}{19\cdot7}$ For all other set of $8$ elements containing a multiple of $19$ and a divisor coprime with $19$ we choose as numerator the multiple of $19$ and as denominator the divisor coprime to $19$
►We can now  to consider just divisors of the  form  $3^{\delta_1}5^{\delta_2}7^{\delta_3}$.
For $n=8$ we choose $\dfrac{d_i}{d_j}=\dfrac{7\cdot3\cdot5}{5}$ (there are other examples).
For $n=7$ one of the $8$ involved divisors must lack. If it is the largest we choose $\dfrac{d_i}{d_j}=\dfrac{7\cdot5}{3}$ and if not we choose as numerator the mentioned largest (there are other examples).
For $n=6$ two of the $8$ concerned divisors should lack. If its are the two largest we choose $\dfrac{d_i}{d_j}=\dfrac{7\cdot3}{5}$ and if not we choose
$\dfrac{d_i}{d_j}=\dfrac{7\cdot3\cdot5}{5}$(there are other examples).
And so on for $n=5,4,3,2$ and the trivial case $n=1$.


Prove the identity $\frac{(2n)!}{2^n \cdot n!} = (2n-1)(2n-3)\cdots 3\cdot 1$ using combinatorial proof.

Question: Prove the identity
$$\frac{(2n)!}{2^n \cdot n!} = (2n-1)(2n-3)\cdots 3\cdot 1$$
using combinatorial proof.
Answer: Hint. It counts the number of ways to choose $n$ disjoint pairs of objects from $2n$ objects.
Answer: Ok, I think, I get the LHS: we order $2n$ objects, thus $(2n)!$, we don't care about the order of objects in each pair, thus $2^n$, and we don't about the order of pairs, thus $n!$ I am struggling with the RHS though. Looks like proof by induction, but I don't see it...
EDIT: I think, you could apply recursive induction for RHS. There $2n-1$ possibilities to pick the first pair from $2n$ objects times number of ways to pick $n-1$ distinct pairs out of $2n-2$ objects.


reference request: Type A crystal proof of Schur-positivity

Question: In this question: https://mathoverflow.net/questions/272306/what-techniques-are-there-to-prove-schur-positivity, one of the techniques listed to prove Schur-positivity is called a Type-A crystal proof, which apparently Stembridge characterized.  Does anyone have a link to the relevant Stembridge paper, or to something that can explain this in more detail?
Answer: I suppose that it is A local characterization of simply-laced crystals (Trans. Am. Math. Soc. 355, No. 12, 4807-4823 (2003)).


Installer can't create sqlite database

Question: I have a drupal page, hosted with azure webapps, on nginx. However, when i start the site, the installer wants to have a database. I am aware that it's bad, but sqlite is an intentional choice because of company reasons.
However, when i try to use sqlite it says it locked.

I have no direct access to the files, once they are deployed. All changes have to be made locally, and then commited and pushed for azure to redeploy it.
Does anybody know how to fix this?
Answer: First, ensure PHP meeets the requirements. Then, read more carefully the instructions on the install screen, which read:

The absolute path to the file where Drupal data will be stored. This must be writable by the web server and should exist outside of the web root.

The screenshot you provided does not show an absolute path.
Comment: The web server needs to be able to write to the database file, and the folder it's in, there's no way to get around that. If your hosting doesn't allow that you either need different hosting, or a different db backend
Comment: I checked my sqlite version, and it was higher then the requirements (3.35.4). I also fixed the filepath to the default. Nothing changed about it.
Comment: Is there any way to check if it is able to write to it?

Installer can't create sqlite database


springboot admin: How to display custom metrics in springboot admin GUI ("Metrics" tab)

Question: We are using serveral microservices with springboot (Vers. 1.4.3) and for monitoring them springboot-admin (Vers. 1.5.0).
Inside our microservices we generate several custom metrics (using the
'@com.codahale.metrics.annotation.Timed' annotation).
While all these custom metrics are displayed through the ordinary actuator-endpoint "/metrics" they are sorrowly not shown in the springboot admin GUI -"Metrics" tab.
Obviously only "counter." and "gauge." metrics are displayed in the latter.
Is there any possibility to configure / modify springboot admin, so that these custom metrics also are shown - either in the existing 'metrics' tab or in another new tab ?
Answer: Ok, meanwhile I found out, that the new  springboot-admin version 1.5.2 will solve our problem:
As I could see at a project from a colleague, this springboot-admin version will display ALL metrics without any restrictions regarding the metrics-key.
[ At the moment we can't upgrade to this version since our springboot-version dependency prevents it but in the future we'll be able to do so.]
So the problem is more or less solved.


return message in linq

Question: how to return a message in linq? please see my code below. my return type is list. please help me.
public List<Product> GetProductsByProductName(string storeId, string productName)
{
    Authenticate();
    int _storeId = Convert.ToInt32(storeId);
    string message = "Item is not added to cart";
    var _products = (from p in context.products.AsEnumerable()
                     where p.StoreId == _storeId && p.ProductName.Contains(productName) && p.ProductIsAvailable.Equals(true)
                     orderby p.ProductName
                     select
                         new Product()
                         {
                             ProductName = p.ProductName,
                             CategoryID = p.CategoryId,
                             QuantityPerUnit = p.ProductUnit,
                             UnitPrice = p.ProductPrice,
                             DiscountValue = p.DiscountValue,
                             DiscountType = p.DiscountType
                         }).ToList();

    if (_products.Count > 0)
    {
        return _products;
    }
    else
    {
        return message.ToList();
    }
}

Answer: you should consider throwing an exception.
instead of return meassage.toList try :
throw new Exception("Item is not added to cart");
public List<Product> GetProductsByProductName(string storeId, string productName)
{
    ...

    if (_products.Count > 0)
    {
        return _products;
    }
    else
    {
        throw new Exception( "Item is not added to cart");

    }
}

you can handle it outside where you call the GetProductsByProductName method
you can even define your own exception like ItemAddException : Exception ....
or you add a new out bool parameter that tells you if it worked, or an out string parameter for messages :)
public List<Product> GetProductsByProductName(string storeId, string productName, out string message)
    {
        ...

        if (_products.Count > 0)
        {
            return _products;
        }
        else
        {
            message = "Item is not added to cart";
            return null; //check if caller can handle nulls ;)
        }
    }

so if the method was called
var l = GetProductsByProductName(storeId, productName);

you will now have to do
string message="";
var l = GetProductsByProductName(string storeId, string productName, out message);
if(String.IsNullOrEmpty(message)==false)
{
   .... do stuff
}

or if you use the exception mehtod :
try
{
  var l = GetProductsByProductName(storeId, productName);
}
catch(Excepion ex)
{
   ... do stuff
}

Comment: That's a ref not an out.
Comment: sorry, it is not working. actually i want return a message to  mobile. this is using for mobile application.
Comment: maybe you should post the calling method too :) means : the caller must handle the out string, or the exception

return message in linq


Show that $\int\limits_0^2x^{-1}e^{-x} dx$ does not converge

Question: I'm trying to show that the integral

$$I:=\int\limits_0^2x^{-1}e^{-x}\mathrm dx$$

diverges.

My attempt: We know that the problem is in the $x \to 0$ part so we have that $x \to 0$ implies $e^{-x} \to 1$ and $x^{-1} \to \infty$. We have that the function is not defined at zero so if we set this integral correctly we have that
$$I= \lim_{\xi \to 0}\int_\xi^2x^{-1}e^{-x}\mathrm dx $$
I think is not possible to interchange the series of $e^x$ with the integral because it is a divergent integral of a series. (Is this correct? Thinking in the answer given HERE).
We can use that $$E\mathrm i(-x) = \int x^{-1}e^{-x}\mathrm dx+\mathrm{Const.}$$
So $$I = E\mathrm i(-2) - \lim_{\xi \to 0}E\mathrm i(-\xi)$$
Can anyone set a hint for what can I do?
Comment: You could compare it to $x^{-1}e^{-2}$.
Comment: Using that $x^{-1}e^{2}> x^{-1}e^{-x}$ and that $ln(x) \to \infty$? @JonasMeyer
Comment: But I don't expect that the integral converges. Clearly diverges. I'm trying to prove it.
Comment: @Rafael: Check your inequality.  And you mean $e^{-2}$?
Comment: No, I just mislead the inequality. If $x^{-1}e^{-2} < x^{-1}e^{-x}$ then using that the integral preserves inequality we have that the integral in $x^{-1}e^{-2} $ goes to infinity and then we must have that the integral in $x^{-1}e^{-x}$ goes to infinity?
Comment: @JonasMeyer I think I get it. Post this hint as an answer and I'll accept it. It is a very usefull one and solves the problem completely. Thanks a lot for your hint!
Answer: Since $x^{-1}e^{-x} \ge x^{-1}e^{-1}$ on $(0,1),$ and $\int_0^1 x^{-1}\,dx = \infty,$ we have $\int_0^1 x^{-1}e^{-x}\,dx=\infty.$
Answer: Let $g(x)=\frac{e^{-x}-1}{x}$ for $x\in (0,2]$. Then $g$ can be made continuous at $x=0$ by defining $g(0)=-1$.
But then $$\int_{\xi}^2 x^{-1}e^{-x}\,dx = \int_{\xi}^2 g(x)\,dx + \int_{\xi}^2 \frac{dx}{x}$$
Since $g$ is continuous on $[0,2]$ you get:
$$\lim_{\xi\to 0+}\int_{\xi}^2 x^{-1}e^{-x}\,dx = \int_{0}^{2}g(x)\,dx + \lim_{\xi\to 0+} \int_{\xi}^{2}\frac{dx}{x}$$
Basically, $x^{-1}e^{-x}$ behaves "like" $\frac{1}{x}$ when $x$ is near zero.
Comment: It's $+$. We have $$x^{-1}e^{-x}= g(x)+\frac{1}{x}.$$ This is a very direct formula.
@MathOverview
Answer: Note that
\begin{align}
\lim_{\xi\to 0}\int_\xi^2x^{-1}e^{-x}\mathrm dx
=&
\lim_{\xi\to 0}\int_\xi^2x^{-1}D_x\big(-e^{-x}\big)\mathrm dx
\\
=&
\lim_{\xi\to 0}\left[
x^{-1}(-e^{-x})\Big|_{\xi}^{2}-\int_\xi^2D_x\big(x^{-1}\big)\big(-e^{-x}\big)\mathrm dx
\right]
\\
=&
\lim_{\xi\to 0}\left[
\frac{1}{x}(-e^{-x})\Big|_{\xi}^{2}
-
\int_\xi^2\left(\frac{1}{x^2}\right)(-e^{-x})\mathrm dx
\right]
\\
=&
\lim_{\xi\to 0}\left[
\underbrace{-\frac{1}{2}(e^{-2})+\frac{1}{\xi}(e^{-\xi})}_{\to \infty}
+
\underbrace{\int_\xi^2\left(\frac{1}{x^2}\right)(e^{-x})\mathrm dx}_{<\infty}
\right]
\end{align}
Answer: By convexity $e^{-x}\geq \max(1-x,0)$, hence
$$ \int_{0}^{2}\frac{e^{-x}}{x}\,dx \geq -1+\int_{0}^{1}\frac{dx}{x} $$
trivially implies divergence.


Where to put Beanstalk instances in VPC?

Question: I've been researching best practices for setting up a web application on AWS. I've setup my db tier in a private subnet. I also have a public subnet for nat instances, bastion host, elb, etc. My question is, is there any advantage in having my beanstalk instances deployed to a private subnet or should I just put them in the public subnet. The AWS article series, Develop, Deploy, and Manage, puts the web servers in a private subnet, but I've seen many others put them in a public one. So I'm confused as to where the web servers should go and the pros/cons of each approach.
[EDIT]:
This is for a public facing website, not an internal one. Just in case it matters.
Answer: The default should be to put them in a private subnet. The main reason for this is security. By putting your EC2 instances in a public subnet, you're opening them up to individual attack.
There are some very bad reasons why people put the EC2 instances in a public subnet:

They want them public for Administrative access.
They want to avoid the costs of running a NAT.
They simply don't know any better.

None of the above reasons are valid reasons.
There are 2 valid reasons why you may want your EC2 instances in a public subnet:

The individual EC2 instances need to be accessed directly by the general public for some reason. But if you have an ELB, then this would be rare.
Your EC2 instances require enough outgoing bandwidth when accessing the internet through the NAT that the biggest NAT cannot keep up. To resolve this, your instances could be in a public subnet using the VPC Internet Gateway.

Unless one of these apply, use a private subnet.


Can any atlas of the manifold act as "local trivialization"?

Question: I'm learning Manifolds theory and on one concept on a vector bundle I couldn't really understand for weeks.
In Loring Tu's Introduction to smooth manifolds, in order to find the local trivialization, we find the collection of $U$ covering the manifold $M$ such that we get a fiber-preserving diffeomorphism $\phi:\pi ^{-1}(U)\to U\times \mathbb{R}^r$ with each fiber being vector space with dimension $r$.
This notion of local trivialization is introduced in the section of vector bundle (not necessarily a tangent bundle) and it seems that every manifold admits local trivialization (not global trivialization). So for the case of manifolds, can we regard this $U$ in local trivialization as an atlas? Even more basically, vector bundle is the generalization of tangent bundle, is it correct?
Comment: This is very confusing to read, so I'm not sure what your exact question is. It doesn't make sense to say "every manifold admits local trivialization". A trivialization is something a vector bundle has, not just the manifold itself. What is true is that any atlas of the manifold induces a trivialization of the tangent bundle as described. This does not hold true for general vector bundles anymore. I also wouldn't think of vector bundles as generalizations of tangent bundles, there's no reason to.
Comment: Yes, a tangent bundle is a vector bundle.
Comment: Okay Thanks! That's what I meant in the question. Manifold induces tangent bundle, and tangent bundle induces local trivialization, by using $U$ an open set in the atlas (reversely, can we make open sets in local trivialization as an atlas?). My last question was asking if every tangent bundle is a vector bundle, which seems to be true.. Sorry for the bad wording
Answer: Tu defines a surjective smooth map $p : E  \to M$ to be locally trivial of rank $r$ if the two conditions (i) and (ii) on the top of p. 134 are satisfied.
Any such collection $\{(U,f )\}$, with $\{U\}$ an open cover of $M$, is called a local trivialization for $E$, and $\{U\}$ is called a trivializing open cover of $M$ for $E$.
You may also say that $\{(U,f )\}$ is a bundle atlas in that case.
If I understand correctly, you ask whether a trivializing open cover $\{U\}$ of $M$ is an atlas for $M$. The answer is no.

We are not given homeomorphisms $\phi_U : U \to V$, where $V$ is an open subset of $\mathbb R^n$. Only a collection $\{(U,\phi_U) \}$ can be a (smooth) atlas.

You could ask whether for each bundle atlas $\{(U,f )\}$ there exists an associated  smooth atlas $\{(U,\phi_U) \}$ for $M$ having the same open sets $U$. This is not the case. The trivial bundle $M \times \mathbb R^k$ has a trivializing open cover with one set (which is the whole manifold $M$). But in general there is no smooth atlas on $M$ with a single chart.

However, what you can do is this: Given a trivializing open cover $\mathcal U$ of $M$, then any open cover $\mathcal V$ which refines $\mathcal U$ is again  a trivializing open cover for $M$. Now take $\mathcal U'$ to be set of all open $U'$ which are contained in some $U \in \mathcal U$ on which there exists a chart $\phi_{U'} : U' \to V'$ belonging to the smooth structure of $M$.


Minimize loss function

Question: Given a random sample $X_1, \dots, X_n$, find the estimator of position $\theta$ that minimize the following loss function
$$g(\theta) = \sum_{i=1}^n (X_i - \theta)^2 ,\quad \quad g(\theta)=\sum_{i=1}^n |X_i - \theta|$$
Now, I've already now what a loss function is, and the definition of risk and minimax. And I just read a couple of examples which gives you a random sample with a fixed distribution and it compares two distint estimators using the risk. But I can't understand the idea of this exercise (and I don't have a rough definition of what "estimator of position" is).
I don't want the answer, just want to know what am I have to do. Any tips?
Thank you
Answer: Estimation of position (or a more common term, estimator for $\theta$, usually denoted as $\hat{\theta}$) means
$$\hat{\theta} = \arg \min_{\theta} g(\theta).$$
I think the purpose of the exercise is to build your intuition on the choice of loss function.
Comment: your intuition is correct when $g$ is smooth. Hence for the first loss function, you can prove by doing that the estimator is the mean. For the second loss function, it is known that the median minimizes it.
Comment: My intuition says "derive $g(\theta)$ and make equals zero", but i'm not sure if it's that so. Besides, the loss function is given, can you be a little bit more specific? Thank you so much in advance
Comment: Or a recommendation on some good texts about this topics, i'm currently using Wasserman: All of statistics

Minimize loss function


Using standard Roman numeral analysis how should 7th and 9th qualities be determined?

Question: Example:
C: V7 or inversions like C: V6/5 are understood to be dominant-seventh chords and C: V9 a dominant ninth chord with a diatonic, major ninth.
I think the basic idea is all the Arabic numeral parts are understood to be diatonic relative to the root indicated by the Roman numeral.
V9 in C major the root of V is G and the 9th above that root is A which is a major ninth.
By comparison iii9 in C major the root of iii is E and the 9th above that root is F which is a minor ninth.
That seems clear enough, but what about when the Roman numeral symbol indicates a chromatic chord?
Examples:
C: V9/ii or Am: I7 or C: iv9
When secondary or borrowed symbols are used I understand that we are temporarily referencing a new tonic/key and I sort of expect the Arabic numerals should then be relative to the temporarily referenced tonic/key.
If that is way it should be done, I get these examples...
C: V9/ii is a secondary dominant relative to tonic/key Dm and V9 in Dm would get a minor-ninth. So the chord C: V9/ii is A C# E G Bb.
Am: I7 is a borrowed chord relative to parallel major A major and I7 in A would get a major-seventh. So the chord Am: I7 is A C# E G#.
C: iv9 is a borrowed chord relative to parallel minor Cm and iv9 in Cm would get a major-ninth. So the chord C: iv9 is F Ab C Eb G.
I think the confusion is when using secondary or borrowed chord the RNA symbol isn't relative to the key denoted by the colon C: , Am:, etc. but by the secondary slash or switching of upper/lower case which indicates a temporary tonic/key or mode change from the key denoted by the colon.
...is this correct?
Comment: @Tim I think `iii9` is `Emb9` rather than `Em9`. It's hard to not be wordy, but my question/suggestion is RNA is diatonic and jazz symbols aren't - to me the jazz symbols are all relative to a dominant chord and its extensions in a major key.
Comment: The first half of this is a great question, but I didn't really get your examples; what do you mean by relative?
Comment: 'iii9 is Em9' spelled E G B D F? Yes, diatonically, but surely a m9 rooted on E is E G B D F#? And 'C iv9 is *relative*. Isn't it *parallel*?(Same as Am: A maj.) I appreciate this question was not easy to put together!
Comment: @Shevliaskovic, relative to a tonic/key. Ex. `V` surely that is _relative to something_ or else you wouldn't be able to know the specific notes to play. Let me try adding some edits in my final three examples.
Comment: @Michael: could you post an example of literature? I'm not sure whether I understand your question. Do you mean that if we are in am and A7 occurs as V7/D it would be unclear whether in RNA was I7 or V7? And if one analysis I7 would this mean a minor or a major 9th?
Comment: Michael Curtis, the iii9 in C major is actually Em***7*** (♭9).
Comment: @AlbrechtHügli, with that particular case I was not thinking secondary dominant, but perhaps a Picardy third ending, something like jazz symbols `Amin... E7 to Amaj7`, in RNA should it be `i... V7 I7`. The question being on the final chord is the 7 M7 or m7 and how to write that figure. Normally RNA doesn't add modifiers to `7` like jazz symbols.
Comment: @MaikaSakuranomiya. I know that the diatonic `iii` ninth chord is. Question is not how to write the jazz symbol, but the RNA symbol. Are all RNA figures assumed to be diatonic? I think yes. How then to write RNA in a chromatics context. with plain daitonic `iii` it should be simple `iii9` in RNA is `E G B D F` in jazz you specify `b9`, in RNA it's already assume to be a diatonic 9th, therefore a minor `m9`
Answer: There are multiple variants of RNA in common use. The distinguishing styles V, v, V+, v° will be readily recognized as symbols for major, minor, augmented, and diminished triads over a root that is a diatonic scale degree (for a chromatic root, a prefixed accidental must be used, as ♭II6 for the Neapolitan sixth).
However, there seems to be no similarly standard convention for distinguishing qualities of 7th and 9th chords, apart from vii°7 and viiø7 for diminished and half-diminished 7th chords respectively. The most sensible convention is to style the Roman numeral according to the quality of the underlying triad and assume the added notes are diatonic unless indicated otherwise, for instance

C: iii9 is E-G-B-D-F (= Em7♭9 in jazz notation)
C: V9/ii is diatonic in the key of ii, i.e. A-C♯-E-G-B♭
C: I7 (or IM7, etc.) is a major seventh chord; C: I♭7 or Idom7 is a dominant seventh chord (a.k.a. V7/IV, but with different functional implications)
C: iv9 is F-A♭-C-E-G, a perfectly normal mixed-mode chord.

In minor keys the picture is muddied by the presence of multiple variants of the 6th and 7th scale degrees. Unfortunately for the standardization-minded, a: VII (G-B-D) and a: vii° (G♯-B-D) are in common use. Musically, 7ths and 9ths of chords tend to be drawn from the natural minor scale because they typically resolve downward. Therefore, I'd interpret a: i7 as a minor seventh (common in sequences) unless clearly written otherwise, e.g. a: i♯79 (sorry I can't make the numerals vertically aligned).
Comment: `Idom7` seems like a jazz oriented RNA mod, `V7/IV` is the usual, functional RNA symbol.
Comment: `Cm:iv9` would be `F Ab C Eb G` so shouldn't the borrowed chord `C:iv9` be the same set of notes? `F Ab C Eb G`
Comment: @MichaelCurtis I saw Idom7 in Aldwell & Schachter for the first chord of Beethoven's 1st Symphony. The point they were making is that the chord, in addition to being V7/IV, can be retrospectively heard as a modified tonic.
Comment: @MichaelCurtis And as to C:iv9, changing the case of the Roman numerals is not the same as moving to the parallel mode (e.g. C:III would be E major, different from Cm:III) so I feel justified in saying that only the third of the chord is affected.
Comment: That's an interesting point about `C:IV` versus `C:iv`, the later I understand to mean borrowed chord rather than "lower the third."
Answer: I assume this question is developed from recent questions concerning accidentals whether they are chromatic or diatonic.
It is a question concerning analysis and different analysis systems : RNA and analysis of Jazz/Pop.
In Jazz - and the Riemann/Maler system would be no confusion while in the RNA you have to decide for modulation or not. If your analysis is continuing in the new key the (V7) are minor 7th and (V9) are minor when they are secondary dominants to ii,iii and vi degree.
If your not changing the key in your analysis there will be no confusion by adding a small flat in front of the 7 in case of I becomes a secondary dominant to IV (as in Jazz the V7b5).
Comment: Yes, the question is about RNA and specifically about _temporary_ chromaitic harmony, not modulations, so how to understand 7 and 9 figures when the RNA is a secondary chord or a borrowed chord. I gave examples to illustrate both cases.
Comment: I understand your last sentence about adding accidentals  - sort of cautionary accidentals to numeric figures as a kind of imitation of jazz or figured bass, but the question is specifically if RNA always assumes _diatonic_ intervals which are diatonic to the relative/temporary tonic.


Pandas - filter users with minimum artists listened to

Question: I want to filter my dataset to users who have listened to a minimum number of unique artists. My aim is to focus on users with relatively higher listenership as a function of artist selection.
Below is a data example and my initial code approach:
full_df.head()

   user artist              plays  gender  age    Country
0   a   devendra banhart    456    m       28.0   United States
1   b   boards of canada    407    m       28.0   United States
2   a   cocorosie           386    m       28.0   United States
3   c   aphex twin          213    m       28.0   United States
4   d   animal collective   203    m       28.0   United States

Code:
eda_df = full_df.groupby('users')['artist'].filter(lambda x: len(x) >= 20)

In this case, user a would display the highest artist count.
Answer: You can use groupby.nunique with pd.DataFrame.transform.
This example, using your data, filters for a minimum unique artist count by user of 1:
res = df[df.groupby('user')['artist'].transform('nunique') > 1]

print(res)

  user           artist  plays gender   age       Country
0    a  devendrabanhart    456      m  28.0  UnitedStates
2    a        cocorosie    386      m  28.0  UnitedStates


The $k$th derivative of $\sin^n x$ as $n \ \sin^{n - k} x$ times a polynomial in $\cos x$

Question: It seems the $k$th derivative of the function $x \mapsto \sin^n x$ can be expressed as $n \ \sin^{n - k} x$ times a polynomial with only even or only odd powers of $\cos x$ (depending on the parity of $k$), with polynomials in $n$ as coefficients, for natural $k$ and integer $n$ and complex $x$.
The highest term is $n^{k-1} \cos^k x$; the ranks of the other polynomial-in-$n$ coefficients for $\cos^{k-2j} x$ seem to be (maximally) $(k-1-j)$.
$$
\frac{\mathrm{d}^0}{\mathrm{d}x^0} \sin^n x = n \ \sin^{n - 0} x \ \left(n^{-1} \cos^0 x\right)\text{ for }n \neq 0
$$
$$
\frac{\mathrm{d}^1}{\mathrm{d}x^1} \sin^n x = n \ \sin^{n - 1} x \ \left(n^0 \cos x\right)
$$
$$
\frac{\mathrm{d}^2}{\mathrm{d}x^2} \sin^n x = n \ \sin^{n - 2} x \ \left(n^1 \cos^2 x - 1\right)
$$
$$
\frac{\mathrm{d}^3}{\mathrm{d}x^3} \sin^n x = n \ \sin^{n - 3} x \ \left(n^2 \cos^3 x + (-3 n + 2) \cos x\right)
$$
$$
\frac{\mathrm{d}^4}{\mathrm{d}x^4} \sin^n x = n \ \sin^{n - 4} x \ \left(n^3 \cos^4 x + (-6 n^2 + 8 n - 4) \cos^2 x + (3 n - 2)\right)
$$
$$
\frac{\mathrm{d}^5}{\mathrm{d}x^5} \sin^n x = n \ \sin^{n - 5} x
$$
$$
\left(n^4 \cos^5 x + (-10 n^3 + 20 n^2 - 20 n + 8) \cos^3 x + (15 n^2 - 30 n + 16) \cos x\right)
$$
$$
\frac{\mathrm{d}^6}{\mathrm{d}x^6} \sin^n x = n \ \sin^{n - 6} x
$$
$$\left(n^5 \cos^6 x + (-15 n^4 + 40 n^3 - 60 n^2 + 48 n - 16) \cos^4 x + (45 n^3 - 150 n^2 + 196 n - 88) \cos^2 x + (-15 n^2 + 30 n - 16)\right)
$$
Is there a general rule to determine the polynomial-in-$n$ coefficients?
Edit:
The OEIS sequence A133341 seems to determine the second polynomial-in-$n$ coefficients (when one alternates the signs, and discards the italic values):

1,
2,
1, 3,
3, 2, 4,
6, 8, 4, 5,
10, 20, 20, 8, 6,
15, 40, 60, 48, 16, 7,
21, 70, 140, 168, 112, 32, 8,
28, 112, 280, 448, 448, 256, 64, 9,
36, 168, 504, 1008, 1344, 1152, 576, 128, 10,
45, 240, 840, 2016, 3360, 3840, 2880, 1280, 256, …
Comment: Statement of Theorem 1.2 is, I believe, what you are seeking, its associated proof on page 10 will help.  https://arxiv.org/pdf/1202.1205.pdf
Comment: Are you familiar with complex numbers?
Comment: Yes, but I fail to see the connection between this question and complex numbers. Feel free to explain if you have found one.
Comment: One way to get a formula for the $i$-th derivative would be the Faà di Bruno's formula. It's all but nice though
Comment: @Kevin Interestingly, at the top of page 12 another solution for d^m/dx^m sin^ℓ  x in another form is deduced from Faà di Bruno's formula, with ℓ+1 cosines and ℓ+1 sines (which presumably cancel each other out for real x, given that they are multiplied with the imaginary unit). The cosines and sines are not raised to any power, they have arguments different from x though.
Comment: What you need is the generalised product rule, for taking the $m$th derivative of a product of $n$ factors. It's similar to the polynomial expansion formula. However, since all your factors here are equal, there should be nice simplifications.
Answer: This answer has since been written out in: https://arxiv.org/pdf/1911.01386.pdf . For the expressions with these polynomials, skip the section "Using the complex definitions and the binomial theorem".
Determining $p_{k}(n)(\cos x)$ recursively
When, for natural $k$, and integer $n$, and complex $x$,
$$
\frac{\mathrm{d}^k}{\mathrm{d}x^k} \sin^n x = \sin^{n - k} x \ p_{k}(n)(\cos x)
$$
with $p_{k}(n)(\cos x)$ a polynomial in $\cos x$ with only terms with even powers of $\cos x$ when $k$ is even, and only terms with odd powers of $\cos x$ when $k$ is odd; with $n^k \cos^k x$ as the highest term;
and note that each coefficient of $p_{k}(n)(\cos x)$ includes the initial factor $n$ that I factored out in the question;
then
$$
\frac{\mathrm{d}^{k+1}}{\mathrm{d}x^{k+1}} \sin^n x = \sin^{n - (k+1)} x \ \left( ((n - k) \cos x) \ p_{k}(n)(\cos x) + (\cos^2 x - 1) \frac{\mathrm{d}}{\mathrm{d}\cos x} p_{k}(n)(\cos x)\right)
$$
with $\frac{\mathrm{d}}{\mathrm{d}\cos x} p_{k}(n)(\cos x)$ a polynomial in $\cos x$ with only terms with odd powers of $\cos x$ when $k$ is odd, and only terms with even powers of $\cos x$ when $k$ is even; with $k \ n \ \cos^{k-1} x$ as the highest term.
So
$$
p_{k+1}(n)(\cos x) = ((n - k) \cos x) \ p_{k}(n)(\cos x) + (\cos^2 x - 1) \frac{\mathrm{d}}{\mathrm{d}\cos x} p_{k}(n)(\cos x)
$$
is a polynomial in $\cos x$ with only terms with odd powers of $\cos x$ when $k$ is even, and only terms with even powers of $\cos x$ when $k$ is odd; with $((n - k)^1 \ n^k  + k \ n) \ \cos^{k+1} x = n^{k+1} \ \cos^{k+1} x$ as the highest term.
Furthermore
For the same polynomials $p_{k}(n)(y)$ also holds
$$
\frac{\mathrm{d}^k}{\mathrm{d}x^k} \cos^n x = (-1)^{k} \cos^{n - k} x \ p_{k}(n)(\sin x)
$$
$$
\frac{\mathrm{d}^k}{\mathrm{d}x^k} \sinh^n x = \sinh^{n - k} x \ p_{k}(n)(\cosh x)
$$


Draw a line inside a UITextView - NSAttributedString

Question: I wish to draw a customizable line inside a UITextView consisting of some text (using NSAttributedString)
Here's what I tried
NSString *unicodeStr = [NSString stringWithFormat:@"%C%C%C", 0x00A0, 0x0009, 0x00A0]; //nbsp, tab, nbsp
NSMutableAttributedString *str = [[NSMutableAttributedString alloc] initWithString:unicodeStr];
NSRange strRange = NSMakeRange(0, str.length);

NSMutableParagraphStyle *const tabStyle = [[NSMutableParagraphStyle alloc] init];
tabStyle.headIndent = 16; //padding on left and right edges
tabStyle.firstLineHeadIndent = 16;
tabStyle.tailIndent = -16;
NSTextTab *listTab = [[NSTextTab alloc] initWithTextAlignment:NSTextAlignmentCenter location:40 options:@{}]; //this is how long I want the line to be
tabStyle.tabStops = @[listTab];
[str  addAttribute:NSParagraphStyleAttributeName value:tabStyle range:strRange];
[str addAttribute:NSStrikethroughStyleAttributeName value:[NSNumber numberWithInt:2] range:strRange];

But no matter what value I provide for the tab stop location (40 in this case) and tailIndent (-16 here), the line only respects the headIndent and spans the entire UITextView width (minus the headIndent of course).
EDIT - I am pretty sure the issue is because I am not using the correct unicode chars (although they seem to be the logical choice). In case this gives someone a hint, if I add a space after the 2nd nbsp i.e. towards the end, the tab is limited to a single tab length
Comment: I'm trying to implement an hr tag (horizontal rule). They are not supported by NSAttributedString when converting from html
Answer: Is it your expected result?

Can you try this:
NSTextTab *listTab = [[NSTextTab alloc] initWithTextAlignment:NSTextAlignmentCenter location:self.textView.frame.size.width - tabStyle.firstLineHeadIndent + tabStyle.tailIndent options:@{}];

And this is the full code:
- (void) viewDidAppear:(BOOL)animated {
  [super viewDidAppear:animated];
  NSString *unicodeStr = @"\n\u00a0\t\t\n";
  NSMutableAttributedString *str = [[NSMutableAttributedString alloc] initWithString:unicodeStr];
  NSRange strRange = NSMakeRange(0, str.length);

  NSMutableParagraphStyle *const tabStyle = [[NSMutableParagraphStyle alloc] init];
  tabStyle.headIndent = 16; //padding on left and right edges
  tabStyle.firstLineHeadIndent = 16;
  tabStyle.tailIndent = -70;
  NSTextTab *listTab = [[NSTextTab alloc] initWithTextAlignment:NSTextAlignmentCenter location:self.textView.frame.size.width - tabStyle.headIndent + tabStyle.tailIndent options:@{}]; //this is how long I want the line to be
  tabStyle.tabStops = @[listTab];
  [str  addAttribute:NSParagraphStyleAttributeName value:tabStyle range:strRange];
  [str addAttribute:NSStrikethroughStyleAttributeName value:[NSNumber numberWithInt:2] range:strRange];

  NSAttributedString *htmlStr = [[NSAttributedString alloc] initWithData:[@"
Lorem ipsum dolor sit er elit lamet
" dataUsingEncoding:NSUnicodeStringEncoding] options:@{ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType } documentAttributes:nil error:nil];

  [str insertAttributedString:htmlStr atIndex:0];
  [str appendAttributedString:htmlStr];

  self.textView.attributedText = str;
}

Comment: why u pass the 'self.textView.frame.size.width' reference when this size is not calculated?
Answer: Here's what I did to solve the same issue. It uses a subclass of NSTextTab:
import UIKit

class RightAnchoredTextTab : NSTextTab {
    weak var textContainer : NSTextContainer!

    required init(textAlignment alignment: NSTextAlignment, location loc: CGFloat, options: [String : AnyObject], textContainer aTextContainer : NSTextContainer) {
        super.init(textAlignment: alignment, location: loc, options: options)
        textContainer = aTextContainer
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }

    override var location: CGFloat {
        get {
           return textContainer.size.width-textContainer.lineFragmentPadding*2-super.location
        }
    }
}

And similar bits similar to other solutions:
func horizontalLine(indent : CGFloat = 30, width : CGFloat = 1) -> NSAttributedString
{
    let paragraphStyle = NSMutableParagraphStyle()

    paragraphStyle.tabStops = []
    paragraphStyle.addTabStop(NSTextTab(textAlignment: .Left, location: indent, options: [:]))
    paragraphStyle.addTabStop(RightAnchoredTextTab(textAlignment: .Right, location: indent, options: [:], textContainer : textView.textContainer))
    paragraphStyle.alignment = .Left

    let attributes = [NSParagraphStyleAttributeName : paragraphStyle, NSStrikethroughStyleAttributeName : width]

    textView.backgroundColor = UIColor.yellowColor()
    let ZeroWidthNonBreakingSpace = "\u{FEFF}"
    return  NSAttributedString(string: "\t\(ZeroWidthNonBreakingSpace)\t\(ZeroWidthNonBreakingSpace)\n", attributes:  attributes)
}

A few notes:

It will probably only work with a single square text container.
NSTextContainer has a lineFragmentPadding. If you've every wondered why you have to indent a right alignment tab by 10 this is it: the default value is 5.
prefixing the text with \n meant there was no strikethrough. No idea why.
This solution works with rotations etc as UITextView calls NSTextTab.location again when the bounds are changed.
Answer: for swift 5,
    let unicodeStr = "\n\u{00a0}\t\t\n"
    let str = NSMutableAttributedString(string: unicodeStr)
    let strRange = NSRange(location: 0, length: str.length)

    let tabStyle = NSMutableParagraphStyle()
    tabStyle.headIndent = 0 //padding on left and right edges
    tabStyle.firstLineHeadIndent = 0
    //tabStyle.tailIndent = -16
    let listTab = NSTextTab(textAlignment: .center, location: textView.frame.size.width-10, options: [:]) //this is how long I want the line to be
    tabStyle.tabStops = [listTab]
    str.addAttribute(.paragraphStyle, value: tabStyle, range: strRange)
    str.addAttribute(.strikethroughStyle, value: NSNumber(value: 2), range: strRange)
    str.addAttribute(.strikethroughColor, value: UIColor.label, range: strRange)
    str.addAttribute(NSAttributedString.Key.font, value: self.currentFont, range: strRange)
    str.addAttribute(NSAttributedString.Key.foregroundColor, value: UIColor.label, range: strRange)

    textView.textStorage.append(str)

    //To set cursor end of document
    let endPosition = self.textView.endOfDocument
    self.textView.selectedTextRange = self.textView.textRange(from: endPosition, to: endPosition)


Condition for convergence of random variables

Question: I am working with the various types of convergence of random variables.
I came across this exercise:
Consider the following sequence of independent r.vs : $(X_i, i\geq1) : Pr(X_i=i^a)=\frac{1}{i^b}, Pr(X_i=0) = 1-\frac{1}{i^b}$ with $a,b>0$
What are the minimal condition for $a,b$ s.t. $X_i\to 0$ considering quadratic convergence, in probabilty and almost sure convergence.
I thought of something among these lines:
For the quadratic: I need $E(X_i^2)\to 0, i \to +\infty$ hence, $
 \frac{(i^a)^2}{n^b} \to 0, i\to +\infty$ which means
    $a < b/2$ Is that right?
As for the almost sure convergence, is it ok for every $a,b$? Because I would say that I need $a<0$ in order to be sure to have always $X_i=0$ but since I can't, it will always be $\neq 0$ with prob $1/i^b$ I need to nullify the probability of it being different then $0$ and thus, $b>0$ is ok. What happens if the condition are not verified? It will still converge, right? Even if not almost surely?
For the convergence in probability I have no idea, honestly, on how to estimate $Pr(|X_i|>\epsilon)$ as $i\to \infty$. Is it $Pr(i^a>\epsilon)$? And to have it go to $0$ I need $a>log_i(\epsilon)$ and $b>0$?
Answer: We have
$$
\mathbb E[X_i^2] = \frac{(i^a)^2}{i^b} = i^{2a-b},
$$
so $\mathbb E[X_i^2]\stackrel{i\to\infty}\longrightarrow 0$ iff $2a-b<0$. It is clear that $X_i$ converges in probability to zero for any $b>0$ since $i^{-b}\stackrel{i\to\infty}\longrightarrow 0$. The $X_i$ converge to zero almost surely iff
$$
\mathbb P\left(\liminf_{i\to\infty}X_i<\varepsilon\right)=1,\ \forall\varepsilon>0.
$$
For any positive integer $i$, there exists $k>i$ such that $\mathbb P(X_k<1)=0$ - take $k > e^{-a}$. It follows that
\begin{align}
\mathbb P\left(\liminf_{i\to\infty}X_i<1\right) &= \mathbb P\left(\bigcup_{i=1}^\infty\bigcap_{j=i}^\infty \{X_j<1\}\right)\\
&\leqslant\sum_{i=1}^\infty \mathbb P\left(\bigcap_{j=i}^\infty \{X_j<1\}\right)\\
&\leqslant \sum_{i=1}^\infty \mathbb P(X_k<1) = 0,
\end{align}
and hence $X_i$ does not converge almost surely to zero.


`encode_www_form': undefined method `map'

Question: when am trying to execute following code
require "net/http"
require "uri"

@appArgs = Array.new
@vmip_and_port = "yyyyy"

def post(url, data)
  uri = URI.parse(url)
  http = Net::HTTP.new(uri.host, uri.port)
  request = Net::HTTP::Post.new(uri.request_uri)
  request.set_form_data(data)
  response = http.request(request)
  return response
end

def click_inapp(id)
  @appArgs.push(id)
  return
end

def finish_inapp()
  data =  @appArgs.join(",")
  res = post("http://" +@vmip_and_port+"/", data)
  return res.body
end
click_inapp("5X7_photo_paper.png")
click_inapp("4X6_photo_paper.png")
finish_inapp()

Am getting
uri/common.rb:931:in `encode_www_form': undefined method `map' for "5X7_photo_paper.png,4X6_photo_paper.png":String (NoMethodError)
    from /home/ushusadmin/.rvm/rubies/ruby-1.9.3-p448/lib/ruby/1.9.1/net/http.rb:1761:in `set_form_data'
    from app_utilities.rb:11:in `post'
    from app_utilities.rb:23:in `finish_inapp'
    from app_utilities.rb:28:in `'

whats wrong with my code.please corect me
Answer: set_form_data is expecting a Hash of field names and values, not an string. So try to:
require "net/http"
require "uri"

@appArgs = Hash.new
@vmip_and_port = "172.16.2.40:9090"

def post(url, data)
  uri = URI.parse(url)
  http = Net::HTTP.new(uri.host, uri.port)
  request = Net::HTTP::Post.new(uri.request_uri)
  request.set_form_data(data)
  response = http.request(request)
  return response
end

def click_inapp(field_name, id)
  @appArgs[field_name] = id
end

def finish_inapp()
  res = post("http://" +@vmip_and_port+"/", @appArgs)
  return res.body
end
click_inapp("png1", "5X7_photo_paper.png")
click_inapp("png2", "4X6_photo_paper.png")
finish_inapp()

I'm not really sure about the rest of the program, as I don't want to test and attack your server at 172.16.2.40:9090 :-)
Try ri Net::HTTP on the console, to have examples.


How do I update modules with security release only using composer?

Question: On a Drupal 8 site, using the drupal-composer/drupal-project template, how would I go about updating only those modules which have a security release?
Our policy is to not update any module in our monthly maintenance routine unless it has a security update.
Ideally I'd like to find a solution which could be automated.
Answer: (I am using Drupal 7 modules as example, but just because there are more examples of security updates for Drupal 7 modules.)
Without custom coding, it's not possible. Drupal.org doesn't use a different name schema for security updates. From the version number you cannot know that version 7.x-3.14 of the Views module was a security update, while version 7.x-3.13 was not a security update.
That information is kept in https://updates.drupal.org/release-history/views/7.x, for the Drupal 7 version of the Views module, or in general in https://updates.drupal.org/release-history/<project short name>/<Drupal version>.
In the list of terms associated with a release, a Release type term whose value is Security update means the release is a security update.
<release>
  <name>views 7.x-3.14</name>
  <version>7.x-3.14</version>
  <tag>7.x-3.14</tag>
  <version_major>3</version_major>
  <version_patch>14</version_patch>
  <status>published</status>
  <release_link>
    https://www.drupal.org/project/views/releases/7.x-3.14
  </release_link>
  <download_link>
    https://ftp.drupal.org/files/projects/views-7.x-3.14.tar.gz
  </download_link>
  <date>1466019539</date>
  <mdhash>168bb684c8f34297be94b03c797841e5</mdhash>
  <filesize>1656594</filesize>
  <files>...</files>
  <terms>
    <term>
      <name>Release type</name>
      <value>Security update</value>
    </term>
    <term>
      <name>Release type</name>
      <value>Bug fixes</value>
    </term>
  </terms>
</release>

The classes under the \Drupal\update namespace can help in writing the required code. UpdateProcessor::parseXml() is the method used to parse the XML data for a single project, but you would probably need to access one of the services Drupal implements.
Comment: Perfect, great answer. We'll be able to process the XML and figure out the release type. The option I had considered was using `drush ups --security-only` and then processing that output but this is cleaner.


Does this NSLOOKUP timeout with ZoneEdit mean their DNS servers are down?

Question: My DNS zone record appears to be degrading. NSLOOKUP on www.whatpub.org gives a timeout. Am I right in saying this means the two ZoneEdit nameservers I use (ns2.zoneedit.com & ns17.zoneedit.com) are not responding to requests?
Cheers, Rob.
Answer: Answering own question, yes NS2 and NS17 are both currently down although the status page says everything is okay. Found a few twitter posts. So it's a case of sit tight...
Answer: ZoneEdit.com is up and down.  See http://zoneedit.com/status.html


In a declarative jenkins pipeline - can I set the agent label dynamically?

Question: Is there a way to set the agent label dynamically and not as plain string?
The job has 2 stages:

First stage - Runs on a "master" agent, always. At the end of this stage I will know on which agent should the 2nd stage run.
Second stage - should run on the agent decided in the first stage.

My (not working) attempt looks like this:
pipeline {
    agent { label 'master' }
    stages {
        stage('Stage1') {
            steps {
                script {
                    env.node_name = "my_node_label"
                }
                echo "node_name: ${env.node_name}"
            }
        }

        stage('Stage2') {
            agent { label "${env.node_name}" }
            steps {
                echo "node_name: ${env.node_name}"
            }
        }
    }
}

The first echo works fine and "my_node_label" is printed.
The second stage fails to run on an agent labeled "my_node_label" and the console prints:

There are no nodes with the label 'null'

Maybe it can help - if I just put "${env}" in the label field I can see that this is a java class as it prints:

There are no nodes with the label 'org.jenkinsci.plugins.workflow.cps.EnvActionImpl@79c0ce06'
Comment: script block has local scope. that's the reason you cant print that on 2nd script block
Comment: Not sure this is true as the first "echo" command works fine and it's outside the script block.
Anyway, in my actual scenario env.node_name is a result returned by a shell script.
If you know any workaround - it would be helpful.
Answer: Here is how I made it: mix scripted and declarative pipeline. First I've used scripted syntax to find, for example, the branch I'm on. Then define AGENT_LABEL variable. This var can be used anywhere along the declarative pipeline
def AGENT_LABEL = null

node('master') {
  stage('Checkout and set agent'){
     checkout scm
     ### Or just use any other approach to figure out agent label: read file, etc
     if (env.BRANCH_NAME == 'master') {
        AGENT_LABEL = "prod"
     } else {
        AGENT_LABEL = "dev"
     }
   }
}

pipeline {
    agent {
       label "${AGENT_LABEL}"
    }

    stages {
        stage('Normal build') {
           steps {
              echo "Running in ${AGENT_LABEL}"
              sh "hostname"
           }
        }

        stage ("Docker build") {
           agent{
             dockerfile {
                dir 'Dockerfiles'
                label "${AGENT_LABEL}"
             }
            }
            steps{
                sh "hostname"
            }
        }
    }
}

Comment: Instead of doing string interpolation (`label "${AGENT_LABEL}"`), you can simply write `label AGENT_LABEL`.
Comment: Why use an agent at all in the first stanza? Just use a closure in the `agent` declaration: `pipeline { agent { label "${env.BRANCH_NAME.equalsIgnoreCase('master') ? 'prod' : 'dev'}" }`
Comment: Could we define using your approach the content of the `agent { "$CONTENT" }` and not `label "${AGENT_LABEL}"` where `CONTENT is calculated within the `node/stage` ?
Answer: To see how this works, use a GString object to do a println and return the variable for the agentName at the same time. You can see from the output that this line evaluates well before any of the other pipeline code.
agentName = "Windows"
agentLabel = "${println 'Right Now the Agent Name is ' + agentName; return agentName}"

pipeline {
    agent none

    stages {
        stage('Prep') {
            steps {
                script {
                    agentName = "Linux"
                }
            }
        }
        stage('Checking') {
            steps {
                script {
                    println agentLabel
                    println agentName
                }
            }
        }
        stage('Final') {
            agent { label agentLabel }

            steps {
                script {
                    println agentLabel
                    println agentName
                }
            }
    }

    }
}

Console output (note that I don't actually have node on this instance labeled Windows, so I aborted after it couldn't find it):
Started by user Admin
[Pipeline] echo
Right Now the Agent Name is Windows
[Pipeline] stage
[Pipeline] { (Prep)
[Pipeline] script
[Pipeline] {
[Pipeline] }
[Pipeline] // script
[Pipeline] }
[Pipeline] // stage
[Pipeline] stage
[Pipeline] { (Checking)
[Pipeline] script
[Pipeline] {
[Pipeline] echo
Windows
[Pipeline] echo
Linux
[Pipeline] }
[Pipeline] // script
[Pipeline] }
[Pipeline] // stage
[Pipeline] stage
[Pipeline] { (Final)
[Pipeline] node
Still waiting to schedule task
There are no nodes with the label 'Windows'
Aborted by Admin
[Pipeline] // node
[Pipeline] }
[Pipeline] // stage
[Pipeline] End of Pipeline
ERROR: Queue task was cancelled
Finished: ABORTED

Notice how the line Right Now the Agent Name is Windows appears very early in the output. This explains why your value is null. That statement is evaluated long before your script modifies the variable.
I might try to use a lazy GString to get the variable later.
agentLabel = "${-> println 'Right Now the Agent Name is ' + agentName; return agentName}"

Unfortunately, this throws an error because it is expecting a type of String. Apparently it can coerce the non-lazy GString to a String on its own, but not the lazy version. So when I force coercion to a String, of course, it evaluates the variable at that time (which is again, before the   pipeline code actually runs).
agent { label agentLabel as String }

You can solve the problem by falling back to the old node allocation method:
agentName = "Windows"
agentLabel = "${-> println 'Right Now the Agent Name is ' + agentName; return agentName}"

pipeline {
    agent none

    stages {
        stage('Prep') {
            steps {
                script {
                    agentName = "Linux"
                }
            }
        }
        stage('Checking') {
            steps {
                script {
                    println agentLabel
                    println agentName
                }
            }
        }
        stage('Final') {

            steps {
                node( agentLabel as String ) {  // Evaluate the node label later
                    echo "TEST"
                }
                script {
                    println agentLabel
                    println agentName
                }
            }
        }
    }
}

You can see from this console output that it now properly finds the Linux node and finishes the pipeline. The early evaluation while agentName == Windows never happens:
Started by user Admin
[Pipeline] stage
[Pipeline] { (Prep)
[Pipeline] script
[Pipeline] {
[Pipeline] }
[Pipeline] // script
[Pipeline] }
[Pipeline] // stage
[Pipeline] stage
[Pipeline] { (Checking)
[Pipeline] script
[Pipeline] {
[Pipeline] echo
Right Now the Agent Name is Linux
[Pipeline] echo
Linux
[Pipeline] }
[Pipeline] // script
[Pipeline] }
[Pipeline] // stage
[Pipeline] stage
[Pipeline] { (Final)
[Pipeline] echo
Right Now the Agent Name is Linux
[Pipeline] node
Running on Slave 1 in /home/jenkinsslave/jenkins/workspace/test
[Pipeline] {
[Pipeline] echo
TEST
[Pipeline] }
[Pipeline] // node
[Pipeline] script
[Pipeline] {
[Pipeline] echo
Right Now the Agent Name is Linux
[Pipeline] echo
Linux
[Pipeline] }
[Pipeline] // script
[Pipeline] }
[Pipeline] // stage
[Pipeline] End of Pipeline
Finished: SUCCESS

This would probably work without the lazy GString and type coercion later, but I didn't try that.
Comment: I can add a script block inside the node block and it works great.
Comment: Did this do what you want?
Comment: kind of.. but I wonder if this solution has a downside:
In the 'Final' stage the node agent is indeed the right one,
but when I want to run a shell script on the agent, if I do it in the script block (the one just below the node block) it will run on the main agent and not the slave(!).
Only if I run it inside the node block it will run on the right slave...
Does this have any downside?
different syntax / capabilities inside a "node" block..?
Comment: No, no downside at all.  The "node" block is the syntax used before declarative pipeline. For your purposes here, this is the same as specifying the agent on the stage. I did just notice, though, that you should probably put an agent on the previous stages, and "agent none" at the pipeline level. Or you can specify an agent at the pipeline level and 'node' should still do what you want. But in my mind it is a little cleaner to specify an agent per stage if you are not using the same one on all stages. But either way, don't run the stage on the flyweight agent on the master.
Answer: it might be something about the context of the script block.
this works, using a label of 'docker' in second stage:
def hotLabel = 'docker'

pipeline {
    agent { label 'master' }
    stages {
        stage('Stage1') {
            steps {
                echo "node_name: ${hotLabel}"
            }
        }

        stage('Stage2') {
            agent { label "${hotLabel}" }
            steps {
                echo "node_name: ${hotLabel}"
            }
        }
    }
}

this does not (gets the same There are no nodes with the label 'null' error):
def hotLabel = null

pipeline {
    agent { label 'master' }
    stages {
        stage('Stage1') {
            steps {
                script {
                    hotLabel = "docker"
                }
            }
        }

        stage('Stage2') {
            agent { label "${hotLabel}" }
            steps {
                echo "node_name: ${hotLabel}"
            }
        }
    }
}

Comment: The problem with this example is the `agent { label 'master' }` at the top of the pipeline overrides any other agent declarations. If you want to specify specific agents (or no agent) at any point in the pipe, you have to start with `agent none` and define an agent in every stage that needs one.
Answer: I used a ternary operator to have mine dynamically change.
For below, if the Jenkins pipeline name ends in "prod" the label used is "myagent-prd". Otherwise, it's just "myagent".
def ENVIRONMENT_NAME="${JOB_NAME}".tokenize('-').last().toLowerCase()

pipeline {
    agent {
      label "myagent${ENVIRONMENT_NAME == "prod" ? "-prd" : "" }"
    }

Answer: This worked for me:
env.agentName = ""

branch_name = "10.1.0"
pipeline {
    agent none

    stages {
        stage('Prep') {
            steps {
                script {
                    println branch_name
                    if ("${branch_name}" == "9.2.0") {
                        env.agentName = "9.2agent"
                    } else {
                        env.agentName = "10.1agent"
                    }
                }
            }
        }

        stage('Finish') {
            steps {
                node (agentName as String) { println env.agentName }
                script {
                    println agentName
                }
            }
        }

    }
}

Output:
SuccessConsole Output
Started by user build
Running in Durability level: MAX_SURVIVABILITY
[Pipeline] stage
[Pipeline] { (Prep)
[Pipeline] script
[Pipeline] {
[Pipeline] echo
10.1.0
[Pipeline] }
[Pipeline] // script
[Pipeline] }
[Pipeline] // stage
[Pipeline] stage
[Pipeline] { (Finish)
[Pipeline] node
Running on 10.1agent in /home/build/jenkins/workspace/testlabel
[Pipeline] {
[Pipeline] echo
rbreg6
[Pipeline] }
[Pipeline] // node
[Pipeline] script
[Pipeline] {
[Pipeline] echo
rbreg6
[Pipeline] }
[Pipeline] // script
[Pipeline] }
[Pipeline] // stage
[Pipeline] End of Pipeline
Finished: SUCCESS

Changing the branch name to 9.2.0:
Started by user build
Running in Durability level: MAX_SURVIVABILITY
[Pipeline] stage
[Pipeline] { (Prep)
[Pipeline] script
[Pipeline] {
[Pipeline] echo
9.2.0
[Pipeline] }
[Pipeline] // script
[Pipeline] }
[Pipeline] // stage
[Pipeline] stage
[Pipeline] { (Finish)
[Pipeline] node
Running on 9.2agent in /shared/build/workspace/testlabel
[Pipeline] {
[Pipeline] echo
rbregistry
[Pipeline] }
[Pipeline] // node
[Pipeline] script
[Pipeline] {
[Pipeline] echo
rbregistry
[Pipeline] }
[Pipeline] // script
[Pipeline] }
[Pipeline] // stage
[Pipeline] End of Pipeline
Finished: SUCCESS

Comment: While this code snippet may solve the question, [including an explanation](http://meta.stackexchange.com/questions/114762/explaining-entirely-code-based-answers) really helps to improve the quality of your post. Remember that you are answering the question for readers in the future, and those people might not know the reasons for your code suggestion.
Comment: Are you saying you can define the agent inside the stage? I'll have to go try this, has anyone tried to do this inside a loop in a script directive?
Answer: I wanted the workflow to stem from a parameterized job to dynamically inject the variable. I found the following solution worked well simply using in-line string operations:

pipeline {

   agent { label 'LBL && '+nodeLabel }
   ...
}

Comment: this is not dynamic enough for my needs - as written in the question:
"At the end of this stage I will know on which agent should the 2nd stage run".
So I don't yet know the node name when the job is starting.
Answer: For my work's pipeline jobs, I needed to solve a similar problem. I did only want to set an agent for the whole pipeline!
I solved this by creating a function that returns the Nodename as String, which I can call in the pipeline directly.
In my case the Nodename is part of a Jenkins environment variable $JOB_BASE_NAME.
But you could use any logic that is allowed in the Jenkins Script Block, which is a big plus, I guess.
// determine agent to run tests on
def agent_selector() {
    if (env.JOB_BASE_NAME.contains('Nodename1')) {
        return "Nodename1"
    } else if (env.JOB_BASE_NAME.contains('Nodename2')) {
        return "Nodename2"
    } else {
        println("Could not get Agent from 'JOB_BASE_NAME' !")
        error('Aborting Build.')
    }
}
// start of pipeline
pipeline {
    agent {label agent_selector()}
    stages {
        stage('Stagestuff') {
            steps {
                echo "Hello World"
            }
        }
    }
}

Answer:
Is there a way to set the agent label dynamically and not as plain string?

So for those who wants to instantly use the relevant agent without run anything on the Jenkins controller, and still be able to pass dynamic agent label and keep it clean as possible:
pipeline {
    agent {
        label env.JENKINS_AGENT_LABEL ?: 'pod-agent'
    }
    ...

In my case, I'm using the environment variable JENKINS_AGENT_LABEL (you can use whatever you want here), and if env.JENKINS_AGENT_LABEL is equal to null, then it will use my default agent label (in my case 'pod-agent').
But if env.JENKINS_AGENT_LABEL is not equal null, then the Jenkins will use the agent label from the value that it will get from env.JENKINS_AGENT_LABEL


How to solve the probability of the binomial distribution sequence below?

Question:
Let $x_0$, $x_1$...$x_n$ be a sequence of independent random variables. $x_i = 1$ has probability $p$ and $x_i = 0$ has probability $1-p$. Let $k$ be the smallest integer such that $x_k = x_{k+1}$. Find probability that $x_k = 1$.

Example: $1,0,0,1,1,\cdots\quad k = 1$ and  $x_k = 0$.
My idea is that the probability of $x_k = 1$ is equal to the probability that no consecutive zero occurs before, which is $1-x_k = 0$ and then this question becomes the same question.
Comment: Welcome to MSE. It will be more likely that you will get an answer if you show us that you made an effort. This should be added to the question rather than in the comments.
Answer: Denote $r:=P(x_k=1)$ and $r_0:=P(x_k=1\mid x_0=0)$ and $r_1:=P(x_k=1\mid x_0=1)$.
Then we have the equalities:

$r=pr_1+(1-p)r_0$
$r_0=pr_1$
$r_1=p+(1-p)r_0$

Do you see why, and can you take it from here?

edit
$\begin{array}{ccccc}
 &  & 0\\
 & 1-p\nearrow &  & \nwarrow\\
\text{start } &  & p\downarrow &  & \uparrow1-p\\
 & p\searrow &  & \nearrow\\
 &  & 1\\
 &  &  & p\searrow\\
 &  &  &  & x_{k}=1
\end{array}$
Comment: Thank you! I have questions on the equalities, I think r = r1+r0 and I couldn't see why r0=pr1, could you explain it more? Thank you in advance.
Comment: I added a (clumsy) picture of the situation in the hope that things become more clear. If $x_0$ has taken its value then we land in "status" $0$ or "status"1. If we are in status $0$ then we can only end up with $x_k=1$ if the next $x_i$ gives a $1$ and secondly from status $1$ we go on to status $x_k=1$. That gives $r_0=pr_1$.
Comment: $r\neq r_1+r_0$ (as you think) but $r=r_1p_1+r_0(1-p)$. In general we do not have $P(A)=P(A\mid B)+P(A\mid B^{\complement})$ but $P(A)=P(A\mid B)P(B)+P(A\mid B^{\complement})P(B^{\complement})$
Comment: Thanks for the picture and explanation! I think I get it!
Answer: For $x_k=1$, the first $k-1$ samples must either be: an alternating sequence of $1,0$ (and $k$ is odd) or $0$ followed by an alternating sequence of $1,0$ (and $k$ is even); and of course samples $x_k, x_{k+1}$ must then be both $1$.


Difficulty in understanding statistics and inference

Question: I have a random variable, X, with cdf $F$ and pdf $f$. I want to estimate a parameter of $F$, say mean, $\mu$.
So what do I do? I construct an estimator, $Y_n$, with several random variable X1, X2,..., Xn from $F$ such that,
$Y_n=g(X1, X2, ..., Xn)$
and make sure that the random variable $Y_n$ has the property, $E[Y_n] = \mu$.
Now what? Initially I had problem 1 and now I am stuck with problem 2. How will I find $E[Y_n]$?
Example:
let $Y_n = 1/n*\sum_{i} X_i$
and we do have $E[Y_n] = \mu$. How do we find $E[Y_n]$?
Suppose we take single observations {x1, x2, ... xn} from our iid $X_i$. How will  $y_n = 1/n*\sum_{i} x_i$ approximate to $\mu$? I know $\lim_{n \to \infty} Y_n$ converges in probability to $\mu$. But that does not mean the value $\lim_{n \to \infty} y_n = \mu$.
Where am I wrong?
Comment: I'm not 100%, but it seems like they're using the Central Limit Thm.
Answer: I am not sure this answers all your questions. Maybe it helps to start by understanding how much knowledge we have about the objects involved. In the classical setting of statistical estimation you give, $\mu=E(X_1)$ is a fixed number which we do not know. But we will assume here that it is finite for simplicity. We do not "find" it like we find the solution of an equation (if we could do that, we would not need statistics), but we can construct estimators for it.
Assuming we have a sample of independent realizations $X_1,\ldots,X_n$ of $X$ and defining $Y_n=(X_1+\cdots+X_n)/n$ as you did above, we get a random variable $Y_n$, which we use to estimate $\mu$. As you stated above, $E(Y_n)=\mu$. But that is not the point, also $E(X_1)=\mu$. So why is it better (not always, only on average!) to use $Y_n$ rather than $X_1$ to estimate $\mu$? Assuming $\sigma^2=\mathrm{Var}(X_1)<\infty$, we find that $Y_n$ has a smaller variance than $X_1$ (namely $\sigma^2/n$, compared to $\sigma^2$). The average squared distance from $Y_n$ to $\mu$ is $n$ times smaller than the one we get if we use $X_1$ as estimator for $\mu$.
We can compare properties (like the variance) of different estimators, because as they are random and may give different results for every sample, we never know for sure what $\mu$ is (in a finite sample). But we may be able to compare e.g. how much the estimates fluctuate around the true value.


PHP Mail Sending Issue

Question: I'm having a hard time getting the following code to run:
$name = 'Kevin';
$company = 'nonw';
$website = 'none';
$email = 'firstname.lastname@example.com';
$phone = 'none';
$message = 'Just a test message.';

$message = "

From: $name

Company: $company

Website: $website

Email: $email

Phone: $phone

$message
";

$subject = '[' . $sitename . '] New contact message from ' . $name . ' ( ' . $email . ' )';

$headers = 'From: ' . $sitename . ' <' . $to . '>\r\nReply-To: ' . $email . '\r\n';

$s = mail($subject, $message, $email, $to);
if($s){
echo '
Your message has been sent.  Thank you for contacting us, someone will be in touch soon.
';
}else{
echo '
There was an error sending your message.  Please try again later.
';
print_r(error_get_last());
}

I have this in my php.ini:
; For Win32 only.
; http://php.net/sendmail-from
;sendmail_from = email@example.com

; For Unix only.  You may supply arguments as well (default: "sendmail -t -i").
; http://php.net/sendmail-path
sendmail_path = "/usr/sbin/sendmail -t -i -f firstname.lastname@example.com"

Have also tried with:
sendmail_path = "/usr/sbin/sendmail -t -i"

I have verified that the server is setup correctly to send email by running this directly on the server echo "test" | mail -s "test mail" email@example.com and I received the email.
What can be going on, or more to the point...  what am I missing?
Comment: Do you get any errors when you run your script? Which div displays? Try adding a `var_dump()` for your individual variables before you're making the `mail()` call to make sure you're passing the correct information.
Comment: i'm a dolt....   you'll see why in a minute
Answer: sorry guys.   I had it spelt wrong in mailconfig.ini
changing "/urs/sbin/sendmail -t -i -f email@example.com" to "/usr/sbin/sendmail -t -i -f firstname.lastname@example.com" did the trick

PHP Mail Sending Issue


MVC - editar form não está a funcionar - codeigniter

Question: Eu tenho um form a imprimir os dados de um utilizador. Quero que o utilizador possa editar esses dados. Mas está-me a dar um erro na view:

Undefined variable: list e Invalid argument supplied for foreach().

O meu código é o seguinte:
Controller:
public function actualizar_perfil()
{
    $this->load->helper('url');

    //definição da lista de regras a aplicar
    $config=array(
        array(
        'field' => 'nome',
        'label' => 'nome',
        'rules' => 'required|min_length[0]|max_length[50]'
        ),
        array(
        'field' => 'telefone',
        'label' => 'telefone',
        ),
        );

    $this->load->helper('url');

        $this->load->library('form_validation');
        $this->form_validation->set_rules($config);

        if(($this->form_validation->run())==FALSE)
        {
            $id = $this->uri->segment(3,0);
            $this->load-> model('perfil_model');
            $data['username'] = $this->session->userdata('username');
            $data['login'] = $this->perfil_model->GetDisplayableByUsernameAP($this->input->post('id'));
            $this->load->library('form_validation');
            $this->load->view('perfil_view',$data);
        }
        else {
            $this->load->helper('url');
            $this->load->model('perfil_model');

            $this->perfil_model->actualizarperfil($this->input->post('id'));

            redirect('controller/perfil');
        }
}

Model:
function actualizarperfil($id)
{   $username = $this->session->userdata('username');
    $data['nome'] = $this->input->post('nome');
    $data['telefone'] = $this->input->post('telefone');

    $this->db->where('id_login', $id);
    $this->db->update('login', $data);
}

function GetDisplayableByUsernameAP($id)
{
    $this->db->select('id_login, nome, username, password, cod_postal, telefone, email, localidade, rua');

    $result = $this->db->get_where('login',array('id_login' => $id));

    return $result->row();
}

View:
<?php echo validation_errors() ?>
  <?php echo form_open('controller/actualizar_perfil') ?>
     <?php foreach ($list as $login): ?>

      Nome:

        <input class="form-control" id="nome" value="<?php echo $login->nome?>" type="text">

      Telefone:

        <input class="form-control" id="telefone" value="<?php echo $login->telefone?>" type="text">

        <a href="actualizar_perfil/<?php echo $login->id_login?> " style="margin-left: 10px; padding:10px;">Guardar

        <input class="btn btn-default" value="Cancelar" type="reset">

   <?php endforeach ?>

No Controller ele entra aqui: form_validation->run())==FALSE;. Não entra no else.
Answer: Possui diversos erros:
View:
Você esqueceu de colocar o nome (name) do inputs:
<?php echo validation_errors(); ?>
<?php echo form_open('controller/actualizar_perfil'); ?>
 <?php foreach ($list as $login): ?>

      Nome:

        <input class="form-control" id="nome" name="nome" value="<?php echo $login->nome;?>" type="text">

      Telefone:

        <input class="form-control" id="telefone" name="telefone" value="<?php echo $login->telefone;?>" type="text">

        <a href="actualizar_perfil/<?php echo $login->id_login;?> " style="margin-left: 10px; padding:10px;">Guardar

        <input class="btn btn-default" value="Cancelar" type="reset">

  <?php endforeach; ?>

ou seja, name="nome" e name="telefone" são as informações aonde o PHP consegue recuperar as informações digitadas nos inputs.
Controller:
Faltou colocar a verificação da regra do telefone, você esqueceu de colocar rules na variável do tipo array $config. Foi colocado no exemplo logo abaixo o required (dado obrigatório), mas, você pode adicionar as outras regras, veja no exemplo:
public function actualizar_perfil()
{
    $this->load->helper('url');

    //definição da lista de regras a aplicar
    $config = array(
        array(
            'field' => 'nome',
            'label' => 'nome',
            'rules' => 'required|min_length[0]|max_length[50]'),
        array(
            'field' => 'telefone',
            'label' => 'telefone',
            'rules' => 'required'),
        );

    $this->load->helper('url');

    $this->load->library('form_validation');
    $this->form_validation->set_rules($config);

    if(($this->form_validation->run())==FALSE)
    {
        $id = $this->uri->segment(3,0);
        $this->load-> model('perfil_model');
        $data['username'] = $this->session->userdata('username');
        $data['login'] = $this->perfil_model->GetDisplayableByUsernameAP($this->input->post('id'));
        $this->load->library('form_validation');
        $this->load->view('perfil_view',$data);
    }
    else {
        $this->load->helper('url');
        $this->load->model('perfil_model');

        $this->perfil_model->actualizarperfil($this->input->post('id'));

        redirect('controller/perfil');
    }

}

No código pode possuir mais alguns erros de sintaxe, verifique corretamente todos os problemas e começe a refatorar seu código. Essas duas dicas vai solucionar uma boa parte, mas, o seu código está sem padrão e fica dificil solucionar na integra todos os problemas. Lembre-se que, um código bem escrito e organizado, ajuda na manutenção.
De um modo geral vai funcionar a parte do request e validation das informações do seu form.


Closed queueing networks

Question: When applying Norton's theorem to a closed queueing network, most documentation I found assumes same service rates for all queues. How do you calculate the throughput and delay if the service times are different for each queue? Does rate conservation apply?
Answer: This paper details how to apply Norton's theorem to a queueing network where (on the second page) "the service rate for the $i$th queue when there are $k$ custoers is $U_i(k)$, where $i=1,\ldots,M$ and $k=1,\ldots,N$." This therefore isn't assuming the same service rate for each queue.

Chandy, K. M.; Herzog, U.; Woo, L. (Jan 1975). Parametric Analysis of Queuing Networks. IBM Journal of Research and Development 19 (1): 36–42. doi:10.1147/rd.191.0036.

I'm not sure what you mean by rate conservation.

Closed queueing networks


Spring boot web application does not have cache-control header

Question: I am using a Spring boot application and there is a requirement to enable security by disabling the caching between the web-pages.
As I understand,  by default, Spring Security sets specific cache-control header values for us, without us having to configure anything.
But for my web application, the following response headers are not present.
Cache-Control", "no-store"
Pragma", "no-cache"
Expires", "0"
I have tried setting them using an interceptor(implementing HandlerInterceptor) and adding the following code in the preHandle, postHandle and afterCompletionMethod.
    response.setHeader("Cache-Control", "no-store"); // HTTP 1.1.
    response.setHeader("Pragma", "no-cache"); // HTTP 1.0.
    response.setHeader("Expires", "0"); // Proxies.

Although the control comes to these methods and the header is set, when I inspect the web-browser, I don't see these headers.
What could be the reason?
Answer: There are different types of setting the header.
I would suggest to set it either with a filter or the configuration.
Configuration
By default spring-boot sets security headers. With the .defaultsDisabled() you disable them and can selective activate the wanted headers.
@EnableWebSecurity
public class WebSecurityConfig extends
WebSecurityConfigurerAdapter {

@Override
protected void configure(HttpSecurity http) throws Exception {
    http
    // ...
    .headers()
        // do not use any default headers unless explicitly listed
        .defaultsDisabled()
        .cacheControl();
}
}

Will set the header to following settings:
Cache-Control: no-cache, no-store, max-age=0, must-revalidate
Pragma: no-cache
Expires: 0

For more detail of the configuration here is the doc. https://docs.spring.io/spring-security/site/docs/4.0.x/reference/html/headers.html
Alternative you can yous a filter.
Filter
@WebFilter("/filter-response-header/*")
public class AddResponseHeaderFilter implements Filter {

    @Override
    public void doFilter(ServletRequest request, ServletResponse response,
      FilterChain chain) throws IOException, ServletException {
        HttpServletResponse httpServletResponse = (HttpServletResponse) response;
        httpServletResponse.setHeader(
          "Cache-Control", "no-store");
httpServletResponse.setHeader(
              "Pragma", "no-cache");
httpServletResponse.setHeader(
              "Expires", "0");
        chain.doFilter(request, response);
    }

For a single response
HttpServletResponse:
HttpServletResponse response
response.addHeader("Cache-Control", "no-store");
response.addHeader("Pragma", "no-cache");
response.addHeader("Expires", "0");

for more have a look here: https://www.baeldung.com/spring-response-header


Select Mysql com uma array em uma tabela

Question: Tenho uma tabela no banco chamada atuação, no que gerado os ID`s das áreas escolhidas pelo usuário ex: 1,5,4,9,15
Preciso que o resultado da consulta em Mysql me retorne todos os usuários que tenha sido selecionado em uma lista de checkbox
alguém pode me dar uma luz de como realizar esta pesquisa, ate mesmo sem repetir o usuário caso ele se encaixe em mais de uma área de atuação escolhida?
Vou simplificar com a Consulta IN, que o resultado foi o mesmo
Utilizando
SELECT * FROM usuarios WHERE atuacao_usuario IN (1,5,6)

Me mostra os resultados pos pussuo usuarios na tabela ja com estas areas selecionadas como na imagem

Agora se retiro o numeral 1da consulta  SELECT * FROM usuarios WHERE atuacao_usuario IN (5,6) nao me retorna nenhum resultado
Comment: Insira parte do código que você ja fez no php.
Comment: Boa tarde @AndreiCoelho, ainda não tenho muita coisa de concreto, so criei uma consulta comum,

Vou colocar a parte do codigo de select na minha pergunta acima
Comment: Opa... melhor agora dá para responder
Comment: WHERE atuacao_usuario IN (1,5,8,7);    https://www.w3resource.com/mysql/comparision-functions-and-operators/in-function.php
Comment: Tem um edit que eu coloquei na resposta. Tente ele depois.
Answer: Você pode utilizar o OR dentro do SELECT. Assim:
SELECT * FROM usuarios WHERE atuacao_usuario = 1 OR atuacao_usuario = 2 ...

Para fazer isso automaticamente. Seu código ficará assim:
$array_atuacao = array(1,5,8,7);

$sql_func = "SELECT * FROM usuarios WHERE ";

foreach($array_atuacao as $atuacao){

    $sql_func .= "atuacao_usuario = ".$atuacao." OR ";

}

$sql_func .= substr($sql_func, 0, -3);

$result_func = $mysqli->query($sql_func);

    while($func = $result_func->fetch_assoc()) {

        echo $func['nome_usuario'] .' - '.$func['atuacao_usuario'];
    };

Ou, como citado pelo @LeoCaracciolo, você pode usar o IN
SELECT * FROM usuarios WHERE atuacao_usuario IN (1,2,3,4)

EDIT
Tente fazer assim:
$array_atuacao = array(1,5,8,7);

$sql_func = "SELECT * FROM usuarios WHERE ";

foreach($array_atuacao as $atuacao){

    $sql_func .= "FIND_IN_SET('$atuacao', atuacao_usuario ) OR ";

}

$sql_func .= substr($sql_func, 0, -3);

Comment: Você pode usar a cláusula IN para substituir muitas condições OR
Comment: Valew @AndreiCoelho, deu certo aqui, so alterei oma concatenação que veio ai na consulta, mas funcionou certinho aqui, obrigado!!
Comment: @MarcosPaulo não esquece de aprovar! Abraço!
Comment: @LeoCaracciolo sim. Vou colocar essa opção.
Comment: Colocando em produção, não deu certo, so funciona se a o primeiro id ( ID da atuacao ) vier marcado.

Onde posso colocar um exemplo funcional?
Ai vc tera uma ideia melhor
Comment: "so funciona se a o primeiro id ( ID da atuacao ) vier marcado" como assim?
Comment: Melhor você inserir tudo na pergunta... HTML, PHP, etc..
Comment: Ok, acabei de editar a pergunta
Comment: @AndreiCoelho, coloquei um exemplo online
http://consultoriatelejet.com.br/teste.php?id=5,1

Muda os id`s de acordo com a busca
Comment: Vamos [continuar esta discussão no chat](https://chat.stackexchange.com/rooms/76761/discussion-between-andrei-coelho-and-marcos-paulo).


Degree of freedom in statistic

Question: I am always having difficulty understanding what degree of freedom really is.
I know that when I post this question people are going to tell me to do some research myself but I did it and I am still having problem understanding it.
I watched youtube videos and read articles ...etc but I still do not understand.
To be specific, let me tell you where I am stuck.
For example
If we have a sample size of 3
{x1,x2,x3} is the set of sample values
At the same time, we assume that we know the sample mean is going to be equal to be 2
knowing there are 3 variables, the first 2 variables can be anything.
Say,
x1 = 1,
x2 = 4.
With  simple calculation we know x3 must be 1 for the sample mean to become 2. In another word, when first and second variables are determined, the third variable must be specific value(not free to be any value) to meet the fact that sample mean must be 2.
Ok, until this point everything makes sense to me.
When it comes to calculating the variance, I am totally confused.
In each and every videos and articles I watched and read always says the same thing. The reason why degree of freedom for estimating the variance is N-1, which N is the sample size. The reason for that is because we know the sample mean is going to equal to specific value in the first place. This logic sound quite contradicting to me!!
The reason why we need a sample mean instead of the population mean is because we do not know the value of population mean in the first place. Now you are telling me that we know the sample mean is going to be specific value as if we already know the population mean? In another word, if we don't know what the population mean is, how are we possibly going to know what value our sample mean is even close to?
Does not the entire concept just sound contradicting? Maybe it is just because of my lack of knowledge but if that is the case, can anyone help me out by explaining to me the concept in simple English?
To summarise the question:
I do not understand why in the first example, we want to assume the sample mean is going to be 2, since in reality when we draw a sample from a population we don't even know the population mean, so how are we going to know sample mean is going to be 2?

@ImATurtle, Thanks for your detailed answer. In response to your answer, I understood that knowing the sample mean is necessary for calculating sample variance. However, my problem is I don't really get how you are going to know the sample mean before you even know all your sample values in the first place. For example, given sample values are {2,3,4,5,6}, we know that the sample mean is 4 only after you draw the sample and do the calculation . The five sample values were freely drawn from the population without doubt. Yet, people keep on saying that we know the sample mean will be 4, therefore after drawing the sample values 2,3,4,5, we know the fifth value is 6. So, what make it possible for us to predict the sample mean is going to be 4 before we even start drawing samples from population?
Answer: Let $(X_1,\ldots,X_n)$ be a simple random sample from normal distribution $\mathcal{N}(\mu, \sigma^2)$ with mean $\mu$ and variance $\sigma^2$. We can write this vector as
$$
(X_1, \ldots, X_n) = \bar{X}_n (1, \ldots, 1) + (X_1 - \bar{X}_n, \ldots, X_n - \bar{X}_n) .
$$
The first vector in this sum belongs to $1$-dimensional vector space $H
=\{\lambda (1, \ldots, 1) | \lambda \in \mathbb{R}\}$ spanned by the vector
$(1, \ldots, 1)$ and the second vector belongs to $(n - 1)$-dimensional vector
space $H^{\bot} =\{(x_1, \ldots, x_n) \in \mathbb{R}^n | x_1 + \cdots + x_n =
0\}$ (you can check that the sum $X_1 + \cdots + X_n - n \bar{X}_n = 0$).
Vector spaces $H$ and $H^{\bot}$ are orthogonal in the sense that for each $u
\in H$ and $v \in H^{\bot}$
$$\langle u, v \rangle = 0$$
where $\langle (u_1, \ldots, u_n), (v_1, \ldots, v_n) \rangle = u_1 v_1 +
\cdots + u_n v_n$ is the standard scalar product on $\mathbb{R}^n$, and
vectors $\bar{X}_n (1, \ldots, 1)$ and $(X_1 - \bar{X}_n, \ldots, X_n -
\bar{X}_n)$ are called the orthogonal projections of vector $(X_1,
\ldots, X_n)$ on vector spaces $H$ and $H^{\bot}$.
We estimate the variance $\sigma^2$ by the sample variance
$$S_n^2 = \frac{1}{n}  \sum_{i = 1}^n (X_i - \bar{X}_n)^2 $$
that is, the sum of squares of coordinates of random vector $(X_1 - \bar{X}_n,
\ldots, X_n - \bar{X}_n)$ we already encountered as an orthogonal projection
of vector $(X_1, \ldots, X_n)$ on the $(n - 1)$-dimensional vector space
$H^{\bot}$ and degrees you ask about corresponds to dimension of vector space
$H^{\bot}$, since then, by Cochran's theorem, $S_n^2$ has $\chi^2$ distribution
with $n - 1$ degrees of freedom.
You could say that, when you estimate parameters $(\mu, \sigma^2)$ of normal
distribution with $(X_n, S_n^2)$ of $n$ degrees of freedom in the sample, $1$
goes into estimation of $\mu$ and remaining $n - 1$ into estimation of
$\sigma^2$.
Answer: My understanding is that if we observe the statistic for the sample variance as being
$$s^2= \frac {\sum_{i=1}^{n} (y_i - \bar y)^2}{n-1}$$
because it is an $\mathbf{unbiased}$ $\mathbf{estimator}$ for the variance. Unbiased simply means that with repeated trials, we observe a convergence under probability of $s^2$ to $\sigma^2$; as $n \rightarrow \infty$, the probability that $s^2=\sigma^2$ is equal to 1. This follows all follows from that fact that
$$\frac{(n-1)s^2}{\sigma^2} \sim \chi^2 (\mathbf{df}=n-1)$$
(And also the fact that the $\chi^2$ distribution is just a special case of the Gamma distribution)
For a less theoretical explanation, I can tell you that you do need to know the sample mean in order to be able to calculate the variance; you cannot calculate deviance from the mean without knowing what the mean is. The same data used to calculate the mean is used to calculate the variance.. So the sample mean is inherently "fixed within the data" if you'd like.
Maybe I've just not fully understood your question. I'd be happy to elaborate more on specific parts if you wish.
Answer: This is late but I'm wondering if I understand things correctly as well.
The way I see it, the sample mean is obtained from other sample means and is used to predict the population mean and variance, as well as the mean and variance for other samples.
Anyway, I think that it's N-1 because a sample of size 1 has a mean, itself, but doesn't have a variance. For chi-square, which gives the distribution of (the sum of the squares of the distance from the mean) of N standard normal random variables, will need to sum N-1, or V, squares. This gives the distribution of the distance for each random variable to the true mean. The t distribution is the normal distribution for the whole population divided by the square root of the average (ratio of the sample variance to the true variance), that had N-1 degrees of freedom. The distribution of the whole population divided by the ratio of the standard deviation of the sample to the standard deviation of the whole. This changes the variance of the t distribution according to degrees of freedom for the sample standard distribution.
Comment: If you're wondering about something and need to ask about it, please [ask](https://math.stackexchange.com/questions/ask) a new question.

Degree of freedom in statistic


How to maintain full width image aspect ratio until specific height, but then crop height?

Question: I want my images to maintain their full width and aspect ratio until they reach 600px height, at which point they crop the height (and still maintain full width). This is where it gets tricky for me because I want to avoid using background-image to accomplish my goal.
Most of my images are 1920x1080 aspect ratio, so once the screen gets smaller than 1070px, the default aspect ratio should be fine. The image auto-scales to 1070x600 for 1070px screens, or 800x450 for 800px screens, or 400x225 for 400px screens, and so on. All good.
But once the screen is bigger than 1070px, the default aspect ratio no longer works for me because height creeps past 600px. I'd like the images to auto-crop to a 600px height at this point, keeping the full width intact:

For 1920px screens: crop the image to 1920x600
For 1500px screens: crop the image to 1500x600

And so on.
add_image_size( 'jd-custom-size', 1920, 600, true ); isn't enough because at a small screen, i.e. 800px, it crops the image to 800x250.
add_image_size( 'jd-custom-size', 9999, 600, true ); creates the same problem.
I'm sure I'm not the first person with this goal, but I'm not quite sure how to google it. Most search queries just turn up basic add_image_size questions.
Any ideas?
Comment: max-height + object-fit, or just max-height if a container wraps them ... any code/snippets to share and show your actual issue ? :) for the html/css part  else you also have http://php.net/manual/en/function.imagecrop.php combined with srcset in html could also be usefull to load an alternative image
Comment: I think you can change the image dinamically by detecting first the screen size
Comment: G-Cyr, this is exactly what I needed. The other responses on this thread could work, but only at specific breakpoints. This one crops 1px at a time until it reaches a 1070px screen, at which point I can turn off the height restriction. If you want to post a formal answer, I'll mark it as correct.

I basically set a div around the image, added `width: 100%; height: 600px;` to the div, and then gave the img `width: 100%; height: 100%; object-fit: cover;`

Then inside my existing 1024px media query, I gave the div `height: 100%;` to remove its 600px restriction and it works beautifully.
Answer: You can use the new srcset and sizes html attributes to achieve that by just passing the cropped image src for each resolution you want:

You can set any unit you want w and h means the real image width and the real image height.
Useful links:

https://css-tricks.com/responsive-images-css/
https://developer.mozilla.org/en-US/docs/Learn/HTML/Multimedia_and_embedding/Responsive_images
Answer: Have you looked at using the CSS clip, combine this with a media query and the solution could be css only.
@media only screen and (min-width : 1500px) {
.myimg{
    position: absolute;
    clip: rect(0px,1500,600px,0px);
}
}

@media only screen and (min-width : 1960px) {
    .myimg{
        position: absolute;
        clip: rect(0px,1960,600px,0px);
    }
    }

Alternatively you could use javascript to get more specific and set the
$(".myimg").css("clip",'rect(0px,1960,600px,0px)');

based on screen detection of width?


Why are the edges of my app icons being cut off?

Question: I have this png image that I want to use as the icon for my application:

I use this on a web application as the save to home screen icon:
<code><link rel="apple-touch-icon" sizes="180x180" href="apple-touch-icon.png" />
</code>
But when I put it on the home screen, it cuts off the corners of the icon:

And the same issue happens when I build an Android app with Meteor, with resized versions of the same image configured as the android_mdpi/android_hdpi/android_xhdpi/android_xxhdpi/android_xxxhdpi icon:

How can I prevent the edges of my icon being cut off like this?
Answer: Depending on your launcher users can change the icon shape on their phone and it automatically changes your icon to the chosen shape.
You can change this at Home Settings -> Change Icon Shape
So you can not prevent the edges being cut off, but in your app, you can define different icons for the different shapes. More information about the adaptive icons:
https://developer.android.com/guide/practices/ui_guidelines/icon_design_adaptive


mail could not send through iphone sdk?

Question: i want to send mail through iphone sdk i know there are lots of answers here on stack overflow but it does not work ,i downloaded the mail composer app from apple site and ran in my simulator ,it displaye that mail has been sent but i dont get it on my email address
Comment: What exactly doesn't work? What did you try, what did you expect to happen, and what happened instead? This question is unanswerable in its current form.
Comment: @shaggy: he wants to send mails using mailcomposer thriugh simulator and he is getting the ack that mail is sent but he is not getting the mail in his inbox. Dats the question. Possible duplication of `http://stackoverflow.com/questions/3520508/cannot-send-email-in-iphone-simulator/3520727#3520727`
Answer: You cannot test mail and message compose controllers in simulator. Mail composer uses the default mail account set up on your device to send the mail. There is no mail account set up in the simulator.
Test it on device...
Answer: YOU CANNOT send mails through simulator. It just shows mail sent for the acknowledgement that your mail code is working and wont crash or have any errors..
For testing you have to use device. SIMULATOR shows you the composer but will never send mail as the mailclient is not installed in it..
hAPPY cODING...
Comment: thanks i hope u r right and can u plz tell can we schedule our mail to send with iphone sdk
Comment: Dont hope.. I am 110% correct in the above case... By schedule Do you mean that you wanna send the mail after several interval of time?
Comment: yes i can use a date picker for that but how to connect the two so that mail can send automatically
Comment: cannot send mail automatically as for sending mail mail composer needs to be opened. The thing you can do is send the time and mailcontent to the server and do the coding of sending mail automatically on serverside maybe PHP. As per my knowledge(correct me if i am wrong) We cannot send mails automatically or without opening composer

mail could not send through iphone sdk?


Binary or multinomial logit?

Question: I am having some doubts on whether I should use binary or multinomial logit.
I am modelling product choice. The dependent variable is the choice of either shampoo or toothpaste. Although my dependent variable has two outcomes, I am wondering whether it is appropriate to use multinomial logit instead of binary.
The case is that the customer does not choose among these two products, but among the whole assortment. And I have taken a sample for only 2 products.
Do you think I should use the multinomial logit?
Comment: You'd use a binary logit (=logistic regression) if the choices were mutually exclusive. Is it possible that someone buys both shampoo and toothpaste?
Comment: Yes, i also thought of that. I am actually modelling another products ( anti-acne and medical shampoo) that appear to be mutually exclusive. I ran market basket analysis first to see if they are sold together and they are not. Then I guess its ok to use binary logit. Thanks a lot :)

But what if they are not mutually exclusive? There will be some bias in results i guess..
Comment: Please amend your question, then, to fully reflect what you are trying to do. It sounds like you might be analyzing all of the choices a consumer could make - that is a different problem from the one you posted.
Comment: The whole assortment consists of 67 aggregated product categories. My whole idea is to filter the categories of interest ( shampoo and toothpaste for example) and to see what influences the choice of either shampoo or toothpaste (or both). But If I want to test the option for not buying any of them, I don't know how to do this.
The problem is that my independent variables are limited - day and time of purchase. And I am trying to test how the seasons and different times of the day ( morning, afternoon, and evening) influence the purchase probability of certain products.
Answer: In addition to @HongOoi 's point, could a person buy neither ? Then you;d have four choices:
<code>Both
Toothpaste
Shampoo
Neither
</code>
It's not exactly clear what your sample is, but it seems to me you have to have these four choices. In that case, multinomial logit is correct.
However, if your sample includes only people who bought one or the other but not both, you could use (ordinary) logistic. Then you would be comparing people who bought toothpaste to people who bought shampoo.
Comment: I agree with @Peter_Flom. It is usually important to include in the model the option of not buying anything. This makes a third option and it is therefore better to have a multinomial outcome model.
Answer: Late answer, but maybe useful for others:
In a binary Choice Model, we estimate
$$\text{Pr}(y_i = 1 \mid x_i) = \frac{\text{exp}(\bf{x_i^\prime \beta_j})}{1+\text{exp}(\bf{x_i^\prime \beta_j})}$$
and in a Multinomial Logit we estimate
$$\text{Pr}(y_i = j \mid x_i) = \frac{\text{exp}(\bf{x_i^\prime \beta_j})}{1+\sum_{h=2}^J \text{exp}(\bf{x_i^\prime \beta_h})}, j = 2\text{,...,}J$$
The first choice $j = 1$ is omitted, because it is taken as the baseline (as is the $0$ choice in the binary logit). When you now set $J=2$ as it is in your case (disregarding the valid objections made by Peter Flom) you get exactly the same as in the binary choice model:
$$\frac{\text{exp}(\bf{x_i^\prime \beta_j})}{1+\sum_{h=2}^{J=2} \text{exp}(\bf{x_i^\prime \beta_h})} = \frac{\text{exp}(\bf{x_i^\prime \beta_j})}{1+\text{exp}(\bf{x_i^\prime \beta_j})}$$
Just be aware that by the definitions above, you have the choice between $0,1$ in the binary choice model and between $1,2$ in the multinomial choice model (with two choices).

Binary or multinomial logit?