Tough quadrilogarithm integral

Question: Solve the follolwing definite integral
$$\int \frac{\operatorname{Li}_4(z)}{1-z}\, dz$$
It is easy for lower powers!
Comment: If it's a definite integral, you forgot the endpoints.
Comment: It is easy to observe that the antiderivative can be found once we know how to evaluate $$ \int \frac{\mathrm{Li}_{2}^{2}(z)}{z} \, dz, $$ which I don't quite know how to manage.
Comment: @sos look at the following http://math.stackexchange.com/questions/462389/definite-dilogarithm-integral-int1-0-frac-operatornameli-22xx-dx?noredirect=1#comment995278_462389
Comment: I think we can use the following generating function

$$\sum_{n\geq 0} H^{(m)}_n z^n = \frac{\operatorname{Li}_m(z)}{1-z}$$
Comment: @Sangchul Lee; The integral in question is crucial if we want to find generating functions of quantities like $H_n^{(m)}/n^q$ where $m+q \ge 5$ and $n$ is a positive integer (see http://math.stackexchange.com/questions/1919402/a-family-of-generating-functions-related-to-generalized-harmonic-numbers-and-pow) . I wonder have you achieved any progress in tackling this integral ?
Answer: Wolfram's integrator can't find it. But it's a relatively simple matter to get a solution in terms of the Kampé de Fériet hypergeometric function:
http://en.wikipedia.org/wiki/Kamp%C3%A9_de_F%C3%A9riet_function
as
$$\int \frac{\mathrm{Li}_4(z)}{1 - z} dz = \frac{z^2}{2}\ ^{1+5}f_{1+4} \left(\begin{matrix}2 : 1, 1; 1, 1; 1, 1; 1, 1; 1, 1; \\ 3 : 2, 1; 2, 1; 2, 1; 2, 1;\end{matrix} z, z\right) + C$$.
To get this solution, first write
$$\frac{\mathrm{Li}_4(z)}{1-z} = \sum_{m=1}^{\infty} \frac{z^m}{m^4 (1-z)}$$
Now, expand
$$\frac{z^m}{1-z} = z^{m-1} \frac{z}{1-z} = z^{m-1} \sum_{n=1}^{\infty} z^n = \sum_{n=1}^{\infty} z^{n+m-1}$$.
So,
$$\sum_{m=1}^{\infty} \frac{z^m}{m^4 (1-z)} = \sum_{m=1}^{\infty} \sum_{n=1}^{\infty} \frac{z^{n+m-1}}{m^4}$$.
Then integrate term-by-term and rewrite with the lower summation indices as 0:
$$\begin{align}\int \left(\sum_{m=1}^{\infty} \sum_{n=1}^{\infty} \frac{z^{n+m-1}}{m^4}\right) dz &= C + \sum_{m=1}^{\infty} \sum_{n=1}^{\infty} \frac{z^{n+m}}{m^4 (n+m)} \\ &= C + z^2 \sum_{m=0}^{\infty} \sum_{n=0}^{\infty} \frac{z^n z^m}{(m+1)^4 (n+m+2)}\end{align} \tag{*}$$.
Now, from the definition of the hypergeometric function:
$$^{p+q} f_{r+s}\left(\begin{matrix}a_1, ..., a_p: b_1, b_1'; ...; ; b_q, b_q' ; \\ c_1, ..., c_r : d_1, d_1' ; ... ; d_s, d_s' ;\end{matrix} z, w\right) = \sum_{m=0}^{\infty} \sum_{n=0}^{\infty} \frac{(a_1)_{m+n} ... (a_p)_{m+n}}{(c_1)_{m+n} ... (c_r)_{m+n}} \frac{(b_1)_m (b_1')_n ... (b_q)_m (b_q)_n}{(d_1)_m (d_1')_n ... (d_s)_m (d_s')_n} \frac{z^m}{m!} \frac{w^n}{n!}$$
the ratio of coefficients of $z^m z^n$ with respect to $m$ (including the factorials) is
$$R_{m,n} = \frac{(a_1+m+n)...(a_p+m+n)}{(c_1+m+n)...(c_r+m+n)} \frac{(b_1+m)...(b_q+m)}{(d_1+m)...(d_s+m)} \frac{1}{m+1}$$
and with respect to $n$,
$$S_{m,n} = \frac{(a_1+m+n)...(a_p+m+n)}{(c_1+m+n)...(c_r+m+n)} \frac{(b_1'+n)...(b_q'+n)}{(d_1'+n)...(d_s'+n)} \frac{1}{n+1}$$.
The ratio of the coefficients of the series marked (*) with respect to $m$ is
$$\frac{(m+1)^4 (n+m+2)}{(m+2)^4 (n+m+3)} = \frac{(m+n+2)}{(m+n+3)} \frac{(m+1)(m+1)(m+1)(m+1)}{(m+2)(m+2)(m+2)(m+2)}$$
and with respect to $n$,
$$\frac{(m+n+2)}{(n+m+3)}$$.
So we see that we should assign $a_1 = 2$, $c_1 = 3$, and $b_{1...5} = 1$, $d_{1...4} = 2$, with one extra factor on b to cancel the factor resulting from the factorial. Then set $b_{1...5}' = 1$ and $d_{1...4}' = 1$ to cancel the $b'$/$d'$ stuff and the other factor resulting from the factorial. This means $p = 1$, $r = 1$, $q = 5$, and $s = 4$. The normalization factor $\frac{1}{2}$ is because the setting of the $a$s, etc. only determines the ratio of terms, and not the initial value to which the multiplication by the ratio is applied, which is given by the term with index $m = n = 0$, which in series (*) is $\frac{1}{2}$. This then gives the desired result for the integral.
Comment: Your idea of linking the result in terms of Kampé de Fériet function is very good, but you don't really afraid that your procedure will have chance that only valid for $|z|<1$ ? If so, how about for $|z|\geq1$ ?
Comment: One should be able to analytically extend the function. This allows one to define the integral at real $z < -1$. In the complex plane, $z = 1$ is a branch point, so it is ambiguous for real $z > 1$ and not real-valued there. It can, of course, be extended to the cut plane, a Riemann surface, or as a multivalued "function".
Answer: I think the best approach that can work on most ranges of $z$ should be as follows:
$\int\dfrac{\text{Li}_4(z)}{1-z}dz$
$=-\int\text{Li}_4(z)~d(\ln(1-z))$
$=-\ln(1-z)\text{Li}_4(z)+\int\ln(1-z)~d(\text{Li}_4(z))$
$=-\ln(1-z)\text{Li}_4(z)+\int\dfrac{\ln(1-z)\text{Li}_3(z)}{z}dz$
$=-\ln(1-z)\text{Li}_4(z)-\int\text{Li}_3(z)~d(\text{Li}_2(z))$
$=-\ln(1-z)\text{Li}_4(z)-\text{Li}_2(z)\text{Li}_3(z)+\int\text{Li}_2(z)~d(\text{Li}_3(z))$
$=-\ln(1-z)\text{Li}_4(z)-\text{Li}_2(z)\text{Li}_3(z)+\int\dfrac{(\text{Li}_2(z))^2}{z}dz$
Then substitute $\text{Li}_2(z)=\sum\limits_{n=1}^\infty\dfrac{z^n}{n^2}$ for $|z|\leq1$ , $\text{Li}_2(z)=\dfrac{\pi^2}{3}-\dfrac{(\ln z)^2}{2}-\sum\limits_{n=1}^\infty\dfrac{1}{n^2z^n}-i\pi\ln z$ for $z\geq1$ and $\text{Li}_2(z)=-\dfrac{\pi^2}{6}-\dfrac{(\ln(-z))^2}{2}-\sum\limits_{n=1}^\infty\dfrac{1}{n^2z^n}$ for $z\leq-1$ respectively for example according to Short calculation of the dilogarithm? for further calculation.
Answer: I know that this is not the full answer but I think at least it is a step in the right direction. Firstly define:
\begin{equation}
J^{(p)}_q(x) := \int\limits_0^x [\log(\frac{x}{t})]^p \frac{Li_q(t)}{1-t} dt
= p!\sum\limits_{n=1}^\infty \frac{H^{(q)}_{n-1}}{n^{p+1}} x^n
\end{equation}
As it has been noted in the previous answers integrating by parts and using the properties of the polylogarithms we easily get:
\begin{equation}
J^{(0)}_4(x)=\int\limits_0^x \frac{Li_4(t)}{1-t} dt = \sum\limits_{l=1}^2 Li_l(x) Li_{5-l}(x) (-1)^{l-1} + (-1)^{2} \int\limits_0^x \frac{[ Li_2(t)]^2}{t} dt
\end{equation}
We will tackle the second integral again by using integration by parts but in a slightly different way . We write $1/t = \log(t)^{'}$ and we integrate by parts three times . Our aim is to reduce the order of the polylogarithm from two to zero. At the first step we compute the antiderivative of $\log(t) \cdot \frac{Li_1(t)}{t}$  and at the second step we compute the antiderivative of the product of the later  with $1/t$. As a result of that process we obtain the following:
\begin{equation}
J^{(0)}_4(x)=\int\limits_0^x \frac{Li_4(t)}{1-t} dt = -\frac{1}{3} Li_2(x) Li_3(x) + Li_1(x) Li_4(x) - \frac{2}{3} \underbrace{\int\limits_0^x \log(\frac{x}{t}) \frac{Li_3(t)}{1-t} dt}_{J^{(1)}_3(x)}
\end{equation}
In terms of Euler sums the result reads:
\begin{eqnarray}
J^{(0)}_4(x)=\sum\limits_{n=1}^\infty \frac{H^{(4)}_{n-1}}{n} x^n &=& -\frac{1}{3} Li_2(x) Li_3(x) + Li_1(x) Li_4(x) - \frac{2}{3}\sum\limits_{n=1}^\infty \frac{H^{(3)}_{n-1}}{n^2} x^n \\
&=& -Li_2(x) Li_3(x) + Li_1(x) Li_4(x)
+2 \sum\limits_{n=1}^\infty \left(\frac{H_{n-1}^{(2)}}{n^3}+2\frac{H_{n-1}}{n^4}\right) x^n \\
&=&-Li_2(x) Li_3(x) + Li_1(x) Li_4(x)
+  J^{(2)}_2(x) + \frac{2}{3} J^{(3)}_1(x) \\
&=&-Li_2(x) Li_3(x) + Li_1(x) Li_4(x)
+  J^{(2)}_2(x) + 4 S_{3,2}(x)
\end{eqnarray}
In the second line we used the series expansion of $Li_2 (x) Li_3(x)$ to eliminate the appropriate Euler sum and in the last line we used A family of generating functions related to generalized harmonic numbers and power functions. . Here $S_{3,2}(x)$ is the generalized Nielsen polylogarithm. Now the only thing we need to compute if $J^{(2)}_2$.

Tough quadrilogarithm integral


How to prove this binomial distribution

Question: Assume that X1 ∼ P(µ1) and X2 ∼ P(µ2) are independent. Prove that the conditional
distribution of X1 under the condition X1 + X2 = N to be the binomial distribution B(N, p),where p = µ1/(µ1 + µ2).
How to do it ? I tried moment generating function but how to transform it into a binomial form?
Comment: Are $X_1$ and $X_2$ supposed to be Poisson distributed? What have you tried so far?
Comment: Yes they are Poisson distributed. I thought it can be solved by proving the M(t) of X1 is similar to M(t) of binomial distribution
Answer: Guide:

First prove that $X_1+X_2\sim\mathsf{Poisson}(\mu_1+\mu_2)$ e.g. by finding an expression for $P(X_1+X_2=k)=\sum_{i=0}^kP(X_1=i\wedge X_2=k-i)$
Now find an expression for $P(X_1=k\mid X_1+X_2=N)=\frac{P(X_1=k\wedge X_2=N-k)}{P(X_1+X_2=N)}$
Comment: Thanks, i am trying your way
Comment: i have more question why it is not P(X1+X2 = k) = P(X1 = i and X2 = k - i)
Comment: i mean why it's a sum
Comment: i have solved it by not using the summation, thank you~
Comment: E.g. $X_1+X_2=1\iff X_1=0$ and $X_2=1$ **or** $X_1=1$ and $X_2=0$. So the probability of LHS will be the **summation** of both probabities on RHS.

How to prove this binomial distribution


Compare client side validation always failing on an editor template

Question: I have a view model with an Email address property and a Confirm Email Address property, as shown below:
public class UserNewModel
{
    [Required]
    [StringLength(100)]
    [DataType(DataType.EmailAddress)]
    [Display(Name = "Email Address")]
    public string EmailAddress { get; set; }

    [Required]
    [StringLength(100)]
    [DataType(DataType.EmailAddress)]
    [Display(Name = "Confirm Email Address")]
    [Compare("EmailAddress", ErrorMessage = "The email address and confirmation email address do not match.")]
    public string ConfirmEmailAddress { get; set; }

}

There is a corresponding EditorTemplate strongly typed to this model:
@model SponsorworksSaaS.UI.Models.UserNewModel

    @Html.LabelFor(m => m.EmailAddress)

    @Html.EditorFor(m => m.EmailAddress)
    @Html.ValidationMessageFor(m => m.EmailAddress)

    @Html.LabelFor(m => m.ConfirmEmailAddress)

    @Html.EditorFor(m => m.ConfirmEmailAddress)
    @Html.ValidationMessageFor(m => m.ConfirmEmailAddress)

My UserNewModel is then contain in other  models, such as:
public class CompanyDetailsModel
{
    ....

    ///
    /// Used to capture the initial user account details when creating a new company
    ///
    [Display(Name = "Initial User Account")]
    public UserNewModel NewCompanyUser { get; set; }

}

and the corresponding strongly typed view associated with this parent model uses @Html.EditorFor to display the editor template:
@model SponsorworksSaaS.UI.Models.CompanyDetailsModel

@using (Html.BeginForm())
{
    @Html.ValidationSummary(true, "Company change was unsuccessful. Please correct the errors and try again.")

        <fieldset>
            <legend>Company Information</legend>

               @Html.EditorFor(m => m.NewCompanyUser)

                <input type="submit" name="btnSubmit" value="Save Company" />

        </fieldset>

}

The compare validation at client side always fails for the email address. If I enter an identical string in the compare email address text box, it always shows the compare validation error message when I move the focus away. Even with the compare validation showing a fail at client side, if I submit the form the ModelState.IsValid is true, although I am not sure if there is any compare validation done at server side.
The view source generated is shown below:

    Email Address

    <input class="text-box single-line" data-val="true" data-val-length="The field Email Address must be a string with a maximum length of 100." data-val-length-max="100" data-val-required="The Email Address field is required." id="NewCompanyUser_EmailAddress" name="NewCompanyUser.EmailAddress" type="text" value="" />

    Confirm Email Address

    <input class="text-box single-line" data-val="true" data-val-equalto="The email address and confirmation email address do not match." data-val-equalto-other="*.EmailAddress" data-val-length="The field Confirm Email Address must be a string with a maximum length of 100." data-val-length-max="100" data-val-required="The Confirm Email Address field is required." id="NewCompanyUser_ConfirmEmailAddress" name="NewCompanyUser.ConfirmEmailAddress" type="text" value="" />

I have tried adding single quotes to the jquery.validate.unobtrusive.js file, as suggested on other posts here, but this did not fix the problem.
element = $(options.form).find(":input[name=" + fullOtherName + "]")[0];

changed to:
element = $(options.form).find(":input[name='" + fullOtherName + "']")[0];

I have also tried using both the min and full js files, but the problem remains the same. In fact if I add some jquery to the ready function:
$(function () {
    var e1 = $('form').find(":input[name=*.EmailAddress]");
    var e2 = $('form').find(":input[name='*.EmailAddress']");
    alert(e1);
    alert(e1[0]);
    alert(e2);
    alert(e2[0]);
});

The alert(e2[0]) returns undefined, but alert(e1[0]) returns the expected text box element.
Comment: Where is the ``? I can't see it anywhere. How are you submitting it?
Comment: The whole view is inside a @using (Html.BeginForm()) {} statement. The validation fails long before the submit occurs, at client-side. I have edited the code above to show the BeginForm() statement.
Answer: Turns out it was the known error in the jquery.validate.unobtrusive.js file. I forgot to clean out the old cached copy! D'oh! The offending line of code is on line 284 in my version of the file 9in case anybody else needs to change it). A search for equalto will get close to the correct section of code.
A clean solution from Visual Studio was enough to do the trick.
I haven't managed to get the  jquery.validate.unobtrusive.min.js file to work though, despite changing the
b.add("equalto",["other"],function(b){var h=g(b.element.name),i=b.params.other,d=e(i,h),f=a(b.form).find(":input[name="+d+"]")[0];c(b,"equalTo",f)});

to
b.add("equalto",["other"],function(b){var h=g(b.element.name),i=b.params.other,d=e(i,h),f=a(b.form).find(":input[name='"+d+"']")[0];c(b,"equalTo",f)});

Note the single quotes around the "+d+" in the find method call.


p-values in multiple linear regression depend on number of predictors?

Question: So I am wondering if there usually is any "correction" being made to p-Values (of single predictors) if you add more predictors to the model? Does anybody know how SPSS handles this?
I am well aware that change of a predictors p-value after including another variable could occur due to 1) the predictors effect (regression coefficient) having changed and 2) because the sample size has decreased (if some of the previously included cases have a missing value at the newly included predictor and we use listwise exclusion). But could a change also be due to 3) the model taking into account that when I test a higher number of predictors, the likeliness of one attaining an effect of a given strength rises?
Comment: if you add more predictors to the model?  I do not think that it should affect  p--value! Why - correction  is invoked.
Answer: There are two things to consider here.
First, the p value reported for an individual coefficient in a standard linear regression is based on a t-test. As that test uses an estimate of the standard error taken from the data, the reliability of the standard error estimate depends on both the number of observations and the number of parameters that are estimated. The degrees of freedom in the t-test decrease as the number of estimated parameters increases: $(N-P)$ for $P$ parameters estimated from $N$ observations. That's the level of correction for numbers of parameters in the p-values reported by standard statistical software from the t-tests for regression coefficients. Note that if the number of parameters estimated is much smaller than the number of observations, this adjustment won't make much of a difference.
Second, which I take to be the basis of your question, is the matter of multiple comparisons, the idea that the more significance tests you perform the more likely you are to find one nominally "significant" result simply by chance: a test at p < 0.05 when a null hypothesis is true will be a false positive in 1 out of 20 comparisons. Standard statistical software and published tables of estimated regression coefficients typically do not correct coefficient p -values for multiple comparisons. See the discusssion on this page for some thoughts.
One exception is software used for big-data analyses like gene-expression studies, which builds in important corrections for multiple comparisons. If you tried to rule out any false-positive results among the thousands of nominally "significant" coefficients you would necessarily miss a lot of true positives. In such situations the false discovery rate, the fraction of "significant" findings likely to be false, is typically controlled. See this page among many others on this site.
Comment: the reliability of the standard error estimate depends on both the number of observations and the number of parameters that are estimated.  It is somehow ambigous and incorrect. please check whether it needs to be there.
Comment: Imagine I do an experiment with 20 observations, but the analysis shows non-significative results.
And I repeat the experiment to get 40 more observations and analyze them together with the previous 20.
I guess this is also some kind of multitesting.
What is the simplest correction I can apply to the p-values ?
Comment: @skan That's a different question from the one asked on this page, so please post it as a [new question](https://stats.stackexchange.com/questions/ask). This site works best if each page is devoted to a single question. See [this page](https://stats.stackexchange.com/help/how-to-ask) for advice on how to pose a question.
Comment: @skan when you ask the new question, it would help to be more specific about why the 40 extra observations were performed. One type of situation would be If you had originally planned on doing 60 observations but preliminary analysis on the first 20 didn't turn out to be "significant." It's completely different if you keep increasing the number of observations until you finally get a "significant" result.
Comment: I have opened a new question. https://stats.stackexchange.com/questions/613289/what-is-the-simpler-experiment-design-and-corrections-i-can-use-for-an-adaptativ


Aggregating time series data to one variable

Question: I have got various time series data for different observations. I want to represent one time series observation by one aggregated variable. The easiest one is to take the mean of the time series, but mean does not capture the variations in the observation over time. I thought of computing the distance (dist) between an arbitrary reference and the time series data.
I am curious to know if there is other technique that I could apply to fairly represent the time series observation by one aggregation variable? Is there any R package that I can use?
Thanks
Comment: What you ask is very much application dependent. Can you tell us more on what you are trying to achieve? For example, if your time series represents a stock the best approach would probably be very different than if you want to characterize an EEG signal.
Comment: The time series are traffic data (i.e., speed, count, spacing.... of vehicles on freeways over time on each day). The goal is to  summarize/aggregate each time series by one variable and then apply multi-dimensional scaling to cluster days of similar traffic characteristics.
Comment: Well in that case why do you require only one aggregation variable? Clustering can be done a number of variables...
Answer: One of the goals of control charts is to aggregate information from a complex process into one or more univariate summary statistics. Depending on the process type (stationary, non-stationary etc) and the dimensionality of the process, different control charts can be used. This might suit you well - especially since you considered distances already.
Two simple control chart approaches to consider are the MEWMA and MCUSUM control charts. These methods are implmented in the MSQC package in R. Analytical procedures for these are implemented in the spc package in R.
Montgomery's Introduction to Statistical Process Control provides implementation details, in clear, non-esoteric wording in case you would like to know more.
Both charts will work well if you don't have too many variables (since they require the inversion of a covariance matrix, which can become problematic if variables are highly correlated), and can handle some level of non-stationarity.
To use these methods, you must first train a model on data without faults (this may be no problem for you - perhaps you have none). This means you should select a value of the forgetting factor (MEWMA) or the reference value parameters (MCUSUM) based on a test set if possible. This can be done by cross-validation, or eye-balling it if you are in a rush and this is mostly for data exploratory purposes.
Once you have the parameters of the control charts, you can apply them "in the wild". This will return to you a univariate control chart statistic summarizing the information from your time series, as well as control limits indicating when your process is behaving atypically.


need help on a simple predicate to match any word in a string to a property

Question: Let's say i want to let user search for my objects using a name property of the objects.
I have no problem if the user only enters one word:
e.g: facial
My predicate will be:
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"name CONTAINS[cd] %@", word];

But what if user enter more than one word separated by space?
I want to do sth like:
NSArray *words = [query componentsSeparatedByString:@" "];
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"name CONTAINS[cd] ANY %@", words];

But it doesnt work. Any guidance?
Thanks!
Comment: i know my another option is to do sth like this:

        NSMutableArray *subPredicates = [[NSMutableArray alloc] init];
        for(NSString *word in words)
        {
            NSPredicate *predicate = [NSPredicate predicateWithFormat:@"name CONTAINS[cd] %@", word];
            [subPredicates addObject:predicate];
        }
        predicate = [NSCompoundPredicate andPredicateWithSubpredicates:subPredicates];

but i hope to see if i can use the keyword ANY which i m not familiar with in this scenario
Answer: Another way of doing this (and I just learnt this myself as a result of your question) is to use subqueries. Check this SO question for more details. You can use subqueries in the following manner –
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SUBQUERY(%@, $str, SELF CONTAINS[cd] $str).@count != 0", words];

NSLog(@"%@", [array filteredArrayUsingPredicate:predicate]);

This seems to work as I've tested it myself but this could also be the arcane & obscure way that Dave has mentioned as it finds no mention in the Predicate Programming Guide.
The format for a SUBQUERY can be found here. It's the same link that you will find in the question linked earlier.
Comment: Yeah, `SUBQUERY` is one of those weirder things of `NSPredicate`. Once you get how it works, you can't help but think of a way to use it in almost every situation.
Answer: As you mentioned (correctly) in the comment, you can do this by building a compound predicate predicate, although you'll want to use orPredicateWithSubpredicates, and not the and variant.
That really is the best way to do this.  There are others, but they rely on more arcane and obscure uses of NSPredicate, and I really recommend going with the build-a-compound-predicate route.
Comment: thanks for the confirmation that this is also a good way to go. thanks


Como criar um script para automatizar troca de link no HTML?

Question: estou realizando manutenção em um sistema que possui em uma página centenas de links da seguinte forma:

 Revista alvo  http://exemplo.com

Note que há um texto fora da tag a. O que desejo fazer, colocar esse texto dentro da tag a com o seu suposto href, o exemplo acima ficaria assim:

  Revista alvo

Estou fazendo essa troca na mão mas há centenas e centenas de links, o que torna cansativo a tarefa. Alguém tem alguma ideia de como posso fazer um script para realizar essa tarefa? Pode ser em qualquer linguagem, PHP, JS etc. Tentei ser o mais claro possível,caso não entendam irei tentar explicar novamente, preciso de ajuda pois é urgente, please!
Comment: Usando o Sublime vc faria isso de boa, ele tbm usa expressões regulares para selecionar areas, usei varias vezes essa ideia
Comment: Pesquisa: `([a-zA-Z0-9 ]+)(.*?)+<\/li>$` e o replace: `$1` algo assim, veja esse exmplo: https://regexr.com/3pedc
Comment: Pode me dar um exemplo de como eu faria @WeesSmith? Não manjo de regex
Answer: Atualização: Caso não queira abrir arquivo por arquivo, você pode criar um script PHP para varrer um diretório a procura de arquivo HTML ou outro caso queira. Veja:
Esse script será executado através do Terminal / PowerShell, então receberá um parâmetro o qual será o diretório a ser varrido. Utilize a função glob para varrer o diretório, ela irá receber um parâmetro que será "{$Dir}/*.html" e irá retornar um array caso tenha encontrado algo, se não encontrar, retornara um array vazio e false em caso de erro.

Antes de utilizar o script abaixo, faça um backup!

// Conta quantos argumentos foi informado.
// O primeiro argumento sempre será o nome do arquivo.
$CountArgs = count($argv);

// Verifica se é menor que 2
if ($CountArgs < 2) {
  echo "Informe um diretório!\n\n";
  exit(0);
}
// Verifica se o argumento é um diretório.
else if ( !is_dir($argv[1]) ) {
  echo "O parâmetro informado não é um diretório!\n\n";
  exit(0);
}
// Guarda o argumento na variável.
$Dir = $argv[1];

// Varre o diretório atrás de arquivos html
// depois percorre a array e executa a função.
foreach (glob("{$Dir}/*.html") as $arquivo) {
  alterar_links($arquivo);
}

function alterar_links($Arquivo) {
  // Lê o arquivo, e guarda o conteúdo na variável
  $Conteudo = file_get_contents($Arquivo);
  // Faz a busca usando a expressão regular
  // e modifica usando um callback
  $Alteracoes = preg_replace_callback("|
([\w\s]+)(.*?)<\/li>|",
    function($retorno) {
      return "
{$retorno[1]}
";
    },
    $Conteudo);
  // Abre o arquivo em modo escrita
  $arquivo = fopen($Arquivo,'w+');
  // Escreve as alterações no arquivo
  fwrite($arquivo, $Alteracoes);
  // Fecha
  fclose($arquivo);
}

Importante: Veja que, ao fazer a alteração, não estou deixando espaço entre a tag li e a tag a:
{$retorno[1]}
. Fazendo assim, caso o script leia novamente o arquivo, ele não faz nenhuma alteração.

Referências:

glob
file_get_contents
preg_replace_callback
fopen
fwrite
fclose

Sublime Text
Você pode utilizar Expressões Regulares para agilizar o processo, veja:

([\w\s]+)(.*?)<\/li>$

Explicação:

(.*?): Captura o texto dentro tag "a" incluindo o fechamento da tag
: Captura os atributos da tag "a"
([\w\s]+): Captura o texto antes da tag "a"

Para utilizar no Sublime Text, aperte CTRL+H depois ALT+R para ativar a pesquisa por Expressões Regulares, no campo Find coloque o código acima, já no campo Replace:

$1

Explicação:

$1: Coloca o texto capturado antes da tag "a"
$2: Coloca os atributos capturados da tag "a"

Observe que utilizei [\w\s]+ ao invés de [a-zA-Z0-9 ]+ porque assim você recupera tudo que estiver antes, já [a-zA-Z0-9 ]+ ira capturar apenas letras, números e os espaços.
Answer: Obrigado a todos que me ajudaram, consegui resolver com o script abaixo que obtive dessa resposta do stackoverflow internacional.

<!DOCTYPE html>

  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>

 Revista alvo  http://exemplo.com

 Revista alvo  http://exemplo.com

 Revista alvo  http://exemplo.com

 Revista alvo  http://exemplo.com

 Revista alvo  http://exemplo.com

 Revista alvo  http://exemplo.com

 Revista alvo  http://exemplo.com

 Revista alvo  http://exemplo.com

 Revista alvo  http://exemplo.com

 Revista alvo  http://exemplo.com

 Revista alvo  http://exemplo.com

  Change


Maximizing $ \frac {y + z + yz}{\left( 1 + y + z \right)^2} $

Question: I was solving a WOOT Problem of the Day and I boiled the problem down to finding the maximum value of $$ \frac {y+z+yz}{\left( 1 + y + z \right)^2}. $$Intuitively, this seems to occur when $y=z$, since $y$ is symmetric, and after that, it is easy to find that $$ \frac {y+z+yz}{\left( 1 + y + z \right)^2} \le \frac {1}{3}. $$This seems "intuitive" but is not a proof. Any ideas for a formal proof?
Comment: Well, it would help if you changed the $\ge$ to $\le$
Comment: Presumably you are restricting $y,z$ to be positive?
Comment: What basis do you have for your intuition apart from wishful thinking?
Comment: @almagest Yes. $\mathrm{}$
Comment: Suppose we take $y=1/1000,z=1000$, then we get about 1/1001. What restrictions are you placing on $y,z$ if any?
Comment: @almagest We want the maximum, not the minimum. There is a unique maximum.
Comment: @almagest Oh whoops, thanks!
Answer: Consider the new variables $u=y+z, v=yz$.  The old conditions of $y,z>0$ translate to $u,v>0$.  However, for any fixed $u$, the variable $v$ must lie in $(0,(u/2)^2]$, where the latter is achieved when $y=z$.
Thus, to maximize $\frac{u+v}{(1+u)^2}$, we set $v=(u^2/4)$, which gives the expression $$\frac{u+u^2/4}{(1+u)^2}$$
In particular this proves that $y=z$ at the maximum, which is indeed $1/3$.
Comment: I think there is a mistake in the reasoning: it is true that for fixed $u$, the expression is at most $\frac{u+\frac{u^2}4}{(1+u)^2}$, but this does not imply that the maximum is attained for $y=z$. It is a priori possible that some other $u$ yields an even bigger expression, while $y\neq z$. For example, compare with finding the maximum of $2x$: this is at most $1+x^2$ with equality if $x=1$, but that does not imply that the maximum is attained for $x=1$.
Comment: The reason the maximum is attained for $y=z$ is by maximizing $yz$ over fixed  $y+z$ equal to a positive constant (and $y,z>0$).  This is a simple optimization problem over a line segment.
Comment: It was really confusing with the example of $2x\leq1+x^2$ in mind, but I can see what you mean.
Answer: Note that $$\frac{1}{3}-\frac{y+z+yz}{(1+y+z)^2}=\frac{(1/4) (2 y-z-1)^2+(3/4) (z-1)^2}{3(1+y+z)^2}\ge 0.$$
The equality is attained when $y=z=1$.
Answer: If you compute the derivatives of $$F=\frac {y+z+yz}{\left( 1 + y + z \right)^2}$$ you have, after simplifications $$F'_y=\frac{-y (z+1)+z^2+1}{(y+z+1)^3}$$ $$F'_z=-\frac{y^2-2 y (2 z+1)+(z-2) z+3}{(y+z+1)^4}$$ Using $F'_y=0$ gives $y=\frac{z^2+1}{z+1}$ and the numerator of $F'_z$ simplifies to $$(1+z+z^2)(z^2+2 z-1)=0$$ So the solutions are  $$y=2 \left(-1-\sqrt{2}\right),z=-1-\sqrt{2},F=\frac{1}{18} \left(1-3 \sqrt{2}\right)$$ $$y=2 \left(-1+\sqrt{2}\right),z=-1+\sqrt{2},F=\frac{1}{18} \left(1+3 \sqrt{2}\right)$$


Unable to remove Server HTTP header with Varnish 5

Question: I have the following vcl_deliver subroutine:
sub vcl_deliver {

 # Remove some HTTP-headers:
 unset resp.http.Server;
 unset resp.http.X-Varnish;
 unset resp.http.Via;
 unset resp.http.X-Cacheable;
 unset resp.http.Age;

 return (deliver);
}

Now the strange thing is that every other HTTP header get's removed except the Server header (I've checked with curl and with Google Chrome). When I debug with varnishlog -g raw, I get the following information:
202443 RespProtocol   c HTTP/1.1
202443 RespStatus     c 200
202443 RespReason     c OK
202443 RespHeader     c Server: nginx
202443 RespHeader     c Content-Type: text/html; charset=UTF-8
202443 RespHeader     c Vary: Accept-Encoding
202443 RespHeader     c Cache-Control: no-cache, private
202443 RespHeader     c Date: Sun, 12 Aug 2018 14:19:11 GMT
202443 RespHeader     c X-Frame-Options: SAMEORIGIN
202443 RespHeader     c X-XSS-Protection: 1; mode=block
202443 RespHeader     c X-Content-Type-Options: nosniff
202443 RespHeader     c Content-Encoding: gzip
202443 RespHeader     c X-Varnish: 202443 168601
202443 RespHeader     c Age: 69910
202443 RespHeader     c Via: 1.1 varnish (Varnish/5.0)
202443 VCL_call       c DELIVER                                                                                [7/171]
202443 RespUnset      c Server: nginx
202443 RespUnset      c X-Varnish: 202443 168601
202443 RespUnset      c Via: 1.1 varnish (Varnish/5.0)
202443 RespUnset      c Age: 69910
202443 VCL_return     c deliver
202443 Timestamp      c Process: 1534153462.090447 0.000147 0.000147
202443 RespUnset      c Content-Encoding: gzip
202443 RespHeader     c Accept-Ranges: bytes
202443 Debug          c "RES_MODE 40"
202443 RespHeader     c Connection: close
202443 Gzip           c U D - 0 0 0 0 0
202443 Timestamp      c Resp: 1534153462.090535 0.000235 0.000088
202443 ReqAcct        c 229 0 229 302 0 302
202443 End            c
202442 SessClose      c REQ_CLOSE 0.000
202442 End            c

As we can seee (RespUnset Server: nginx) Varnish is trying to remove the HTTP Server header - but why does it still appear when I debug with curl or Google Chrome?
Answer: You must be using Varnish with nginx "sandwich" for SSL termination:

nginx (SSL) -> Varnish -> nginx

So naturally, after removing Serverheader in Varnish, the nginx (SSL) still sends a header of its own.
The solution is to remove the Server header in nginx as well, e.g. using headers-more nginx module:
more_clear_headers Server;

Comment: Very good, MOLODEZ!


How to prevent submit last questionof a form if there is no answer

Question: I have a form of a survey with questions. First I hide all questions and I show one after another with button Next. I've made validation and it works but only for the last question it is not working. I've provided also Php validation if someone doesn't have JavaScript enabled. Now when you have not chosen an answer for the last question,it does not submit form, but it returns to the first question of survey and you have to choose them again. That's my problem - how to validate last quesion? Here's my code:
$(function () {
    $( document ).ready(hideAllRows);
    $( document ).ready(showFirst);
    $('#button').hide();
});

function hideAllRows(){
    $('#questionsTable tr').each(function() {
        $(this).hide();
    });
}

$(function () {
    $("#next").click(showNextQuestion);
});

var currentInd = 1;
var prevInd = 1;
function showNextQuestion(){
    $(function () {
        var indId = "#"+currentInd;
        prevInd = currentInd - 1;
        var prevId = "#"+prevInd;

        //validation
        var isAnyClicked = false;
        if ($(prevId + " input[type='radio']:checked").val()) {
            isAnyClicked = true;
        }

        if(currentInd > 0 && currentInd  != $('#questions_count').val() && isAnyClicked == false) {
            alert('Моля, отговорете!');
        }

        else {
            //hide previous question
            $(prevId).hide();

            //show next question
            var indId = "#"+currentInd;
            $(indId).show();
            currentInd++;
            if(currentInd  == $('#questions_count').val()) {
                $('#button').show();
                $("#next").hide();
            }
        }
    });
}

function showFirst(){
    $(function () {
        $('#0').each(function() {
            $(this).show();
        });
    });
}

.
<?php

$att=array('id'=>'form');
echo form_open('index/survey_fill/' .$survey_id .'/'. $question_id , $att); ?>
<input type='hidden' name='questions_count' id='questions_count' value='<?php echo count($question); ?>' />

Question

  <?php
    echo validation_errors();
 $index = 0;
    foreach ($question as $row)
    {
        echo "
";
        $index++;
    ?>

        <?php echo "$row->question"; ?>

        <?php echo "<input type='hidden' name='question_id' value='$row->question_id' />"; ?>
        <?php

        $data=array(
            'name' =>  'answer['.$row->question_id.']',
            'value' => '5',
            'class' => 'answer'

        );

        echo "<input type='hidden' name='survey_id' value='$row->survey_id'>";

        echo form_radio($data);
        echo " 5 ";
        $data=array(
            'name' =>  'answer['.$row->question_id.']',
            'value' => '4',
            'class' => 'answer'
        );
        echo form_radio($data);
         echo "4";

    <?php
    }

?>

 <?php echo "<input type='hidden' name='question_id' value='$row->question_id' />"; ?>
  <?php  echo '<input type="submit" id="button" name = "submit" value="Submit" class="btn btn-success">';
  ?>
<input type="button" id="next" name = "next" value="Next" class="btn btn-success">
</form>

I tried with this:
$(document).ready(function() {
    var currentInd=1;
    $('form').on('submit', function(e){
        isAnyClicked = false;

        if (currentInd  = $('#questions_count').val() &&
                ($(currentInd + " input[type='radio']:checked").val())) {
             isAnyClicked = true;
             $(currentInd ).hide();
             alert(" answer selected");
        } if (currentInd  = $('#questions_count').val() && isAnyClicked == false)  {
            $('tr' + currentInd).css({ display: 'block' });

             e.preventDefault();
             alert("select answer");
             currentInd++;
         }
    });
});

It prevents form submit, but even I have selected answer, form does not submit. How to make first condition if you have chosen answer, form to subit? It always run second condition and form does not submit. Thanks!
Answer: You can prevent form to be submitted with following code:
$(document).ready(function() {
  $('form').on('submit', function(e){
    // validation code here
    if(!AllFieldsAreValid) {
      e.preventDefault();
    }
  });
});

You can define AllFieldsAreValid as True or False when all fields are filled correctly or not.
Comment: Form does not send, but it shows me again first question. How to stay on the last question in my case? Last question is when if( currentInd  = $('#questions_count').val()) { I can't do validation for it.
Comment: I could not to find where foreach ($question as $row){ is ended }. I think you can write all code with PHP and visible HTML codes. then using of Jquery for hide/show unneeded sections.
Comment: I edited my question. Now form does not submit even you have chosen some answer of last question. How to do form to submit if you have chosen some answer of last question? :)
Comment: I think
. Problem here now is that even when you choose answer, it doesn't submit form. I think this if does not run: if( currentInd  = $('#questions_count').val() && ($(currentInd + " input[type='radio']:checked").val())) {

          isAnyClicked = true;
          $(currentInd ).hide();
    alert(" answer");

  }
Comment: You must add return true;   after last if . Please use http://jsfiddle.net/ for html part (produced by PHP) and jquery or javascript. So please send link here for more details.


Views AJAX not work in block node.tpl

Question: i have some block with sorting exposed filter on region "tab" and i show his in node.tpl like this:
<code>print render(block_get_blocks_by_region('tab'));
</code>
In my block i not have any problem with AJAX in paginator. But my sorting exposed filter not work at all.
After several hours testing i figured out what my block works ( AJAX sorting filter + paginator) if i show his in any another region on page.tpl.
That things i see in header, if show his through any region on page.tpl:

"better_exposed_filters":{"datepicker":false,"slider":false,"settings":[]},"views":{"ajax_path":"/views/ajax","ajaxViews":{"views_dom_id:7ff6de2549b84f9553122b84f32d822b":{"view_name":"person_books","view_display_id":"block_1","view_args":"61/61","view_path":"node/61","view_base_path":null,"view_dom_id":"7ff6de2549b84f9553122b84f32d822b","pager_element":"0"}}}

That things i see in header, if show his through region "tab" in node.tpl:

"better_exposed_filters":{"datepicker":false,"slider":false,"settings":[]},"views":{"ajax_path":"/views/ajax","ajaxViews":{"views_dom_id:21d228e5cc07884c39ecda6d29b417c4":{"view_name":"person_books","view_display_id":"block_1","view_args":"61/61","view_path":"node/61","view_base_path":null,"view_dom_id":"21d228e5cc07884c39ecda6d29b417c4","pager_element":"0"},"views_dom_id:a94bccf7913b478becb33a3a27ec903d":{"view_name":"person_books","view_display_id":"block_1","view_args":"61/61","view_path":"node/61","view_base_path":null,"view_dom_id":"a94bccf7913b478becb33a3a27ec903d","pager_element":"0"},"views_dom_id:da94f68eea44bf9ead4034e965977935":{"view_name":"person_books","view_display_id":"block_1","view_args":"61/61","view_path":"node/61","view_base_path":null,"view_dom_id":"da94f68eea44bf9ead4034e965977935","pager_element":"0"}}}

How can i fix it? Why views send many view_dom_id in header if i show my block through region in node.tpl?
P.S. i tryed show views through views_embed_view in node.tpl - same things, not helped me :/
Answer: fixed... always, REMEMBER!! always shutdown block in block UI. if not do it, this piece of shit gives something like:

{"view_name":"person_books","view_display_id":"block_1","view_args":"61/61","view_path":"node/61","view_base_path":null,"view_dom_id":"a94bccf7913b478becb33a3a27ec903d","pager_element":"0"}

in page header and your ajax may work not so clear :)

Views AJAX not work in block node.tpl


Tomcat unpack wars into directory other than appBase

Question: We would like to configure Tomcat in the following way (where X -SL-> Y represents a symlink named X pointing to a path Y):

CATALINA_HOME/webapps -SL-> /var/data/nas/deploymentconfiguration_a
/var/data/nas/deploymentconfiguration_a/myapp.war -SL-> /var/data/nas/wars/app1.war

The idea is to be able to configure which applications are deployed on a particular Tomcat instance by having a series of symlinks to WARs in a deployment configuration folder, and having anoher symlink named webapps from CATALINA_HOME to a particular deployment configuration folder.
Many Tomcat instances would point to the same deployment configuration folder.
I hope that's clear :S
The whole /var/data/nas tree would be read-only.
In trials, the main problem we are running up against is that Tomcat is obviously trying to explode the war into the deployment configuration folder (which it considers to be appBase), which is read only.
Is there a way to get Tomcat to unpack its wars into some kind of local work folder (I don't think there is, based upon a quick scan through the source code), or is the only way to proceed to stop Tomcat from exploding the war files in the first place?
We are using Tomcat 6.
Edit
We are going to be running multiple Tomcat instances against the same configuration. So there could be 10 Tomcats running against deploymentconfiguration_a and 10 against deploymentconfiguration_b, but there could be some commonality between the actual WAR files in each deployment configuration (ie deploymentconfiguration_a could have WARs 1, 2 and 5 while deploymentconfiguration_b could have WARs 1, 5 and 7).
The reason it is RO is to avoid accidental modification of a particular configuration, and also to avoid one instance of Tomcat treading on the toes of another.
Comment: Can you describe a bit more your Tomcat "instances"? Are you running multiple Tomcats against a given set of files? Or are there multiple Tomcats running multiple different apps on from your NAS? And why does it have to be R/O?
Comment: Would having multiple  declarations with different appBase attributes help alleviate the problem?
Comment: Also, is there a reason you are running multiple Tomcat instead of having one Tomcat with multiple  entries?
Comment: re: the question about running multiple Tomcat vs multiple  entries, not all Tomcat instances are on the same hardware.
Comment: re: multiple  declarations, we are trying to standardise the configuration of the Tomcat instances so that we only have to create the correct symlink in order to correctly deploy a new Tomcat instance. Perhaps we could symlink to the correct configuration file?
Answer: Based on what you've given me (and thanks for batting back and forth with me). I think these are your options:

Insert a unpackWars="false" into the Host directive within your server.xml file and run the apps directly from the war files.
Manually expand the wars on your nas into the proper deployment directories.

I give either of those recommendations only based on the fact that the file system where these deployments are going would be read only for the Tomcats involved.
I would personally go with option #1. Unless you need to see the individual files for some reason, there's no good reason to run with the files expanded.  (Unless of course you've got a bad application that needs to reference files within the war...)
I might also go so far as to also put autoDeploy="off". Unless you think you are going to be changing the war files underneath these groups of Tomcats on the spot?


How to filter single field in a view

Question: I am running Drupal 7 with the latest version of the Views module.
I have a content type called "School," which has an entity reference field for "classroom." The "classroom" content type has a radio button field for whether it has an assigned teacher.
I'd like my view to output a table which will list the total number of classrooms in each school (so school name in the first column, # of classrooms in the second column). After some messing around, I was able to get this working.
However, now I'd like to add a third column where I display the # of classrooms which have an assigned teacher. So if the classroom doesn't have a teacher assigned, it doesn't get included in the count. Anyone know how to accomplish this? It doesn't look like I can filter on individual fields...
Answer: If this were an SQL query your new column could be a subquery. I mean this new value of # of classrooms with assigned teachers has its own business logic, seperate from the list of data your already returning.
You can accomplish this using Views Field View. This lets you embed a view result -- per row of your existing view. From the project page:

This module allows you to embed a view as a field in a view. A new
  field handler is made available, so this can also be used in area
  (header/footer/empty) handlers as well as rows.
This view handler can accept arguments from fields of the parent view
  using tokens and pass them into the child view for each row. Raw or
  rendered token values can be used, as well as static values.
It's highly recommended to use this module in conjunction with views
  caching. Views Content cache and Cache Actions are good ways of
  caching views.

So:

Make a new view; called for instance with the human name of "sum rooms assigned teachers" (the machine name will be sum_rooms_assigned_teachers).
For this View simply use display mode of Show Fields; and include like the NID as a field; Under advanced settings enable Aggregation for the View. For the NID value use the Count aggregation.
Add a contextual filter to this view based on the school name.
Save your view.

Then in your parent view:

After installing Views Field View. Add a new Field your view of Global: View.
select the view named sum_rooms_assigned_teachers. Provide the contextual filter to the view of your school name or ID; it will look like [!field_school_entityreference_id] or something similiar.
Give this field whatever label you want.

Your main view should now show a room count. In the helper view you may want to deny access to anyone but the Administrator or other role -- as this is simply a helper view for this other view; and rather useless by itself.
Comment: this works, but if there are no classrooms with a teacher assigned, nothing shows up. Any way to output a 0?

How to filter single field in a view


One line proof, convexity of a set

Question: Let $A \subset \mathbb R^n$ be a set, and we define $B$ to be the set of all convex combinations of elements of $A$.
By convex combination I mean $\sum_{i=1}^{p}t_ix_i$ where $x_i \in A$, $t_i \geq 0, \sum_{i=1}^p t_i = 1$ for some $p$.
I want to understand this proof that $B$ is convex:
Take $x,y \in B, \lambda \in [0, 1]$:
$\displaystyle \lambda x + (1-\lambda)y = \lambda \sum_{i=1}^pt_ix_i + (1-\lambda)\sum_{i=1}^rs_iy_i = \sum_{i=1}^{p+r}\xi_iz_i$
Where $\xi_i = \lambda t_i + (1-\lambda)s_i, \xi_i \geq0, \sum_{i=1}^{p+r}\xi_i = 1$
I can't understand what $z_i$ is and why $z_i \in A$.
Comment: The $z_i$ are the sequence of all $x_i$ and $y_i$, with possible repetitions. For example, $z_i=x_i$, for $i=1,...,p$ and $z_i=y_{i-r}$, for $i=r+1,...,p+r$. But they are reusing $t_i$ and $s_i$ for a new pair of sequences when they write $\chi_i$. Re-define $t_i=$ (the original) $t_i$ for $i=1,2,...,r$ and $t_i=0$ for $i>r$, and re-define $s_i=0$ for $i=1,...,r$ and $s_i=$ (the original) $r_{i-r}$, for $i=r+1,...,p+r$.
Comment: Nicer would have been to say that both $x$ and $y$ are convex combinations $\sum_{i=1}^{n}t_ix_i$ and $\sum_{i=1}^{n}s_ix_i$ of the same set of points $x_1,...,x_n$ of $A$ by possibly putting some coefficients $t_i$ and $s_i$ equal to zero when the corresponding $x_i$ is not needed in the convex combination. Then $p=r=n$, one doesn't need a new variable $z_i$, and $\lambda x+(1-\lambda)y=\sum_{i=1}^{n}[\lambda t_i+(1-\lambda)s_i]x_i$.
Answer: It is sloppy.
Suppose $x= \sum_{i=1}^p t_i x_i$ and $y=\sum_{j=1}^r s_j y_j$ with $t,s$ satisfying the relevant constraints.
Let $z=(x_1,...,x_p,y_1,...,y_r)$,
$\bar{t} = (t_1,...,t_p,0,...,0)$ and $\bar{s} = (0,...,0,s_1,...,s_r)$, then we can write
$x=\sum_{k=1}^{p+r} \bar{t_k}z_k $, $y=\sum_{k=1}^{p+r} \bar{s_k}z_k $.
Then $\lambda x+(1-\lambda)y = \sum_{k=1}^{p+r} (\lambda\bar{t_k} +(1-\lambda) \bar{s_k}) z_k $.
Letting $\xi=(t_1,...,t_p,s_1,...,s_r)$, we have $\lambda x+(1-\lambda)y = \sum_{k=1}^{p+r} \xi_k z_k $.
It is straightforward to check that $\xi$ satisfies the summation and non negativity constraints.
Comment: Gotcha, thanks. Would have taken my a long time to understand what the poet meant on my own.

One line proof, convexity of a set


Problema com Checkbox ASP.NET "The parameter conversion from type 'System.String' to type 'System.Boolean' failed."

Question: Estou tendo o seguinte problema com um checkbox
Tenho uma lista de checkbox que é carregada dinamicamente (conforme os itens que existem no banco um checkbox é gerado). Atualmente tenho apenas três itens sendo os ids 1, 2 e 3. Dentro do sistema quando eu mando salvar o objeto que contém uma lista destes itens é passado por algumas validações, e quando retorna para a View a mensagem de validação do sistema é exibida, se seleciono um  checkbox referente ao ID 2 ou 3 o  fluxo funciona normalmente, quando eu seleciono o checkbox com id 1 toda parte do backend funciona normalmente porém quando  retorna para a view e ao tentar renderizar o checkbox novamente retorna o seguinte erro:
 [FormatException: Cadeia de caracteres não foi reconhecida como Boolean válido.
   System.Boolean.Parse(String value) +12394192
   System.ComponentModel.BooleanConverter.ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, Object value) +123

FormatException: 1 não é um valor válido para Boolean.
   System.ComponentModel.BooleanConverter.ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, Object value) +281
   System.Web.Mvc.ValueProviderResult.ConvertSimpleType(CultureInfo culture, Object value, Type destinationType) +393

InvalidOperationException: The parameter conversion from type 'System.String' to type 'System.Boolean' failed. See the inner exception for more information.]
   System.Web.Mvc.ValueProviderResult.ConvertSimpleType(CultureInfo culture, Object value, Type destinationType) +541
   System.Web.Mvc.ValueProviderResult.UnwrapPossibleArrayType(CultureInfo culture, Object value, Type destinationType) +258
   System.Web.Mvc.ValueProviderResult.ConvertTo(Type type, CultureInfo culture) +51
   System.Web.Mvc.HtmlHelper.GetModelStateValue(String key, Type destinationType) +70
   System.Web.Mvc.Html.InputExtensions.InputHelper(HtmlHelper htmlHelper, InputType inputType, ModelMetadata metadata, String name, Object value, Boolean useViewData, Boolean isChecked, Boolean setId, Boolean isExplicitValue, String format, IDictionary`2 htmlAttributes) +245
   System.Web.Mvc.Html.InputExtensions.CheckBoxHelper(HtmlHelper htmlHelper, ModelMetadata metadata, String name, Nullable`1 isChecked, IDictionary`2 htmlAttributes) +153
   System.Web.Mvc.Html.InputExtensions.CheckBox(HtmlHelper htmlHelper, String name, Object htmlAttributes) +40
   ASP._Page_Views_SolicitacaoServico_Inserir_cshtml.Execute() in c:\Projetos\VALERENDA\ValeRenda\ValeRendaMVC\Views\SolicitacaoServico\Inserir.cshtml:65
   System.Web.WebPages.WebPageBase.ExecutePageHierarchy() +197
   System.Web.Mvc.WebViewPage.ExecutePageHierarchy() +105
   System.Web.WebPages.StartPage.RunPage() +17
   System.Web.WebPages.StartPage.ExecutePageHierarchy() +64
   System.Web.WebPages.WebPageBase.ExecutePageHierarchy(WebPageContext pageContext, TextWriter writer, WebPageRenderingBase startPage) +78
   System.Web.Mvc.RazorView.RenderView(ViewContext viewContext, TextWriter writer, Object instance) +235
   System.Web.Mvc.BuildManagerCompiledView.Render(ViewContext viewContext, TextWriter writer) +107
   System.Web.Mvc.ViewResultBase.ExecuteResult(ControllerContext context) +291
   System.Web.Mvc.ControllerActionInvoker.InvokeActionResult(ControllerContext controllerContext, ActionResult actionResult) +13
   System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilterRecursive(IList`1 filters, Int32 filterIndex, ResultExecutingContext preContext, ControllerContext controllerContext, ActionResult actionResult) +56
   System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilterRecursive(IList`1 filters, Int32 filterIndex, ResultExecutingContext preContext, ControllerContext controllerContext, ActionResult actionResult) +420
   System.Web.Mvc.ControllerActionInvoker.InvokeActionResultWithFilters(ControllerContext controllerContext, IList`1 filters, ActionResult actionResult) +52
   System.Web.Mvc.Async.<>c__DisplayClass2b.<BeginInvokeAction>b__1c() +173
   System.Web.Mvc.Async.<>c__DisplayClass21.<BeginInvokeAction>b__1e(IAsyncResult asyncResult) +100
   System.Web.Mvc.Async.WrappedAsyncResult`1.CallEndDelegate(IAsyncResult asyncResult) +10
   System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +49
   System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeAction(IAsyncResult asyncResult) +27
   System.Web.Mvc.Controller.<BeginExecuteCore>b__1d(IAsyncResult asyncResult, ExecuteCoreState innerState) +13
   System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +29
   System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +49
   System.Web.Mvc.Controller.EndExecuteCore(IAsyncResult asyncResult) +36
   System.Web.Mvc.Controller.<BeginExecute>b__15(IAsyncResult asyncResult, Controller controller) +12
   System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +22
   System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +49
   System.Web.Mvc.Controller.EndExecute(IAsyncResult asyncResult) +26
   System.Web.Mvc.Controller.System.Web.Mvc.Async.IAsyncController.EndExecute(IAsyncResult asyncResult) +10
   System.Web.Mvc.MvcHandler.<BeginProcessRequest>b__5(IAsyncResult asyncResult, ProcessRequestState innerState) +21
   System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +29
   System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +49
   System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) +28
   System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result) +9
   System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +9765045
   System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +155

CSHTML onde é gerado o Checkbox
Ocorrências

    @if (TempData["SelecionarOcorrencia"] != null)
    {
        if (((List<TipoOcorrenciaViewModel>)TempData["SelecionarOcorrencia"]).Count() > 0)
        {
            foreach (TipoOcorrenciaViewModel item in (List<TipoOcorrenciaViewModel>)TempData["SelecionarOcorrencia"])
            {

                    @Html.CheckBox("OcorrenciasSelecionadas",  new { @Value = item.TipoOcorrenciaID})
                    @item.Descricao

            }
        }
    }

View Model
public class TipoOcorrenciaViewModel
    {

        public int TipoOcorrenciaID { get; set; }

        public string Descricao { get; set; }

        public string Sigla { get; set; }

        public bool Ativo { get; set; }

        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
        public virtual ICollection<Ocorrencia> Ocorrencia { get; set; }

        public bool ExigeAnexo { get; set; }

    }

Vi algumas repostas relacionadas a erros parecidos porém em situações diferentes, não consigo identificar o que possa ser, já que só acontece com o ID 1 nos outros funciona perfeitamente
EDIT

fiz um teste removendo o item com id 1 da lista antes de renderizar
ao selecionar o primeiro checkbox da lista da o mesmo erro
ao selecionar o segundo funciona normal
Comment: Se quando você seleciona IDs 2 e 3 tudo funciona, mas somente para o ID 1 não funciona, tente comparar os campos entre esses objetos, pois parece que algum campo relacionado ao ID 1 precisa ser convertido/tratado.
Comment: Opa Renan, já havia verificado isso, mas dei mais uma olhada para desencargo de consciência e não há diferenças nos objetos só os valores dos atributos mesmo
Answer: Consegui resolver de uma forma que não me agradou muito, foi uma solução paliativa
com base nesta postagem do StackOverflow em inglês
troquei o @Html.Checkbox pela tag input html

   @if (Model != null && @Model.OcorrenciasSelecionadas.Contains(item.TipoOcorrenciaID.ToString()))
   {
    <input type="checkbox" name="OcorrenciasSelecionadas" value="@item.TipoOcorrenciaID" checked>
   }
   else
   {
    <input type="checkbox" name="OcorrenciasSelecionadas" value="@item.TipoOcorrenciaID">
   }
    @item.Descricao


How to update ParentID field in SQL

Question: I have some records that were imported to SQL. One of the fields 'FieldToChage' was a ParentID that referenced an old key value. When I imported the data to SQL, the new key value does not correspond with the old key value contained in 'FieldToChage'.
Here is simplified schema of my imported table:
[dbo].[zChangeTable](
      [ID] [int] IDENTITY(1,1) NOT NULL,
      [FieldToChange] [int] NULL,
      [OldID] [int] NOT NULL,

What i need is the field titled 'FieldToChange' (ParentID) to reference the new key value with the old index in field 'OldID'.
Here is a sample of the existing table data:
ID      FieldToChange   OldID
159      NULL            143
160      143             142
161      143             145
25       174             171
26       174             172
204      NULL            173
17       NULL            174

So an update statement is needed that walks thru the table and updates the 'FieldToChange' as shown below...
ID      FieldToChange   OldID
159      NULL            143
160      159             142
161      159             145
25       17              171
26       17              172
204      NULL            173
17       NULL            174

hope this makes sense...
thanks in advance
Answer: UPDATE t
SET t.FieldToChange = t1.ID
FROM zChangeTable t JOIN zChangeTable t1 ON t.FieldToChange = t1.OldID

Answer: Do it like this:
update zChangeTable
set t1.FieldToChange = t2.ID
from zChangeTable t1
inner join zChangeTable t2 on t1.FieldToChange = t2.OldID

Answer: The easiest way to do this is to do the import in two parts: first adding the records, then going back and assigning the parent ID column. For the sake of simplicity, I'll use the table names OldTable and NewTable
insert into NewTable
(
    OldID
)
select
    ID

from OldTable

update nt set
    FieldToChange = ntp.ID

from NewTable nt

join OldTable ot on ot.ID = nt.OldID
join NewTable ntp on ntp.OldID = ot.ParentID

Answer: The easiest way to fix this would be to import the table with Identity Insert enabled and preserve the values in the identity column "ID".
SET IDENTITY_INSERT zChangeTable ON
GO
/* Import the data, including values for ID */
GO
SET IDENTITY_INSERT zChangeTable OFF
GO

How to update ParentID field in SQL


serve images from protected folder using Oauth2, angular and yii2 REST

Question: I have project that have to deal with very sensitive images, which shouldn't be accessable for unauthorised users, saved on protected location. I've done this before, for regular http requests, but now I have angular app on frontend with Oauth2 client, and Yii2 powered API on server side. I am wondering what is best practice to do this, should I create new yii\web\Controller to serve image (creating and deleting images would still be in rest controller), which should bring me some difficulties with authorisation, and it looks kind a hacky.
Or should I use raw output format in yii REST controller, and render image as response?
I would prefer second approach if it is feasable, because I'm new with angular.js, and not sure how to do this, and idealy I would like to render images simple as

I would like to exclude base64 encoding, since that would take some processing power on both sides
Answer: The second approach is possible via URL.createObjectURL. On the PHP side, you would just use something like readfile(). On the Angular side, try something like this
$http.get('example/image/123', {
    responseType: 'blob',
    headers: {
        Authorization: 'Bearer super-secret-token'
    },
    transformResponse: function(data) {
        return ($window.URL || $window.webkitURL).createObjectURL(data);
    }
}).then(function(response) {
    $scope.imageUri = response.data;
});

and in your template

You should probably also fire URL.revokeObjectURL when you no longer need the image such as when your current scope is destroyed, eg
$scope.$on('$destroy', function() {
    ($window.URL || $window.webkitURL).revokeObjectURL($scope.imageUri);
});

Comment: Just addition. Better use `x-send-file` headers for apache with mod enabled or nginx. Because `readfile()` will hit performance badly for high loads.
Comment: @Phil, I would rather bind response data directly to ``src`` attribute with ``element.attr('src', response.data)`` so there is no need to contain and revoke data from ``$scope`` object. Thanks
Comment: @dzona sure, you can do that. Using `$scope` was just an example


(Proof-verification) Proof that multiplication of natural numbers is commutative

Question: This isn't that rigorous, in that assumes that axioms about the addition of natural numbers have already been shown and proven, and I think it also assumes distributivity of multiplication. I don't know if the distributive property is something that has to be shown or assumed.

Anyway, for any natural number $n$, we have that $$n*1 = 1*n $$ because the left hand side is $$ \underbrace{1+ 1 + \dots + 1}_{n\ \text{times}} $$ which is the definition of $n$. Likewise, the right hand side is defined to be $n$. So they are equal.
Now we can use this to show that multiplication with $2$ is commutative, i.e. for any $n$ $$n * 2 = 2 *n$$ The left hand side equals $$ n * (1+1) = n*1 + n*1 = n + n = 1*n + 1*n = (1+1)*n = 2*n$$ Then we can show that multiplication with $3$ is commutative knowing that multiplication with both $1$ and $2$ is commutative, and that multiplication with arbitrary $m$ is commutative knowing that multiplication with $1$ and $m-1$ is commutative.

Is this correct? I see at least two potential problems:

It assumes the distributive property of multiplication for natural numbers. While I find this axiom to be more "common sense" than commutativity, perhaps it should also be proved somehow. And maybe the proof relies essentially on commutativity of multiplication, leading to circular reasoning.

It seems to use not only regular induction, but strong induction. In other words, I am not sure if multiplication being commutative for $m-1$ can be used as the induction hypothesis in regular induction or not, since it seems like it uses implicitly that multiplication is commutative for all lower natural numbers. I think ultimately this comes down to my not understanding the difference between induction and strong induction -- they are supposed to be equivalent, but I imagine that at such a foundational level the distinction between them might be important. What's the difference between simple induction and strong induction?

Context:
This might be related to this question: Why Does Induction Prove Multiplication is Commutative? To be honest I am not sure though since I don't understand that question.
I remember reading somewhere, after doing a Google search, that one can prove that multiplication of natural numbers is commutative by induction. I didn't understand the argument at the time, probably because I didn't put in the effort to understand it properly, but I think I have the idea now, and want to confirm or verify that this is correct. It was stated similar to this: proof of commutativity of multiplication for natural numbers using Peano's axiom
Comment: If this is a proof under the Peano's axioms you need them, and the definition of multiplication by Peano. The definition of multiplication under the Peano context is $$S(m)\cdot n=(m\cdot n)+m$$ where $S(n)$ is the succesor function. If it is under the context of a group it will be different.
Comment: If it is for the first time you can just say to them that it is commutative, i.e. that $ab=ba$. If you want to explain a bit more it will be interesting use a rectangle to represent multiplication, then they can see that is the same rectangle no matter what go first.
Comment: thre is a proof for non-negative ints on quora https://www.quora.com/What-is-the-mathematical-proof-of-the-commutative-property-of-multiplication
Comment: You need (strong) induction and the binary operation $+$ to splice in the commutative multiplication operation. See https://math.stackexchange.com/questions/2974212/algebraically-constructing-the-natural-numbers-using-a-binary-operation-satisfyi
Comment: @Masacroso I am just looking for a way to explain to a 3rd grader learning multiplication for the first time that it is commutative.
Comment: @user211299 This is very helpful, thank you!
Comment: @CopyPasteIt Thanks for looking into this; I appreciate it!
Answer: [Community wiki] First, one can establish that there is a proof of the left distributive property that doesn't rely on commutativity of multiplication. (And it seems that the right distributive property's proof also doesn't rely on commutativity of multiplication, basically by using the same argument as at the top of this post or an analogous version of the argument for left distributivity. I.e. we don't need to appeal to use commutativity of multiplication to prove right-distributivity either.)
I.e. using distributivity to prove commutativity of multiplication seems kosher to me.
Now it must again be warned that my understanding of the distinction between "regular" and strong induction is weak (especially since both principles can be used to prove the other, so in some sense they are logically equivalent? not sure that's actually true),
but anyway it seems that this answer on Quora by Jeff David (brought to my attention by @user211299) gives a proof sketch only using distributivity and what seems to more obviously be regular induction than the proof sketch given above in this post. Since quora seems like an unreliable place to store a good answer, I will copy-paste it here without claiming credit for it:

Here is a proof for all non-negative integers.
We are attempting to show that $ab=ba$, where $a$ and $b$ are non-negative integers. Let's introduce a new equivalence, $b+e=a$ (i.e. $e$ is defined as the difference between $a$ and $b$; note that if $e=0$ then the proof becomes trivial. Also note that we assume $a \ge b$; this does not affect our result as the variables are symmetrical). Now we write:
1) $ab= \sum_{i=i}^a b $
This is nothing more than stating the definition of b multiplied by a, ie b summed a times. We can also write:
2) $ba=b(b+e)$
since $b+e=a$, by our own definition. We now try to show that equation (2) can be rewritten in the form of equation (1). We expand on equation (2) by writing:
3) $b(b+e)=\sum_{i=1}^b (b+e)$
This is very similar to what we did regarding equation (1), ie $b(b+e)$ is just $(b+e)$ summed $b$ times. Using some properties of addition, we can transform the right hand side of (3) to read:
4) $\sum_{i=1}^b (b+e)=\sum_{i=1}^b b+\sum_{i=1}^b e$
Now what we are going to do is assume the very thing we set out to prove! That is usually a big no-no unless you are using induction, which is basically where this is going.
5) Assume: $\sum_{i=1}^b e =\sum_{i=1}^e b$
We now substitute (5) back into (4) and proceed:
6) $\sum_{i=1}^b (b+e) = \sum_{i=1}^b b + \sum_{i=1}^e b$
The right hand side of (6) can be simplified:
7) $\sum_{i=1}^b b + \sum_{i=1}^e b = \sum_{i=1}^{b+e} b$
Finally, we make use of the fact that $b+e=a$:
8) $\sum_{i=1}^{b+e}b = \sum_{i=1}^a b$
Comparing (8) to (1) yields what we set out to prove:
9) $ab=ba$
Note that the proof hinges on equation (5), which is nothing more than a restatement of that which we set out to prove, namely:
5a) $be=eb$
The advantage that we have now (after going through all that work) is that we have reduced the number space of the original problem; $e$ by definition is less than $a$ (in the case where $e$ is equal to $a$, $b$ is identically $0$, and the whole proof becomes trivial). We can continue in this way to reduce the number space of the problem until we eventually get to a base case which can be shown to be trivially true (namely when $e=0$); this is the nature of inductive proof .
I know this isn't as formal as a textbook proof, but it is a cute little intuitive proof that I had not yet seen presented in such a way on the internet, so I thought I would submit it. I really hope it helps someone!


Open Atrium: How to change Task assignment from users to groups?

Question: I'm trying to change the Task content-type to be able to assign tasks to groups, and only show those tasks in Task List that are assigned to your group you are added. I've tried by adding a new field with Entity Reference to groups, to select multiple and this part is okay and working fine.
I'm blocked when I'm trying to set the filters in the Views to get the current user's group and show the task if it's assigned to that group.
Thanks a lot!
Answer: Edit the Task content-type, add a new Entity Reference field for oa_group_ref.
Edit the Task List view and set a contextual filter on the added field, and provide the default value for the filter with the OG groups of the current user, and allow multiple values in More options.
In query settings set the Distinct to make it work with multiple assignment.


Problema ao aplicar Pop up Jquery em plataforma de e-commerce

Question: Estou trabalhando com uma plataforma de e-commerce, no caso a loja integrada. Tenho acesso a incluir html para personalizar, porém o código é ativado para todas as páginas do site, existe algo que eu possa fazer para que fique apenas na home sob as atuais condições que estou?
<code>$(document).ready(function() {

    var maskHeight = $(document).height();
    var maskWidth = $(window).width();

    $('#mask').css({'width':maskWidth,'height':maskHeight});

    $('#mask').fadeIn(1000);
    $('#mask').fadeTo("slow",0.8);

    //Get the window height and width
    var winH = $(window).height();
    var winW = $(window).width();

    $('#dialog2').css('top',  winH/2-$('#dialog2').height()/2);
    $('#dialog2').css('left', winW/2-$('#dialog2').width()/2);

    $('#dialog2').fadeIn(2000);

  $('.window .close').click(function (e) {
    e.preventDefault();

    $('#mask').hide();
    $('.window').hide();
  });

  $('#mask').click(function () {
    $(this).hide();
    $('.window').hide();
  });

});
</code>
Comment: Use o botão [edit] para poder adicionar mais informações a ela.
Comment: Bem vindo ao SOpt, poderia colocar um print mostrando o problema ? já deu para entender que você está sofrendo um efeito em cascata por carregar esse script em todas as paginas, mas queria saber exatamente como isso ocorre e qual plataforma é
Comment: Já consegui resolver o problema, como encerro esta pergunta para não prender a atenção da galera que vem ajudar?
Comment: Responda a pergunta com a solução para o problema. Você não vai conseguir marcar como resposta por causa da reputação (eu acho).
Answer: Bom o problema foi resolvido sem a necessidade de alterar algo, consegui colocar esse pop up apenas na home através da plataforma.
Obrigado
Comment: Pode explicar como fez isso? A mesma solução que encontrou pode ajudar e ser útil para outros usuários.


Java get random double between two doubles

Question: I want to get a random between two doubles.
Example:
0.00 and 0.50

then get random between them
output is:
0.23

how do i do this with java
Answer: Simple, for this range [min,max]
return min + Math.random() * (max - min);


Pegar id e nome via form, ambos forenig key

Question: Basicamente o usuario entra no perfil da empresa e faz um comentario e uma avaliação de nota.
Preciso que nesse form sejam passados o ID da empresa e pego o ID ou o Nome do Usuario
Tenho um sistema que usa USER extendidos para Usuario e Negocio.
E criei uma tabela Comentario, que importa o Id do User da tabela Negocio e o Nome da tabela usuario.
Mais não estou conseguindo passar via view a id da empresa nem o nome do usuario que está comentando.
Lembrando que só usuarios cadastrados poderão comentar
models.py
class Negocio(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    empresa = models.CharField(max_length=50, blank=False)

class Usuario(models.Model):

    nome = models.CharField(max_length=50, blank=False)
    sobrenome = models.CharField(max_length=50, blank=False)

class Comentario(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    nome = models.ForeignKey(Usuario, on_delete=models.CASCADE)
    comentario = models.CharField(max_length=255, blank=True)
    nota = models.CharField(max_length=255, choices=NOTA_CHOICES, blank=True)

views.py
def comentario_form(request):
    comentario = Comentario.objects.all()
    form = ComentarioForm()
    data = {'comentario': comentario, 'form': form}
    return render(request, 'profile_negocio/comentario.html', data)

def cadastro_comentario(request):
    if request.method == 'POST':
        form = ComentarioForm(request.POST)
        if form.is_valid():
            user = form.save()
            form.instance.user = request.user
            form.instance.nome = request.user
            user.usuario.nome = form.cleaned_data.get('comentario')
            user.usuario.sobrenome = form.cleaned_data.get('nota')
            user.save()

            return redirect('sistema_perfil')
    else:
        form = UsuarioForm()
    return render(request, 'profile_negocio/comentario.html', {'form': form})

comentario.html
<form method="post" action="{% url 'cadastro_comentario' %}"
    class="form-signin" enctype="multipart/form-data" id="form" name="form" validate>
      {% csrf_token %}

          {{ form.comentario| as_crispy_field}}

              {{ form.nota| as_crispy_field}}

  <input type="submit" class="btn btn-primary ">

profile.html
{% for comentario in comentarios %}

            {{ comentario.nome }} - Nota: {{ comentario.nota }}

            {{ comentario.comentario }}

{% endfor %}

Comment: Não entendi qual é a pergunta, algum problema em alguma parte do codigo? Em que parte do codigo vc precisa de ajuda?
Comment: Na view, preciso que passe automaticamente para o ofrmulario a id do Negócio, que é a página onde o usuário vai comentar e passar tbm o nome do usuário que está comentando
Comment: Vou melhorar a formatcao para ver se fica mais claro.
Answer: Brother, dei uma refatorada no código usando CBV, tenta ai:
#models.py
class Negocio(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    empresa = models.CharField(max_length=50, blank=False)

class Usuario(models.Model):
    nome = models.CharField(max_length=50, blank=False)
    sobrenome = models.CharField(max_length=50, blank=False)

class Comentario(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    nome = models.ForeignKey(Usuario, on_delete=models.CASCADE)
    empresa = models.ForeignKey(Negocio, on_delete=models.CASCADE)
    comentario = models.CharField(max_length=255, blank=True)
    nota = models.CharField(max_length=255, choices=NOTA_CHOICES, blank=True)

#forms.py
from django import forms

class ComentarioForm(forms.ModelForm):
    class Meta:
        model = Comentario
        fields = '__all__'

#views.py
from django.views import generic
from django.urls import reverse_lazy

class ComentarioFormView(generic.UpdateView):

    model = Comentario
    form_class = ComentarioForm
    template_name = 'profile_negocio/comentario.html'
    success_url = reverse_lazy('name_da_url_para_direcionar_em_caso_de_sucesso_s2')

    def Negocio(self):
        return Negocio.objects.all()

    def form_valid(self, form):
        form = form
        comentario = Comentario(
                user=self.request.user.username,
                nome=form.cleaned_data.get('nome'),
                empresa=form.cleaned_data.get('empresa'),
                comentario=form.cleaned_data.get('comentario'),
                nota=form.cleaned_data.get('nota'),
            )
        comentario.save()
        return super().form_valid(form)


Implementing IP fragmentation

Question: I'm working on an application that does network traffic generation. The application has eth1 in promiscous mode. So it directly handles all incoming and outgoing traffic.
One of the features I'm implementing is IP fragmentation and defragmentation. Incoming fragments need to be reassembled, and outgoing packets need to be fragmented if their sizes exceed the MTU of 1500 bytes.
One simple way of testing my application is by sending a ping command to the IP address of eth1:
ping -c1 -s 20000 10.3.2.1

This is working fine.
However, once the packet size exceeds ~53000 bytes it fails. According to Wireshark I receive fragments until fragment offset ~51000 and then nothing, followed by a reassembly timeout.
The maximum size of an IP packet is 65535 bytes. The ping command allows specifying a size up until 65507. This actually works if I ping to eth0 (OS controlled).
When inspecting the application from the inside with GDB all is going well. Stepping through the code reveals that the fragments enter my application, the IP packet is succesfully reassembled and then fragmented again, and the fragments are sent back to the sender. Even for the last fragment the return value of send(...) (socket API) is equal to the size of the fragment, indicating success.
Does anybody have an idea what could be going wrong?
Operating system is Linux (based on RTLinux).
Comment: Operating System?? Why are you using the OS's built-in firewall to reassemble packets for you?
Comment: @Chris S: The OS in Linux. I'm reassembling the packets myself.
Comment: It's what I've been assigned to do.
Comment: Yick, that's a rough one. I haven't seen a problem like this before, but have you tried using tcpdump or wireshark to verify that all the source packets actually hit the wire?
Comment: According to Wireshark the fragments are sent up until the one with fragment offset 51800. The remaining ones don't arrive.
Answer: If the packets are correctly fragmented then reassembled on client side, but the reverse does not work,
A -----> B
         |
A <--x-- B

I would suggest first to try to inverse the roles (since the problem is on the way back) and check if, this time, the fragmented packets/reassembling can be performed by A
A <----- B
|
?

If not, there is a problem in the packets management from B to A, could be a firewall limitation, or any router or switch you may have in between.
Answer: The maximum TCP segment you can have is 65,495 bytes.

If you concern the headers ... it could be the bound you are looking for :>
Also, do you have a constant window for TCP or it's adapting itself ? Maybe a smaller window is used and you can't send more data
Comment: The TCP header is normally between 40 and 60 bytes; up to 100 bytes with all the options (which isn't possible in all packets). Ethernet adds 38, so let's use 100, the MTU is 1500, less overhead would be 1400 bytes of data. So to get 65,495 bytes you need 47 packets, which would take 4,700 bytes off the top, and leave over 60KB for data still. If the MTU was significantly less, this may be a problem, but it's not the 51KB limit he's hitting.
Comment: Another point is ... what's your topology ? Maybe timeout is too short and you should increase it. Or the reassemble buffer.
Comment: The reassembly and fragmentation occur on IP level. The response is initiated by ICMP. So TCP is never involved.
Comment: Here is a senario that involves TCP.
Let's say that the bitrate is different for uplink / downlink ... and as a result TCP window is different for each way.

A-> B (TCP window ... 50000)
B-> A (TCP window ... 45000)

A send a 50000 TCP segment fragmented in N packets. B reassembles the packet. Now we have two cases.
B could either forward packet to upper level and put 45000 bytes, or he could redirect the packet back to A.
Now A will receive a packet 50000 bytes, but his receiving buffer (window) is  45000. So ... you can't reassemble it :>
Answer: Solved
The issue was packet loss. The IP response was sent to a switch over a gigabit line. This switch in turn forwarded the messages over a 100 MBit line. This means that packets arrived at greater speed than that they left, causing memory usage inside the switch to quickly rise. Once all memory was used the switch had no other option but to start dropping packets.

Implementing IP fragmentation


How to set variable to a huge number

Question: I try to do something like this:
<code>Dim x = 1000000000000000000000000000000000000
</code>
But it gives me an overflow exception.  How can I do something like this?
Comment: And what the *** is such a number for?
Comment: Please only ask one question per question.  If you have two questions, please ask the second one as a separate post.  I have edited out your second question from this one.
Answer: All data types are stored as bits, and there is a maximum number that most can hold. Learn about the data types and their limitations from MSDN:https://msdn.microsoft.com/en-us/library/47zceaw7.aspx
Also see this answer:Is there any big integer class for Visual Basic .NET (128 or more bits)?
Answer: If you don't have to perform algorythm on it, just store it as a string. But you can separate it in multiple parts if you have to do it, because it seems that it is not possible to use handle values like this.

How to set variable to a huge number


Understanding of upper bound of summation being a random variable

Question: I'm having trouble understanding some homework and would love it if any of you could be of any assistance. I have to prove that
$$\mathbb{E} \left[ \sum_{k=1}^\infty \beta^{k-1}R_k  \right]=\mathbb{E} \left[ \sum_{k=1}^TR_k  \right]  $$
And I'm not sure how to handle it so I'm trying to split it up in parts and one of the things that make the least sense is that $T$ is a geometric random variable with $P(T=k)=\beta^{k-1}(1-\beta)$.
I have never seen an upper bound being a random variable and can't find anything about it. I'm thinking that it might be possible to rewrite the right-side sum to an infinite sum like this:
$$ \mathbb{E} \left[ \sum_{k=1}^TR_k  \right] = \mathbb{E} \left[ \sum_{k=1}^\infty P(T=k)R_k  \right]$$
Then by linearity we could move the expectation in and since $\mathbb{E} \left( P(T=k) \right)=\frac{\beta^{k-1}(1-\beta)}{1-\beta}$ (success probability is $1-\beta$) which would give us the same on both sides. But I feel like this isn't the case and I'm making Gauss turn in his grave. Every input is appreciated, thank you!
Comment: Have you heard of the [law of total expectation](https://en.wikipedia.org/wiki/Law_of_total_expectation)? Seems like it should help you and roughly line up with your intuition.
Comment: What are the $R_k$?
Comment: I tried to make it fairly step-by-step in my answer below, but feel free to ask questions if something seems unclear.
Comment: @LuizMaxCarvalho They are iid random variables denoting income in time $k$ with discount factor $\beta $
Comment: @Fimpellizieri I have heard about it briefly but I'm having trouble linking it to my problem. I feel like I've heard about a lot of stuff and they make sense separately but I can't link them to each other. I will look more into it though, thank you!
Answer: By the law of total expectation, we have
$$\begin{align}
\mathbb{E} \left( \sum_{k=1}^TR_k  \right)
&=
\Bbb E\left(\mathbb{E} \left( \sum_{k=1}^TR_k  \middle | T\right) \right)
\\&=
\sum_{n\geqslant 1}\left[\mathbb{E} \left( \sum_{k=1}^TR_k  \middle | T = n\right) \cdot \Bbb P(T= n)\right]
\\&=
\sum_{n\geqslant 1}\left[\mathbb{E} \left( \sum_{k=1}^nR_k  \right) \cdot \Bbb P(T= n)\right]
\\&=
\sum_{n\geqslant 1} \left[ \left(\sum_{k=1}^n\mathbb{E}(R_k)\right) \cdot \beta^{n-1}(1-\beta)\right]
\end{align}$$
If we now change the order of summations
$$\begin{align}
\mathbb{E} \left( \sum_{k=1}^TR_k  \right)
&=
\sum_{n\geqslant 1} \left[ \left(\sum_{k=1}^n\mathbb{E}(R_k)\right) \cdot \beta^{n-1}(1-\beta)\right]
\\&=
\sum_{k\geqslant 1} \Bbb E(R_k)\left(\sum_{n\geqslant k}\beta^{n-1}(1-\beta)\right)
\\&=
\sum_{k\geqslant 1} (1-\beta) \Bbb E(R_k)\left(\sum_{n\geqslant 0}\beta^{n+k-1}\right)
\\&=
\sum_{k\geqslant 1} \beta^{k-1}(1-\beta) \Bbb E(R_k)\left(\sum_{n\geqslant 0}\beta^{n}\right)
\\&=
\sum_{k\geqslant 1} \beta^{k-1}(1-\beta) \Bbb E(R_k)\frac1{1-\beta}
\\&=
\sum_{k\geqslant 1}  \beta^{k-1}\Bbb E(R_k)
\\&=
\sum_{k\geqslant 1}  \Bbb E\left(\beta^{k-1}R_k\right)
=
\Bbb E\left(\sum_{k\geqslant 1}  \beta^{k-1}R_k\right).
\end{align}$$
Comment: You're welcome! Glad to have helped
Comment: Thank you so much for all the time and effort. It all makes more sense now, I really owe you one, you deserve the best!


Repetir numero a cada contagem

Question: Como eu faço isso em php, por favor me ajudem:
( A cada 3 vezes )
0 = 0
1 = 0
2 = 0

3 = 1
4 = 1
5 = 1

6 = 2
7 = 2
8 = 2

Assim por diante .. Este é um exemplo simples do que gostaria de fazer, pois na verdade gostaria de implementar um menu de distribuição de processos onde existem 2 coordenadores e um diretor, mas para simplificar dei este exemplo simples acima.
Answer: Deixo abaixo uma solução em javascript para que seja testável aqui no site. A ideia é usar o operador % (modulo) para verificar quando incrementar a variável que está a direita da igualdade, o módulo será igual a 0 somente nos múltiplos do intervalo desejado, por exemplo se o intervalo for 3, o modulo de i será igual a 0 quando i será 3, 6, 9 ... Veja aqui mais explicações sobre o calculo do módulo se você não é familiarizado com o mesmo.

let repetir = 9,
    current = -1,
    intervalo = 3;

for(let i = 0; i < repetir; i++){
  if(i % intervalo === 0)
    current++;

  console.log(`${i} = ${current}`);
}

E aqui a tradução do mesmo em PHP:
$repetir = 9;
$current = -1;
$intervalo = 3;

for($i = 0; $i < $repetir; $i++){
  if($i % $intervalo == 0)
    $current++;

    echo "$i = $current
";
}

Repetir numero a cada contagem


I am looking to present the greatest predictor of performance given the following R output for multiple linear regression

Question: I used Linear regression analysis with a sample and recieved the table below. How do I interpret the results?
The underlying problem is finding the greatest contributor to $SMTQ$.

$SMTQ$ - Sports Mental Toughness Questionaire
$Confa$ - Confidence
$Consa$ - Constancy
$Conta$ - Control

How do I understand the result sin the table? Is there any reason to calculate the standardized regression coefficients rather than the unstandardised ones listed in table? Should I present both values for a valid interpretation?
Comment: Why do you think hierarchical is preferable, or even possible here?
Comment: We have an r2 value for total smtq rather than individual measures. When looking for the greatest predictor this would have been helpful.
Comment: please indicate full form of your abrevitions and sime_thing about objectives of your study and the sample.
Comment: Depending on what is the real question (we don't know it yet) I would use semipartial $R^2$ and use the bootstrap to get a 0.95 compatibility interval for the rank of predictor importance on this metric.  For an example see Section 5.4 of [RMS](https://hbiostat.org/doc/bbr.pdf).  Bootstrapping ranks fully exposes the difficulty of the ranking task and often will prevent one from declaring a clear winner.
Comment: See https://stats.meta.stackexchange.com/a/4554/919 for the close reasons.
Answer: You have only one statistically significant covariate, which is 'smtq$confa' with p-value 4.65e-13. Other coefficients are not statistically significant even at 10% level. Standardization would not affect the p-values. Hierarchical or multiple linear regression would not give you different results in your setup, given the magnitude of the p-values for different coefficients.
So, the covariate 'smtq$confa' is the best predictor in your problem.
Comment: @joy statistical "significance" is an arbitrary concept that should not play a role here.
Comment: Thank you for your input. What values are best to present when discussing the findings?
Comment: It depends on the field of your study. In Statistics related works, usually the detailed output of the computation, which you have presented in the question, is presented first. Then, the significant predictors are stated based on the p-values. Finally, the implications are discussed. In other fields, where the statistical methodology is used only to identify the significant variables, the implications are more stressed upon, and the variables which are not statistically significant are ignored from the discussion or presentation.
Comment: pvalues of such t-test for the covariates would not be affected by standardization. An an example, [compare the pvalues obtained in this answer](https://stats.stackexchange.com/a/93400/344944).
Comment: @FrankHarrell it is not clear to me why would you call statistical significance an arbitrary concept, although I agree that it depends on the nominal level, which is (somewhat arbitrarily) set to 5%, 1%, etc. In this particular case, from the p-values, it is seen that only one p-value is not only small but effectively 0, while others are relatively large. So, it will be 'statistically significant' according to its definition for almost any arbitrarily set nominal level.
Comment: Because it is clearly not helpful in general to get excited about a predictor with p=0.049 while ignoring a predictor with p=0.051 (I realize things are more extreme for the current dataset).  Statistical significance should play no role here.  Instead, quantify the predictive value of **all** or the pre-specified predictors.
Comment: I agree with your statement about not getting "excited about a predictor with p=0.049 while ignoring a predictor with p=0.051". On the other hand, it is perhaps hard for things to get more extreme than they are in the current dataset. Regarding your assertion that statistical significance should play no role, particularly in view of the current set of p-values, I would say that your stand is in a philosophical disagreement with perhaps the dominant view in the statistical community, which can be clearly seen to influence the very format of the results presented in R for the current analysis.
Comment: Although everything you write is plausible, it's not necessarily correct. On the face of it -- with just the given information -- one cannot determine which might be a "best predictor," because these statistics tell us little about prediction.  For instance, it's possible the "most significant" variable contributes little to the prediction after the other variables are included, but those others don't look "significant" because they are highly correlated.  We also have no information about effect sizes -- and reporting standardized coefficients would actually help with that.


Destrutor de Classe em C++ Chamado no meio do código

Question: Estou me aprofundando no uso do C++, e estou tendo dificuldade em migrar uma aplicação que usa callbacks e um singleton para gerenciar configurações.
Durante a inicialização do código ainda na função main, crio o singleton responsável pela manutenção das configurações (CycloConfig) e tenho uma função auxiliar que funciona como callback de uma interface gráfica que chama a função correta de uma outra classe conforme determinadas ações do usuário da interface, e assim muda algumas configurações que serão usadas.
Até ai parece tudo bem, porém quando executo a aplicação, na parte quando não uso mais funções que setam valores de configuração na função principal o destrutor está sendo chamado. mas a classe de configuração ainda será usada dentro do callback o que significa que ela é usada a qualquer momento para setar novos valores e este valores são lidos simultaneamente em um loop na função principal.
Já tentei colocar o destrutor no final do código quando a função principal termina, logo antes do return chamando-o configo.~CycloConfig(); e já tirei parâmetros de optimização do código.
Mas mesmo assim ele ainda destrói o objeto quando não o uso mais para setar valores na função principal (main). Apesar de precisar ler os valores que foram atualizados pelo callback.
A objeto criado da classe CycloConfig não é passado como parâmetro, uma vez que é um singleton e não pode ser instanciado. apenas obtido através deum factory method:
CycloConfig& CycloConfig::get() {
#if __cplusplus < 201103L
#warning "Este código é seguro com o uso do C+11, pode haver problemas relativo a concorrencia em verões inferiores."
#endif
    static CycloConfig instance;
    return instance;
}

Callback:
void MouseCallback(int event, int x, int y,
        int __attribute__((__unused__)) flags,
        void __attribute__((__unused__)) *data) {
    CycloConfig config = CycloConfig::get();
    static InteractionHandler ih(config.getAddress());
    if (ih.hasCurrentCallbackFunction()) {
        switch (event) {
        case (cv::EVENT_LBUTTONDOWN):
            ih.callCurrentCallBack(x, y);
            ih.nextStep();
            break;
        default:
            //printf("Error: MouseCallback: event = %d\n", event);
            //exit(EXIT_FAILURE);
            break;
        }
    }
}

Inicio da função principal:
int main(int argc, char **argv) {

    unsigned long debug = 1;

    std::cout << "*****************************************************"
            << std::endl;
    std::cout << "** Obtendo configurações                           **"
            << std::endl;
    CycloConfig config = CycloConfig::get();
    std::cout << "** configurações carregadas                        **"
            << std::endl;
    std::cout.flush();
...

Fim da Função principal:
...

    delete cap;
    if (outputDevice)
        delete outputDevice;
    if (outputFile)
        delete outputFile;

    config.~CycloConfig();
    exit(0);
    return 0;
}

Construtores e destrutores da Classe de Configuração:
CycloConfig::CycloConfig() {
    this->LoadData();
    std::cout << "** CycloConfig> Criado." << std::endl;
}

CycloConfig::~CycloConfig() {
    this->PersistData();
    std::cout << "** CycloConfig> Descartado." << std::endl;

}
...
class CycloConfig {
private:
    const char *configFile = "CycloTracker.conf";
    ConfigData data;

    CycloConfig();

public:
    virtual ~CycloConfig();

    void PersistData();
    void LoadData();

    static CycloConfig& get();

Comment: Existem muito poucas ocasiões onde você deve chamar o destrutor explicitamente, e a sua não é uma delas. É bem provável que seu objeto esteja sendo copiado ser passado de parâmetro para alguma função, e esta cópia esteja sendo destruída. Mostre um pouco de código, principalmente trechos que passem seu singleton como parâmetro ou retorno. Assim vai ser mais fácil dar uma ajuda mais concreta.
Comment: Olá, adicionei alguns códigos espero que sejam suficientes.
Answer: Seu problema encontra-se na forma como você está acessando seu objeto singleton. A função de acesso está corretamente retornando o objeto por referência mas, tanto na função MouseCallback quanto na main estão sendo declaradas variáveis "normais" do objeto, que acabam gerando cópias dele. E no momento que estas cópias saem de escopo elas são destruídas, fazendo com que o destrutor seja chamado.
A solução simples é apenas mudar a declaração das variáveis locais para um tipo referência, ou ponteiro:
CycloConfig config = CycloConfig::get(); //Cópia

CycloConfig &config = CycloConfig::get(); //Referência

CycloConfig *config = &CycloConfig::get(); //Ponteiro

C++ trata primariamente objetos definidos pelo usuário da mesma forma que os tipos básicos da linguagem. Então, da mesma forma, se houvesse uma função retornando uma referência para um int e seu valor fosse atribuído a uma variável local, esta variável é uma cópia, completamente independente da referência original.
Para tipos simples, a destruição é trivial e a cópia é feita pela simples replicação dos bits, mas para tipos definidos pelo usuário podem ser definidos destrutores, construtores de cópia e operadores de atribuição. Se não forem definidos, o compilador os gera automaticamente. Mas, para singletons e outros casos especiais, é possível suprimir esta geração:
class CycloConfig {
    ....
    //Desabilita Construtor de Cópia gerado pelo compilador
    CycloConfig(const CycloConfig &) = delete;

    //Desabilita Operador de Atribuição gerado pelo compilador
    CycloConfig &operator=(const CycloConfig &) = delete;
    ....
};

Desta forma, caso se tente copiar o objeto inadvertidamente (como aconteceu no problema) o compilador irá impedir, avisando que as operações de cópia foram desabilitadas pelo usuário.
Comment: Usei a opção por referência e o problema persiste. Fiz um log de passos: https://gist.github.com/carlosdelfino/26a9518c7c7e776ee3970d30bf6d74b7
Comment: @Delfino Já tentou mudar sua classe para "deletar" as operações de cópia?
Comment: Como assim?, no link acima do gist eu coloquei o arquivo principal onde o problema ocorre. ele ainda está bastante confuso porque estou migrando e limpando o código aos poucos.
Comment: Veja a parte final da resposta, eu fiz uma atualização. Faça aquilo para garantir que não estejam sendo criadas cópias em nenhum outro lugar. Além disso você ainda está chamando explicitamente o destrutor no final da função main, o que é errado.
Comment: o problema está resolvido.
100% Obrigado.