How do you stop your hands from tensing when performing solo acoustic guitar?

Question: I've been playing guitar for around 12 years or so, but never played in front of others while learning (minus family members or friends on occasion). Recently, I convinced myself to finally start performing solo acoustic guitar at open mics. However, besides the normal nerves of playing in front of people (which I'm working on), my hands tense up rather quickly once I start playing.
I play finger-style acoustic guitar (Andy McKee, Don Ross, Calum Graham, etc.) and need my hands and fingers to be able to remain flexible during performances. For example, I just performed Calum Graham's piece called 12:34, but there are quite a few pinch harmonics throughout. (Including a few instances where they are the focus of a phrase.) When I practice at home, they are not an issue, but my hands get tense when performing and the harmonics do not ring out, or sound at all. A lot of the time, I find that the first pinch is decent, but as I play the following notes, it's as if my thumb ceases to move and doesn't do the actual pinch motion.
I was hoping that someone here might have advice for this specific issue. Is this just directly tied to the stage fright? Or are there any exercises that may help alleviate this problem? If it is just due to the stage fright, does anyone have tips on overcoming the nerves for a live-performance-newbie (besides repeatedly performing)?
Obviously, there are MANY more problems with my live performances, but my hands' flexibility is absolutely crucial for this style of playing so I'm focusing on that for now.
Any tips for playing this style (or playing live in general) would be greatly appreciated! The frequent mistakes are not great for the confidence to force myself back on the stage. Thanks in advance!
Comment: Do you practice in the same posture as when performing?
Comment: I noticed a suggested edit by a user named "Acoustic Tony". If this is you, User Tony, you might want to contact the moderation team to [merge the two accounts](https://meta.stackexchange.com/q/18232/401908).
Answer: This is an interesting question.  Before finishing the entire description I would have opted for your technique is not up to par and you are getting fatigued.  However, you point out that this does not bother you at home and that it starts right away on stage (after the first pinch).
If this is solely a performance anxiety issue it's probably psychological.  You are nervous and that causes muscles to tense.  Once they tense it's a vicious cycle!
After one mishap the mind might go to one of two places in my experience.  (1) I need to repeat that last bit and get it right, or (2) oh no it's falling apart I hope the next one isn't so bad.
Neither of these is a useful mind frame for performance.  If this is a fair evaluation of what's going on then I can relate as I have had varying degrees of stage fright in my life.  One thing to consider is that if you are playing solo (no back up) then you really are naked (and possibly afraid [couldn't resist]).  What helps me is working with bands either as the front or as back up.  If you can get on stage and back someone else up for a song or two that may give you a chance to acclimate to the climate and relax a bit while someone else has the heat on them.  Sorry if that sounds selfish but it's true.  Of course you need to do a decent job as a back up or all eyes are on you, but in my experience this is a low key task.  It puts you in front of the audience for a while in a non-threatening way and hopefully in time your nerves will calm down.
It has been my experience that my stage fright peaks right before the first song but then completely vanishes.  This is probably due to years of live playing.  The calm during the storm is critical for job security.  I do it for a living and if I had the problem you are describing that would not be possible.
Sight readers have the problem of wanting to stop and go back when they mess up and that is not possible during a gig.  One thing that helps with this is to do regular sight reading exercises.  There are good books by William Levitt on this.  The goal is not to read a song to learn it but to set the metronome at a decent speed and NEVER STOP, even if you F@$k up.  Always stay on beat and either stop and jump in on time or recover as gracefully as possible.  I am not suggesting that you have a sight reading problem but this method can help you relax during performance.  The same tension builds (or used to build) when I played in large orchestras and missed a cue or felt like I might fall out of sync with the group.  That mishap causes extreme tension and loss of confidence and eventually an inability to move forward.  You could try the same approach when practicing at home by simply pretending you are on stage and either playing with a metronome or a recording of the song(s) you want to perform.  If you mess up, let it go, DON'T STOP just pick up ASAP.  The flow of time will not stop for you, or anyone, and that is one thing live performance teaches you.  Keep track of how well or poorly you do with the pick up and try, try, again.  You will find that even though mistakes come you are better able to handle them gracefully.
Now on to technique.  Based on what you have said I'm going to guess that your technique is fine but it is worth mentioning that if you have any bad habits, or poorly developed techniques, or even if you don't know the songs you are playing perfectly, these will all come out amplified by 100x's when you get nervous.  If your hand is cramping to fatigue you are definitely squeezing too hard but my question to you is, do you practice long enough at home to know when you will fatigue?  Believe it or not many guitarists practice bits and pieces of songs, and get really good, but don't rehearse the entire pieces.  On performance day they might fall apart 2 minuets into a 5 minute song because they haven't tested themselves.  Be honest with yourself.  If you have noodled with a tune and really think you know it make sure you are playing several times in a row without fatigue before attempting it on stage.  If you cannot get through it w/o a hand cramp or other issue at home it will not happen on stage.  And again, nerves will make it worse.  What I'm saying is make sure your body is really ready for it.  That will help reduce the amount of tension generated by stage fright.   It's all about reducing risk.  If you know the song inside out and don't fatigue you might be able to let your body take over.  If you cannot get through the tune several times at home then you are probably not ready.  If you start getting hand pain you may need to evaluate your technique and improve it.
Last but not least on the stage fright front usually playing more makes it go away.  But if you get the same type of anxiety talking to people in tense situations, like returning something at a store, giving a presentation at work, you might want to try regular meditation or TM.  The long term effects are that the tendency to get anxiety simply goes away in all situations.
Comment: +1. Like I say to students - you can't *unmake* a mistake. It's already happened - carry on, take no notice, keep up with the piece. And always blame the bass player (often me...)
Comment: Hey ggcg

I had a longer message I wanted to leave, but I'm not 100% sure how one does that so I'm just leaving a comment.

Thank you for all the advice! There were a lot of issues with the initial performance of 12:34, but my second go around was much smoother. I learned the tune in a week because I was so hopped up on inspiration so I think I needed a little more time to practice.
Comment: @Tony, I'm glad it helped and that your second attempt was better.  It is really easy to "get hopped up" when playing out.  At least you want to rather than staying in.
Answer: Playing in front of an audience has almost nothing in common with playing at home with family and friends, so stage fright sets in and you tense up. Not only that, but your hyper- critical ears kick in and you hear things about your own playing that you never noticed before and often it throws your concentration off. It feels somewhat traumatic when it's happening, at least it did for me. If I remember correctly, I faced that dilemma for a few weeks when I first started playing publicly, and although my performances were not a pleasant thing for me, I eventually came to realize I was still standing at the end of the performance, the trauma was all in my head, and others had enjoyed my performance and some were returning to see me perform again. What was happening for me was the negative feelings were being replaced with the positive feedback from the audience. Add to that, performing in public was less and less a new experience and the uncertainty that goes with new experiences was fading  for me each time I performed. Now, I make certain I'm well fed and rested and take steps to insure my own  comfort, comfortable shoes and clothes and the like, when I'm on stage and I approach the whole thing as a social situation that I'm there to enjoy, as opposed to a performance that someone may decide to critique. I just kept in mind that I really wanted to be a performer and I wasn't going to let stage fright stop me. And it didn't.


Path needed for solving these linear equations in Zn (my example Z105)

Question: So these are two equations :
$$49x \equiv 21 \pmod {105}$$
$$64x \equiv 21 \pmod {105}$$
I should find the multiplicative inverse of $64$ and then $49$ that gets the result of $1$
so....
In the first equation i know that the $\gcd(49, 21)$ is $7$
So reducing them, I have $7x \equiv 7 \pmod {105}$
and $105 = 15 \times 7$
here I get lost!!

In the second equation
I know that $64$ and $21$ are coprime with each other, so euclidean algorithm, bezout identity, smth like 64v + 21w = 1 right.. and if I found V I basically found the x... but I get lost somewhere...
first I do the $\gcd(105, 64)$ then with bezout identity I want to find v and w such that = $1$
and I have $25$ for the bigger term and $-41$ for the smaller term...
but $64 x 25 + 21(-41)$ doesn't equal to $1$
again,, lost... connection not found!! :D
please help... maybe i chose the wrong direction, and math doesn't do for me!
Comment: Just for the record, I used a quick python program (brute-force) to compute that the inverse of 64 is 64 modulo 105, which yields x=84 mod 105 from the second congruence. The first congruence is satisfied by x=84, so there's the solution, for all it's worth. Basically, I focused on solving the second congruence first, since 64 and 105 are coprime, meaning 64 has a unique multiplicative inverse mod 105.
Comment: The congruence $49x\equiv21\pmod{105}$ is equivalent to $7x\equiv3\pmod{15}$, not what you wrote. It boils down to $x\equiv9\pmod{15}$. There are seven classes modulo $105$ that satisfy this, and among them is $84$.
Comment: for the 3, my bad,,, i meant that, but i didn;t knew that i could use the gcd do divide the mod too.
thank you!:)
Answer: The inverse of $64$ modulo $105$ can be found with the Euclidean algorithm:
\begin{align}
105&=64\cdot 1+41\\
64&=41\cdot 1+23\\
41&=23\cdot 1+18\\
23&=18\cdot 1+5\\
18&=5\cdot 3+3\\
5&=3\cdot 1+2\\
3&=2\cdot 1+1
\end{align}
Thus
\begin{align}\def\c#1{\color{red}{#1}}
1&=\c{3}-\c{2}\\
&=\c{3}-(\c{5}-\c{3})=(-1)\cdot\c{5}+2\cdot\c{3}\\
&=(-1)\cdot\c{5}+2(\c{18}-3\cdot\c{5})=(-7)\cdot\c{5}+2\cdot\c{18}\\
&=-7(\c{23}-\c{18})+2\cdot\c{18}=(-7)\cdot\c{23}+(-5)\cdot\c{18}\\
&=(-7)\cdot\c{23}+(-5)(\c{41}-\c{23})=(-2)\cdot\c{23}+(-5)\cdot\c{41}\\
&=(-2)(\c{64}-\c{41})+(-5)\cdot\c{41}=(-2)\cdot\c{64}+(-3)\cdot\c{41}\\
&=(-2)\cdot\c{64}+(-3)(\c{105}-\c{64})=\c{64}+(-3)\cdot\c{105}
\end{align}
and it turns out that the inverse is $64$.
Therefore, from the second equation, we get that
$$
x\equiv 64\cdot21\equiv1344\equiv84\pmod{105}
$$
Now
$$
49\cdot 84=4116\equiv21\pmod{105}
$$
and you're done.
Answer: Note that you could combine these equations and get:
$15x\equiv0 (\mod 105)$ which would reduce your initial equations to $4x\equiv21 (\mod 105)$
From here, you could use the Chinese Remainder Theorem for one idea or look at $21+105k$ and find a multiple of 4 there.
$21+3*105= 21+315 = 336 = 4 * 84$
Thus, try $x\equiv84 (\mod 105)$ as one solution.


Connection between some inequalities

Question: Let $I \subset \mathbb{R}$ be an interval, $f: I \rightarrow \mathbb{R}$ be a function and let $n \geq 2, n \in \mathbb{N}$ be fixed number.
Let's consider the following conditions:

$\displaystyle f\left(\frac{x_1+x_2}{2}\right) \leq \frac{f(x_1)+f(x_2)}{2}  \textrm{ for } x_1, x_2 \in I$;
$\displaystyle f\left(\frac{x_1+...+x_n}{n}\right) \leq \frac{f(x_1)+...+f(x_n)}{n}
\textrm{ for } x_1,...,x_n \in I$.

By https://math.stackexchange.com/a/83398/22907 1. implies 2.
Does 2. imply 1. ?
Comment: If $n$ is even, $n=2p$ just take $x_1=\ldots=x_p=a$ and $x_{p+1}=\ldots,=x_{2p}=b$. If $n=2p+1$, put $x_1=\ldots=x_p=a$, $x_{p+1}=\ldots=x_{2p}=b$ and $x_{2p+1}=\frac{a+b}2$.
Comment: @Davide: I liked the short version better... *Ma non importa*.
Comment: isn't (2) a special case of (1), when you set n to 2?
Comment: @Emmad: That's what I thought when I looked at the question at the first sight. But I looked at it again, I found that here $n$ is fixed.
Comment: Offtop: Is the implication (2 to 1) also true if we demand $x_i \lt x_{i+1}$ and do not assume continousity / measurability of $f$?
Comment: @Davide: You might copy this as an answer.
Comment: @DidierPiau Done, I took me time, sine I tough was I told for the odd case was wrong, but now I am convinced it's not the case.
Answer: Let $a,b\in I$.
If $n$ is even, $n=2p$ just take $x_1=\ldots=x_p=a$ and $x_{p+1}=\ldots,=x_{2p}=b$.
We get
$$f\left(\frac 1{2p}\left(\sum_{j=1}^pa+\sum_{j=1}^pb\right)\right)\leq \frac{\sum_{j=1}^pf(a)+\sum_{j=1}^pf(b)}{2p},$$
so
$$f\left(\frac{pa+pb}{2p}\right)\leq \frac{pf(a)+pf(b)}{2p}\Rightarrow f\left(\frac{a+b}2\right)\leq \frac{f(a)+f(b)}2.$$
If $n=2p+1$, put $x_1=\ldots=x_p=a$, $x_{p+1}=\ldots=x_{2p}=b$ and $x_{2p+1}=\frac{a+b}2\in I$. We get, using 2. that
$$f\left(\frac{a+b}2\right)=f\left(\frac{pa+\frac a2+pb+\frac b2}{2p+1}\right)\leq
\frac{pf(a)+pf(b)+f\left(\frac{a+b}2\right)}{2p+1}$$
so $$f\left(\frac{a+b}2\right)\left(1-\frac 1{2p+1}\right)\leq p\frac{f(a)+f(b)}{2p+1}$$
hence $2pf\left(\frac{a+b}2\right)\leq p(f(a)+f(b))$, QED.

Connection between some inequalities


Conditional expectation of second moment given sum of iid variables.

Question: We have $\xi_i \geq 0$, $\forall i = \overline{1,n}$ (i.i.d. variables).
Assume that $S_n = \xi_1 +...+ \xi_n$.
It is easy to show that $\mathrm{E} (\xi_1\vert S_n = 1) = \frac{1}{n}$.
Now we want to look at the second moment: $\mathrm{E}(\xi_1^2\vert S_n = 1)$.
1) Since $0\leq\xi_i\leq 1$ then $\xi_i\geq \xi_i^2,\: \forall i=\overline{1,n},$ finally, $\mathrm{E}(\xi_1^2\vert S_n = 1) \leq \mathrm{E}(\xi_1\vert S_n = 1) = \frac{1}{n}$.
2) On the other hand,
by Jensen's  inequality we have: $(\mathrm{E}(\xi_1\vert S_n = 1))^2\leq \mathrm{E}(\xi_1^2\vert S_n = 1),$ where$(\mathrm{E}(\xi_1\vert S_n = 1))^2 = \frac{1}{n^2}$.
The question is: how can we prove that the second moment has order of $\frac{1}{n^2}$; namely how we can get upper bound as $\frac{c}{n^2}$, where $c$ is a constant?
Comment: If the random variables $(\xi_i)$ are i.i.d. exponential, then $$E(\xi_1^2\mid S_n)=\frac{2S_n^2}{n(n+1)}.$$
Comment: @Stef because we have condition that $S_n=1$.
Comment: Which is the distribution the $ξ_i$?
Comment: It isn't mentioned. But we can assume that density is a known function f(x).
Comment: Ok, but then how do you know that $ξ_i<1$? in 1).
Comment: Here you kinda need to assume that $P(S_1 = 1) \neq 0$ otherwise conditioning on improbable event is a good way to end up with wrong results.
Comment: @Did and how have you shown that? By the integrating the conditional density?
Comment: More or less, yes.
Answer: You can't prove it, because it might not be true.
Suppose $\xi_i$ take nonnegative integer values. Then the only way to have $S_n = 1$ is that one $\xi_i = 1$ while all the rest are $0$.  So  for such a distribution, $E(\xi_i^2 | S_n = 1) = 1/n$, and indeed
$E(\xi_i^p | S_n = 1) = 1/n$ for all positive $p$.
More generally, if $P(0 < \xi_i < \epsilon) = 0$ for some $\epsilon > 0$, then
$\xi_i^2 \ge \epsilon \xi_i$ a.s. so $E(\xi_1^2 | S_n) \ge \epsilon E(\xi_1 | S_n)$.


Guitar high e string breaking when tuning up new string

Question: I've recently encountered a problem with my 2016 Gibson Les Paul 50's Tribute.
A few weeks ago I replaced my set of Ernie Ball 11's with a set of 10's. All was going well until I went to tune the high e string. Once it had reached about the C or D below in tune, it began to de-tune rapidly. Tuning it up again, it reached the same point before letting out a ping noise, and instantly tuning right down again. I was using the G force electric tuner to tune, which I though might be a  little fast for the fresh string.
I threaded a new string and wound up the string manually, and slowly, but the same problem occurred. I tried again later using another new string, with no luck.
I believe the string is coming unwound at the end where it threads around the little ring, as I can't imagine what else would cause it to de-tune so quickly. Any help with what might be wrong would be much appreciated. The guitar has a G force tuners, titanium nut, titanium saddles and a stop bar tailpiece
Cheers
Comment: Put more windings on it at the tuning peg?
Comment: If it is unwinding itself off the brass ring at the bridge, you'll be left with that ring separate or nearly so from the end of the string. Sounds like it came from a faulty batch, and should go back to the supplier. I've known it happen, but only once in thousands of string changes. If that end is intact, as Todd says, use three or more turns round the tuning post. But you suspect the bridge end - look carefully at the string there. String not actually broken?
Comment: Todd's comment should be an answer.
Answer: What you've described is the sound of the string slipping at the tuning peg end.
Are you threading the string through the tuning peg correctly? (Don't be embarrassed, I didn't find out I was doing it wrong until I took lessons).
On a Les Paul 1st String you should turn the tuning peg until the hole through it is running parallel to the nut i.e perpendicular to the string.  Then you thread the string through the bridge, pull it hand-tight (not too tight) to the tuning peg, insert it through the left side of the hole, pull it out through the right side, wind it counter clockwise back UNDER the string and bend it up so as the string tightens, it locks the string tighter - the string end should stick vertically up from the peg.  On the thinner strings you should have the string slightly looser so that you get more turns before it gets up to tension and each turn should be over the string-end to increase the "locking" effect.  On a wound string (4,5,6), you don't need as many turns of the tuning peg to lock it efficiently so you can pull it tighter as you put it through the peg.
Answer: When this has happened to me, it was slippage on the tuning post and I remedied it with more windings on the tuning post.


Como atualizar todos os registros de todas as tabelas que tenham FK de uma tabela

Question: Tenho as seguintes tabelas:
CREATE TABLE Contrato (
  [Id [int] NOT NULL IDENTITY,
  [Nome] [varchar](150),
  [Ativo] [bit]
  PRIMARY KEY ([Id])
)
CREATE TABLE [dbo].[ItemContrato] (
  [Id] [int] NOT NULL IDENTITY,
  [ContratoId] [int],
  [Nome] [varchar](150),
  [Ativo] [bit]
  PRIMARY KEY ([Id])
)
 ALTER TABLE [dbo].[ItemContrato] ADD FOREIGN KEY ([ContratoId]) REFERENCES [dbo].[Contrato] ([Id]);

Com os seguintes registros:
 Contrato
 Id | Nome      | Ativo
 1  |Contrato A |  1
 2  |Contrato B |  1

 ItemContrato
 Id | ContratoId | Nome                | Ativo
 1  |     1      |Item de Contrato A1  |  1
 2  |     1      |Item de Contrato A2  |  1
 3  |     2      |Item de Contrato B1  |  1

Quero saber se há como, ou qual a melhor maneira para: Quando eu der um UPDATE na tabela Contrato setando Ativo = 0, o mesmo seja feito em todas as tabelas que tenham uma chave estrangeira da tabela Contrato.
Estou criando uma aplicação usando ASP.NET MVC com EntityFramework e DDD.
Obrigado
Answer: Levando em conta que você tenha um contexto Context.
var result = Context.Contrato.Include(rel => rel.ItemContrato).FirstOrDefault(prop => prop.Id == id);

Nesse código eu carrego minha entidade Contrato a ser modificada e todos ItemContrato relacionado a ela, você pode alterar a expressão do FirstOrDefault de acordo com o seu gosto.
Context.Entry(result).State = EntityState.Modified;
result.Ativo = 0;
foreach (var itemContrato in result.ItemContratos)
{
    itemContrato.Ativo = 0;
    Context.Entry(itemContrato).State = EntityState.Modified;
}
Context.SaveChanges();

Pode não ser a melhor maneira a ser feito, mas vai resolver seu problema.
Comment: Não entendi exatamente onde deveria fazer essa implementação, tenho pouca experiência com essa estrutura que estou trabalhando. Mas sim, tenho um Context
Comment: No DDD isso vai dentro de sua camada de persistência, pode ser um repository pattern que você esteja utilizando, ou outro padrão.
Comment: No meu caso eu tenho um repositório com os métodos especializados da entidade Contrato. Devo fazer um override do meu método Update?
Comment: Não, porque essa implementação é um **cenário especifico** onde o seu update vai adicionar um Ativo igual a zero, se quiser sobrescrever o seu base.Update(), você precisa alterar meu exemplo.
Comment: Na verdade é um cenário que deve ocorrer em todas as situações. Minha intenção é, ao torar um registro inativo, todos "filhos" desse registro também se tornem inativos. Me disseram que poderia fazer com trigger também, mas ainda não sei qual seria a melhor opção
Comment: Trigger também poderia ser utilizado para um resultado parecido.
Answer: A melhor solução seria não replicar a informação para a tabela ItemContrato, afinal isso seria redundância. A melhor forma seria buscar a informação direto da tabela de origem:
SELECT ic.id,
       ic.contratoid,
       ic.nome,
       c.ativo
  FROM ItemContrato ic WITH(NOLOCK)
       INNER JOIN Contrato c WITH(NOLOCK) ON c.id = ic.contratoid;

Porém caso realmente queira replicar a informação, sugiro a utilização de uma trigger para realizar a alteração:
IF OBJECT_ID('tgr_contrato_aiu', 'TR') IS NULL
BEGIN
  EXEC('CREATE TRIGGER tgr_contrato_aiu ON Contrato FOR INSERT, UPDATE AS BEGIN SELECT 1 END');
END;
GO

ALTER TRIGGER tgr_contrato_aiu
ON Contrato
FOR INSERT, UPDATE
AS
BEGIN
  DECLARE @nome_tabela VARCHAR(100),
          @query       VARCHAR(MAX);

  SET NOCOUNT ON;

  -- Pega o nome da tabela para a qual a TRIGGER é executada
  SELECT @nome_tabela = OBJECT_NAME(o.parent_object_id)
    FROM sys.objects o WITH(NOLOCK)
   WHERE o.name = OBJECT_NAME(@@PROCID);

  SELECT @query = isnull(@query + CHAR(10), '') + 'UPDATE f' + CHAR(10) +
                                                  '   SET f.ativo = ' +  + CAST(i.ativo AS VARCHAR) + CHAR(10) +
                                                  '  FROM ' + tf.name + ' f' + CHAR(10) +
                                                  ' WHERE f.' + c.name + ' = ' + CAST(i.id AS VARCHAR) + ';' + CHAR(10)
    FROM sys.tables t WITH(NOLOCK)
         INNER JOIN sys.foreign_keys fk WITH(NOLOCK) ON fk.referenced_object_id = t.object_id
         INNER JOIN sys.tables tf WITH(NOLOCK) ON tf.object_id = fk.parent_object_id
         INNER JOIN sys.foreign_key_columns fkc WITH(NOLOCK) ON fkc.constraint_object_id = fk.object_id
         INNER JOIN sys.columns c WITH(NOLOCK) ON c.object_id = fkc.parent_object_id
                                              AND c.column_id = fkc.parent_column_id
         CROSS JOIN inserted i
         INNER JOIN deleted d ON d.id = i.id
   WHERE t.name = @nome_tabela
     -- Somente se mudar algo na coluna "Ativo"
     AND i.ativo <> d.ativo
     -- Garante que exista a coluna "Ativo" na tabela filha
     AND EXISTS(SELECT 1
                  FROM sys.columns cf WITH(NOLOCK)
                 WHERE cf.object_id = fkc.parent_object_id
                   AND cf.name = 'ATIVO');

  IF @query IS NOT NULL
  BEGIN
    -- PRINT @query;
    EXEC(@query);
  END;
END;
GO

A trigger acima busca todas as chaves estrangeiras relacionadas a tabela Contrato, juntamente com suas colunas e, dinamicamente, atualiza a coluna Ativo de acordo com o valor que foi inserido. Note que a trigger é executadas depois de cada INSERT e UPDATE.
Sugiro também a criação de uma trigger para a tabela ItemContrato que garantirá que quando um novo registro for inserido, já esteja com a informação da coluna Ativo da maneira que é esperada:
IF OBJECT_ID('tgr_itemcontrato_ai', 'TR') IS NULL
BEGIN
  EXEC('CREATE TRIGGER tgr_itemcontrato_ai ON ItemContrato FOR INSERT AS BEGIN SELECT 1 END');
END;
GO

ALTER TRIGGER tgr_itemcontrato_ai
ON ItemContrato
FOR INSERT
AS
BEGIN
  SET NOCOUNT ON;

  UPDATE ic
     SET ic.ativo = c.ativo
    FROM ItemContrato ic
         INNER JOIN inserted i ON i.id = ic.id
         INNER JOIN Contrato c ON c.id = ic.contratoid;
END;
GO

Para teste utilizei as seguintes inclusões nas tabelas:
SET NOCOUNT ON;

DECLARE @ultimo_codigo INT;

-- Inserção dos dados para teste
-- Contrato "X"
INSERT INTO Contrato(nome, ativo)
              VALUES('X', 1);
SET @ultimo_codigo = SCOPE_IDENTITY();

INSERT INTO ItemContrato(contratoid, nome)
                  VALUES(@ultimo_codigo, 'A'),
                        (@ultimo_codigo, 'B'),
                        (@ultimo_codigo, 'C');

-- Contrato "Y"
INSERT INTO Contrato(nome, ativo)
              VALUES('Y', 1);
SET @ultimo_codigo = SCOPE_IDENTITY();

INSERT INTO ItemContrato(contratoid, nome)
                  VALUES(@ultimo_codigo, 'D'),
                        (@ultimo_codigo, 'E'),
                        (@ultimo_codigo, 'F'),
                        (@ultimo_codigo, 'G');

-- Contrato "Z"
INSERT INTO Contrato(nome, ativo)
              VALUES('Z', 0);
SET @ultimo_codigo = SCOPE_IDENTITY();

INSERT INTO ItemContrato(contratoid, nome)
                  VALUES(@ultimo_codigo, 'H'),
                        (@ultimo_codigo, 'I'),
                        (@ultimo_codigo, 'J');

Obtendo os resultados a seguir logo após a inserção:
╔════╦══════╦═══════╗
║ Id ║ Nome ║ Ativo ║
╠════╬══════╬═══════╣
║ 1  ║ X    ║ 1     ║
║ 2  ║ Y    ║ 1     ║
║ 3  ║ Z    ║ 0     ║
╚════╩══════╩═══════╝

╔════╦════════════╦══════╦═══════╗
║ Id ║ ContratoId ║ Nome ║ Ativo ║
╠════╬════════════╬══════╬═══════╣
║ 1  ║ 1          ║ A    ║ 1     ║
║ 2  ║ 1          ║ B    ║ 1     ║
║ 3  ║ 1          ║ C    ║ 1     ║
║ 4  ║ 2          ║ D    ║ 1     ║
║ 5  ║ 2          ║ E    ║ 1     ║
║ 6  ║ 2          ║ F    ║ 1     ║
║ 7  ║ 2          ║ G    ║ 1     ║
║ 8  ║ 3          ║ H    ║ 0     ║
║ 9  ║ 3          ║ I    ║ 0     ║
║10  ║ 3          ║ J    ║ 0     ║
╚════╩════════════╩══════╩═══════╝

Logo após realizei o seguinte UPDATE:
-- Atualização dos contratos "X" e "Z"
UPDATE c
   SET c.ativo = 0
  FROM Contrato c
 WHERE c.nome = 'X';

UPDATE c
   SET c.ativo = 1
  FROM Contrato c
 WHERE c.nome = 'Z';

E os registros após o UPDATE são:
╔════╦══════╦═══════╗
║ Id ║ Nome ║ Ativo ║
╠════╬══════╬═══════╣
║ 1  ║ X    ║ 0     ║
║ 2  ║ Y    ║ 1     ║
║ 3  ║ Z    ║ 1     ║
╚════╩══════╩═══════╝

╔════╦════════════╦══════╦═══════╗
║ Id ║ ContratoId ║ Nome ║ Ativo ║
╠════╬════════════╬══════╬═══════╣
║ 1  ║ 1          ║ A    ║ 0     ║
║ 2  ║ 1          ║ B    ║ 0     ║
║ 3  ║ 1          ║ C    ║ 0     ║
║ 4  ║ 2          ║ D    ║ 1     ║
║ 5  ║ 2          ║ E    ║ 1     ║
║ 6  ║ 2          ║ F    ║ 1     ║
║ 7  ║ 2          ║ G    ║ 1     ║
║ 8  ║ 3          ║ H    ║ 1     ║
║ 9  ║ 3          ║ I    ║ 1     ║
║10  ║ 3          ║ J    ║ 1     ║
╚════╩════════════╩══════╩═══════╝

No caso da primeira query proposta os resultados antes do UPDATE para a tabela ItemContrato foram:
╔════╦════════════╦══════╦═══════╗
║ Id ║ ContratoId ║ Nome ║ Ativo ║
╠════╬════════════╬══════╬═══════╣
║ 1  ║ 1          ║ A    ║ 1     ║
║ 2  ║ 1          ║ B    ║ 1     ║
║ 3  ║ 1          ║ C    ║ 1     ║
║ 4  ║ 2          ║ D    ║ 1     ║
║ 5  ║ 2          ║ E    ║ 1     ║
║ 6  ║ 2          ║ F    ║ 1     ║
║ 7  ║ 2          ║ G    ║ 1     ║
║ 8  ║ 3          ║ H    ║ 0     ║
║ 9  ║ 3          ║ I    ║ 0     ║
║10  ║ 3          ║ J    ║ 0     ║
╚════╩════════════╩══════╩═══════╝

E após o UPDATE:
╔════╦════════════╦══════╦═══════╗
║ Id ║ ContratoId ║ Nome ║ Ativo ║
╠════╬════════════╬══════╬═══════╣
║ 1  ║ 1          ║ A    ║ 0     ║
║ 2  ║ 1          ║ B    ║ 0     ║
║ 3  ║ 1          ║ C    ║ 0     ║
║ 4  ║ 2          ║ D    ║ 1     ║
║ 5  ║ 2          ║ E    ║ 1     ║
║ 6  ║ 2          ║ F    ║ 1     ║
║ 7  ║ 2          ║ G    ║ 1     ║
║ 8  ║ 3          ║ H    ║ 1     ║
║ 9  ║ 3          ║ I    ║ 1     ║
║10  ║ 3          ║ J    ║ 1     ║
╚════╩════════════╩══════╩═══════╝

Note que os resultados são os mesmos, provando assim que para este caso a utilização do JOIN para evitar a redundância é a melhor opção.


Debugging cocos2dx in eclipse Android NDK

Question: I'm starting to use cocos2dx in my personal computer with Windows 7. It was a pain in the ass configuring all the environment with Eclipse and its CDT plugin, and Android NDK, but finally, I could run a game inside my Android phone.
The problem I'm facing right now is that I can't debug my game. I tried many things but looks like it is not able to reach the breakpoints I put.
Here is what I'm using in my Properties>C++ Build:
C:\ndk-r9c\ndk-build.cmd NDK_DEBUG=1 DEBUG=1 NDK_APPLICATION_MK=jni/Application.mk

And this is what I've got in Application.mk:
APP_STL := gnustl_static
APP_CPPFLAGS := -frtti -DCC_ENABLE_CHIPMUNK_INTEGRATION=1 -DCOCOS2D_DEBUG=1 -DDEBUG -    DANDROID_DEBUG_LEVEL=ANDROID_LOG_VERBOSE -DJSON_DEBUG
APP_OPTIM := debug

I don't know what else to try. I tried creating a new C++ debug configuration, but it needs a C++ executable and I can't find it inside the obj or bin folder of my Android project.
Any tips please? :(
Cheers!
Comment: Take a look at my answer here: http://stackoverflow.com/questions/17705109/how-to-debug-c-c-code-ndk-in-eclipse
Answer: from eclipse you can do a right click on your project, and select Debug as -> Android Native Application to debug it.
I've made a screencast here demonstrating this feature.


Is there a way to transfer table data from Access to Quickbooks with new ID?

Question: I am currently testing QODBC and OpenSync to find a way to let me enter information through Access and have it sync and show up in QuickBooks.
QuickBooks auto generates keys for each entry, but when entering new data the user is left to enter all of the fields themselves including the ID field. Is there a way to make Access generate QuickBooks ID's?
By ID I mean the primary ID field in each table is empty and is filled with Quickbook keys.
Answer: Are you letting the users type directly into the tables?
In every QODBC application I have written, Access uses a front end to gather the data and then create the new record using VBA. When Access generates a new record that is QODBC linked, QuickBooks automatically assigns a new primary key ID to it.
Comment: Can you give me an example of how your application is making QODBC makes QuickBooks generate a new Primary ID?
Comment: Standard SQL `INSERT` statements is one way: `DoCmd.RunSQL "INSERT INTO [QODBC linked table] ([FieldNames]) VALUES ([Values to be Inserted])"`. No primary key needed, it is auto-generated.


Three independent events

Question: Let $A$ and $B$ be independent events and let $P(A),P(B) \in (0,1)$.
Let $C$ be the event $A \cup B \setminus A \cap B$.
Prove that if $A,C$ are independent and $B,C$ are independent then $P(A)=P(B)$.
We have that
$$P(A \cap B) = P(A)P(B) \\ P(A \cap C) = P(A)P(C) \\ P(B \cap C) = P(B)P(C)$$
and I suppose that $$P(C) = P((A \cap B^c) \cup (A^c \cap B)) = P(A \cap B^c) + P(A^c \cap B)=P(A)P(B^c) + P(A^c)P(B)$$
but I have no idea how can I solve this problem.
Answer: From $P(A)=P(AB)+P(AB^c)$ and $P(B)=P(AB)+P(A^cB)$ on subtraction,
$$P(A)-P(B)=P(AB^c)-P(AB^c).\tag{1}$$
Since $C=AB^c \cup A^cB$ we have $P(AC)=P(AB^c)=P(A)P(C)$ (last by independence), and similarly $P(BC)=P(A^cB)=P(B)P(C).$ Subtracting these, and using (1),
$$(P(A)-P(B))P(C)=P(A)-P(B).$$
Rearranging this gives
$$(P(A)-P(B))[1-P(C)].$$
If now $P(C)<1$ we have $P(A)=P(B)$ as desired. But $P(C)=1$ leads to $P(A)=P(B)=1$ easily.
ADDED: Actually $P(C)=1$ does not lead to $P(A)=P(B).$
Since $P(C)=P(AB^c)+P(A^cB)=1$ we have $P(A\cap B)=0$ (and also $P( (A \cup B)^c)=0$). Then $P(A)=P(AB^c)$ and $P(B)=P(A^cB)$, each since the intersection $AB$ has probability $0$. Thus $1=P(C)=P(A)+P(B)$ and $P(AB)=0=P(A)P(B)$, so that either $P(A)=0,P(B)=1$ or else $P(A)=1,P(B)=0.$ This contradicts the assumption at the beginning that the probabilities of $A,B$ are in the open interval $(0,1).$
Comment: Well $1=P(AB^c)+P(A^cB)$ and so the complement of $[AB^c \cup A^cB]$ has probability zero. Since $AB=A \cap B$ is contained in that complement, we also have $P(AB)=0$. [Note I'm using here and in above answer the notation $AB=A \cap B$]
Comment: @user2213654 The best way I've found is by using Venn diagrams. You can place veriable names in the regions, and try to express the problem assumptions as equations or inequalities on the varibles. Of course if some intersection is empty that region is labeled by a $0$. This way you can sometimes see what's going on better.
Comment: Could you tell me why $P(C)=1$ leads to $P(A)=P(B)=1$ ?
Comment: @user2213654 I've fixed the ending now. The case of $P(C)=1$ doesn't lead to $P(A)=P(B)=1$ but does lead to a contradiction to your assumption that probabilities are strictly between $0$ and $1$.
Comment: In first line you wrote that $P(A \cap B) = 0$. Could you me tell why? I didn't understand it.
Comment: Ok, now I understood. But I have one question more. Is it any algorithm how solve similar tasks? I have always a lot of problem with similar tasks because I don't have any idea how begin solving and I'm so confused when I see similar tasks.

Three independent events


Multi-level Bayesian hierarchical regression using rjags

Question: I am trying to to implement a Bayesian hierarchical Model in R. I have a few predictor variables (2 metric and one categorical) and am trying to predict quarterly home sales in the US. Each sales observation is for a state that is a member of a region, which in turn make up the population as a whole. I am using the rjags package.
I want to implement the model so that the coefficients for individual states are drawn from distributions determined by their region, which in turn are determined by the population. Essentially, I want to model this as a three-level hierarchy. However, I only understand how to implement the two-level hierarchy, i.e., state-level coefficients are a function of the population.
I have prepared an example that highlights my question and (hopefully) provides a framework for an answer. Below is my code that generates dummy data and implements my model. I would appreciate any insight into how to accomlish this as well as other suggeestions on how to improve my code, model structure, or anything else.
<code># load rjags for modeling
library(rjags)

# data
Nregion <- nlevels(state.region)
Nstate <- length(state.abb)
Nqtr <- 20
N <- Nstate * Nqtr # number of obs
y <- runif(N, 4500, 5500) # regresand
x1 <- dplyr::lag(y); x1[is.na(x1)] <- 4500 # lag of y as covaritate
x2 <- rnorm(N, 100, Nqtr) # second covariates
a1 <- rep(seq(1, 4), Nstate * 5) #qtr of the year
s <- as.factor(rep(state.abb, Nqtr)) # state
r <- as.factor(rep(state.region, Nqtr)) # region

# model
modelstring = "
  model {
    for ( i in 1:N ) {
      y[i] ~ dnorm(y.hat[i], tau.i)
      y.hat[i] <- b0[s[i]] + b1[s[i]] * x1[i] + b2[s[i]] * x2[i] + b3[s[i], a1[i]]
    }

    for ( s in 1:Nstate ) {
      b0[s] ~ dnorm(b0u, b0t)
      b1[s] ~ dnorm(b1u, b1t)
      b2[s] ~ dnorm(b2u, b2t)

      for ( j in 1:Nqtr ) {
        b3[s, j] ~ dnorm(0, tau.sq.alpha)
      }

    }

    b0u ~ dnorm(0, .0001)
    b0t ~ dgamma(0.001, 0.001)
    b1u ~ dnorm(0, .0001)
    b1t ~ dgamma(0.001, 0.001)
    b2u ~ dnorm(0, .0001)
    b2t ~ dgamma(0.001, 0.001)
    tau.i ~ dgamma(0.001, 0.001)
    tau.sq.alpha ~ dgamma(0.001, 0.001)
    sigma.sq.alpha <- 1 / tau.sq.alpha

  }
"
# write to file
writeLines(modelstring, con="model.txt")

# create jags model object
jags <- jags.model('model.txt',
                   data = list('x1' = x1,
                               'x2' = x2,
                               'a1' = a1,
                               'y' = y,
                               'N' = N,
                               's' = s,
                               'Nstate' = Nstate,
                               'Nqtr' = Nqtr),
                   n.chains = 4,
                   n.adapt = 100)
</code>
Answer: You want a distribution for
  each quarter (given a state),
  each state (given a region), and
  each region.
That means you'll need at least some state parameters indexed by s (in your model b0, b1, b2), region parameters indexed by r (which I'll call c0, c1, c2), and global parameters (which I'll call d0, d1, d2). Your model should look something like this:
<code>modelstring = "
  model {
    for ( i in 1:N ) {
      y[i] ~ dnorm(y.hat[i], tau.i)
      y.hat[i] <- b0[s[i]] + b1[s[i]] * x1[i] + b2[s[i]] * x2[i] + b3[s[i], a1[i]]
    }

    for ( s in 1:Nstate ) {
      b0[s] ~ dnorm(c0[r[s]], b0t)
      b1[s] ~ dnorm(c1[r[s]], b1t)
      b2[s] ~ dnorm(c2[r[s]], b2t)

      for ( j in 1:Nqtr ) {
        b3[s, j] ~ dnorm(0, tau.sq.alpha)
      }

    }

    for ( r in 1:Nregion ) {
      c0[r] ~ dnorm(d0, c0t)
      c1[r] ~ dnorm(d1, c1t)
      c2[r] ~ dnorm(d2, c2t)
    }

    b0t ~ dgamma(0.001, 0.001)
    b1t ~ dgamma(0.001, 0.001)
    b2t ~ dgamma(0.001, 0.001)
    c0t ~ dgamma(0.001, 0.001)
    c1t ~ dgamma(0.001, 0.001)
    c2t ~ dgamma(0.001, 0.001)
    d0 ~ dnorm(0, .0001)
    d1 ~ dnorm(0, .0001)
    d2 ~ dnorm(0, .0001)
    tau.i ~ dgamma(0.001, 0.001)
    tau.sq.alpha ~ dgamma(0.001, 0.001)
    sigma.sq.alpha <- 1 / tau.sq.alpha

    }
"
</code>
where r[s] gives a region index, given a state index.


What is the best way to compare (personality) data from two time points?

Question: I have collected personality data (big five) for N = 50 at two times, approximately 10 years apart. I simply want to see how stable the traits are across this time point (i.e. is there a statistical difference in say, agreeableness between from collection time 1 to collection time 2). I know you can use t-tests/ANOVAs for each of the traits, but I wondered if there are other ways which may be better/more sophisticated/more reliable?
Any thoughts would be greatly appreciated.
Answer: You might consider some form of longitudinal structural equation modelling (see Little, 2013), like a latent panel model. You would not only be able to look at stability or change in levels of big five factors, but you could also assess longitudinal invariance of personality factors (Little, 2013, provides good coverage of longitudinal invariance, specifically, but Vandenberg & Lance, 2000, is a good general conceptual intro to invariance testing), which isn't something you can do with the more typical approaches. In a nutshell, this would allow you to ask the more foundational question (before comparing mean-levels of a personality factor over time) of whether the structure of personality is stable over those 10 years. I'm not a personality psychologist, so I don't know how intuitively plausible that possibility is, but it doesn't seem wholly unreasonable to suggest that the way personality manifests in a person might change over a decade (i.e., the distinctions between agreeableness, extraversion, openness, neuroticism, and conscientious might become more/less nuanced).
If you're new to SEM, this CV thread here has a number of really good answers outlining the benefits of this approach to analyzing data.
References
Little, T. D. (2013). Longitudinal structural equation modeling. New York, NY: Guilford Press.
Vandenberg, R. J., & Lance, C. E. (2000). A review and synthesis of the measurement invariance literature: Suggestions, practices, and recommendations for organizational researchers. Organizational Research Methods, 3, 4-70.


Reshaping data from a grid and populating a column with the data frame name

Question: Main question: Is there a way to populate a df with the data frame name other than just typing it in and pasting it manually?
I have 20 csv files in a folder that have a grid of data that looks somewhat like this.
File 1:

X1
X2
X3

Y1
1
2
3

Y2
4
5
6

Y3
7
8
9

File 2:

X1
X2
X3

Y1
1
4
7

Y2
2
5
8

Y3
3
6
9

Note: X1,2,3 and Y1,2,3 are co-ordinates, while the populated values are just example values and are not indicative of any pattern
Each file has a unique ID e.g., US_plot_1.csv, US_plot_2.csv, UK_plot_1.csv, US_plot_2.csv,
I want to populate a df that sorts these files into columns that R can analyse, grouped by filename i.e.,

filename
X
Y
Values

US_plot_1
X1
Y1
1

US_plot_1
X1
Y2
4

US_plot_1
X1
Y3
7

US_plot_1
X2
Y1
2

US_plot_1
X2
Y2
5

US_plot_1
X2
Y3
8

US_plot_1
X3
Y1
3

US_plot_1
X3
Y2
6

US_plot_1
X3
Y3
9

US_plot_2
X1
Y1
1

US_plot_2
X1
Y2
2

US_plot_2
X1
Y3
3

I understand for the populating the data I can loop it.
df<- lapply(Sys.glob("*.csv"), read.csv) #to load all the csvs
df<- as.data.frame(df)
df<-lapply(split(sequence(ncol(df)), rep(1:(4/4), each = 4)), function(x) df[, x])

filenames<- list.files(path=getwd())  #to get the filenames
filenames2<- substr(filenames, 1, 9)

for (i in 1:20) {
     assign(paste(filenames2[i], i), data.frame(df[[i]]))
}

Then when I need to change each data into an r-analysable df I can use the tidyr package with gather():
US_plot_1<-DF %>% gather (X_coord, Value, X1:X3)

I know I can always resort to just manually pasting it in using
US_plot_1$filename<-paste("US_plot_1")

But I was wondering if there was a more efficient way?
Answer: You can do this within the lapply command :
library(dplyr)
library(tidyr)

filenames <- Sys.glob("*.csv")

df<- lapply(filenames, function(x) {
  #Read the csv
  read.csv(x) %>%
    #Get the data in long format, gather is retired using pivot_longer
    pivot_longer(cols = starts_with('X')) %>%
    #Adding a new column as filename
    mutate(filename = tools::file_path_sans_ext(x))
})

If you want them as separate dataframes :
names(df) <- tools::file_path_sans_ext(filenames)
list2env(df, .GlobalEnv)

Comment: I realise I never replied: thank you very much!


What is the correct string gauge for an Alvarez LJ2E acoustic guitar?

Question: I am going to change the strings on this guitar for the first time. A google search brings up one website that says that it uses 13-56 strings, but this is not mentioned on the official Alvarez website, and I want to make sure I get the string gauge correct.
Edit: Apologies for the poorly worded question. I specifically wanted to know the string gauge that Alvarez ships this model with, not what is "correct".
Answer: There is no correct gauge - for any guitar. There is a manufacturer's recommended gauge, but most players will have their own favourite gauge - I have for 50 odd years - based on playability, tone, volume, and other personal factors.
Since you have already been playing this guitar, are you totally satisfied, or are there chaanges you'd like to make? Maybe change the top three for lightre gauge, a plain third, a thicker bottom string?If you're totally satisfied, go to the string shop, get them measured, or do like I do, use a gauge to check: (Vernier, caliper). Or contact Alvarez...
Comment: That's a fair comment. Although going up or down a couple of thou won't make *that* much difference. If you do change the gauge, it's worth the trouble to find just how much it goes out. On the lower frets there won't be so much change that it becomes unplayable. I changed to.008s on an old (50year old) Epiphone acoustic years ago, and it's been fine all that time.
Comment: I'm concerned that the intonation will go off if I use a string gauge that's different from the one that came with the guitar.
Comment: Thanks for the explanation Tim, that sounds encouraging :) it's easy to get paranoid reading about guitar on the internet.
Comment: I got a reply from a Parts and Service Manager at Alvarez. This guitar ships with D'Addario EXP16 strings, a light gauge set .012 through .053. Your answer was very helpful but I will set mine to the "accepted answer" since it directly answers the question. Thanks Tim!
Comment: Due to an edit in the question, this answer doesn't supply exactly what OP asks for, however, it stays as is!
Answer: Got a reply from a Parts and Service Manager at Alvarez. This guitar ships with D'Addario EXP16 strings, a light gauge set .012 through .053. Hope this is useful for someone else!
Comment: As Tim mentioned, despite them shipping the guitar with that set, it doesn't mean it is the correct set. The correct set depends much more on the player than the guitar.
Comment: To be honest, this answer is only useful to owners of Alvarez LJ2E guitars - maybe one in 50,000 readers - or less?
Comment: This question is also only useful to owners of that guitar, so that seems appropriate given the scope? If this site is not a good place for model-specific questions, I will make a note of that.


Retirar tag  usando php e deixar somente texto

Question: Estou utilizando o PHPMailer para fazer envios de emails, porem no corpo do email tem um campo (endereco) que está chegando como link (para o maps) para o destinatário.
Já utilizei o strip_tags() mas não resolveu. Localmente funciona, porem quando testo online não funciona.
Código:
 $end = $_POST['endereco'];
 $enderecoFormatado= strip_tags($end, '');

 $corpo = "

      Endereco:

        $enderecoFormatado

";

 $corpo = utf8_decode($corpo);
 $mail->msgHTML($corpo);

Comment: Pode ser que o cliente de email detecte URLs e os transformam em links.
Comment: E não tem como eu restringir isso? (Mexendo no meu código é claro), de alguma forma que só chegue o texto para ele?
Answer: Em geral não tem como evitar isso, porque o cliente de email adiciona links automaticamente quando encontra URLs válidas no corpo da mensagem.
Porém, existe um truque que engana o sistema e não adiciona os links. Basta colocar os endereços (URLs) entre as tags  (sem href nem nada, apenas ). Exemplo:
http://www.site.com

Inclusive funciona com endereços de email:
firstname.lastname@example.com

Obs.: Testado no Gmail e Hotmail com sucesso.
Comment: Fiz vários testes e não veio como link. Vc testou no Gmail?
Comment: Nos meus dominios
Comment: Pois é, a resposta é que não tem como evitar isso. Só apresentei uma forma que funciona pelo menos no Gmail e Hotmail.
Comment: Pois é, que eu saiba,  somente em `$mail->IsHTML(false);` daí vai tudo como texto
Comment: Poderia ser, mas só no caso de ser texto puro.
Comment: Deu certo aqui cara, muito obrigado pela dica.


F# Compilation error when implementing C# interface

Question: I have this interface written in C#...
public interface IFoo {
    IEnumerable<T> Bar<T>(IEnumerable<T> list);
}

A simple C# implementation is straightforward...
public class CsFoo : IFoo
{
    public IEnumerable<T> Bar<T>(IEnumerable<T> list)
    {
        return list;
    }
}

A simple F# implementation is also straightforward...
type FsFoo() =
    interface IFoo with
        member this.Bar list =
            list

But when I try to match on list...
type FsFoo() =
    interface IFoo with
        member this.Bar list =
            match list with
                | [] -> []        // error
                | list -> list

I get this error...

This expression was expected to have type
  System.Collections.Generic.IEnumerable<'a> but here has type 'b list

Can you help me understand this error and how I should change the F# code to fix it?
Thank you...
Comment: You're trying to use list pattern matching with the sequence.
Actually, the error states it rather clearly.
If you want to use list pattern matching, you have to convert the sequence to the list: `list |> Seq.toList`.
Answer: Your interface does not use a list, it uses IEnumerable<T> and because of that you should use Seq when dealing with the interface in F#.
type FsFoo() =
    interface IFoo with
        member this.Bar list =
            match Seq.isEmpty list with
                | true -> Seq.empty        // input is empty
                | false -> list            // input is not empty

But it's actually pointless, because it just passes parameter value as result value, so it's exactly the same as
type FsFoo() =
    interface IFoo with
        member this.Bar list = list

Comment: Okay.  That makes sense.  (But perhaps I erred here by contriving an example that results in an error message that is a duplicate of the one I see in my actual program, but does not represent my actual problem.)


Remainder of division of ${6}^{7^n}$ to $43$

Question:
What is the Remainder of the division of ${6}^{7^n}$ to $43$?

I've tried with Fermat's little theorem, but it haven't work.
Update : lab bhattacharjee gave a nice proof. But I want to know if this proof is correct.
${6^7}^n = ({6^7})^{7^{n-1}}$
$6^7 = ({6^3})^2$ * 6
$6^3 = 216 = 1(mod 43) => ({6^3})^2 = 1^2 = 1 (mod 43) => 6^7 = 6 (mod 43) => ({6^7})^{7^{n-1}} = 6^{7^{n-1}} (mod 43) <=> {6^7}^n = {6^7}^{n-1} (mod 43)$
The same way we obtain $6^{7^{n-1}} = 6^{7^{n-2}} (mod 43)$
$6^{7^{n-2}} = 6^{7^{n-3}} (mod 43)$
...
${6^7}^2 = {6^7}^1 (mod 43)$
${6^7}^1 = {6^7}^0 = 6 (mod 43)$
So ${6^7}^n = 6 (mod 43)$
Comment: $6^3=216\equiv 1(mod 43)$
Comment: @lab bhattacharjee Is it correct (the proof)?
Comment: @user3313320 sorry, writting mistake
Answer: As $\phi(43)=42$
$\implies6^{(7^n)}\equiv6^{7^n\pmod{42}}\pmod{43}$
let use find $7^n\pmod{42}$
Now as $(7^n,42)=7$ for integer $n\ge1$
we shall find $7^{n-1}\pmod6$
$7\equiv1\pmod6\implies7^{n-1}\equiv1^{n-1}\equiv1$
$\implies7^n\equiv7\cdot1\pmod{6\cdot7}\equiv7$
$\implies6^{(7^n)}\equiv6^7\pmod{43}$
Now use $6^3\equiv1\pmod{43}$ and $6^7=(6^3)^2\cdot6\equiv?\pmod{43}$
Comment: I can't get the second line with 6^(7^n) = 6^7^n (mod 42) (mod 43)...
Comment: @scummy, As $6^{42}\equiv1\pmod{43}$
Comment: I can undersant this, but still can't get the second line.
Comment: @scummy, If $7^n=42m+r,$   $$6^{(7^n)}\equiv6^{42m+r}=(6^{42})^m\cdot6^r\equiv1^m\cdot6^r\pmod{43}$$
Comment: Sorry - just didn't see it. Thanks!
Answer: As $6^3\equiv1\pmod{43}$  $$6^{(7^n)}\equiv6^{(7^n)\pmod3}\pmod{43}$$
and $7\equiv1\pmod3\implies7^n\equiv1^n\equiv1$
$$6^{(7^n)}\equiv6^1\pmod{43}$$
Comment: @scummy, Please clarify your question.
Comment: Could we speak at chat? It's quite hard here 'cause you can edit a comment every 5 minutes.
Comment: I've sent it [here](http://chat.stackexchange.com/rooms/26895/room-for-scummy-and-lab-bhattacharjee)


Surface integral in a cylindrical coordinate system

Question: Let
$$\mathbf{F}(x,y,z) = \left({-x\,{\bf i}-3\,x\,y^2\,{\bf j}+z\,{\bf k}}\right).$$
so then the $\nabla\cdot\mathbf{F}= -6yx$
then
$$V = \left\{(x,y,z)\mid 0\le z\le 2xy,~ x^2+y^2\le {1}\right\},$$
I want to evaluate the surface integral:
$$\displaystyle\iint_{S}\left(\mathbf{F}\cdot\mathbf{n}\right)dS$$
I know that $S=\delta V$
So parametrization is
$$x = r\cos(\theta)$$
$$y=r\sin(\theta)$$
$$z = z$$
and then $0 \le \theta \le2\pi$ and $0\le z \le 2xy$
 and $r=1$
But how do I calculate the integral?
Answer: We can use divergence theorem, and we have
$$\displaystyle\iint_{S}\left(\mathbf{F}\cdot\mathbf{n}\right)dS)=\iiint_V \nabla\mathbf{F}\,dV$$
with $\nabla\mathbf{F}= -6yx$.
By cylindrical coordinates the set up should be
$$\iiint_V \nabla\mathbf{F}\,dV=\int_0^{2\pi}d\theta\int_0^1dr\int_0^{2r^2\cos \theta \sin \theta}-6r^3\cos\theta \sin \theta \,dz$$
Comment: Okey but what are the limit values of that integral then
Comment: @vvv I'll add something on that.
Comment: What is the answer because I got some random answer $(-6*\pi*sin^2(\theta))$
Comment: @vvv It seems equal to $\pi/2$ see [here](https://www.wolframalpha.com/input/?i=int+%28-6r%5E3cos+t+sin+t%29+dz+dr+dt+z%3D0..%282r%5E2+cos+t+sin+t%29+r%3D0..1+t%3D0..2pi).


Simplifying expression in summation notation

Question: Can anyone provide some guidance on how to simplify this expression, if at all possible? Thank you.
$$\sum_{i=1}^{n} {n\choose i} (-1)^{i+1} 2^{n^2+2(n-i)}$$
Answer: Observe you have
\begin{align}
-2^{n^2} \sum^n_{i=1} \binom{n}{i}(-1)^i 4^{n-i}
\end{align}
Comment: ... and recognize a binomial expansion (https://en.wikipedia.org/wiki/Binomial_theorem) up to to the first term.


Ball in hand on the black - where can it go?

Question: If I made a foul (such as scratching the cue ball), my opponent has the ball in hand.
Where can they place it, if they are on the black?
Answer: Playing with BCA/APA rules the ball  can be placed anywhere on the table.
Comment: Can you refer directly to a rule for this? Preferably, citing the rules document also.


Get user input and check it, linux

Question: I am a beginner at unix and I am trying to use a while loop to get a user integer input for 2 numbers, but I need to check if it is an integer and reask if it's not, so I attempted to utilize if statements inside the while loop. I cannot get this to work, what am I doing wrong with the while and if loop?
       #! /bin/bash
<code>    echo "Enter first number:"

    while read number1
    do
      if[[ $number1 ]] && [ $input -eq $input 2>/dev/null ]
      then
        echo "$number1"

      else
        echo "$number1 is not an integer or not defined.Try again"
      fi
     done

    echo "Enter second number:"
    while read number2
       do
        if[[ $number2 ]] && [ $input -eq $input 2>/dev/null ]
            then
              echo "$number2"
        else
              echo "$number2 is not an integer or not defined.Try again"
         fi
    done
</code>
Comment: Please include in your question the mandatory four:  ① What did you try, ② what did you expect to happen, ③ what did you observe instead, and ④ why is this not matching your expectation.  You provided ① and ②.
Comment: Check your spaces (always around `[[` and `]]`) and your quotes.
Answer: If you are trying to get the number and checking it until it becomes integer, Please try the below code.
<code>#!/bin/bash
echo "enter number"
while read number1
do
if ! [[ $number1 =~ ^[0-9]+$ ]]
then
        echo "number is not an integer"

else
        echo "number is an integer"
        exit;
fi
done
</code>

Get user input and check it, linux


Como colorir SVG sem o path fill?

Question: Bom, rasterizei uma imagem e preciso colori-la. A questão é que a mesma não é nenhuma forma geométrica(gola de camiseta) e preciso dar a opção do usuario de colorir ela.
No entanto ao exportar o svg não aparece o atributo Fill, que usaria para fazer essa coloração..
Como colorir esse svg?
Segue o codigo do svg que é renderizado:
<svg xmlns="http://www.w3.org/2000/svg"
  xmlns:xlink="http://www.w3.org/1999/xlink"
  preserveAspectRatio="xMidYMid" width="54" height="37" viewBox="0 0 54 37">
    <image xlink:href="data:img/png;base64,iVBORw0KGgoAAAANSUhEUgAAADYAAAAlCAMAAAA+2eraAAAABGdBTUEAALGPC/xhBQAAACBjSFJNAAB6JgAAgIQAAPoAAACA6AAAdTAAAOpgAAA6mAAAF3CculE8AAAB5lBMVEUAAACzzB6zzB6zzB6zzB6zzB6zzB6zzB6zzB6zzB6zzB6zzB6zzB6zzB6zzB6zzB6zzB6zzB6zzB6zzB6zzB6zzB6zzB6zzB6zzB6zzB6zzB6zzB6zzB6zzB6zzB6zzB6zzB6zzB6zzB6zzB6zzB6zzB6zzB6zzB6zzB6zzB6zzB6zzB6zzB6zzB6zzB6zzB6zzB6zzB6zzB6zzB6zzB6zzB6zzB6zzB6zzB6zzB6zzB6zzB6zzB6zzB6zzB6zzB6zzB6zzB6zzB6zzB6zzB6zzB6zzB6zzB6zzB6zzB6zzB6zzB6zzB6zzB6zzB6zzB6zzB6zzB6zzB6zzB6zzB6zzB6zzB6zzB6zzB6zzB6zzB6zzB6zzB6zzB6zzB6zzB6zzB6zzB6zzB6zzB6zzB6zzB6zzB6zzB6zzB6zzB6zzB6zzB6zzB6zzB6zzB6zzB6zzB6zzB6zzB6zzB6zzB6zzB6zzB6zzB6zzB6zzB6zzB6zzB6zzB6zzB6zzB6zzB6zzB6zzB6zzB6zzB6zzB6zzB6zzB6zzB6zzB6zzB6zzB6zzB6zzB6zzB6zzB6zzB6zzB6zzB6zzB6zzB6zzB6zzB6zzB6zzB6zzB6zzB6zzB6zzB6zzB6zzB6zzB6zzB6zzB4AAAB1WLE/AAAAoHRSTlMAIrLUfTEBAzmD1n8J9uefVxQjaK3wTNz9051iBxE+c6zkv/vXq4tuUDQhBhs7WHSSueVAvi+hsB/3TlSj0c2lYCmKqSZch8O7mXxKkw7m73gYLGaJl7eBclI4GhLsE1oWCgIEMvnBm8Qn2S17z9sFtd4MLvjF42rzj7xI0hk69F9pr5aIuKQP3eo3/lsLdgiuJJWQepxVp6oVooKYQ6iG+RY0bgAAAAFiS0dEAIgFHUgAAAAJcEhZcwAAFxEAABcRAcom8z8AAAIsSURBVDjLY2BgYGBkYmZhZWMgArBzcHJxQ5g83LwLgICPX0AQvx4hYRFRkEqwPjHxBTAgISklzSqDTYesnLyCIlwdSJ/SAlSgrKKqpq6hqSWrzcAuqyOkq6dvYGiEpgaoz3gBGQCoz5AMbSYMDKYSpGvjAPrOjGRd5qBgsrCEcKysbWzxqLWzd4CFmiM4eJ0gPGcGBhdXNzN3LFo8PL28NRm0oTwfSKz4+oF5/gFgXmCQRrBXSKhNGMgkT7XwiMio6BiwjDNEV2wcNDbjIXyjBOQo9vXVTkxCcJMZUlIhyqRhQmxpEIF0fGkrEerxDETqzYSESpYrHm0+0PDIRhLLgYjlBuLUFZUHUeKELJgPdYG9Ly5tBRAFhUUoosUlKIGLAUrLwNISxmjiERBtqeVYdaVXQKQr0SXYqqCxUI1Fl5UkRLKGB0Oqlg8iJRmFIVUHceGCekcsRspBo7MUPTgTc6GpqgGrBxqhsmZo4k1Q8WYcwdUCkU7zRBENyYIIt7Lj0MbWBlFgiJzKyqGBWNPOgAtoM0HzljMsVrUjOyBCnYwMuEEiNFEvsIEFIpSf2sWADxRBc2kZxJ2JpRBudw8DftALjfaOdKA7GVWglvUxEAL9E6BKRSYG2UGZnAR1AeuHSehFyWQidAHBlG4UXVOJqo2AYFo9kq7p7ETqYmBgLYPrmqFNtC4GhpnQAF0wi3i7wAEzG1w3zEkiSRcQzAVWa5OJDQ0kEDNvPi4pAHQb17SBoGL0AAAAAElFTkSuQmCC"
      width="54" height="37"/>
</svg>

Comment: Como vc gerou esse svg? Tem alguma coisa estranha ai, parece um base64 dentro do svg... Até onde sei base64 não tem fill e não permiti trocar cores assim...
Comment: O @hugocsl tem razão. Você até que está usando uma tag svg, mas o conteúdo não é referente. Portanto, não é possível colorir.
Answer:

<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"
preserveAspectRatio="xMidYMid" width="130" height="60" viewBox="0 0 130 60">
<desc>
Imagem de gola de camiseta, rasterizada, com opção de colorir.
(feColorMatrix hueRotate)
</desc>
<defs>
<filter id="filter">
<feColorMatrix id="matrix" type="hueRotate" values="0"/>
</filter>
</defs>
<image x="25%" xlink:href="data:img/png;base64,iVBORw0KGgoAAAANSUhEUgAAADYAAAAlCAMAAAA+2eraAAAABGdBTUEAALGPC/xhBQAAACBjSFJNAAB6JgAAgIQAAPoAAACA6AAAdTAAAOpgAAA6mAAAF3CculE8AAAB5lBMVEUAAACzzB6zzB6zzB6zzB6zzB6zzB6zzB6zzB6zzB6zzB6zzB6zzB6zzB6zzB6zzB6zzB6zzB6zzB6zzB6zzB6zzB6zzB6zzB6zzB6zzB6zzB6zzB6zzB6zzB6zzB6zzB6zzB6zzB6zzB6zzB6zzB6zzB6zzB6zzB6zzB6zzB6zzB6zzB6zzB6zzB6zzB6zzB6zzB6zzB6zzB6zzB6zzB6zzB6zzB6zzB6zzB6zzB6zzB6zzB6zzB6zzB6zzB6zzB6zzB6zzB6zzB6zzB6zzB6zzB6zzB6zzB6zzB6zzB6zzB6zzB6zzB6zzB6zzB6zzB6zzB6zzB6zzB6zzB6zzB6zzB6zzB6zzB6zzB6zzB6zzB6zzB6zzB6zzB6zzB6zzB6zzB6zzB6zzB6zzB6zzB6zzB6zzB6zzB6zzB6zzB6zzB6zzB6zzB6zzB6zzB6zzB6zzB6zzB6zzB6zzB6zzB6zzB6zzB6zzB6zzB6zzB6zzB6zzB6zzB6zzB6zzB6zzB6zzB6zzB6zzB6zzB6zzB6zzB6zzB6zzB6zzB6zzB6zzB6zzB6zzB6zzB6zzB6zzB6zzB6zzB6zzB6zzB6zzB6zzB6zzB6zzB6zzB6zzB6zzB6zzB6zzB6zzB6zzB6zzB6zzB4AAAB1WLE/AAAAoHRSTlMAIrLUfTEBAzmD1n8J9uefVxQjaK3wTNz9051iBxE+c6zkv/vXq4tuUDQhBhs7WHSSueVAvi+hsB/3TlSj0c2lYCmKqSZch8O7mXxKkw7m73gYLGaJl7eBclI4GhLsE1oWCgIEMvnBm8Qn2S17z9sFtd4MLvjF42rzj7xI0hk69F9pr5aIuKQP3eo3/lsLdgiuJJWQepxVp6oVooKYQ6iG+RY0bgAAAAFiS0dEAIgFHUgAAAAJcEhZcwAAFxEAABcRAcom8z8AAAIsSURBVDjLY2BgYGBkYmZhZWMgArBzcHJxQ5g83LwLgICPX0AQvx4hYRFRkEqwPjHxBTAgISklzSqDTYesnLyCIlwdSJ/SAlSgrKKqpq6hqSWrzcAuqyOkq6dvYGiEpgaoz3gBGQCoz5AMbSYMDKYSpGvjAPrOjGRd5qBgsrCEcKysbWzxqLWzd4CFmiM4eJ0gPGcGBhdXNzN3LFo8PL28NRm0oTwfSKz4+oF5/gFgXmCQRrBXSKhNGMgkT7XwiMio6BiwjDNEV2wcNDbjIXyjBOQo9vXVTkxCcJMZUlIhyqRhQmxpEIF0fGkrEerxDETqzYSESpYrHm0+0PDIRhLLgYjlBuLUFZUHUeKELJgPdYG9Ly5tBRAFhUUoosUlKIGLAUrLwNISxmjiERBtqeVYdaVXQKQr0SXYqqCxUI1Fl5UkRLKGB0Oqlg8iJRmFIVUHceGCekcsRspBo7MUPTgTc6GpqgGrBxqhsmZo4k1Q8WYcwdUCkU7zRBENyYIIt7Lj0MbWBlFgiJzKyqGBWNPOgAtoM0HzljMsVrUjOyBCnYwMuEEiNFEvsIEFIpSf2sWADxRBc2kZxJ2JpRBudw8DftALjfaOdKA7GVWglvUxEAL9E6BKRSYG2UGZnAR1AeuHSehFyWQidAHBlG4UXVOJqo2AYFo9kq7p7ETqYmBgLYPrmqFNtC4GhpnQAF0wi3i7wAEzG1w3zEkiSRcQzAVWa5OJDQ0kEDNvPi4pAHQb17SBoGL0AAAAAElFTkSuQmCC"
width="54" height="37" filter="url(#filter)"/>
<foreignObject y="65%" width="130" height="21">
<select xmlns="http://www.w3.org/1999/xhtml"
onclick="matrix.setAttribute('values', event.target.value)">
<option value="0">yellowgreen</option>
<option value="45">mediumseagreen</option>
<option value="90">lightseagreen</option>
<option value="135">skyblue</option>
<option value="180">lightsteelblue</option>
<option value="225">violet</option>
<option value="270">lightpink</option>
</select>
</foreignObject>
</svg>

Como colorir SVG sem o path fill?


Proper statistical significance tests for small samples of unknown distribution

Question: The title basically says it all; what is considered to be a proper statistical test in the literature for comparing small samples of unknown distribution? That is to say, I run an experiment something like 10 times (because of the long running time, getting a significantly larger sample is not possible) under certain settings (say configuration x), and I run it another 10 times under different settings (say configuration y), and so I get two sets of 10 numbers which indicate performance, one set of 10 results for x and one set of 10 results for y. I want to know whether the differences between these samples are statistically significant, such that I can say something like "running the experiment with configuration x gives significantly higher/lower results than running it with configuration y".
Specifically, I am doing an experiment in which I run an algorithm and get a performance indicator back (a number); the question is whether the difference I see (I would generally compare them myself by average), is actually statistically significant.
From what I know Student's t-test is often considered quite good; though it assumes your distribution is like a normal distribution. I've seen Wilcoxon's signed-rank test used for cases like this, but I'm not sure whether it's really proper (I'm not an expert on statistical analysis). As far as I'm aware it also makes a similar assumption that your results are normally distributed; perhaps that's not a weird assumption if you're just re-running the same experiment (which has some random elements) a number of times, I don't know. I could say the results look like they might be normally distributed, but what do I know, especially with a sample size of 10?
Comment: I'm unclear on what is being compared. Are you trying to compare the 10 results to one another? All of them to some baseline expected vale? Some other comparison?
Comment: @CFD I've modified the first paragraph, I hope this is better
Answer: If you can't make any assumptions about the underlying distributions, you will need a non-parametric test. In this case you could use the Mann-Whitney U  test (aka Wilcoxon rank-sum test). This is different from the Wilcoxon signed rank-sum test, which is used for paired data.
If you find after collecting the data that the results are approximately normal in each group (and have similar variance), you can use the t-test which will be more powerful than the Wilcoxon rank-sum test.


mysql: add integer values with duplicate primary key

Question: I want to redistribute some values in a table in a database I manage.
Firstname(varchar), Lastname(varchar), Date(date), Icecream_consumed(int)

Where the combination of Firstname, Lastname, and Date make the primary key for this table. Changing the structure of this table is not an option.
There are 80 total unique combinations of Firstname and LastName in the database but i want to get that number down to 5 and add some of the records with the smaller total Icecream_consumed to the ones with the highest total. So that only the top 5 FirstName and LastName combinations have all the Icecream_consumed count.
For example if I execute the query:
  SELECT Firstname, Lastname, SUM(Icecream_consumed)
    FROM table_name
GROUP BY Firstname, Lastname
ORDER BY SUM(Icecream_consumed);

I want it to only have 5 results, not 80.  How can I modify the records within the table to reflect this without manually updating each record?  A simple update would not work as it would be inserting where existing records with the same primary key exist.
EDIT: I noticed that the column ID was kind of ambiguous.  So I removed it from this example.
EDIT2: Here is an example:
Existing:
Firstname, Lastname, SUM(Icecream_consumed)
John  Doe   1500
Joe   Doe   1400
Alex  Foo   1111
John  Foo   1000
Ben   Foo    999
Sue   Cool   500
Bill  Smith  200
Ben   Smith  150

I want to change the tables so that the sum(icecream_consumed) values associated with sue, cool, bill smith, and ben smith are associated with john doe so that only 5 results are visible.  However if i tried to update all records for sue cool to be john doe instead, there would be a conflict with the primary keys since they both might have values for icecream_consumed for the same dates.
The outcome might look like:
John  Doe   2000
Joe   Doe   1600
Alex  Foo   1261
John  Foo   1000
Ben   Foo    999

Comment: You want to modify the records (to get the `SUM` updated) without modifying them (keep the same primary key) ? if not, a small example of "current" vs. "wanted" would help understanding better what you're trying to achieve.
Comment: sounds like a job for `insert into x select ... from ... on duplicate key update consumed = consumed + y`
Comment: Jack could you phrase your answer in the form of the example i gave above?  I was looking into the "on duplicate key" phrase, and what you provided seems like it would add the values but I also need to eliminate the smaller record so we maintain the same total count and are not just adding new numbers out of nowhere.
Answer: Working example on SQL Fiddle: http://sqlfiddle.com/#!2/0e8ab/1
Because MySql cannot run sub selects in update statements if the subselect is the same table as the one in the update, you need to first temporarily copy the data into another table - so DO NOT run this when data is still going into the database as it is not an atomic operation. You need to shut down any applications using the database first.
-- Create a copy of the data
CREATE TABLE table_name_copy SELECT * FROM table_name;

-- Update the rows with the most Icecream_consumed to have the total
UPDATE table_name t1 SET t1.Icecream_consumed = (
    SELECT SUM(t2.Icecream_consumed)
    FROM table_name_copy t2
    WHERE t2.Firstname = t1.FirstName AND t2.Lastname = t1.Lastname
)
WHERE id = (
    SELECT id
    FROM table_name_copy t2
    WHERE t2.Firstname = t1.FirstName AND t2.Lastname = t1.Lastname
    ORDER BY Icecream_consumed DESC LIMIT 1
);

-- Delete the other rows that don't have the new totalled Icecream_consumed
DELETE FROM table_name
WHERE id != (
    SELECT t2.id
    FROM table_name_copy t2
    WHERE t2.Firstname = table_name.FirstName AND t2.Lastname = table_name.Lastname
    ORDER BY Icecream_consumed DESC LIMIT 1
);

-- Remove the copied table
DROP TABLE table_name_copy;

Comment: This is an option I hadn't considered and it makes sense, nice work.  I now wonder if there is a way to do the same operation without creating a temporary table.
Comment: The only thing I can think off the top of my head is to write a small script or application to do the data migration. But to be honest that is probably more work. I've fixed some mistakes and added a working example, to this answer, to show it works.


UserId is empty guid

Question: I am getting following error when I am trying to resolve a case in MS Dynamics CRM Online 'UserId is empty guid!'. There is no plugin and workflow running in the background at the time of case resolution. When I try to resolve the Case through admin, it is working fine without any error. I copied this error from browser console as Plugin Trace Log is not throwing any error. I know it is related to security roles but not able to understand which role I have to tweak.
Please find the stack-trace below.
<code>error: {code: "0x80040217", message: "UserId is empty guid! ",…}
code: "0x80040217"
innererror: {message: "UserId is empty guid! ",…}
message: "UserId is empty guid! "
stacktrace: "   at Microsoft.Crm.Extensibility.OrganizationSdkServiceInternal.Execute(OrganizationRequest request, CorrelationToken correlationToken, CallerOriginToken callerOriginToken, WebServiceType serviceType, Boolean checkAdminMode, ExecutionContext executionContext, Dictionary`2 optionalParameters)
↵   at Microsoft.Crm.Extensibility.OData.CrmODataExecutionContext.Execute(OrganizationRequest request, ExecutionContext executionContext)
↵   at Microsoft.Crm.Extensibility.OData.CrmODataServiceDataProvider.ExecuteOperation(CrmODataExecutionContext context, EdmOperation edmOperation, Dictionary`2 parameters, Dictionary`2 boundParameters)
↵   at Microsoft.Crm.Extensibility.OData.ActionController.ProcessOperationRequest(String operationName, Dictionary`2 operationParameters, EntityReference entityReference, String boundEntityName, String boundEntityType)
↵   at Microsoft.Crm.Extensibility.OData.ActionController.<>c__DisplayClass9_0.<PostUnboundAction>b__0()
↵   at Microsoft.PowerApps.CoreFramework.ActivityLoggerExtensions.Execute[TResult](ILogger logger, EventId eventId, ActivityType activityType, Func`1 func, IEnumerable`1 additionalCustomProperties)
↵   at Microsoft.Xrm.Telemetry.XrmTelemetryExtensions.Execute[TResult](ILogger logger, XrmTelemetryActivityType activityType, Func`1 func)
↵   at lambda_method(Closure , Object , Object[] )
↵   at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ActionExecutor.<>c__DisplayClass10.<GetExecutor>b__9(Object instance, Object[] methodParameters)
↵   at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ExecuteAsync(HttpControllerContext controllerContext, IDictionary`2 arguments, CancellationToken cancellationToken)
↵--- End of stack trace from previous location where exception was thrown ---
↵   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
↵   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
↵   at System.Web.Http.Controllers.ApiControllerActionInvoker.<InvokeActionAsyncCore>d__0.MoveNext()
↵--- End of stack trace from previous location where exception was thrown ---
↵   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
↵   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
↵   at System.Web.Http.Controllers.ActionFilterResult.<ExecuteAsync>d__2.MoveNext()
↵--- End of stack trace from previous location where exception was thrown ---
↵   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
↵   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
↵   at System.Web.Http.Dispatcher.HttpControllerDispatcher.<SendAsync>d__1.MoveNext()"
type: "System.ServiceModel.FaultException`1[[Microsoft.Xrm.Sdk.OrganizationServiceFault, Microsoft.Xrm.Sdk, Version=22.214.171.124, Culture=neutral, PublicKeyToken=31bf3856ad364e35]]"
message: "UserId is empty guid! "
</code>
Error Screenshot -
Comment: That definitely looks like a custom exception, so custom code must be running somewhere.
Comment: No there is no plugin and workflow running in the background, as I have mentioned.
Answer: I was able to resolve this issue, as it was due to read permission was not available in Calendar Entity in service management. I tried trial and error approach by changing the permissions of individual entities one by one.
I don't understand why Dynamics does not throw appropriate error so that it becomes easy to resolve the issue.

UserId is empty guid


How to generate pdf file from a specific type of content?

Question: I have a content type named "employees".
I want that when I add an employee(creating content of type employee) it should also generate a pdf file which will contain the data which I inserted during adding content.
And a link on that node appears stated that "Download the pdf".
Answer: You can achieve this functionality with print module. For documentation click here.
This module depends on the libraries you can install any of them.
1. dompdf
2. mPDF
3. TCPDF(Best in performance)
4. wkhtmltopdf
Comment: can I change the text of the link which is appearing on a node page?
Comment: I find the way to change the text of the link :)


moving tabs in NERDTREE tabs

Question: I am using the NERDTree and NERDTree tabs plugin. In order to move between tabs I found these shortcuts which work fine:
nnoremap tp :tabprev<CR>
nnoremap tn :tabnext<CR>
nnoremap tf :tabfirst<CR>
nnoremap tl :tablast<CR>

However, I also want ability to re-arrange tabs. Searching online, i found the following:
" useful mappings for managing tabs
map <leader>tn :tabnew<cr>
map <leader>to :tabonly<cr>
map <leader>tc :tabclose<cr>
map <leader>tm :tabmove

I have included the above in my .vimrc file but don't understand how to use them. What is  mean ? How do I rearrange tabs using the above commands or are these commands useless ?
Comment: Why don't you have a look at `:help :tabnew`, `:help :tabonly`, `:help :tabclose` and `:help :tabmove`?
Answer: You can execute one of these command by pressing your leader key then the rest of the mapping. The default leader key is \ so your first mapping would be \tn. You can see what is mapped to what by issuing the :map command with out any agruments. You can narrow this down by mode for example by doing :nmap, :imap, or :vmap. You can also supply one argument which will narrow down the results much further. e.g. :nmap \ will show all normal mappings that start with \.
However there are a few concerns with your mappings:

You should supply a mode with your mappings
Unless you have a good reason it should be a in noremap form. e.g. nnoremap <leader>tn :tabnew<cr>
Your tp, tn, tf, and tl overshadow the the t command which is quite handy
gt and gT are the default tab tabnext/tabprev mappings.
You seem to be making heavy use of Vim's tab. It should be noted that Vim's tabs serve a different purpose than that of other editors. See: Using Vim's tabs like buffers
As you don't seem know about the t command I am going to suggest you take a look at vimtutor. See :h tutor or run vimtutor from the command line.
It might also be wise to forgo some of the plugins until you get a better grip on how Vim works.
You may want to reconsider the use of NerdTree as Vim does not support the "drawer" and it will interfere with windows/splitting. See: Oil and vinegar - split windows and the project drawer

For more information see:
:h <leader>
:h t

Comment: NerdTree is a fine plugin however there are issues which stick out like a sore thumb when NerdTree is used as an "always on" project drawer. 1) It makes splitting and window navigation trickier 2) It wastes space because it is not likely needed to see the file structure anywhere near 100% of the time. I have another answer that might help clarify these issues and how to address them: [Files, Buffers, and Splits Oh My!](http://stackoverflow.com/a/23121220/438329).

moving tabs in NERDTREE tabs


javascript não cria elemento html e não adiciona na pagina

Question: Estou começando no javascript e queria criar elementos html dinamicamente mas quando carrega a pagina ela fica em branco e não adiciona os elementos
código abaixo:
function add (){

    var texto = document.createTextNode("teste");
    var p = document.createElement("p");
    var ptexto = p.appendChild(texto);
    var body = document.getElementsByTagName("body")[0];
    body.appendChild(ptexto);

}

Answer: Acho que queres inserir o p e não o ptexto certo?
De qualquer maneira o teu código funciona, vê aqui:

function add() {
  var texto = document.createTextNode("teste");
  var p = document.createElement("p");
  var ptexto = p.appendChild(texto);
  var body = document.getElementsByTagName("body")[0];
  body.appendChild(ptexto);
}

add();

Mas acho que o que queres é:

function add() {
  var texto = document.createTextNode("teste");
  var p = document.createElement("p");
  var ptexto = p.appendChild(texto);
  document.body.appendChild(p);
}

add();
p {
  background-color: #eef;
  padding: 5px;
}

E nesse caso não precisas do textNode, podes fazer assim:

function add() {
  var p = document.createElement("p");
  p.textContent = 'teste!!';
  document.body.appendChild(p);
}

add();
p {
  background-color: #eef;
  padding: 5px;
}
Comment: @MarceosDourado isso aparece se estiveres a adicionar o JavaScript dentro do `head`. Coloca no final do `body` ou com `window.load = function(){ /* o código aqui */ }`
Comment: @MarceosDourado Asssim: `[seu html] ... `
Comment: obrigado a todos, tentei executar no navegador mas não apareceu, e aparece uma msg a hora que inspeciono a pagina aparece    Uncaught TypeError: Cannot read property 'appendChild' of undefined seria algo de configuração?
Comment: Sergio e eu acho que tu queres recordar, vejo que bela song,  https://www.youtube.com/watch?v=Rr7TaaJ60Ws
Comment: @LeoCaracciolo :)


Where is the service container compiled to?

Question: Where is the service container compiled to in Drupal 8, in the database or in a file?
Comment: @mradcliffe, that's the normal Symfony way to do it, compile the service container to a single php file. For better performance Drupal as changed this and stores it now in database in the table `cache_container`. How to take a look inside: https://www.drupal.org/node/2540430
Comment: In a protected directory inside the site's configured files path `php/**/` unless cache is turned off then it won't use it (i.e. for development)
Comment: This appears to have been closed a bit prematurely, @4k4 care to post that as an answer?
Comment: What do you mean by "service file compiled"? Are you referring to D8 service objects?
Comment: Yes, i think that Drupal like symfony compiled each services interpreting the compiler pass ecc...
Comment: ! THZ @mradcliffe 4k4
Comment: Oh, man, I guess I haven't been paying attention, and it used to be in that location.
Answer: As @mradcliffe described in a commment, the normal Symfony way to compile and cache the service container is a single php file. Drupal used this until Sep. 2015. If you have an older installation, you still find the compiled container in php/**/, because it was never deleted by newer versions.
For better performance Drupal has changed this and stores it now in database in the table cache_container. The change record and how to take a look inside the container to debug it:
Change record: The service container definition is now stored in the database by default


Example of a curve which is C1 continuous but not G1 continuous.

Question: I'm reading about parametric and geometric continuity using  these UC Berkeley Lecture notes.
In the section "Graph of the curve", this is written:

While the conditions for parametric continuity seem stronger than
geometric continuity, they are not. There are C1 curves that are not
G1.

Can anyone give an example for such a curve?
Found a similar question here but the example given is of a curve which is G1 continuous but not C1 continuous.
These Cornell lectures seemingly give an example of such a curve but it is not very clear. (Page 6 of the pdf)
Answer: Consider the parameterized curve $\gamma(t)=(t^3,t^2)$. This parameterization is clearly $C^1$, because each component is (infinitely!) differentiable.
However, the graph of the curve looks like this:

As you can see, the left and right tangent vectors at the origin (where $t=0$) do not match, so the curve is not $G^1$.
This is possible because $\gamma'(0)=\left<0,0\right>$. That is, the parameterization comes gradually to a stop at $t=0$, which allows it to smoothly traverse a geometrically unsmooth curve.


Does a surjective linear map commute with the interior of a convex body?

Question: Let $T:\Bbb R^n \to \Bbb R^m $ be a surjective linear map.
Suppose $A\subset\Bbb R^n$ is convex, compact, $0\in \operatorname{int}(A)$, and centrally symmetric.
Is it true that $T(\operatorname{int}(A))=\operatorname{int}(T(A))$?.
Notes:

$\operatorname{int}(S)$ means interior of $S$ in the topology of $\mathbb{R}^n$ or $\mathbb{R}^m$.
Convexity is important: e.g., consider the image of sphere $S^2\subset \mathbb{R}^3$ under projection
$A$ having nonempty interior is also important: consider the image of a disk $D^2\subset \mathbb{R}^3$ under the same projection.
Comment: The $\supseteq$ direction is trivial and in the general true without any hypothesis on $C$ ...
Answer: Since $T$ is surjective, it is open. Therefore $T(\operatorname{int} A)$ is an open subset of $T(A)$, so $T(\operatorname{int} A) \subseteq \operatorname{int} T(A)$.
Pick an $a_0 \in \operatorname{int} A$, and choose an arbitrary $y \in \bigl(\operatorname{int} T(A)\bigr) \setminus \{T(a_0)\}$. Then there is an $\varepsilon > 0$ such that $z = T(a_0) + (1+\varepsilon)\bigl(y - T(a_0)\bigr) \in \operatorname{int} T(A)$. Choose $x \in A \cap T^{-1}(\{z\})$. Then the "tipless cone"
$$C = \{ tx + (1-t)a : t \in [0,1),\, a \in \operatorname{int} A\}$$
is open, and by convexity contained in $A$, hence $C \subseteq \operatorname{int} A$. We have
$$w = a_0 + \frac{1}{1+\varepsilon}(x - a_0) \in C$$
and
\begin{align}
T(w) &= T(a_0) + \frac{1}{1+\varepsilon}\bigl(T(x) - T(a_0)\bigr) \\
&= T(a_0) + \frac{1}{1+\varepsilon}\bigl(z - T(a_0)\bigr) \\
&= T(a_0) + \frac{1}{1+\varepsilon}(1+\varepsilon)\bigl(y - T(a_0)\bigr) \\
&= y,
\end{align}
showing $y \in T(\operatorname{int} A)$. Since clearly also $T(a_0) \in T(\operatorname{int} A)$, it follows that $\operatorname{int} T(A) \subseteq T(\operatorname{int} A)$.
We note that the proof only used that $T$ is an open linear map, and $A$ convex with nonempty interior, so the result also holds in an infinite-dimensional setting.
Answer: The answer is 'yes'.  The proof is based on the lemma:
Lemma. Suppose $A$ is compact and convex in $\mathbb{R}^n$,
and $0$ is an interior point of $A$.
Let $R$ be a ray based at $0$.
Then $R$ intersects $\partial A$ in exactly one point $\bar{x}$.
All the points in the half-open segment
$[0,\bar{x})$ are interior points of $A$.
Proof. See for example: the book Topology and Geometry by Bredon, p. 56.
And for your question:
It is easy to show that $T(A)$ is convex and compact.
The easy part:
Since $T$ is surjective, by the open mapping theorem,
$T( \mathrm{int}(A) )$ is open, and it is certainly a subset of $T(A)$, therefore
$T( \mathrm{int}(A) ) \subseteq \mathrm{int}(T(A))$.
The hard part:
Conversely, suppose $y \in \mathrm{int}(T(A))$; we must show $y=T(a)$ for some $a \in \mathrm{int}(A)$.
By the open mapping theorem, $T(0)$ is an interior point of $T(A)$.
If $T(0)=y$ we are done.
Otherwise let $R_Y$ be the ray based at $T(0)$ through $y$.
By the Lemma, $R_Y$ intersects $\partial T(A)$ in a unique point $\bar{y}$.
Since $y$ is an interior point and $\bar{y}$ is a boundary point, $y \ne \bar{y}$.
Let $y_1$ be the midpoint of segment $[y,\bar{y})$.
By the Lemma, $y_1 \in \mathrm{int}(T(A)) \subseteq T(A)$.
Pick $a_1 \in A$ so $T(a_1)=y_1$; clearly $a_1 \ne 0$.
Consider the ray $R_X$ based at $0$ and passing through $a_1$.
$a_1$ is either an interior point or a boundary point of $A$,
but in either case, by the Lemma,
all the points in $[0,a_1)$ are interior points.
$T$ maps the segment $[0,a_1)$ to $[T(0),y_1)$.
Since the given $y \in [T(0),y_1)$,
one of those interior points in $[0,a_1)$ maps to $y$.
We are done.
Note that there is no assumption about symmetry.


How to achieve Jaco Pastorius' percussive effect

Question: An example of what I mean:

I haven't been able to find any tutorials on how to get this effect, though.
Comment: Which effect do you mean. Can you describe what but you mean.
Comment: Okay, that doesn't match your question title. Do want instruction on how he does it? The video makes it fairly obvious. Happy to post a detailed answer if you can't see what he is doing.
Comment: If you could give some detail that would be great (I'm admittedly not the best bass player, but I've not come close to emulating the effect).  And if you have a better suggestion for the question title, I'll update that, too.
Comment: I linked to a specific point in the video that I hoped would demonstrate it.  It's the long slide up the fretboard, some muted percussive noises, then shorter slides down.
Answer: For a lot of this track it sounds like Jaco Pastorius has a synth effect on his bass, but that isn't that relevant for this percussion effect.
What he is doing is muting or damping with his left hand and using the right to act as a tom. The movement of his hand up and down the fretboard gives a tonal change (fractionally) but this is basically a percussion technique.
When trying to replicate this, don't worry about where your right hand is, concentrate on the tapping with fingers and the damping with the heel of your palm.
Comment: Worth noting that Jaco plays a fretless bass, so the slides up and down are going to be pretty different on a typical bass.
Comment: good point - with frets your note will be well defined, whereas here you can hear a tone/pitch difference but it is in the background amongst the percussive thud.


Show post if true/false is yes. Advanced custom fields

Question: I have managed to get my loop to show only the posts that display true on an advanced custom field.
But I now only want to show one post. I cant seem to get it to only loop one of the posts that features the true/false field as yes.
'posts_per_page' => '1'
Doesn't work as it only shows the latest post.. which if its not ticked it just shows blank.
<?php
$args = array(
    'post_type' => 'event'
    );
$the_query = new WP_Query( $args );
?>

        <?php if ( have_posts() ) : while ( $the_query->have_posts() ) : $the_query->the_post(); ?>

                <?php if ( 'yes' == get_field('sponsored_event') ): ?>

                        <div class="sponsored-image" style="background-image: url(<?php the_field( 'event_image' ); ?>);">

Sponsored Event

<?php the_title(); ?>

Date

<?php the_field( 'event_location' ); ?>

<?php the_field( 'event_time' ); ?>

<?php the_field( 'excerpt' ); ?>

                <?php endif; ?>

        <?php endwhile; else: ?>

    <?php endif; ?>

<?php wp_reset_query(); ?>

Comment: Replied with an answer below. Implement this and share thoughts. As well as added the answer here to. http://stackoverflow.com/questions/39276798/show-most-recent-post-if-yes-chosen-as-radio-button-value.
Answer: The ACF Radio button Yes/No field is to be manipulated the other way. You have to get the Output and then compare with the value that you need.
Syntax:
$variable = get_field('field_name', $post->ID);

Where the $post->ID will be appering from the Loop that you use.
if (get_field('sponsored_event') == 'yes') {
    // code to run if the above is true
}
else
{
     // code for else part
}

Make sure that the value saved into the DB for the radio button is like you give in the if statement
This is an Optional for you to use the meta_value in the Query. if you dod't use you can fetch the acf value with the help of the post ID that you get from the loop of Wp_Query
Change the Wp_Query like this if you need only one post that to the latest one that has been stored.
$args = array( 'post_type' => 'event', 'posts_per_page' => 1,'order'=>'DESC','orderby'=>'ID','meta_key'=> 'sponsored_event','meta_value'=>'yes');

Else if you want all the posts that has been stored you can use like this.
$args = array( 'post_type' => 'event', 'posts_per_page' => -1,'order'=>'DESC','orderby'=>'ID','meta_key'=> 'sponsored_event','meta_value'=>'yes');

Note:
post_per_page=10 -> Will bring the 10 posts from your post type
post_per_page=-1 -> will bring infinite posts that your post type has
Entire Loop:
<?php
$args = array(
  'posts_per_page'  => 1,
  'post_type'       => 'event',
  'meta_key'        => 'sponsored_event',
  'meta_value'  => 'yes'
);
$the_query = new WP_Query( $args );
?>
        <?php if ($the_query->have_posts() ) : while ( $the_query->have_posts() ) : $the_query->the_post(); ?>

                        <div class="sponsored-image" style="background-image: url(<?php the_field( 'event_image' ); ?>);">

Sponsored Event

<?php the_title(); ?>

Date

<?php the_field( 'event_location' ); ?>

<?php the_field( 'event_time' ); ?>

<?php the_field( 'excerpt' ); ?>

        <?php endwhile; else: ?>
    <?php endif; ?>
<?php wp_reset_query(); ?>

Your If statement in the query seems to be Incorrect and i have added the Query Executed output over to that if statement.
Comment: Hi Naresh. I've made a number of edits to your prior posts to remove the quote device (`>`). This is only for quotes, i.e. something from another source, like a manual, an error message or a speech. It isn't a general highlighter, and is confusing if it is used as such. Thanks!
Comment: Thank you for this:
I have tried to use the new loop but it doesnt work.
Could you show me your whole loop?
Lee
Answer: You should use Meta Query here. Change your args array to:
// args
$args = array(
    'numberposts'   => 1,
    'post_type'     => 'event',
    'posts_per_page' => '1'
    'meta_key'      => 'sponsored_event',
    'meta_value'    => 'yes'
);

Answer: For those who are still stuck. I solved this with the following:
$args = array(
    'post_type' => 'event',
    'meta_query' => array(
        array(
            'key' => 'sponsored_event',
            'compare' => '!=',
            'value' => ''
        )
    ),
)

I think the ACF True/False value returns 1 and 0. Somehow, a query with value 1 returns nothing but with comparison != and no value attached to it, works.


2 Reverse DNS towards same IP. Is it bad?

Question: We are moving our mail server to Amazon Cloud
We currently have a reverse DNS for our mail server with current provider.
When moving to Amazon, we have to cancel that one and get Amazon to create a reverse DNS for our domain towards the amazon IP.
Now i would like to create 2 Reverse DNS records towards the same Amazon IP.
Reason beeing that one is getting faded out and a new will be intreduced over the next year.
Question.. Is it ok in this situation to ask Amazon to create Reverse DNS for 2 subdomains towards the same IP?
Thanks for your time
Regards
Morten
Answer: Yes. An IP address can have multiple PTRs (pointing to multiple DNS names). This is somewhat uncommon but by standard.
Do make sure that all these DNS names resolve back to the same IP address (by their A record), otherwise FcrDNS will fail.


JavaScript end of loop NaN for a numerical addition

Question: when I run this program I end up with NaN at the end; I'd appreciate some form of explanation, as I'm stumped! I have an odd feeling it has to do something with scope...
https://jsfiddle.net/Smuggles/evj46a23/
var array = []

var range = function(start, end) {
  for (var count = start; count <= end; count++) {
    array.push(start);
    start += 1;
  }
  console.log(array);
}

var sum = function() {
  var result = 0
  var arrayLength = array.length
  for (var count = 0; count <= arrayLength; count++) {
    result += array[count]
    console.log(result);
  }
}

console.log(sum(range(1, 10)));

Comment: You have to `return result;`.
Answer: 2 things:

You need to change the for loop in the sum function to be < arrayLength and not <= arrayLength. You are dealing with array lengths which start with a 0 index.
You need to return the result from the sum function

var array = [];

var range = function(start, end) {
  for (var count = start; count <= end; count++) {
    array.push(start);
    start += 1;
  }
};

var sum = function() {
  var result = 0;
  var arrayLength = array.length;
  for (var count = 0; count < arrayLength; count++) {
    result += array[count];
  }
  return result;
};

console.log(sum(range(1, 10)));

Given an array of [4,5,6], the indexes would be as follows:
0: 4
1: 5
2: 6

Therefore, when you use the length property of the array (3), you are referencing an index that does not exist, which returns undefined. It tries to do the math on the undefined, which causes a NaN. This is why you have to use < arrayLength.

The functional approach:
It would help to make those functions a bit more "pure". Instead of maintaining state outside of the functions (with var array = []), just return the values from the functions: See the following for example:

function range(start, end) {
  var arr = [];
  for (var i = start; i <= end; i++) {
    arr.push(i);
  }
  return arr;
}

function sumArray(array) {
  return array.reduce(function(a, b) {
    return a + b;
  });
}

console.log(sumArray(range(1, 10)));

Each function takes arguments, and simply returns the result. This way, you approach this a little more "functional".
Answer: Description in Comments of Code

var array = [];

var range = function(start, end) {
  //simplified the loop to remove unnecessary variables
  for (; start <= end; start++) {
    array.push(start);
  }

  return array;
}

var sum = function() {
  var result = 0;
  // move length to scope of the loop
  // change to < rather than <= due to zero index nature of arrays
  for (var count = 0, length = array.length; count < length; count++) {
    result += array[count];
  }

  // return the result from the function
  return result;
}

// gets an array from 1-10
var arr = range(1, 10);
// print the array to the console
console.log(arr);
// print the sum to the console
console.log(sum(arr));