Preciso somar valores de uma tabela

Question: Possuo um SELECT e nele eu exibo a soma dos valores de venda de cada produto, teria como eu fazer um somatório total da tabela que efetuei a soma ?
SELECT
     cadpro.descricao,
     sum(itensped.total_venda) AS total_venda
FROM itensped
INNER JOIN pedido ON
    itensped.id = pedido.id
NNER JOIN cadpro ON
    itensped.id_cadpro = cadpro.id
INNER JOIN cadgrp ON
    cadpro.id_grupo = cadgrp.id
       WHERE pedido.empresa = 1
             AND pedido.filial = 1
             AND pedido.data_venda BETWEEN '2017-05-01' AND '2017-05-31'
             AND total_venda > 0
GROUP BY cadgrp.nome_grupo
ORDER BY  total_venda DESC LIMIT 10

Resultado do Select queria fazer um somatório total de total_venda
Answer: Uma vez que quer o somatório total dos 10 produtos com maior valor de venda, sugeria uma sub-query. Exemplo:
SELECT COALESCE(descricao, 'Somatório total de vendas'),
       SUM(total_venda) Total_Venda
  FROM
(
    SELECT
         cadpro.descricao,
         sum(itensped.total_venda) AS total_venda
    FROM itensped
    INNER JOIN pedido ON
        itensped.id = pedido.id
    INNER JOIN cadpro ON
        itensped.id_cadpro = cadpro.id
    INNER JOIN cadgrp ON
        cadpro.id_grupo = cadgrp.id
           WHERE pedido.empresa = 1
                 AND pedido.filial = 1
                 AND pedido.data_venda BETWEEN '2017-05-01' AND '2017-05-31'
                 AND total_venda > 0
    GROUP BY cadpro.descricao
    ORDER BY  total_venda DESC LIMIT 10
) Res
GROUP BY descricao WITH ROLLUP

Isto irá resultar num conjunto de resultados com 11 registos. Os 10 produtos com maior valor de venda e um registo com o somatório total para esses 10 produtos.
Se o objectivo é apenas devolver um único registo com o somatório total de total_venda pode fazer:
SELECT 'Somatório total de vendas',
       SUM(total_venda) Total_Venda
  FROM
(
    SELECT
         cadpro.descricao,
         sum(itensped.total_venda) AS total_venda
    FROM itensped
    INNER JOIN pedido ON
        itensped.id = pedido.id
    INNER JOIN cadpro ON
        itensped.id_cadpro = cadpro.id
    INNER JOIN cadgrp ON
        cadpro.id_grupo = cadgrp.id
           WHERE pedido.empresa = 1
                 AND pedido.filial = 1
                 AND pedido.data_venda BETWEEN '2017-05-01' AND '2017-05-31'
                 AND total_venda > 0
    GROUP BY cadpro.descricao
    ORDER BY  total_venda DESC LIMIT 10
) Res

Comment: me ajudou do jeito que queria, muito obrigado cara. Somente na primeira solução que encontrei erro de Incorrect parameter count in the call the native function "ISNULL" mas, a segunda funcionou
Comment: foi sim, muito obrigado cara
Comment: @VictorT., substitui ISNULL por COALESCE. O erro deve agora ter sido corrigido.

Preciso somar valores de uma tabela


Conditional Probability a Raffle

Question: I would like to know the probability of each number coming out in a raffle in which we have from $1$ to $25$ and are drawn $15$ numbers, would be $\frac{1}{15}$ or $\frac{1}{25}$, or another percentage?
Similar problem:
What is the probability of getting two five consecutive with a six-sided die? The probability of each independent event is equal to $\frac{1}{6}$. This gives us $\frac{1}{6}\times \frac{1}{6} = \frac{1}{36}$, $0.027$ or $2.7$%.
Answer: If $15$ numbers are drawn out of $25$, the probability of any particular number coming up is $15/25=3/5$ (assuming they are drawn without replacement, i.e. $15$ different numbers are drawn).
For your second question, your answer is correct.

Conditional Probability a Raffle


Understanding continuity of probabilities

Question: I am reading a book called All of Statistics by Larry Wasserman that includes a theorem called "continuity of probabilities."
It says that if $A_{n} \rightarrow A$ then $P(A_{n}) \rightarrow P(A)$ as $n \rightarrow \infty$
I am trying to understand what that statement means in English and to understand its import. How can one probability imply another?
I understand that $A_{n}$ can be broken into lots of disjoint $B_{n}$ which can be added up to form $A_{n}$ -- but I don't see the big picture or how that relates to sample spaces.
Comment: Are the sets $A_n$ nested?
Comment: @mattbiesecker yes
Answer: If we have $A_1 \subseteq A_2 \subseteq A_3 \subseteq \dots$ and $A=\cup_{n=1}^\infty A_n,$ we write $A_n \nearrow A.$   Given this assumption, a probability measure satisfies $\lim_{n\to \infty} P(A_n) = P(A).$  The word "continuity in probability" is analogous to continuity at point for a function (e.g.  As $x$ approaches $c$,  we have $f(x)$ approaches $f(c).$ )
Comment: so the idea is as n approaches infinity, the probability of the last (i.e. nth) of the nested sets approaches the probability of the union of all of the nested sets?
Answer: I was trying to find the use of this theorem in a practical sense and came up with a following example.
Suppose you have some sort of distribution from $[0,2]$ on a real number line.
Now you want to find the probability of a number lying between $[0,1]$
Now,
Consider an event defined by the following equations and the occurrence of these events are governed by the above probability distribution in the range of $[0,2]$:
$A_n = [0, 2^{-\frac1n} )$. Therefore
$$A_1 = [0,.5)$$
$$A_2 = [0,.71)$$
$$A_3 = [0,.8)$$
 and so on and as $n$ tends to infinity
$A_n = [0,1)$
Here $P(A_n)$ would be some function giving a value. This value is the probability of the occurrence of An. This would also give the probability of the number lying in the interval $[0,1]$.
This is my understanding of this theorem as I am also reading the same book.
Comment: Welcome to MSE. For some basic information about writing mathematics at this site see, *e.g.*, [basic help on mathjax notation](/help/notation), [mathjax tutorial and quick reference](//math.meta.stackexchange.com/q/5020), [main meta site math tutorial](//meta.stackexchange.com/a/70559) and [equation editing how-to](//math.meta.stackexchange.com/q/1773).


Is changing the hostname on a remote Ubuntu 16.04 safe?

Question: When installing a Postfix mail server I learned that the hostname is an important part of the servers FQDN.
But the servers hostname is not related to the domain name I'm hosting or the SSL cert for my domain... and I need to use secure SMTP.
Should I change the hostname? or can I achieve secure SMTP using masquerading?
I'm concerned if I change the hostname on my remove server I'll run head first into a brick.
this command looks to take care of all the details
http://manpages.ubuntu.com/manpages/trusty/man1/hostnamectl.1.html
or I could manually edit these..
/etc/hosts
/etc/hostname
but can/should I make it work via masquerading instead?
Answer: Do you have console access through a KVM of some sort? If so, that should help you if you do get into a bind. That said, simply changing the server's hostname shouldn't be a problem, unless you have a STIG'd server with FIPS compliance (I'm betting that's unlikely).
You'll want to run the hostname command, AND you'll want to edit /etc/hostname, as if you don't edit the /etc/hostname file, next time the server reboots, it will revert back to the original hostname.


Android: Add both search recent suggests and custom suggests

Question: I want to add some suggestions for a search widget and I don't know how to show both recent and custom suggestions. The snippet below gives me an
CursorIndexOutOfBoundsException: Requested column: 4, # of columns: 4
Any ideas?
My code for the custom suggestions
@Override
public Cursor query(Uri uri, String[] projection, String selection,
                    String[] selectionArgs, String sortOrder) {

    List<String> suggestions = new ArrayList<String>();
    suggestions.add("iphone");
    Cursor recentCursor = super.query(uri, projection, selection, selectionArgs,
            sortOrder);
    MatrixCursor cursor = new MatrixCursor(new String[] { BaseColumns._ID,
            SearchManager.SUGGEST_COLUMN_TEXT_1,
            SearchManager.SUGGEST_COLUMN_INTENT_DATA,
            SearchManager.SUGGEST_COLUMN_QUERY } );
    for (int i = 0; i < suggestions.size(); ++i) {
        String suggestion = suggestions.get(i);
        Object[] row = { Integer.toString(i),
                suggestion,
                suggestion, suggestion };
        cursor.addRow(row);
    }

    Cursor[] cursors = new Cursor[] { recentCursor, cursor};
    return new MergeCursor(cursors);
}

Answer: recentCursor has 5th column which is SUGGEST_COLUMN_FORMAT, so you can not merge 5 columns to 4
Answer: I believe you've forgotten to add SUGGEST_COLUMN_ICON_1 column to the cursor.


Override quicktabs tab titles

Question: I have a quicktabs instance that shows lists of content by year (2012, 2011, 2010 and so on). Each tab is a views generated block that pulls content by date using relative values (current year, current year-1, etc.). How can I override the title of each of the tabs so that I don´t have to hardcode year values as tabs titles? Thanks in advance.
Answer: I finally got this to work by adding on my template.php:
<code>function YOURTHEME_quicktabs_alter($quicktabs) {
if ($quicktabs->machine_name == 'YOUR_QTABS_NAME') {
  $currYear = date('Y');
  for ($i = 0; $i <= 3 ; $i++ ) {
    $yr = ($currYear-$i);
    $quicktabs->tabs[$i]['title'] = t($yr);
  }
}
</code>
}
}
Comment: You don't need to add it to a theme; you can add that code in a custom module.

Override quicktabs tab titles


European Football release clause amount

Question: Neymar's release clause at Barcelona has been increased to €222 million (£192.5m).
The cost of buying the Brazilian out of his contract has been automatically raised as part of his current deal at Camp Nou.
When putting pen to paper in October 2016, Barca inserted a €200m buy-out clause in Neymar's terms.
Having sought to price Neymar out of the current market, his release clause will be nudged up again to €250m in 2018.
So what stops a club from putting an absurd release clause amount on a players contract?
Answer:
What stops a club from putting an absurd release clause amount on a
players contract?

Nothing, except the player himself (or his agent).
The value of the release clause of a player is proportional to the unwillingness of the club to sell the player in the future. For example, in an interview to the BBC, Cristiano Ronaldo's agent Jorge Mendes said that Ronaldo's release clause from Real Madrid was 1 billion euros! Which essentially means that at the time of signing that contract neither Real Madrid nor Cristiano Ronaldo were considering any possible transfer negotiations with other clubs during his contract.
The release clauses can be absurdly high, but then if the club declines any transfer offers (despite the will of the player) below the release clause, then the players that wanted to be transferred may get angry and wait till the end of their contracts and then would go for free.
The less years there are left in the contract of a player to play for his club, the less is the power of the release clause. Why? Because, if a club declines transfer offers below the release clause when the player's contract is due soon, eventually, a player may leave his current club for free when his contract will expire.
The rule of thumb for the club is when defining the release clause is to make it high enough, in order to create a room for possible future transfer negotiations, but also keeping in mind that players' agents will not agree to the extremely large release clauses if the player himself may consider in the future leaving the club during his contract.

European Football release clause amount


Is $x+1$ a factor of $x^{2016}-1$?

Question: $$x^{2016}-1=(x-1)(1+x+x^2+x^3+\dots+x^{2015})$$
If $x+1$ is a factor of $x^{2016}-1$, then $(1+x+x^2+x^3+\dots+x^{2015})=(x+1)G(x)$, where $G(x)$ is some polynomial.
What is $G(x)$ if $x+1$ is also a factor?
Comment: $G(x) = (1+x+\cdots+x^{2015})/(1+x)$.  Is this question "I don't know how to tell if a linear polynomial divides another polynomial" or "I don't know how to do polynomial long division?"
Comment: Is $t-1$ a factor of $t^{1008}-1$? Is $x^2-1$ a factor of $x^{2016}-1$? Is $x+1$ a factor of $x^2-1$? Hence?
Answer: Hint: If $x_0=-1$ is a zero of $x^{2016}-1$, then $(x-(-1))$ is a factor of $(x^{2016}-1)$.
In order to find $G(x)=(x^{2016}-1)/(x+1)$ you need to apply polynomial long division (you should see the pattern).
Answer: Yes, $x+1$ is a factor of $x^{2016}-1$ and
$$x^{2016}-1=(x+1)(x^{2015}-x^{2014}+x^{2013}-\cdots-x^2+x-1)$$
Then
$$G(x)=1+x^2+x^4+\dots+x^{2014}$$
More generally, $x-r$ is a factor of $P(x)$ if and only if $P(r)=0$. In this case, $P(x)=x^{2016}-1$ and $P(-1)=0$, so $x+1$ is a factor of $x^{2016}-1$.
Comment: So x-1 and x+1 cant be both factors of x^2016 - 1 now?  Since its reduced to (x+1) g(x)  now.  x^2016 - 1 is equal to (x+1) g(x) or (x-1) p(x) ,it cant be reduced to (x+1) (x-1) h(x).  So either x-1 or x+1 is the factor, not both.
Comment: @YolandaHui $(x+1)(x-1)(1+x^2+x^4+\dots+x^{2014})=x^{2016}-1$
Comment: Is x^2-1 also a factor?
Comment: @YolandaHui _Yes..._ $(x+1)(x-1)=x^2-1$
Comment: Using geometric series, (x+1)(1+x^2+...+x^2014) is not equal to 1+x+x^2+...+x^2015
Comment: @YolandaHui They are equal. Only even exponents are included in the large term - there's an $x^{144}$ but no $x^{389}$, for example.
Answer: Use this simple lemma

$(x-a)$ is a factor of $P(x)$ if and only if $P(a)=0$
Answer: \begin{align}
x^{2016}-1=&(x^2)^{1008}-1=(x^2-1)((x^2)^{1007}+\dots+x^2+1)\\
&=(x+1)(x-1)(x^{2014}+\dots+x^2+1).
\end{align}

Is $x+1$ a factor of $x^{2016}-1$?


What should i conclude from the following workout?

Question: We know that for any value of $x$ other than $0$, $a^x\ne e^x$ where $a>e, a\in R^+$ but we do know that for some value of $p$, $$pa^x=e^x\ldots(1)$$
you see $p$ is a positive number because of the above assumption.
we all know that $$\frac{\operatorname{d}e^x}{dx}=e^x, \frac{\operatorname{d}a^x}{dx}=a^x\times \log_e a$$
so using above known things, i am going to differentiate equation $(1)$ with respect to $x$
$$\frac{\operatorname d \left(pa^x\right)}{dx}=\frac{\operatorname de^x}{dx}\implies pa^x\ln a = e^x\ldots(2)$$
Note that $p$ is a number and i am talking at a particular value of $x$.
Now from (1) and (2) we can say that $$pa^x=pa^x\ln a\implies a=e,$$
but earlier it was taken that $a>e$ but this turn out to be $a=e$.
But you see at a particular value of $x$ which could be any number, $a$ will comes equal to $e$.
So, what should i conclude from the above?
Comment: It's good to learn from mistakes.  As Andrew's answer points out, just because two functions $f(x)=g(x)$ at some isolated value of $x$ does not imply $f'(x)=g'(x)$.  So everything after you try to differentiate (1) is mistaken.  You might try solving (1) for $p$ to see that for fixed $a$, the value of $p$ depends on $x$, so that correctly differentiating (1) with repsect to $x$ requires us to account for that dependence.
Answer: When you write
$$
pa^{x} = e^{x},
\tag{1}
$$
you're saying (1) holds for one single $x$. When you differentiate to obtain
$$
pa^{x} \ln a = e^{x},
\tag{2}
$$
you're implicitly assuming (1) holds for all $x$ in some open interval.
That is, (2) does not follow from (1) in your situation; any conclusion obtained jointly from (1) and (2) is logically suspect. (Compare Differentiating both sides of a non-differential equation.)


Loss sequence for glmnet

Question: Is the loss sequence returned by cv.glmnet (the slot "cvm") on the standardized variable scale or the original scale?  This only affects the penalty part of the loss, I think.  In other words, are models obtained by calling cv.glmnet with standardize=TRUE comparable to those obtained with standardize=FALSE?
Answer: When you look at the help for cv.glmnet, you will notice it has as its final "parameter": ...
The parameter explanation below tells you that you can pass in any parameter there that glmnet supports (e.g.: standardize=FALSE), and all glmnet fits used during the crossvalidation will receive these parameters.
Comment: I don't understand how this answers the question.  It's possible that e.g standardize=TRUE will give you the loss sequence back on the original scale, right?
Comment: The scaling only affects the way the model is fit (mainly because the relative importance of the variables changes). The results that are returned (i.e. the estimated parameters) are always returned in their original scale, regardless of this  parameter. Whether you calculate predicted values with scaled parameters and scaled data or with both unscaled will give the same results, so it should not matter for any predictive measure, as long as all fits happen the same way (scaled or not).

Loss sequence for glmnet


Hahn-Banach: Operators

Question: Given two Banach spaces $X$ and $Y$.
(More generally locally convex spaces)
Regard a closed subspace $U\subseteq X$.
Does every bounded operator extend:
$$T\in\mathcal{B}(U,Y)\implies T_E\in\mathcal{B}(X,Y)$$
I guess not but I couldn't come up with a counterexample..
Answer: No. Say $X=L^1(\Bbb T)$, and let $$Y=U=H^1(\Bbb T)=\{f\in L^1(\Bbb T):\hat f(n)=0,n<0\}.$$So $H^1$ is just the classical Hardy space, the class of functions that extend to holomorphic functions in the unit disk.
Define $T:U\to Y$ by $Tf=f$. If $T$ extended to an operator on $X$ that would be a projection from $L^1$ onto $H^1$, and there is no such projection. (See Rudin Functional Analysis: An averaging argument shows that if there is a bounded projection then the "obvious" projection would work, but it's not bounded.)
Come to think of it, we get a similar example if $X$ is any Banach space and $U$ is a non-complemented subspace; the above is the only non-complemented subspace I happen to know. (Ok, there's also $H^\infty\subset L^\infty$.)
Comment: Thank you so much!! I was exactly hoping for a construction on a non-complemented subspace. Thank you! :)
Comment: I'm sorry but I have to ask: Why does it necessarily have to extend to a *projection*?
Comment: ??? The extension would be $T:L^1\to H^1$, with $Tf=f$ for every $f\in H^1$. That's the _definition_ of "$T$ is a projection from $L^1$ onto $H^1$".
Comment: So you mean projection simply in the sense of a surjection acting as identity on the range but nothing else about its *kernel*?
Comment: Ok I had a look in Rudin and I understand now: It clearly becomes $P^2=P$.
Comment: The original extension $T$ also satisfies $T^2=T$. That's the same as saying that $Tf=f$ for every $f\in H^1$. Now that averaging argument gives a translation-invariant $P$.

Hahn-Banach: Operators


Angular5 element inside *ngif is allways undefined

Question: In the following scenario, when I click the first div childDiv is always marked as undefined Because methodB returns false, if at some point methodB returns true and childDiv is rendered, when I click the first div again childDiv is still undefined.

   ...

<div *ngIf="methodB()"
   <paper-chip #chip label="Hello">

        H

   </paper-chip>

What can I do so that if methodB returns true childDiv it is not undefined?
Answer: Why invoking childDiv click, when you can simply call its click method?
Try something like this:

   <div *ngIf="methodB()" id="childDiv" #childDiv (click)="someOtherMethod()'

Comment: You are right! I need to change my example to show the real problem


How to plot POSIXct objects / timestamps independent of day?

Question: I hope the question title makes sense. I am collecting some data using a Google Form. The form is always submitted between 5 and 7 pm but on different days. I want to plot the time component of the timestamp on the x-axis versus some other value from the form. I want to make sure that all time plots end up in the same two-hour window in the plot (i.e., between 5 and 7pm) regardless of the date component of the timestamp.
I have downloaded the responses as a CSV and can read in the timestamps without any issues:
demo <- as.POSIXct(demo$Timestamp, format="%m/%d/%Y %H:%M:%S")
And the data looks like this:
> demo
 [1] "2015-10-12 17:02:42 CEST" "2015-10-12 17:02:46 CEST" "2015-10-12 17:02:46 CEST"
 [4] "2015-10-12 17:02:50 CEST" "2015-10-12 17:02:52 CEST" "2015-10-12 17:02:55 CEST"
 [7] "2015-10-12 17:02:58 CEST" "2015-10-12 17:03:02 CEST" "2015-10-12 17:03:09 CEST"
[10] "2015-10-12 17:03:15 CEST" "2015-10-12 17:03:22 CEST" "2015-10-12 17:03:24 CEST"
[13] "2015-10-12 17:03:36 CEST" "2015-10-12 17:03:48 CEST" "2015-10-12 17:04:07 CEST"
[16] "2015-10-12 17:09:20 CEST"

I can plot these using something as simple as this:
plot(demo, rnorm(length(demo)))

But I want the range on the x-axis to be 5-7pm and I need to make sure that all data is plotted in that two-hour range, independent on the day the data was recorded at. If I do something like this:
startTime <- as.POSIXct("17:00:00", format="%H:%M:%S")
endTime <- as.POSIXct("19:00:00", format="%H:%M:%S")
plot(demo, rnorm(length(demo)), xlim=c(startTime, endTime), xaxt='n')
axis.POSIXct(1, at = seq(startTime, endTime, by="hour"), format = "%M", labels=c("17:00", "18:00", "19:00"))

I get the right outline for the plot but no data. This is because startTime and endTime will be set to the current date. If I explicitly use make them the same date as the data in demo ...
startTime <- as.POSIXct("10/12/2015 17:00:00", format="%m/%d/%Y %H:%M:%S")
endTime <- as.POSIXct("10/12/2015 19:00:00", format="%m/%d/%Y %H:%M:%S")

... the data shows up in the plot exactly the way I want them to.
However: I can't add data points from any other day. Can someone explain to me how I can manipulate/use POSIXct objects to strip them of their "date" component and plot them in the same plot?

For testing purposes, you can copy this vector to reproduce the code I posted above:
demo <- as.POSIXct(c("2015-10-12 17:02:42 CEST", "2015-10-12 17:02:46 CEST", "2015-10-12 17:02:46 CEST", "2015-10-12 17:02:50 CEST", "2015-10-12 17:02:52 CEST", "2015-10-12 17:02:55 CEST", "2015-10-12 17:02:58 CEST", "2015-10-12 17:03:02 CEST", "2015-10-12 17:03:09 CEST", "2015-10-12 17:03:15 CEST", "2015-10-12 17:03:22 CEST", "2015-10-12 17:03:24 CEST", "2015-10-12 17:03:36 CEST", "2015-10-12 17:03:48 CEST", "2015-10-12 17:04:07 CEST", "2015-10-12 17:09:20 CEST"))

Comment: I would hack it with regex `demo[grepl("1[789](?=:\\d{2}:)", demo, perl=T)]`. But you can try to work with `lubridate` or `chron` or another hour minute formatting method.
Answer: You could try getting the hours and minutes out using lubridate, then reformatting back to POSIXct. This will work as the default origin for POSIXct is the current date.
library(lubridate)
demo <- as.POSIXct(paste(hour(demo), minute(demo)), format = "%H %M")

Comment: Ahh, this is perfect. That way, I can *convert* all my times to "today" and they all show up in the same two-hour window. I am a little mad that I didn't think of this myself - thank you very much for your help!


Can I exclude a fixed factor from a glmer to test the main effect of different continuous variable?

Question: I'm unsure how to proceed to report my effects.
I have a glmer to run a logistic regression:
glmres.RU.conf.full = glmer(correct ~ choiceConf.scaled * condition + (1 + choiceConf.scaled|subject)  + (1|cityPair), data = myDataForglm.RU, family = binomial)

I'm interested in two things: (1) the interaction between choiceConf.scaled * condition and (2) the main effect of choiceConf.scaled.
Testing my interaction effect doing a likelihood ratio test is straightforward:
glmres.RU.conf.sum  = glmer(correct ~ choiceConf.scaled + condition + (1 + choiceConf.scaled|subject)  + (1|cityPair), data = myDataForglm.RU, family = binomial)
anova(glmres.RU.conf.full, glmres.RU.conf.sum)

                    Df    AIC    BIC  logLik deviance  Chisq Chi Df Pr(>Chisq)
glmres.RU.conf.sum   7 4467.4 4513.5 -2226.7   4453.4
glmres.RU.conf.full  8 4469.3 4522.0 -2226.7   4453.3 0.0606      1     0.8056

I am unsure about what the correct null model to test the main effect of choiceConf.scaled is. I can think of two approaches. First, I could compare a model including the two fixed effects vs. one including only the fixed factor I'm not interested in.
glmres.RU.conf.sum  = glmer(correct ~ choiceConf.scaled + condition + (1 + choiceConf.scaled|subject)  + (1|cityPair), data = myDataForglm.RU, family = binomial)
glmres.RU.null      = glmer(correct ~ condition                     + (1 |subject)                     + (1|cityPair), data = myDataForglm.RU, family = binomial)

               Df    AIC    BIC  logLik deviance  Chisq Chi Df Pr(>Chisq)
glmres.RU.null      4 4471.8 4498.2 -2231.9   4463.8
glmres.RU.conf.sum  7 4467.4 4513.5 -2226.7   4453.4 10.443      3    0.01515 *

Note that the AIC and BIC go in different directions. For the BIC, the null model is better (presumably because it's penalizing the 3 Df difference too strongly). So I tried to find a way to compare models that don't differ so much in complexity. I could do this by never considering the effect of condition in my model at all (I'm not interested in it for now, after all).
glmres.confOnly.full     = glmer(correct ~ choiceConf.scaled            + (1 + choiceConf.scaled|subject)  + (1|cityPair), data = myDataForglm.RU, family = binomial)
glmres.confOnly.null     = glmer(correct ~ 1                            + (1 |subject)                     + (1|cityPair), data = myDataForglm.RU, family = binomial)

anova(glmres.confOnly.full, glmres.confOnly.null)

                 Df    AIC    BIC  logLik deviance Chisq Chi Df Pr(>Chisq)
glmres.confOnly.null  3 5178.4 5198.2 -2586.2   5172.4
glmres.confOnly.full  6 5082.8 5122.4 -2535.4   5070.8 101.6      3  < 2.2e-16 ***

But this sounds incorrect to me. Is it ok to exclude factors (that are known to have a significant effect) from a model? Given that the BIC values are so different between the first and the second approach, I suspect it's not correct.
Any other comments welcome.
Answer: This really isn't specific to GLMMs, or even to GLMs. It's a basic issue with model testing in any kind of models descended from linear models (i.e. [G]LM[M]s ...) Ideally, you wouldn't use AIC/BIC to "test the effect of a parameter" - while the answers often go in similar directions, they are not designed for hypothesis testing.
Let's take a look at an example with a strong interaction:
beta <- c(0,1,0,-2)
set.seed(101)
dd <- data.frame(x=rnorm(100),
                 y=factor(sample(c("a","b"),size=100,replace=TRUE)))
dd$z <- rnorm(100,mean=model.matrix(~x*y,dd) %*% beta,sd=0.2)
with(dd,plot(z~x,col=as.numeric(y)))
legend("bottomright",legend=paste0("y=",c("a","b")),col=1:2,pch=1)

The question is: what do you mean when you say "test the main effect"?  Whether the main effect of $x$ is significant, and in which direction, depends entirely on what value of $y$ you decide on.
If you use R's defaults, you are implicitly testing the effect of x at the baseline level of y ("a" in this case)
## helper function
pp <- function(...) {
    cc <- coef(summary(lm(z~x*y,dd,...)))
    printCoefmat(cc,digits=3)
}
pp()
##             Estimate Std. Error t value Pr(>|t|)
## (Intercept)   0.0249     0.0236    1.05     0.29
## x             1.0242     0.0255   40.23   <2e-16 ***
## yb           -0.0338     0.0373   -0.91     0.37
## x:yb         -2.0045     0.0401  -49.99   <2e-16 ***

So in this case, x is strongly significant (slope=1.02 with SE of 0.0255).
If we change to "SAS-style" contrasts where the last level ($y$="b") is the baseline, we get a strongly negative effect (-0.98 with SE of SE 0.03).
pp(contrasts=list(y=contr.SAS))
##             Estimate Std. Error t value Pr(>|t|)
## (Intercept) -0.00889    0.02892   -0.31     0.76
## x           -0.98022    0.03098  -31.64   <2e-16 ***
## y1           0.03380    0.03734    0.91     0.37
## x:y1         2.00445    0.04010   49.99   <2e-16 ***

Or, if we use sum-to-zero contrasts, we get the average of the slopes when y=a and y=b - about zero (slope = 0.02, SE = 0.02)
pp(contrasts=list(y=contr.sum))
##             Estimate Std. Error t value Pr(>|t|)
## (Intercept)  0.00801    0.01867    0.43     0.67
## x            0.02201    0.02005    1.10     0.28
## y1           0.01690    0.01867    0.91     0.37
## x:y1         1.00223    0.02005   49.99   <2e-16 ***

The question here is whether "halfway between conditions" means anything at all; if my levels were (e.g.) "male" and "female", is looking at the halfway point sensible?
Another reasonable choice would be to test the combination of the main effect and its interaction (i.e. the total effect of x) by comparing models with and without x:
anova(lm(z~x*y,dd),lm(z~y,dd))
## Analysis of Variance Table
##
## Model 1: z ~ x * y
## Model 2: z ~ y
##   Res.Df    RSS Df Sum of Sq    F    Pr(>F)
## 1     96  3.208
## 2     98 90.748 -2   -87.541 1310 < 2.2e-16 ***

The bottom line is that when you want to test main effects in the presence of interactions you have to decide what you mean.  This is why some old-school statisticians start to foam at the mouth and mutter about the principle of marginality when this topic comes up ...


How to seperate regex and get every occurences?

Question: Hi I have the following string of log . I want to get every occurences with seperate comma .
srcnat: in:(none)(ether5) out:ether1, src-mac 11:aa:22:bb:33:cc, proto TCP (SYN), 10.5.59.207:49361->184.108.40.206:443, len 64

I want to get

"srcnat: in:(none)(ether5) out:ether1"
"src-mac 11:aa:22:bb:33:cc"
"proto TCP (SYN)"
"10.5.59.207:49361->126.96.36.199:443"

I can get "srcnat: in:(none)(ether5) out:ether1"  with regex (^[^,]*) . How can i get others separately
Comment: What language are you working with?
Comment: The new question wizard does a good job noticing: Regular expression questions get better answers if they …include a tag for **one** specific engine or language (perl, pcre, c#, etc...) …show the pattern that isn't working …Provide some examples of input text that should match, *and also* ones that shouldn't match …describe the desired results, and how the pattern isn't producing them. There are no more excuses.
Comment: I want to create Rsyslog config with this. Rsyslog running under ubuntu 16.04 server.I dont know what language . I m following documentation. Configuratin like this : $template test,"%msg:R,ERE,1,BLANK:(^[^,]*)--end%\n"
Answer: Since you didn't specify your language, I go with Java that I'm more comfortable with. Split with
myString.split(,\s+(?=(?:(?:[^']*'){2})*[^']*$), -1)

This allows you to split by a comma followed by a space, while ignoring the ones in a quotation.
Comment: @melpomene I assumed Java.
Answer: What you may want is the regex /([^,]+)(?=,)/g.
This will match (in groups) anything that is not a comma, up until a comma is found.
This can be seen on Regex101, or in the following:

var regex = /([^,]+)(?=,)/g;
var string = "srcnat: in:(none)(ether5) out:ether1, src-mac 11:aa:22:bb:33:cc, proto TCP (SYN), 10.5.59.207:49361->126.96.36.199:443, len 64";

console.log(string.match(regex));


rsync & source/dest & tar.gz beginner thing, too primitive for FAQs:

Question: actually, I AM being ashame about my question (both parts of it) but could anyone help me with my problem?
*) I have read how to use rsync BUT could anyone give me an example how to type it in?
rsync -a source dest
is comprehensible BUT how do I write source and dest?
(they are called sda1 and sda2 in my linux)
is it "rsync -a sda1 sda2" (for example, for copying all of sda1 to sda2 ?)
and
*) I have downloaded a driver and an executable for linux (they are .tar.gz)
since I dont care about the MD5 key (I would not know how to use that, either)
my problem is only
a) in which folder /root/??? do I have to copy the contents of the driver .tar.gz
(or does that need an extra installation routine? I want to use it with DSL damn small linux from CD without installing the -- I think -- debian which it is, so I still should be able to copy it into a virtual disk part in memory claimed to be used by DSL) ?
and
b) in which folder /root/??? do I have to copy the executable (and how do I start it) ?
(or, same question, does that need an extra installation?)
thank you for your patience, whoever would care about me
Regina
Comment: These questions are a better fit for either http://unix.stackexchange.com or [SU], as they don't appear to be related to professional system administration (see our [FAQ]).
Comment: I would like to answer the MD5 part since you can use in in the future with a lot of programs. Simply run `md5 filename`. It will return an output similar to this one: `MD5 (filename) = db24a67c07085d581763af058f34129d`. (The actual returned value should differ). You compare the value stored in a known safe this_should_be_the_value.md5 file with the one you generated. If someone tampered with the file then the values do not match.
Answer: First, sda1 and sda2 are likely partition names, not mounted file systems. You will need to check if they are already mounted. To do this, use the command mount without any parameters. If they don't appear in this list, you have to mount them first, e.g. with mount /dev/sda1 /mnt/data1 and mount /dev/sda2 /mnt/data2.
If this is done, you can just use
rsync -av /mnt/data1 /mnt/data2

If one or both are already mounted, replace /mnt/data1/ (or data2 with the respective mount point).
Also, should you actually have two directories named sda1 and sda2, the command will in fact be
rsync -av /path/to/sda1 /path/to/sda2

Please rephrase the second question, stating what you have and what you want to do, without irrelevant additional infos like the MD5 part. Also, try to use the formatting tools that are available to make your text more readable. As it stands, it is quite confusing.


Arithmetic Questions:

Question: There was one Mess for 30 boarders in a certain hotel. If the number of boarders was increased by 10, the expenses of the mess increased by rs40 per month, while the average expenditure per head diminished by rs 2 . Find the original monthly expenses
I am not able to solve this question, How to solve ? please anyone guide me for the Answer
Answer: Hint:
If the mess spends $x $ amount on thirty boarders, the average expenditure for the thirty boarders is $=\displaystyle \frac {x}{30} $.
Similarly, the average expenditure for forty boarders is $=\displaystyle \frac {x+40}{40} $.
Thus , $$\frac {x}{30} - \frac {x+40}{40} =2$$
Hope you can take it from here.

Arithmetic Questions:


Inequalities for combinations of $\int f $ and $\int (1/f)$ where $m\le f\le M$ on an interval

Question: Let $f\in C[a,b]$. Assume that $\min_{[a,b]}f=m>0$ and $M=\max_{[a,b]}f$.
Which one is true?
a. $$\frac{1}{M}\int_a^bf(x)dx+m\int_a^b\frac{1}{f(x)}dx\geq 2\sqrt{\frac{m}{M}}(b-a)$$
b. $$\int_a^bf(x)dx\int\frac{1}{f(x)}dx\geq (b-a)^2$$
c. $$\int f(x)dx\int_a^b\frac{1}{f(x)}dx\leq (b-a)^2$$
For the first one
$$\frac{1}{M}\int _a^bf(x)+m\int _a^b\frac{1}{f(x)}dx\geq {\frac{m}{M}}(b-a)+{\frac{m}{M}}(b-a)$$
 and the last two I am not getting.
How to find these?
Answer: For a. Note that if $x > 0$, we have ${x\over M} + {m \over x} \ge 2 \sqrt{m \over M}$ (the function is strictly convex and unbounded as $x \downarrow 0$ and $x \to \infty$, differentiate to find the minimiser).

 $\int_a^b ({f(x) \over M} + {m \over f(x)})dx \ge \int_a^b2 \sqrt{m \over M} dx$.

For b. use Cauchy-Schwarz with the functions $x \mapsto \sqrt{f(x)}$ and
$x \mapsto \sqrt{1 \over f(x)}$.

 Let $g(x) = \sqrt{f(x)}, h(x) = \sqrt{1 \over f(x)}$. Then $(\int_a^b g(x)h(x)dx )^2 \le \int_a^b g(x)^2 dx \int_a^b h^2(x) dx$.

For c. pick any non-constant $f$ that satisfies the hypotheses.
Comment: what if $x=0$ @copper.hat
Comment: We have $f(y) \ge m > 0$. (Replace $x$ in the formula above by $f(x)$ and integrate over $[a,b]$.)
Comment: I did not get that $f(y)>0$ how does this imply $x\neq 0$
Comment: Emm, why are you concerned with $x=0$? It is irrelevant to the problem.
Comment: I added an explicit computation above, but try to figure it out first...
Comment: Oh thanks I got it but are u sure b is correct I am getting c to be true since by Cauchy $f.g\leq (f^2)^{\frac{1}{2}}.g^2^{\frac{1}{2}}$ @copper.hat
Comment: Yes I am. I have added the explicit computation above, but try to figure it out first...
Comment: Thanks for your answer It was of great help
Comment: Glad to be able to help!
Answer: In fact,we have this following stronger inequality:
$$\left(\int_{a}^{b}f(x)dx\right)\cdot\left(\int_{a}^{b}\dfrac{1}{f(x)}dx\right)\le \dfrac{(m+M)^2(b-a)^2}{4Mm}$$
proof  :since $
m\le f(x)\le M$
so we have
$$\dfrac{(f-M)(f-m)}{f}<0\Longrightarrow f+\dfrac{Mm}{f}\le M+m$$
so
$$\int_{a}^{b}f(x)dx+Mm\int_{a}^{b}\dfrac{1}{f(x)}dx\le \int_{a}^{b}(M+m)dx=(M+m)(b-a)$$
use AM-GM inequality we have
$$\int_{a}^{b}f(x)dx+Mm\int_{a}^{b}\dfrac{1}{f(x)}dx\ge 2\sqrt{Mm\left(\int_{a}^{b}f(x)dx\right)\cdot\left(\int_{a}^{b}\dfrac{1}{f(x)}dx\right)}$$
so we have
$$\left(\int_{a}^{b}f(x)dx\right)\cdot\left(\int_{a}^{b}\dfrac{1}{f(x)}dx\right)\le \dfrac{(m+M)^2(b-a)^2}{4Mm}$$
Other hand use Cauchy-Schwarz inequality we have
$$\left(\int_{a}^{b}f(x)dx\right)\cdot\left(\int_{a}^{b}\dfrac{1}{f(x)}dx\right)\ge (b-a)^2$$
Comment: what is $n$ here?


Guitar unusual buzzing

Question: I built a guitar (bought a LP body and the electronics) and wired everything in it myself. However, There is a strange buzzing that stops when I touch the tailpiece (or any metal when the strings are on it). This doesn't seem to be normal buzz though; it only occurs when the volume for the selected pickup (they are humbuckers) is under a certain point (around 9) and the buzz gets louder as you turn the tone up. what is the cause of this buzz, and does anybody have any suggestions on how to fix it?
P.S. I have used multiple amps, and every one buzzes when the guitar is plugged in.
Answer: Usually this sort of hum or buzz is because of the resistor in the volume pot.  When the volume is at 10, the resistor is not being used.  This means that the pickup is essentially directly connected to the amp.  There's no chance for 60 cycle hum to enter the signal except through bad cables, etc.  When below 10 the resistor itself will pick up 60 cycle hum, which is what you're hearing.  Usually, grounding the volume pot casing will fix the problem.  When this doesn't fix it, it's usually that the pot is poorly insulated internally.  Replacing with a higher quality pot should fix it.
Comment: could the wire used make a difference? I just used some bare copper wire I had laying around for ground (and I have cts pots (the standard))
Comment: It shouldn't matter that the ground isn't sheathed.  You can try bypassing the volume pot.  If the hum is still there, then the tone pot is suspect.  Bypass it too to be certain.  Does the hum stop if you turn the tone pot all the way down?
Comment: yes, it does stop when it is at 0, and gets louder as it gets closer to 10
Comment: Ok, could be a bad tone capacitor or an ungrounded tone pot (if the capacitor is soldered to the tone pot casing). Or it could be a capacitor with too small a value.  If it's not any of that, we're past what I know.
Answer: Quite simple actually, I had the exact same problem when I did the exact same thing, it it very likely caused by either a dodgy solder connection,a ground loop, or a lack of magnetic shielding.
The reason for buzzing by a dodgy solder connection is clear the electricity doesn't pass through easily causing a buzzing.
A ground loop is what happens when there is a 'loop' in the ground wiring. If this is the case, try to touch other metal parts of the guitar, does the buzzing stop? You will have to pull apart the wiring and ensure there isn't a loop in the wiring of the ground.
Buzzing from dodgy magnetic shielding can sometimes rarely cause a buzzing. Outside magnetic impulses cause current in wires and therefore buzzing. At guitar shops or even hardware and electronics stores there should be some magnetic shielding paint which you paint on the wood around the electronics to exude outer magnetic impulses.

Guitar unusual buzzing


How to calculate standard deviation of a series of binary outcomes?

Question: I'm trying to calculate the standard deviation of a series of binary outcomes and would like confirmation that my computations of SDEV are correct or not (as explained further below my outcomes shown below in yellow in the illustration don't make sense to me thus I ask for help). I am calculating the rate that a population of elements reaches a state of "C" over time. This is a binary outcome: either an element reaches state C or it doesn't.
Columns F and K, with formulas exposed to their immediate rights respectively, show my SDEV calculations. Column F calculates SDEV for each period independently (based on elements reaching state C in each period per Column B), and column K calculates SDEV on a cumulative basis (based on elements cumulatively reaching state C per Column C).
Where things don't make sense is shown in rows 16-20 below: expanding the population by a factor of 10, but keeping the rates of reaching state of C the same, results in much higher SDEV (columns F and K, rows 16-20). Clearly I am doing something wrong.
Ultimately, what I will be trying to do here, is run simulations to derive a distribution of possible cumulative C percentages in Period X. Thus I need to make sure I get SDEV correct. The actual population of elements I am working with is 68,000.
Answer: You are confusing Bernoulli distribution with binomial distribution. Bernoulli distribution is a distribution for binary events, where the probability of "success" is $p$ and the standard deviation is $\sqrt{p(1-p)}$. The binomial distribution is about running $n$ Bernoulli trials with the same probability $p$ (e.g. you are tossing a coin $n$ times), it is a distribution for the total number of successes. The second distribution has a standard deviation equal to $\sqrt{np(1-p)}$.
You calculated the standard deviation for the binomial distribution, i.e. for the number of successes, so it grows with $n$. Maybe wanted to calculate the standard error for the mean of binomial distribution ($p$)?
So your calculations are correct, but you are either misinterpreting them, or you wanted to calculate the standard error while calculating standard deviation.
Comment: I think your description of "divide by sqrt(n) afterwards" is incorrect, or at least ambiguous. The standard error of the mean of the binomial distribution is sqrt(p(1-p)/n). So to get that from sqrt(np(1-p)) we need to divide by n, not sqrt(n). Right?
Comment: @DavidLukeThiessen you are right, the wording was confusing. I removed it as the link alone suffices.
Comment: Thank you for the detailed explanation! I learned important points from this. We'll just say it's been a very long time since my last statistics class and I need to polish up some.


Unresolved dependency File Entity error

Question: I'm trying to run a serious of updates on Drupal.
However, I'm seeing to be running into the following error:
Unresolved dependency   File Entity (Version >7.x-2.0 required)
Media requires this module and version. Currently using File Entity version 2.0-beta2
Where would the directory structure be so I can update the file entity and do the updates.
Answer: Modules are typically found in sites/site_name/module. That's often sites/default/modules.
If your site was installed by a non-standard installation profile, they could also be at /profiles/profile_name/modules, or somewhere else under the profile folder, instead.
To find it quickly, run this from your web root:
<code>find . -name file_entity.info
</code>

Unresolved dependency File Entity error


Is there a way to know if the navigator is fullscreen (F11)

Question: In javascript, Is there a way to know if the navigator is fullscreen ?
I mean real fullscreen (F11 with chrome).
I need to propose it to the user only if he hasn't done it yet.
Comment: http://stackoverflow.com/questions/21103478/fullscreenchange-event-not-firing-in-chrome
Comment: `if (window.innerHeight == screen.height)` comes to mind, but it's probably not very accurate
Comment: There's no native API to check if the navigator is in fullscreen mode ... but you have the fullscreenEnabled method that return true if the context object and all ancestor browsing context's documents have their fullscreen enabled flag set ... if it returns false there must be an element in FS mode (or not?).

https://dvcs.w3.org/hg/fullscreen/raw-file/tip/Overview.html#api

https://developer.mozilla.org/en-US/docs/Web/Guide/API/DOM/Using_full_screen_mode
Comment: you can use css to hide the button in non-fullscreen: https://developer.mozilla.org/en-US/docs/Web/CSS/:fullscreen
Answer: For new browsers, this will work
<code>function isFullScreen(){
    return (!window.screenTop && !window.screenY)
}
</code>
Comment: Not sure if this works. I always get true. In fullscreen and in not fullscreen.
Comment: What browser do you have?
Comment: tells me true in chrome from the console, non-maximized.


A question regarding a possible misprint on showing why a part bertrands lemma leads to a certain result

Question: I got a question in an assignment but I'm sure it has to be a misprint, any clarification on this would be much appreciated ( though I want to work the actual problem out myself)
It's about Bertrands postulate, particularly we've been asked to consider the lemma which states that for $n>2$ and $\tfrac{2n}{3}<p\leq n$, $p$ does not divide $\pmatrix{2n\\n}$, and then explain why this means that all prime factors of $\pmatrix{2n\\n}$ satisfy $p\leq \tfrac{2n}{3}$.
but then take for example $n=3$ then  $\pmatrix{2n\\n}$= $\pmatrix{6\\3}=\tfrac{126.96.36.199.2.1}{188.8.131.52.2.1.}=\tfrac{6.5.4}{3.2}=5.2^2$ and so 5 appears in the prime decomposition. But then this contradicts what we were trying to show because $\tfrac{2n}{3}=\tfrac{6}{3}=2$and 5 is certainly not less than 2. Surely the thing we should be trying to show is that $p\geq\tfrac{2n}{3}$ , no ?
Answer: First, it is correct that $\binom{2n}{n}$ has no prime factor $p$ such that $\frac{2n}3 \lt p \le n$.
It follows that all prime factors $p$ are either $\le \frac{2n}3$ or greater than $n$.  As you've seen with $n = 3$, both cases can occur.
Since the intent is to prove Bertrand's postulate, i.e., that there is some prime between $n$ and $2n$, I suspect the plan was to assume the contrary and eventually arrive at a contradiction.  Under this assumption, all prime factors of $\binom{2n}{n}$ must be either $\le \frac{2n}3$ or greater than $2n$.  If that is what's going on, your next step is simply to eliminate the possibility that $p \gt 2n$.  That isn't hard.  The difficult step is to show that the contribution of the primes $\lt \frac{2n}3$ is not actually large enough to produce $\binom{2n}{n}$, yielding the desired contradiction.
Comment: Sorry I should have been more clear, we don't actually have to prove bertrands postulate, just explain why the part of the lemma I stated means that $p\leq\tfrac{2n}{3}$. But I assume your answer is still what I would need to use to explain this


Javascript - Unable to convert string to number

Question: Im creating a string parser app, This is my app flow

select all text in a website from a browser
paste it on my site, and it will convert it into something

The problem is when i tried to convert a string number using either Number(myString) or parseInt(myString) i got NaN.
But when i use a dummy variable like let i = "19" , it will correctly convert it to number.
What i have tried is converting my string to urlEncoded format, and the result is:
for string 21 , the encoded result is %E2%80%AD21%E2%80%AC
So i am concluding that the string that i got from copy pasting in a web browser is unparseable due to some kind of formatting.
How do i fix this behaviour?
Comment: The easiest way to help but to be able to see what you're actually getting from the browser before you parse it.

Chances are you're catching some other data which isn't a number.
Comment: sample string that i got from browser `(19|−14)` is encoded to: `%E2%80%AD%28%E2%80%AD19%E2%80%AC%7C%E2%80%AD%E2%88%92%E2%80%AD14%E2%80%AC%E2%80%AC%29%E2%80%AC`

you can urldecode my string and play with the value
Comment: `+decodeURIComponent('%E2%80%AD21%E2%80%AC').replace(/^.(.*).$/, '$1')` seems to work
Comment: What's it worth of, if we'd implement our own parser, it's _your parser_ which doesn't work here, and if we can't see the code, we can't fix your parser either.
Answer: You can use replace(/[^\x20-\x7E]/g, '') to replace non-printable ASCII chars like so:

const sillyString = decodeURIComponent("%E2%80%AD21%E2%80%AC");
console.log(sillyString);
console.log(parseInt(sillyString));
console.log(parseInt(sillyString.replace(/[^\x20-\x7E]/g, '')));

Maybe that will help?


Dimension of subsets of nonsigular variety

Question: Could  you help me to prove this question? Do you have any idea?
Let $X$ be a nonsingular  variety and $Y \subseteq X$ is  close and nonsingular . Then for any $x \in Y$   which $\dim Y_x=\dim X_x -n$ there is an affine open neighborhood $ U$, $ x\in U\subseteq X$ such that $Y\cap U=V(f_1,\ldots,f_n)$ where   $ (f_1,\ldots,f_n) $ is a regular sequence of $\mathcal{O}(U)  $.
Comment: Basically it's a property of regular local rings.
Answer: Because $X$ and $Y$ are non-sigular, the conormal bundle to $Y$ in $X$
is a locally free sheaf on $Y$ of rank $n$.  Choose an affine n.h. $U = $
Spec $A$ of $x$ in $X$ such that over the intersection $U \cap Y$ the conormal
bundle becomes free.  If we let $I$ be the ideal in $A$ cutting out $Y$
(so $U \cap Y =$ Spec $A/I$), then the conormal bundle is the sheaf associated to the module $I/I^2$.   Thus $I/I^2$ is free of rank $n$ over $A/I$,
and so is generated by $n$ elements.
A Nakayama-type argument will now show that $I$ is generated by $n$ elements,
say $f_1,\ldots,f_n$.  The fact that these form a regular sequence is related
to the fact that they give a free basis for $I/I^2$.


How to Get the Value of field_code_file

Question: Considering that I know the NID of the node, how can I get the value of one of the field that belongs to that NID?
I tried everything I can to get the value of field_code_file with the following code:
$node = node_load($_GET['nid']);
$wrapper = entity_metadata_wrapper('node', $node);
$file = $wrapper->field_code_file->value();

The value returned by $file is "array". Here's the value:
Array ( [#theme] => field [#weight] => 0 [#title] => Code File [#access] => 1 [#label_display] => above [#view_mode] => _custom_display [#language] => und [#field_name] => field_code_file [#field_type] => file [#field_translatable] => 0 [#entity_type] => node [#bundle] => source_code [#object] => stdClass Object ( [vid] => 71 [uid] => 1 [title] => Billing Software [log] => You can now download the installer for Billing System. This is important if you don't have crystal reports v8.5 in your machine. [status] => 1 [comment] => 2 [promote] => 1 [sticky] => 0 [ds_switch] => [nid] => 29 [type] => source_code [language] => und [created] => 1227189989 [changed] => 1260934297 [tnid] => 0 [translate] => 0 [revision_timestamp] => 1260934297 [revision_uid] => 1 [body] => Array ( [und] => Array ( [0] => Array ( [value] =>

) ) ) [field_screenshot] => Array ( [und] => Array ( [0] => Array ( [fid] => 36 [alt] => [title] => [width] => [height] => [uid] => 1 [filename] => Billing Screenshot.jpg [uri] => public://images/admin/Billing Screenshot.jpg [filemime] => image/jpeg [filesize] => 35357 [status] => 1 [timestamp] => 1227589659 ) ) ) [field_code_file] => Array ( [und] => Array ( [0] => Array ( [fid] => 37 [display] => 1 [description] => [uid] => 1 [filename] => Billing System.zip [uri] => public://download/admin/Billing System.zip [filemime] => application/zip [filesize] => 864517 [status] => 1 [timestamp] => 1227589659 ) ) ) [field_terms_and_conditions] => Array ( [und] => Array ( [0] => Array ( [value] => 1 ) ) ) [field_language] => Array ( [und] => Array ( [0] => Array ( [tid] => 7 [taxonomy_term] => stdClass Object ( [tid] => 7 [vid] => 5 [name] => Visual Basic [description] => [format] => [weight] => 0 [vocabulary_machine_name] => vocabulary_5 [metatags] => Array ( ) ) ) ) ) [field_tags] => Array ( [und] => Array ( [0] => Array ( [tid] => 52 [taxonomy_term] => stdClass Object ( [tid] => 52 [vid] => 10 [name] => visual basic [description] => [format] => [weight] => 0 [vocabulary_machine_name] => vocabulary_10 [metatags] => Array ( ) ) ) [1] => Array ( [tid] => 55 [taxonomy_term] => stdClass Object ( [tid] => 55 [vid] => 10 [name] => billing [description] => [format] => [weight] => 0 [vocabulary_machine_name] => vocabulary_10 [metatags] => Array ( ) ) ) [2] => Array ( [tid] => 323 [taxonomy_term] => stdClass Object ( [tid] => 323 [vid] => 10 [name] => cable tv [description] => [format] => [weight] => 0 [vocabulary_machine_name] => vocabulary_10 [metatags] => Array ( ) ) ) ) ) [metatags] => Array ( ) [cid] => 75722 [last_comment_timestamp] => 1386138557 [last_comment_name] => Legendx [last_comment_uid] => 0 [comment_count] => 442 [name] => admin [picture] => 1 [data] => a:7:{s:14:"picture_delete";i:0;s:14:"picture_upload";s:0:"";s:7:"contact";i:1;s:13:"form_build_id";s:37:"form-df16b3b26332f9a4dd7de12c3f483943";s:9:"nodewords";a:9:{s:8:"abstract";a:1:{s:5:"value";s:0:"";}s:9:"canonical";a:1:{s:5:"value";s:0:"";}s:9:"copyright";a:1:{s:5:"value";s:0:"";}s:11:"description";a:1:{s:5:"value";s:0:"";}s:8:"keywords";a:1:{s:5:"value";s:0:"";}s:13:"revisit-after";a:1:{s:5:"value";s:1:"1";}s:6:"robots";a:2:{s:5:"value";a:6:{s:9:"noarchive";i:0;s:8:"nofollow";i:0;s:7:"noindex";i:0;s:5:"noodp";i:0;s:9:"nosnippet";i:0;s:6:"noydir";i:0;}s:11:"use_default";i:0;}s:8:"dc.title";a:1:{s:5:"value";s:0:"";}s:8:"location";a:2:{s:8:"latitude";s:0:"";s:9:"longitude";s:0:"";}}s:4:"info";s:106:"To receive an update on your email please enter your email at Feed subscription at the right of this page.";s:6:"format";s:1:"2";} [_field_view_prepared] => 1 [entity_view_prepared] => 1 [content] => Array ( ) ) [#items] => Array ( [0] => Array ( [fid] => 37 [display] => 1 [description] => [uid] => 1 [filename] => Billing System.zip [uri] => public://download/admin/Billing System.zip [filemime] => application/zip [filesize] => 864517 [status] => 1 [timestamp] => 1227589659 ) ) [#formatter] => file_default [0] => Array ( [#theme] => file_link [#file] => stdClass Object ( [fid] => 37 [display] => 1 [description] => [uid] => 1 [filename] => Billing System.zip [uri] => public://download/admin/Billing System.zip [filemime] => application/zip [filesize] => 864517 [status] => 1 [timestamp] => 1227589659 ) ) )

I am expecting a value like this:
http://www.mysite.com/sites/default/files/download/admin/Billing%20System.zip

I'm using this code in my simple module that I created.
For Jeet:
Thanks. When I use this command print_r($file), it returns this value:
Array ( [0] => Array ( [fid] => 37 [display] => 1 [description] => [uid] => 1 [filename] => Billing System.zip [uri] => public://download/admin/Billing System.zip [filemime] => application/zip [filesize] => 864517 [status] => 1 [timestamp] => 1227589659 ) )

Now how can I get the full url like:
http://www.mysite.com/sites/default/files/download/admin/Billing%20System.zip

I'm trying to understand what you mean by file_create_url($uri), but I can't crack my head on it.
Can you please explain it to me further?
Thank you
Comment: Since you haven't shown what is failing, eg, what is being returned instead of what you are hoping for, perhaps http://deeson-online.co.uk/labs/programatically-access-field-data-using-entitymetadatawrapper-drupal can shed some light on the various ways of doing this
Comment: Hi, I updated my post.
Answer: Assuming the field is a file type.
$node = node_load($_GET['nid']);
$file = field_get_items('node', $node, 'field_code_file');

Print the $file. you will get a URI index. To get your full path to file use function file_create_url($uri)
Let me know if this doesn't get you the result.
Comment: Thank you. I almost there. I updated my post. Please try to look at it.
Comment: Glad I could help. :)

How to Get the Value of field_code_file


Use a different password for SSH access from local login

Question: Unfortunately, not all (client) software that supports SSH/SFTP supports publickey authentication.
How would one set up a standard Ubuntu desktop (with sshd enabled) so that you could use an easy password to login locally, but need a different (more secure) password to login to the same account via SSH?
I would prefer to remain able to login to the desktop user via publickey auth, for those programs that do support it.
Comment: Use an SSH key and encrypt the key with the "easy" password.
Comment: only way I'm aware of requires a FreeIPA domain and hbac
Comment: @TheFiddlerWins That doesn't work, because the apps I'm talking about simply do not support publickey auth. They literally have 'host', 'port', 'username', 'password'. I'd like to use a secure password there, and an easy password for local logins to the same user.
Answer: Have another user for SSH Login and use sudo
or su - if need to Access the Desktop-User Profile.
Disable the Desktop-User in /etc/ssh/sshd_conf with "DenyUsers":
/etc/ssh/sshd_config:

...
DenyUsers Desktop-User
...
Comment: This would prevent logging in to the desktop user with publickey auth, correct? I'd rather avoid that if possible.
Answer: I don't know if I understand your request but if I understand right, you need a user who can log in to the server locally and via SSH but with different passwords?
If that is the case, simply create an SSH keypair with a different password and allow remote login with SSH keypair. In /etc/ssh/sshd_config find the line: PasswordAuthentication. Set this to no. From this point the users will be able to log in to your server via SSH if they have a private key available on their client, and they will have to enter the SSH keys passphrase instead the users password that you use to log in locally.
Comment: As I've said, lots of clients simply do not support logins using keypairs, and using a different third party app to connect isn't so feasible on mobile.
Answer: OpenSSH and other ssh servers I'm aware of don't allow changing these things only for ssh logins, but there are ways to hack your way around it.
OpenSSH can use PAM for authentication. Unfortunately it doesn't allow specifying a non-default PAM service, so you'll need to change the main PAM configuration. Pam isn't very flexible, but there are modules that allow PAM to run a custom script on login, so you could try to create a pam script that detects SSH logins and then accepts a different password from a non-SSH login. I don't know PAM in detail, so this is just a general description
Another (probably easier) way to hack the system could be to run the SSH server in a separate mount namespace, and bind-mount a different /etc/shadow with different passwords, then SSHd would use these while local logins would not. (Note that if a user logs in over SSH and then is able to run login or in some other way attempt a local login that will also be checked against the SSH password database.)
edit: the above answers how using a different SSH password is possible, but I wouldn't recommend it unless you know very well what you are doing, as you're tinkering with security systems. I've added a new answer with a more practical approach.
Comment: Yes, its possible to use PAM to implement different authentication methods for different systems - but sshd has its own config on the Linux hosts here. OTOH I would NOT recommend this approach to someone without a lot of expertise in Linux/Unix.
Answer: Re-reading this question a few years later, this is what I would do in this case:

Configure your main user to be secure. I.e. configure sshd to only allow logins with publickey, and then use the short desktop login password you want.

Set up a secondary user with password login over ssh enabled, and configure the more secure password for this user. Then configure sudo to allow sudo-ing from the secondary user to the main user, optionally without requiring a password. You could even set up the default shell for ssh to be something like /usr/bin/sudo -i -u mainuser /bin/bash, so you automatically end up in a shell session for your main user when you log in over ssh.

See here for how to enable password login over ssh only for specific users.
Another possibility is running a secondary ssh server that allows changing the login password just for the ssh login, like Dropbear. But now you have a second ssh server on your system, which might have its own vulnerabilities, so I would prefer using the standard sshd with a secondary user.
A third option I just thought of is to create a copy of your user in /etc/passwd and /etc/shadow, with a different username and password, but the same UID as your main user. Reading these questions, that seems to be a more-or-less supported usage of the passwd file for creating an alias with a different password. But I would still prefer the first option if that works for you, as it is less arcane.


Generate variable according to distribution exp(x)/(exp(1)-1)

Question: I need to generate variable from the distribution $\ e^x \over e-1$ from 0 to 1 only using uniform variables.
The idea I'm following is the Inverse Transforming. I get the inverse cdf function and apply the uniform variable on it, so:
The cdf is the same as the original distribution.
The inverse is: $\ ln(x(e-1)) $
But this function is < 0  for x in [0,1], so it is not the distribution of $\ e^x \over e-1$. What am I doing wrong?
Comment: The integral $\int_0^t e^u/(e-1) du$ is very much not $e^t/(e-1)$.  How do I know that without doing anything (even pretending I don't know the answer)?   They don't agree at $t=0$..
Comment: Your function $e^x/(e-1)$ is not a cdf, or at least there is something missing from your description!
Comment: I'm using the cdf integrating $\ e^x \over e-1$ which is $\ e^x \over e-1$
Comment: please tag self study
Comment: $\mathbb{P}(X\leq t) = \int_0^t f(u)dt$, where $f$ is the density for your r.v. $X$ ....
Comment: Ohhh I get it now. When x = 0, the integral value is $\ 1 \over (e-1) $
Answer: You integrated the PDF incorrectly and thus your CDF is wrong- it should be $F(x) = \frac{e^x - 1}{e - 1}$, which has inverse $g(y) = \ln(1 + (e-1)y))$, which is positive for $y \ge 0$.
Answer: The inverse that you're using must be of the CDF, not PDF.
Knuth in Vol2 of TAOCP has a ton methods to generate randoms if you're interested.
Comment: I'm using the cdf integrating $\ e^x \over e-1$ which is $\ e^x \over e-1$


how to get data from string in javascript

Question: I have such string test1/test2/test3/test4/test5
How can I get those tests in separate variables or in array or smth using javascript or jquery ?
Comment: `var arrTests = myString.split("/");`
Comment: -1 for terminal laziness. Did you not bother searching first?
Comment: possible duplicate of [How do I split this string with JavaScript?](http://stackoverflow.com/questions/96428/how-do-i-split-this-string-with-javascript)
Comment: -100 to you. Did you not bother read books only and not visit this site at all ?
Answer: var arrayOfBits = string.split(separator)

Answer: Use split
MN Documentation for split
var data = "test1/test2/test3/test4/test5".split("/");
Answer: You could use split (so no jQuery required) -
var arr = "test1/test2/test3/test4/test5".split("/");
console.log(arr);

Demo http://jsfiddle.net/ipr101/hXLE7/
Answer: You can use String.split(), where you specify the separator as "/" in the API, and get the array of values in return.
Answer: You can split a string by a delimiter.
https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String/split


Does more variables mean tighter confidence intervals?

Question: Assume that the true (but unknown) relationship in a population between $Y$ and $X1, X2, X3, X4$ is $$Y=\beta_0 + \beta_1 X_1 + \beta_2 X_2 + \beta_3 X_3 + \beta_4 X_4.$$ Further assume that I have a sample from the population that I wish to model using linear regression and I fit the following two regression models:
\begin{align}
Model \;1: \quad Y & =\beta_0 + \beta_1 X_1 + \beta_2 X_2 \\
Model \;2: \quad Y & =\beta_0 + \beta_1 X_1 + \beta_2 X_2 + \beta_3 X_3 + \beta_4 X_4
\end{align}
After obtaining my estimates $\hat{\beta}_0, \ldots, \hat{\beta}_4$ I then compute the predicted value of $Y$ for some covariate values $\tilde{x}_1, \ldots,\tilde{x}_4$. Additionally, I compute the confidence interval of my prediction, e.g. for model 1,
$$
\tilde{y} = \hat{\beta}_0 + \hat{\beta}_1 \tilde{x}_1+\hat{\beta}_2 \tilde{x}_2
$$
with confidence interval in the usual way, i.e.,  $$\tilde{y} \pm t_{n-3} \hat{\sigma} \sqrt{\tilde{x}^T(X^TX)^{-1}\tilde{x}}$$ where $\tilde{x}=(\tilde{x}_1, \tilde{x}_2)^T$.
Now I do the same thing with model 2, which is the more correct model and compare the interval width of the confidence interval for the prediction. Do I get a tighter confidence interval for my prediction? I tried it in R for a simple simulated data set and the answer was yes. In this example I varied the value of $\tilde{x}_1$ and fixed the values of the other covariates.
library(survival)
set.seed(13)
n <- 200

x1 <- rnorm(n)
x2 <- rbinom(n, 1, 0.5)
x3 <- rnorm(n)
x4 <- rbinom(n, 1, 0.5)
b0 <- 2
b1 <- 1.2
b2 <- 1.8
b3 <- -2.2
b4 <- 0.8
mu <- b0+b1*x1+b2*x2+b3*x3+b4*x4
eps <- rnorm(n,0,1.5)
y <- mu+eps

fit2 <- lm(y~x1+x2)
summary(fit2)
fit4 <- lm(y~x1+x2+x3+x4)
summary(fit4)

newdata <- data.frame(x1=seq(-2,2,0.1), x2=1, x3=0.5, x4=1)

pred2 <- predict(fit2, newdata, se.fit=TRUE,interval="confidence")
pred4 <- predict(fit4, newdata, se.fit=TRUE,interval="confidence")

plot(newdata$x1, pred2$fit[,3]-pred2$fit[,2],type="l", ylim=c(0,2), lwd=2, main="Interval     width (upper-lower bound)", ylab="Interval Width", xlab="x1")
lines(newdata$x1, pred4$fit[,3]-pred4$fit[,2], lty=2, lwd=2)
legend(-2,0.6, lty=c(1,2), lwd=2, legend=c("2 covariates", "4 covariates"))

My question: Is this always the case?
Or more general:

If the variables have an effect on my model, do I ALWAYS get a tighter confidence interval if I include more variables in my model?
On the other hand, if the variables do not have an effect, do I get wider confidence intervals for the prediction?
How about the standard errors of the parameter estiamtes?
Is this also true when confounding is present?
How about other regression models such as logistic regression or mixed models?

Here I only considered confidence intervals for the prediction, but my question also applies to prediction intervals.
Comment: Also, increasing the number of predictors has the effect of reducing the t-statistic as well.
Answer:
do I ALWAYS get a tighter confidence interval if I include more variables in my model?

Yes, you do (EDIT: ...basically. Subject to some caveats. See comments below). Here's why: adding more variables reduces the SSE and thereby the variance of the model, on which your confidence and prediction intervals depend. This even happens (to a lesser extent) when the variables you are adding are completely independent of the response:
a=rnorm(100)
b=rnorm(100)
c=rnorm(100)
d=rnorm(100)
e=rnorm(100)

summary(lm(a~b))$sigma       # 0.9634881
summary(lm(a~b+c))$sigma     # 0.961776
summary(lm(a~b+c+d))$sigma   # 0.9640104 (Went up a smidgen)
summary(lm(a~b+c+d+e))$sigma # 0.9588491 (and down we go again...)

But this does not mean you have a better model. In fact, this is how overfitting happens.
Consider the following example: let's say we draw a sample from a quadratic function with noise added.

A first order model will fit this poorly and have very high bias.

A second order model fits well, which is not surprising since this is how the data was generated in the first place.

But let's say we don't know that's how the data was generated, so we fit increasingly higher order models.

As the complexity of the model increases, we're able to capture more of the fluctuations in the data, effectively fitting our model to the noise, to patterns that aren't really there. With enough complexity, we can build a model that will go through each point in our data nearly exactly.

As you can see, as the order of the model increases, so does the fit. We can see this quantitatively by plotting the training error:

But if we draw more points from our generating function, we will observe the test error diverges rapidly.

The moral of the story is to be wary of overfitting your model. Don't just rely on metrics like adjusted-R2, consider validating your model against held out data (a "test" set) or evaluating your model using techniques like cross validation.
For posterity, here's the code for this tutorial:
set.seed(123)
xv = seq(-5,15,length.out=1e4)
X=sample(xv,20)
gen=function(v){v^2 + 7*rnorm(length(v))}
Y=gen(X)
df = data.frame(x=X,y=Y)
plot(X,Y)
lines(xv,xv^2, col="blue") # true model
legend("topleft", "True Model", lty=1, col="blue")

build_formula = function(N){
  paste('y~poly(x,',N,',raw=T)')
}

deg=c(1,2,10,20)
formulas = sapply(deg[2:4], build_formula)
formulas = c('y~x', formulas)
pred = lapply(formulas
              ,function(f){
                predict(
                  lm(f, data=df)
                  ,newdata=list(x=xv))
                            })
# Progressively add fit lines to the plot
lapply(1:length(pred), function(i){
  plot(df, main=paste(deg[i],"-Degree"))
  lapply(1:i,function(n){
    lines(xv,pred[[n]], col=n)
  })
  })

# let's actually generate models from poly 1:20 to calculate MSE
deg=seq(1,20)
formulas = sapply(deg, build_formula)
pred.train = lapply(formulas
                   ,function(f){
                     predict(
                       lm(f, data=df)
                       ,newdata=list(x=df$x))
                   })

pred.test = lapply(formulas
              ,function(f){
                predict(
                  lm(f, data=df)
                  ,newdata=list(x=xv))
              })

rmse.train = unlist(lapply(pred.train,function(P){
  regr.eval(df$y,P, stats="rmse")
}))

yv=gen(xv)
rmse.test = unlist(lapply(pred.test,function(P){
  regr.eval(yv,P, stats="rmse")
}))

plot(rmse.train, type='l', col='blue'
     , main="Training Error"
     ,xlab="Model Complexity")

plot(rmse.test, type='l', col='red'
     , main="Train vs. Test Error"
     ,xlab="Model Complexity")
lines(rmse.train, type='l', col='blue')
legend("topleft", c("Test","Train"), lty=c(1,1), col=c("red","blue"))

Comment: This is a wonderful answer, full of useful information--but it's wrong, for several reasons: (1) you overlook the effect of the reduced degrees of freedom in $t_{n-3}.$ This is profound when $n$ is small (which is exactly when $t$ distributions should be used instead of Normal distributions). (2) You overlook the effect of $\tilde{x}^T(X^TX)^{-1}\tilde{x}$: prediction bands can actually widen with more variables, such as when the new ones have little additional predictive value.
Comment: Those are two really important points. It's also worthwhile to mention how slight non-linearities can induce wrong signs on the coefficients, see for example the paper ["Let's Put Garbage-can Regressions and Garbage-can Probits Where They Belong"](http://qssi.psu.edu/files/Achen_GarbageCan.pdf). Tremendous effort on the answer -- would be great to add clarifying remarks along these lines so that it's not misleading when people find this.
Comment: @ely The link in your comment is dead, but I think this is the article. http://www.saramitchell.org/achen04.pdf


Order of unknowns in Prolog constraint logic programming (clpr)

Question: I have:
:-use_module(library(clpr)).
comp(X, Y, Z):-
    {X = Y * Z, Y = Z, Y > 0, Z > 0}.

Which with the query:
?-comp(X,3,Z).

Yields:
X = 9.0,
Z = 3.0

as expected. But why doesn't
comp(9,Y,Z).

also give me values for Y and Z? What I get is instead:
{Z>0.0,Y=Z,9-Y*Z=0.0},
{9-Y*Z=0.0},
{9-Y*Z=0.0}

Thanks!
Answer: Probably a weakness of the used CLP(R) that quadratic case doesn't work so well. After Y = Z, it is evident that X = Y**2, and then with X = 9 and Y > 0, you should easily get Y = 3. Which CLP(R) do you use?
A CLP(R) need not only support linear equalities and inequalities. Using for example Gröbner Basis algorithm a CLP(R) could do more, even algebraically. Some computer algebra system can do that easily.
So I guess its not a problem of Prolog per se, rather of the library. Strictly speaking CLP(X) only indicates a domain X. For the domain R of real numbers there is wide variety of potential equation and inequation solvers.
Comment: jumping to X = Y**2 is easy for humans, but even X = Y*Y with a known X should conclude Y must be discoverable as well. How, is another issue. But it could be done even numerically...
Answer: Better with constraints over finite domains using this module:
:-use_module(library(clpfd)).
comp(X, Y, Z):-
    X #= Y * Z, Y #= Z, Y #> 0, Z #> 0.

With
comp(9,Y,Z).

I get:
Y = Z, Z = 3


Use a different mediaplayer in an Android App

Question: For a project of mine I am more or less stuck with the mediaplayer AwesomePlayer. The downside of this player is that the fps is too low and it can't seem to handle the clips well.
Now I went on the playstore and tried out different kinds of mediaplayers and found one that has no problems with the clips and has a good fps. My question hereby is: Is there a way to use a different mediaplayer in my Android App?
-Edit-
A little sidenote: The player must only show the video, not the rest of the gui. There also shouldn't be any user interaction required in order to play a video (Everything will be done in the code).
Answer: Yes, you can also invoke installed Android video player to play the video with just a few lines of code. This example plays a video file from external storage.
<code>Uri fileUri = Uri.fromFile(videoFile);
  Intent intent = new Intent();
  intent.setAction(Intent.ACTION_VIEW);
  intent.setDataAndType(fileUri,
        URLConnection.guessContentTypeFromName(fileUri.toString()));
  startActivity(intent);
</code>
Intent chooser will show up to let user pick his preferred video player. I wrote a blog to discuss how to do it in detail, http://software.intel.com/en-us/blogs/2014/03/20/video-playing-with-android-media-player. Hope it helps.
Comment: The problem with playing the video's is that there should be no user interaction required for it. The application is used for narrowcasting. So it must be able to just start playing video's on start-up. There should also be no UI of the player on the screen.


Multivariate Taylor Series Derivation (2D)

Question: I am trying to understand the derivation here
kiwi.atmos.colostate.edu/group/dave/pdf/TaylorSeries.pdf
I understand how first, second total differentials are derived. I do not understand how they are plugged into a form that is compatible with the single variable Taylor Series, which is
$f(x) = f(a) + f'(a)(x-a) + \frac{1}{2!}f''(a) (x-a)^2 + ...$
The coefficients of multivariate expansion are exactly the same as the single variable version. Sure given the total differential, $(x-a)$ is substituted for $dx$, $(y-b)$ for $dy$, but it's not shown why, or how the rest of $f(x,y)$ expansion should mirror the single variable form based on the total differential. Expansion for $f(x,y)$ is below
$f(x,y) = f(a,b) +
\bigg[(x-a)\frac{\partial}{\partial x} + (y-b)\frac{\partial}{\partial x}\bigg]f +
\frac{1}{2!}
\bigg[(x-a)\frac{\partial}{\partial x} + (y-b)\frac{\partial}{\partial x}\bigg]^2 f + ...
$
If you know a better 2D Taylor Series derivation, that would be welcome as well.
Thanks,
Comment: This is not a rigorous proof: Suppose that one can write $f(x,y)=f(a,b)+A(x-a)+B(y-b)+C(x-a)^2+D(x-a)(y-b)+E(y-b)^2+\cdots$, how can the values $A, B, C, D, E, \dots$ be determined?
Comment: I think I came across a similar idea here http://www.physics.miami.edu/~nearing/mathmethods/series.pdf pg 7. Thanks.
Answer: So we want to express $f(a+u,b+v)$ in terms of $f(a,b)$, the increment $(u,v)$ and the partial derivatives of $f$ at $(a,b)$. To this end we look at the auxiliary function
$$\phi(t):=f(a+t u, b+t v)\qquad(0\leq t\leq 1)\ .$$
By the one-variable Taylor theorem we have
$$f(a+u,b+v)=\phi(1)=\sum_{r=0}^n{1\over r!}\phi^{(r)}(0)+{\rm error\ term}\ .\qquad(*)$$
Therefore we have to compute the successive derivatives of $\phi$ at $t=0$.
Obviously $$\phi^{(0)}(t)=\phi(t)=f(a+tu,b+tv)$$ and therefore $\phi^{(0)}(0)=f(a,b)$. To compute $\phi'(t)$ we need the chain rule:
$$\phi'(t)={d\over dt}\phi(t)={d\over dt}f(a+t u,b+ t v)=f_1(a+t u,b+ tv)u+f_2(a+ tu, b+ tv) v\ ,$$
whence $\phi'(0)=f_1(a,b)u+f_2(a,b)v$. Proceeding in this manner we get
$$\eqalign{\phi''(t)&={d\over dt}\bigl(f_1(a+t u,b+ tv)u+f_2(a+ tu, b+ tv) v\bigr) \cr
&=f_{11}(a+tu,b+tv)u^2+2f_{12}(a+tu,b+tv) uv +f_{22}(a+tu,b+tv)v^2\cr}$$
and therefore
$\phi''(0)=f_{11}(a,b)u^2 + 2f_{12}(a,b)uv+f_{22}(a,b) v^2\ .$
And so on for the higher derivatives of $\phi$. The values $\phi(0)$, $\phi'(0)$, $\phi''(0)$, $\ldots$ so obtained have to be plugged into the equation $(*)$
Of course all of this could be written up more elegantly using vector notation.
Comment: Hi Christian, with $1$ in $f_1$ did you mean the first block of variables, which are $a+tu$?
Comment: Similar idea http://math.uc.edu/~halpern/Calc.4/Handouts/Taylorseries.pdf
Comment: @user6786: $f$ is a function of two real inputs, whatever their name. By $f_1$ I mean the partial derivative with respect to the first input. It seemed strange to write $f_x$ when there is nowhere an $x$ in the argument.
Answer: If you are looking for a physical intuition behind multivariate Taylor series, remember that $ T_x = \partial_x$ is the generator of translations, as for suitable class of functions:
$$
   (T_x f)(x) = \lim_{\epsilon \to 0} \frac{ f(x+\epsilon) - f(x)}{\epsilon}
$$
Thus $\mathcal{T}_a = \mathrm{e}^{a T_x}$ is the operator of translation by $a$:
$$
    (\mathcal{T}_a f)(x) = f(x+a)
$$
Writing defining series of exponential give univariate Taylor expansion:
$$
    f(x+a) = (1 + a T_x + \frac{a^2}{2!} T_x \circ T_x + \ldots ) \circ f(x)
$$
Taking this to mulrivariate, the translation by vector $\vec{u}$ becomes
$$
 \mathcal{T}_\vec{u} = \exp( \sum_{i=1}^n u_i T_{x_i} ) = \circ_{i=1}^n \mathcal{T}_{u_i}
$$
You can now develop each univariate translation operator into a series, giving the multivariate Taylor expansion formula or, alternatively, you could expand the combined exponential:
$$
   f(\vec{x} + \vec{u}) = \sum_{n=0}^\infty \frac{1}{n!} \left( \langle \vec{u}, \mathcal{T}_{\vec{x}} \rangle \right)^n \circ f(\vec{x})
$$
Hope this helps.


Pegar Resposta de uma API que retorna erro 500

Question: Seguinte, tenho uma API que retorna erro 500 toda vez que infringe a regra de negócio me retornando um status e uma mensagem. Sabemos que não é uma boa prática retornar status 500 nessas circunstâncias, mas tem alguma forma de eu pegar o JSON que ela me retorna, mesmo ela estourando status 500?
Ele não cai nem no then nem no cath
Comment: Coloca o código pro pessoal te ajudar melhor
Answer: De forma bem simples, você nunca vai conseguir, entenda o por que.
O motivo é, erros com código de 500 a 599, são normalmente associados a erros na aplicação de servidor, que falhou ao operar uma requisição.
O que você deve fazer é primeiro, qualquer erro dentro desse intervalo entre 500 e 599, deve ser tratado como falha na API e você deve trata-lo mesmo sem saber o motivo da falha. Ou seja, verifique o httpstatus antes de qualquer coisa, se estiver entre 500 e 599, trate como uma falha na API e não espere que ela te retorne o motivo da falha.
Tenha em mente que, se você manda um valor que a API não espera e ela retorna um erro 500 por exemplo, é porque provavelmente o tipo do valor que você está mandando é inesperado.
Oposto a situação acima, se a API trata um tipo de dados que não é o esperado, é bem provável que ela retorne para você um erro 400 e o motivo do erro.
Referência: Lista de códigos de status HTTP
Answer: Para pegar a mensagem de erro 500 de uma requisição POST com JavaScript usando o Axios, você pode usar o método axios.post() para enviar a requisição e, em seguida, verificar o status da resposta. Se o status for "500", você pode acessar a mensagem de erro através do objeto error.response.data. Aqui está um exemplo:
axios.post('your_url',{data: your_data})
.then(response => {
    console.log(response.data);
  })
  .catch(error => {
    if (error.response.status === 500) {
      console.log(error.response.data);
    }
  });


Sum of roots of unity using a particular argument

Question: On this post it claims that for $n>1$ the sum of the $n$th roots of unity may be written as $S=1+\omega_1+\omega_2+\cdots+\omega_{n-1}$ and then multiplied on both sides by $\omega_1$, where $\omega_1\neq1$, to obtain $S=\omega_1 S$. Hence, $S=0$.
Question: How is $S=\omega_1S$ obtained by multiplying both sides by $\omega_1$? That is not clear to me at all (that really seems to be the main argument). Everything else is fine, but I do not see how $S=\omega_1 S$ immediately follows from multiplying both sides by $\omega_1$. Any insight would be appreciated.
Comment: Notice that $$\omega_{k+1}=\omega_k\cdot\omega$$And $\omega_n=1$.  (if you still do not see this, look at the roots of unity on the complex plane.  Multiplying by $\omega$ should be a simple rotation)
Answer: We have:
$1\cdot\omega_1=\omega_1$
$\omega_1\cdot\omega_1=\omega_2$
$\omega_2\cdot\omega_1=\omega_3$
etc.
so multiplying the original equation by S gives
$\omega_1S=\omega_1+\omega_2+\dots +\omega_{n-1}+\omega_n=\omega_1+\omega_2+\dots +\omega_{n-1}+1=S$
and the result follows.
(Note that this works because of the unit complex circle. Relative to the x-axis (the real axis), $\omega_1$ has an argument of $\frac{2\pi i}{n}$, and $\omega_k$ has an argument of $\frac{2k\pi i}{n}.$)
Answer: As the product of two roots of unity is a root of unity, multiplication by $\omega_1$ of all elements in the list $(1, \omega_1,\dots ,\omega_n)$ results in a permutation of these elements. Hence, as their sum is a symmetric function of them, it is invariant by a permutation  of its terms.
Note:
Another proof consists in noting the $n$-th roots of unity are the roots of the the polynomial $X^n-1$.  $S=0\;$ simply results from Vieta's relations.
Answer:
for $n>1$ the sum of the $n$th roots of unity may be written as $S=1+\omega_1+\omega_2+\cdots+\omega_{n-1}$ and then multiplied on both sides by $\omega_1$, where $\omega_1\neq1$, to obtain $S=\omega_1 S$. Hence, $S=0$.

The implied notation is $\omega_k=e^{i \frac{2k \pi}{n}}=\omega_1^k\,$ for $\,k=0,\cdots,n-1\,$.
Then $S=\omega_1^0+\omega_1^1+\cdots+\omega_1^{n-1}\,$, so $\omega_1 \cdot S = \omega_1^1 + \omega_1^2+\cdots+\omega_1^n=S\,$ since $\omega_1^n=1=\omega_1^0\,$.

As far as the proposition itself, the direct proof that $\,S=0\,$ is using Vieta's relations, since $\omega_k$ are by definition the roots of $z^n-1=0\,$.


MIPS Input Taking

Question: How to take input in main function in mips?
Comment: Depends on what OS you are using and what runtime libraries are available. Try providing more information.
Comment: in windows and compiling via pcspim
Answer: It depends.  If you are going to ask for an integer it should be
li $v0, 5
syscall

If you are going to ask for a float should be
li $v0, 6
syscall

If you are going to ask for a double it should be
li $v0, 7
syscall

And if you are going to ask for an string it should be
li $v0, 8
syscall

But, if you are going to ask for an string and the input is going to take maximum number of characters, then you should use $a1instead of $a0 when printing it.

MIPS Input Taking


Problem with Google Analytics module: "undefined index"

Question: I use "Google Analytics" module (version 7.x-2.1 = up to date) and I get the following error message:

Notice : Undefined index: value in googleanalytics_page_alter() (ligne
  217 in
  .../www/sites/all/modules/google_analytics/googleanalytics.module)

Any idea how can I solve it? Perhaps some manual modifications in the googleanalytics.module file?
Comment: possible duplicate of [Undefined index message in drupal](http://drupal.stackexchange.com/questions/14782/undefined-index-message-in-drupal)
Comment: @KrishnaMohan: Technically it is on topic because it is a module support request, not a bug or feature request. Even though it looks like a bug report until you look into it further.
Answer: This is a support request on Drupal.org for this here.
Since it is not really a bug or feature request though it is technically on topic here so the summary of that issue is:

Make sure that you have run update.php.
If that didn't fix the problem then try re-saving your google analytics settings (it would be a good idea to confirm that they are what they should be before saving).

Also I would recommend that if you get error messages like that to search google and the drupal.org issue queue for the module(s) in question.
Comment: Your advice (n°2) worked. Thanks! By the way, I searched before posting here... (I know the "policy" on SE sites) but without success.
Comment: Search tip for drupal module bugs is to search in google like this: drupal MODULE_NAME ERROR_MESSAGE. But only the actual error message, not the file name or line number. If you end up needing to include the file name then omit the path and just use the file name. When I did that in this case the drupal.org issue I linked to was the first result.


How to get subsequent fields to populate after creating a node using webform rules?

Question: I've been going crazy trying to figure this out. I think I am close, but seem to be missing something with the rule actions. Any help would be most appreciated.
Background:
I'm trying to create nodes from webforms that will pull in certain fields from the webform, namely, first and last names (text fields), affiliation (from an entity filed), and conference to attend (check box list). The reason for this node content type is to pull the conference registrants names and affiliations into a view that will list on each conference page. The content type for the attendees is called "Conference Participants." The reason for doing this is so the staff in my department does not have to manually enter each person who register.
Present Status:
I started using this process last year with minor success. That is, I was able to use Rules to take a submitted webform and create a node with the participants last, first name as the title. I set the content type to not publish so either I or the staff members could verify the information and publish. As it now stands, the workflow is:

Events - Event: After a webform has been submitted
Conditions – Elements: Webform has a name – Parameter: The form id of
the submitted form: [form-id: value, Webforms: Summer Conference
Actions – Elements:

Create a new entity – Parameter: Entity type: Node, Content type:
Conference Participants, Title: [data:last_name-value], ..., Author:
[node:author] Provides variables: Created entity (entity_created)

Issues:
I have not been able to pull any of the text fields (first and last name) from the webform into the node. For my testing, I've created a new "email" text field in the node because it is a standard field with most forms. There is a check box list of conference names in which more than one can be checked. I also have an entity type filed (auto complete) of universities around the world which are not pulling in. I suspect this one may be a bit more complicated since it is an entity type field and I may need to use another type of action, e.g. loop. I should add that there are other fields in the content type (Conference Year and a text box for participants to manually type in an institution that is not listed in the entity filed). I have the conference year checked automatically for 2018 (see screen shot below).

Drupal and Module Background:

Drupal 7
Rules Module
Webform Rules
Conditional Rules

What I've tested:
•   Conditionals

NOT an authenticated user
Entity has field
Set a data value
Add a variable (with webform tokens using raw and just the value)

Posts I've looked at:

How to do a data comparison to submitted webform data when using the Rules module?
How to use webform submission data in a Rules Condition?
How do you make entity fields appear in Rules when converting a Webform submission to node?
How to implement a multi step approval with webforms/entityforms based on form components?
Data types and data selection

Screen shots
Summer Conference Participant Rule workflow

Conditions: Elements: Webform has name

Actions: Elements: Create a new entity

Actions: Elements: Add a variable

Actions: Elements: Save Entity

Rule Export
{ "rules_summer_conference_participants" : {
"LABEL" : "Summer Conference Participants",
"PLUGIN" : "reaction rule",
"OWNER" : "rules",
"REQUIRES" : [ "webform_rules", "rules", "rules_conditional" ],
"ON" : { "webform_rules_submit" : [] },
"IF" : [
  { "webform_has_id" : {
      "form_id" : [ "form-id" ],
      "selected_webform" : { "value" : { "webform-client-form-86866" : "webform-client-form-86866" } }
    }
  }
],
"DO" : [
  { "entity_create" : {
      "USING" : {
        "type" : "node",
        "param_type" : "conference_participants",
        "param_title" : "[data:last_name-value], [data:first_name-value]",
        "param_author" : [ "node:author" ]
      },
      "PROVIDE" : { "entity_created" : { "conference_participant_webform" : "Conference Participant Webform" } }
    }
  },
  { "CONDITIONAL" : [
      {
        "IF" : { "entity_has_field" : { "entity" : [ "node" ], "field" : "field_email" } },
        "DO" : [
          { "variable_add" : {
              "USING" : { "type" : "text", "value" : "[data:email-value]" },
              "PROVIDE" : { "variable_added" : { "field_email" : "email" } }
            }
          }
        ]
      }
    ]
  },
  { "entity_save" : { "data" : [ "node" ], "immediate" : "1" } }
]  }}

Debug Info
Rules debug information:
" Reacting on event After a webform has been submitted.

0 ms Reacting on event After a webform has been submitted.
10.813 ms Evaluating conditions of rule Summer Conference
Participants.
11.057 ms The condition webform_has_id evaluated to TRUE
11.067 ms AND evaluated to TRUE.
"Rule Summer Conference Participants fires.

0 ms Rule Summer Conference Participants fires.
28.914 ms Evaluating the action entity_create.
29.263 ms Added the provided variable conference_participant_webform of type node
31.59 ms Evaluating the action variable_add.
31.649 ms Added the provided variable field_email of type text
31.747 ms Evaluating the action entity_save.
31.8 ms Saved node of type node.
727.681 ms Rule Summer Conference Participants has fired.

738.827 ms Evaluating conditions of rule Conference Participant.
741.628 ms The condition webform_has_id evaluated to FALSE
741.639 ms AND evaluated to FALSE.
741.68 ms Saved conference_participant_webform of type node.
861.009 ms Finished reacting on event After a webform has been submitted.
Answer: I'm not sure if these are the only issues you need to address to get the subsequent fields to populate, but I'm pretty sure these are 2 things within your Rules Actions that don't seem right to me:

You don't need that "Conditional Rules"-condition, which IMO always evaluates to FALSE (and hence no variable ever gets "added", with an initial value as in your rule). To QA-test this, just (temporary) also display some "hello"-Drupal message within that CONDITIONAL, I bet you will not ever get such message (which proofs the CONDITIONAL should not be there).
After you removed the CONDITIONAL (Rules Action), try to assign an initial value of [data:email-value-raw] to the variable you added, instead of the [data:email-value] in your current rule.
The machine name field_email for the variable you added seems suspecious to me ... If that is ALSO the machine name of your node's field (for the node being created), then try to rework this Rules Action like so:

use whatever other machine name for the variable being added (let's assume you name it email_entered_on_form), with an initial value of [data:email-value-raw].
add another rules action to "set a data value", whereas you should set a value for field_email, and with a value equal to email_entered_on_form.


Getting NULLs on measures

Question: I have this this MDX query for a SSRS dataset and I'm getting Nulls on all measures, any clue ?
WITH
MEMBER  [Measures].[CA TTC PC]
as ( STRTOMEMBER(@FromAxeTempsTemps2) : STRTOMEMBER(@ToAxeTempsTemps2),
 [Axe Scenario].[Scenario].&[Réalisé]
,  [Measures].[CA TTC] )
MEMBER  [Measures].[CA HT PC]
as ( STRTOMEMBER(@FromAxeTempsTemps2) : STRTOMEMBER(@ToAxeTempsTemps2),
 [Axe Scenario].[Scenario].&[Réalisé]
,  [Measures].[CA HT] )
MEMBER  [Measures].[Marge PC]
as ( STRTOMEMBER(@FromAxeTempsTemps2) : STRTOMEMBER(@ToAxeTempsTemps2),
 [Axe Scenario].[Scenario].&[Réalisé]
,  [Measures].[Marge] )
MEMBER  [Measures].[TauxMarge PC]
as ( STRTOMEMBER(@FromAxeTempsTemps2) : STRTOMEMBER(@ToAxeTempsTemps2),
 [Axe Scenario].[Scenario].&[Réalisé]
,  [Measures].[Taux Marge] )
MEMBER  [Measures].[Quantite Vendue PC]
as ( STRTOMEMBER(@FromAxeTempsTemps2) : STRTOMEMBER(@ToAxeTempsTemps2),
 [Axe Scenario].[Scenario].&[Réalisé]
,  [Measures].[Quantite Vendue] )
MEMBER  [Measures].[Nbr De Tickets PC]
as ( STRTOMEMBER(@FromAxeTempsTemps2) : STRTOMEMBER(@ToAxeTempsTemps2)
, [Measures].[Nombre De Tickets] )
SELECT
{ [Measures].[CA HT],
[Measures].[CA TTC],
 [Measures].[Marge], [Measures].[Taux Marge] ,
[Measures].[Nombre Tickets],[Measures].[Marge PC]
, [Measures].[Quantite Vendue], [Measures].[CA TTC PC] ,
  [Measures].[TauxMarge PC] , [Measures].[Quantite Vendue PC] ,
 [Measures].[Nbr De Tickets PC] ,[Measures].[Nombre De Tickets]
,[Measures].[CA HT PC]
} ON COLUMNS,
NON EMPTY { (
[Axe Structure Marchandise].[H-Code-SSFamille].[Code Famille].ALLMEMBERS
* [Axe Structure Marchandise].[H-Libellé-SSFamille].[Famille].ALLMEMBERS
* [Axe Scenario].[Scenario Id].[Scenario Id].ALLMEMBERS
* [Axe Date Scénarios].[Aggregation].[Aggregation].ALLMEMBERS
* [Axe Date Scénarios].[Comparaison].[Comparaison].ALLMEMBERS
*[Axe Promotion].[Type Vente].[Type Vente].ALLMEMBERS ) }
DIMENSION PROPERTIES MEMBER_CAPTION, MEMBER_UNIQUE_NAME
ON ROWS FROM ( SELECT ( { [Axe Date Scénarios].[Comparaison].&[0]} )
ON COLUMNS FROM ( SELECT ( { [Axe Date Scénarios].[Aggregation].&[0] } )
ON COLUMNS FROM ( SELECT ( STRTOSET(@AxeSiteCodeSite) )
ON COLUMNS
FROM ( SELECT ( STRTOSET(@AxeVarianteSensibilite) )
ON COLUMNS
FROM ( SELECT ( STRTOSET(@AxeStructureMarchandiseCodeRayon) )
ON COLUMNS FROM ( SELECT ( STRTOSET(@AxeSiteCodeBU, CONSTRAINED) )
ON COLUMNS FROM ( SELECT ( STRTOMEMBER(@FromAxeTempsTemps) : STRTOMEMBER(@ToAxeTempsTemps) )
ON COLUMNS FROM ( SELECT ( {[Axe Scenario].[Scenario].&[Objectif], [Axe Scenario].[Scenario].&[Réalisé] } )
ON COLUMNS
FROM ( SELECT ( -{[Axe Structure Marchandise].[Libelle Rayon].&[CONSIGNES], [Axe Structure Marchandise].[Libelle Rayon].&[DECONSIGNES]} )
ON COLUMNS
FROM ( SELECT ( -{[Axe Site].[Code Site].&[4], [Axe Site].[Code Site].&[101], [Axe Site].[Code Site].&[137] } ) ON COLUMNS
FROM [DataMartLabelVie]))))))) )))
WHERE (StrToSet(@AxeStructureMarchandiseCodeRayon, CONSTRAINED),
IIF( STRTOSET(@FromAxeTempsTemps).Count = 1, STRTOSET(@FromAxeTempsTemps), [AxeTemps].[Date].currentmember )
, IIF( STRTOSET(@AxeSiteCodeBU, CONSTRAINED).Count = 1,
STRTOSET(@AxeSiteCodeBU, CONSTRAINED), [Axe Site].[Code BU].currentmember ) )
CELL PROPERTIES VALUE, BACK_COLOR, FORE_COLOR, FORMATTED_VALUE, FORMAT_STRING, FONT_NAME, FONT_SIZE, FONT_FLAGS

Answer: You need to create a very simple script based on your complex script, which does not return nulls. For example start here:
SELECT
  (
    -{
       [Axe Site].[Code Site].&[4]
     , [Axe Site].[Code Site].&[101]
     , [Axe Site].[Code Site].&[137]
     }
   ) ON COLUMNS
FROM [DataMartLabelVie];

...does the above return nulls? Hopefully no, so then add some of the complexity of the big script e.g.
SELECT
  (
     {[Axe Scenario].[Scenario].&[Objectif], [Axe Scenario].[Scenario].&[Réalisé] }
  )
ON COLUMNS
FROM
(
  SELECT
    (
      -{
         [Axe Site].[Code Site].&[4]
       , [Axe Site].[Code Site].&[101]
       , [Axe Site].[Code Site].&[137]
       }
     ) ON COLUMNS
  FROM [DataMartLabelVie]
);

Do you now get the nulls - no? ok add some more complexity..
etc, etc until you find the problem.

Getting NULLs on measures


printing an entity reference field in a special display mode

Question: I have an entity reference field. The referenced entity has multiple display modes.
I'd like to print this field 2 two times in a template, with 2 different display modes like so:
{{ content.field_ref_entity.display_mode_xy }}
and
{{ content.field_ref_entity.display_mode_yz }}
Is it possible to define the display mode of the referenced entity in field printing? If yes, how?
Answer: See my explanation in How can you render fields from an entity reference in node templates? [Drupal 8], which touches that topic as well.
In short, not with content, that can only contain a field once, at least without additional modules (not sure if display suite or so can do this). But you can call the view() mode on the field with either the of a view mode from where to pick the configuration or pass it the desired configuration directly. The structure is the same as what stored for the configuration in the entity view display config entities for a field.
Not sure about the exact twig syntax for the array, the view display would be like this: `{{ node.field_ref_entity.view('teaser') }}. You could also prepare it in preprocess and then just print a variable if building that configuration array is too tedious in twig.