In-app only notifications / interactive toasts

Question: Our Android app currently has a large number of dialog and alert boxes.  I'd like to switch these to toasts, but there's a problem - some of them require the user to choose whether to view more info or just dismiss the popup.  It doesn't look like there's a way to do this with toasts.
Is there any existing Android library that supports tappable toasts (i.e., you tap it and it triggers a function call to a listener in the app, sort of like a notification)?  If not, is there a recommended alternative for this "tap-here-to-do-something-otherwise-I'll-just-vanish-in-a-few-seconds" UI pattern, or should I just roll my own fragment class for it?
Comment: That creates a custom layout, not custom interaction.
Comment: Hi I'm not quite sure.. but did you try the custom-toast-view~? http://developer.android.com/guide/topics/ui/notifiers/toasts.html#CustomToastView
Comment: I have done the similar thing using a dialog. You can read Toast source code, and copy the WindowParams, which will get you what you want.
Answer: I have to do something similar to my app so I wrote, DropViewNotification, a boiler plate to make it happen by animating the so-called notification into the screen. It doesn't do automatic dismiss as this should only act as a tool.
It accept any kind of view to make it versatile as I need to put at least two or three obvious view into it (TextView, ProgressBar, ImageView). You can switch it's content on the fly if you want to. Animation can also be customized for both showing and dismissing of the notification and the main content.
In real-life you might want to consider adding controller class to handle the display of the content and auto dismissal, etc. Hope it's of some use to you.


Expressing exponential form to trigonometric form

Question:
Express $e^{-\frac{1}{2}i\theta} - e^{\frac{1}{2}i\theta}$ in trigonometric form, and show that $(1-e^{i\theta})^2 = -4e^{i\theta}\sin^2\left(\frac{1}{2}\theta\right)$

By inspection, I noticed that the former expression is identical to $-2i\sin\left(\frac{1}{2}\theta\right)$. I cannot for the life of me figure out the second part. My first attempt involved expanding the L.H.S to achieve
$$(1-e^{i\theta})^2 = e^{2i\theta} - 2e^{i\theta} + 1$$
and attempted to multiply the R.H.S of the expanded form by $e^{-\frac{1}{2}\theta}$ to try and use the identity that was achieved in the former part of the question, but could not immediately notice anything of use.
Any help or hints would be greatly appreciated.
Comment: Hint: Compare the square of what you got from the first expression to the RHS you are aiming for. What factor is missing?
Answer: Just to clarify, using the fact that $$e^{ix} = \cos(x) + i\sin(x)$$ and expanding everything out gives us the first identity:
\begin{align*}
e^{-\frac{1}{2}i\theta} - e^{\frac{1}{2}i\theta} &= \cos\left(-\frac{\theta}{2}\right) + i\sin\left(-\frac{\theta}{2}\right) - \cos\left(\frac{\theta}{2}\right) - i\sin\left(\frac{\theta}{2}\right) = -2i\sin\left(\frac{\theta}{2}\right).
\end{align*}
Next, notice that $$-4\sin^{2}\left(-\frac{\theta}{2}\right) = \left(e^{-\frac{1}{2}i\theta} - e^{\frac{1}{2}i\theta}\right)^{2} = e^{i\theta} - 2 + e^{-i\theta}.$$
Can you take it from there?


Choosing Cycles for Jordan Canonical Form

Question: Let $T: \mathbb{R}^3 \rightarrow \mathbb{R}^3$. Suppose the characteristic polynomial of $T$ is $f(t) = (t-\lambda)^3$ for the eigenvalue $\lambda$. Suppose also that $\dim E_\lambda = 2$, and that $\beta = \{v_1,v_2\}$ is a basis for this eigenspace.
If I wanted to create the Jordan Canonical Form Matrix for $T$, I would require a basis $\alpha = \beta \cup \text{span}(v_3)$ where $v_3 \in K_\lambda$, the generalized Eigenspace of $\lambda$.
Let $a,b$ be vectors such that
$$(T-\lambda I)a = v_1 \qquad (T-\lambda I)b = v_2$$
Would both $a$ and $b$ be appropriate choices for $v_3$?
Answer: Either is an appropriate choice assuming it exists. But at most one of $a$ and $b$ can exist, and it's possible that neither exists.
You have to choose $v_1$ and $v_2$ more carefully. You should really find $a$ or $b$ first, i.e., find a solution to the set of equations
$$(T-\lambda I)^2 a = 0 \\ (T-\lambda I) a \ne 0$$
and then set $v_1 = (T-\lambda I)a$. Then find another $\lambda$-eigenvector $v_2$ which is independent from $v_1$.
Also, if the characteristic polynomial is $(t-\lambda)^3$, then the generalized $\lambda$-eigenspace is all of $\mathbb{R}^3$. So you need a better $v_3$ than you claim you do.
At most one can exist:
If both existed, then $\{v_1,v_2,a,b\}$ would be linearly independent: if
$$c_1v_1 + c_2a + d_1v_2 + d_2b = 0,$$
with $c_1,c_2,d_1,d_2 \in \mathbb{R}$, then apply $(T-\lambda I)$ to both sides, so that
$$c_2v_1 + d_2v_2 = 0,$$
which implies $c_2=d_2=0$ since $\{v_1,v_2\}$ is a linearly independent set, and then
$$c_1v_1 + d_1v_2 = 0,$$
and so $c_1=d_1=0$ for the same reason. But $\dim(\mathbb{R}^3) < 4$.
It's possible that neither exists:
Consider
$$T=\begin{pmatrix} 1 & 0 & 0 \\ 0 & 1 & 1 \\ 0 & 0 & 1 \end{pmatrix},$$
which has characteristic polynomial $(t-1)^3$. Taking
$$v_1 = \begin{pmatrix} 1 \\ 1 \\ 0 \end{pmatrix} \text{ and }\; v_2= \begin{pmatrix} 1 \\ -1 \\ 0 \end{pmatrix},$$
the equations $(T-I)a = v_1$ and $(T-I)b = v_2$ have no solutions, but $\{v_1,v_2\}$ is a basis for the $1$-eigenspace.
Comment: In your example where neither exists, it is guaranteed that there will exist another set of vectors, say $w_1,w_2$ that would form a basis such that one of $a,b$ will exist?
Comment: Yes, because the eigenvalues are real (not complex) and it can be proven that any such matrix can be put into Jordan normal form over $\mathbb{R}$. Take $w_1 = (1,0,0)^T$ and $w_2 = (0,1,0)^T$. Then $b = (0,0,1)^T$ is a solution to $(T-I)b = w_2$. (Hint: I put $T$ in JNF to begin with.)


Displaying Only the first x words of a string in rails

Question: <%= message.content %>

I can display a message like this, but in some situations I would like to display only the first 5 words of the string and then show an ellipsis (...)
Comment: what's a "word"? is `mother-in-law` one word or three? How about `co-ordinate`?
Comment: possible duplicate: http://stackoverflow.com/questions/6235762/truncate-string-to-the-first-n-words
Answer: In rails 4.2 you can use truncate_words.
'Once upon a time in a world far far away'.truncate_words(4)
=> "Once upon a time..."

Answer: you can use truncate to limit length of string
truncate("Once upon a time in a world far far away", :length => 17, :separator => ' ')
# => "Once upon a..."

with given space separator it won't cut your words.
If you want exactly 5 words you can do something like this
class String
  def words_limit(limit)
    string_arr = self.split(' ')
    string_arr.count > limit ? "#{string_arr[0..(limit-1)].join(' ')}..." : self
  end
end
text = "aa bb cc dd ee ff"
p text.words_limit(3)
# => aa bb cc...

Answer: Try the following:
'this is a line of some words'.split[0..3].join(' ')
=> "this is a line"

Answer:    # Message helper
   def content_excerpt(c)
     return unlessc
     c.split(" ")[0..4].join + "..."
   end

   # View
   <%= message.content_excerpt %>

But the common way is truncate method
   # Message helper
   def content_excerpt(c)
     return unless c
     truncate(c, :length => 20)
   end


Chamar interface gráfica no java

Question: Minha duvida é simples, acredito eu. Preciso chamar essa interface CadastroGUI d = new CadastroGUI(); que já tenho pronta, mas quero que os campos já aparecam preenchidos, afinal, é um comando de consulta por CPF onde quero como retorno as informações do cliente.
O Código
public void actionPerformed(ActionEvent arg0) {

                String cpf = txtCPF.getText();

                DaoCadastro c = new DaoCadastro();
                ArrayList <Cadastro> co = new ArrayList <Cadastro>();

                CadastroGUI d = new CadastroGUI();
                d.setVisible(true);

                co = c.listaAlterar(cpf);
                int a=0;

                for (a=0; a<co.size();a++)

                {
                    txtNome.setText (co.get(a).Nome);
                    txtCPF.setText (co.get(a).CPF);
                    txtEndereco.setText(co.get(a).Endereco);
                    txtSexo.setText(co.get(a).Sexo);
                    txtDataNasc.setText (co.get(a).Datanasc);

            }

Comment: cuidado ao usar a palavra interface dessa forma, em java ela tem outro significado. Como vc envia as informações para o CadastroGUI? ela é um JFrame?
Comment: Você chama CadastroGui de outra tela e quer que ela venha preenchida com as informações da tela anterior?
Comment: Eu tenho o modelo CadastroGui pronto, então quero fazer uma consulta através do CPF em outra interface, chamar a CadastroGui quando preencher o CPF e apertar um jbutton `procurar`  e receber as informações já `setadas` na CadastroGui que vai ser chamada
Comment: Quando eu coloco esse  **CadastroGUI d = new CadastroGUI();
                d.setVisible(true);** ela ta vindo, mas não esta preenchida. Quero que venha preenchida com as informações que estão ligadas ao CPF que vou procurar.
Comment: Essas informações veem da tela que chama CadastroGUI ou você já traz direto do banco?
Comment: O que o @Skywalker disse é verdade. Sugiro que edite o titulo da pergunta para "interface grafica" já que estamos falando de GUI's.
Comment: Cada vez vou aprendendo mais com vocês, porque sou iniciante em programação kk. Eu trago do banco @DiegoFelipe.
Comment: É JFrame sim @Skywalker, as informações preenchidas em JTextFields.
Comment: envie as informações que você deseja exibir no CadastroGUI por um construtor. Faça um construtor no CadastroGUI.
Answer: Crie um outro construtor em CadastroGUI com parâmetro para o seu arraylist:
    CadastroGUI(ArrayList<Cadastro> co)
    {
        CadastroGUI();
        //aqui você faz o preenchimento dos campos.
        int a=0;
        for (a=0; a < co.size(); a++)
        {
            txtNome.setText (co.get(a).Nome);
            txtCPF.setText (co.get(a).CPF);
            txtEndereco.setText(co.get(a).Endereco);
            txtSexo.setText(co.get(a).Sexo);
            txtDataNasc.setText (co.get(a).Datanasc);
        }
    }

E no seu evento você simplesmente chama ele passando o arraylist por parâmetro:
    public void actionPerformed(ActionEvent arg0)
    {
        String cpf = txtCPF.getText();
        DaoCadastro c = new DaoCadastro();
        ArrayList <Cadastro> co = new ArrayList <Cadastro>();
        co = c.listaAlterar(cpf);
        CadastroGUI d = new CadastroGUI(co);
        d.setVisible(true);
    }

Chamar interface gráfica no java


Cisco ASA - Restrict IP for WebVPN access

Question: I've got a Cisco ASA5510 with Firmware Version 8.0(5).
I'd like to restrict the source IPs that are allowed to access the Router through WebVPN (port 443). Here is the relevant part of the config.
access-list outside_access_in extended permit ip host 18.104.22.168 any
access-list outside_access_in extended deny ip any any
[...]
access-group outside_access_in in interface outside
[...]
webvpn
 enable outside
 svc image disk0:/anyconnect-win-2.3.0254-k9.pkg 1
 svc enable
 tunnel-group-list enable

Still, my webvpn port is available from all over the world. How can I fix this?
Answer: first define the extended ACL that permits specific source-adresses for VPN/WEBVPN, I have used the name internet
ciscoasa(config)# access-list internet extended permit tcp host 126.96.36.199 any
ciscoasa(config)# access-list internet extended deny ip any any

then bind the extended ACL with the access-group command and the option control-plane together
ciscoasa(config)# access-group internet in interface outside control-plane

this should work with your version 8.x (ASA command reference lists this option in 8.x)
Comment: This is the correct answer. It works, I have personally verified it. Note that if you apply this restriction, it will also apply to IPSec coming in, so you might want to permit udp/500, udp/4500, eh and esp.
Answer: You can apply a management access rule to the control plan of the asa and effectively permit/deny specific source addresses from accessing the webvpn address. Please reference the following:
http://www.cisco.com/c/en/us/td/docs/security/asa/asa83/asdm63/configuration_guide/config/access_management.html
Answer: In the meantime I've found out that there is no exact solution for this problem :(
According to Cisco Support Forums, there is no way to block webvpn using access lists.
Possible solutions to the problem are:

Place another router (Netgear, Cisco 800, ...) with firewall in front of the ASA
Try (legacy) IPsec VPN client
In my case, a Site-to-Site VPN would also be possible
Comment: This answer is factually incorrect, tekcert.com and @Roli's answers are correct.


CSS Grid Layout - Como centralizar horizontalmente todos os elementos em todas as Grid Lines de uma Sub-Grid?

Question: Estou trabalhando em um projeto de faculdade e estamos utilizando Grid Layout para fazer o design de um e-commerce voltado para animais. Surgiu uma duvida durante o processo de criação em relação à centralização do conteúdo das grids em diferentes resoluções e tipos de dispositivos.
O código CSS simplificado é:
#produtos-grid {
    grid-area: grid-produtos;
    display: grid;
    grid-template-areas:    "produtos-destaque-titulo"
                            "produtos-destaque"
    grid-row-gap: 10px;
}

#produtos-destaque-titulo-grid {
    grid-area: produtos-destaque-titulo;
}

#produtos-destaque-grid {
    grid-area: produtos-destaque;
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(225px, 350px));
    text-align: center;
    justify-content: center;
    margin: 0 0 20px 0;
    grid-row-gap: 1em;
}

Ainda não estamos adicionando os itens diretamente do banco de dados com o php porque o projeto está bem no começo nesse ponto e não tivemos tempo de modelar tudo, por isso a info foi colocada diretamente no HTML para testar o posicionamento dos elementos na view. Novamente, o código resumido é:

Mais Vendidos

            <a href="<?=base_url()?>/index.php/produto/visualizar/17">
              <img class="card-img-top" src="<?=base_url()?>/assets/imagens/produtos/cama-suiça-bege-bichinho-chic.jpg" alt="Imagem Produto">

Cama Suiça Bege Bichinho Chic

a partir de: R$ 51,90

            <a href="<?=base_url()?>index.php/produto/visualizar/1">
              <img class="card-img-top" src="<?=base_url()?>/assets/imagens/produtos/racao-whiskas-gatos-castrados-carne.jpg" alt="Imagem Produto">

Ração Whiskas Gatos Castrados Carne

a partir de: R$ 11,99

            <a href="<?=base_url()?>index.php/produto/visualizar/5">
              <img class="card-img-top" src="<?=base_url()?>/assets/imagens/produtos/brinquedo-cenoura-nylon-buddy-toys.jpg" alt="Imagem Produto">

Brinquedo Cenoura Nylon Buddy Toys

a partir de: R$ 37,90

O código gera o seguinte resultado quando a propriedade width do display está igual ou acima de 1200px:

Quando a resolução está abaixo de 1200px, uma das imagens é jogada diretamente para a posição abaixo das outras (2º Grid Line), o que é exatamente o que queremos. O problema é que a imagem deveria estar Centralizada no meio das outras duas, e não à esquerda.

Qual solução pode ser utilizada para centralizar todos os items da grid horizontalmente, independente da Grid Line em que se encontram?
Comment: Jovem se vc colocar o HTML ajuda... Só com CSS complica te dar uma resposta precisa... Principalmente pe vc está usando "grid-template-areas" como vamos saber a estrutura do html, fica complicado
Comment: Atualizado, por algum motivo esqueci de colocar o HTML e só adicionei o CSS. O resto do HTML é estruturado similar ao acima, existe uma grid para produtos de cães, gatos, medicamentos e outros.
Comment: Já tentou dar um "margin: 0 auto;" no produto?
Comment: @DiegoSantos Foi a primeira solução que tentei, antes de saber que existia o Justify-Content, e lembro que não funcionou. Sinceramente, não me lembro o porquê exatamente de não ter funcionado, só lembro que deu muito errado
Comment: Qual o css do "card bordered"?
Comment: É a classe Card do Bootstrap 4 com uma borda simples ao redor. Uso o bootstrap 4 só no Banner e nas cards, tô até pensando em retirar e fazer na mão depois quando tiver um tempo livre pra eliminar a dependência
Comment: Cara se vc está usando Bootstrap 4 vc deveria usar o FlexBox que é nativo do BS4 e resolve isso fácil
Comment: @hugocsl como disse acima, estou exatamente no processo de retirar o bootstrap 4, e não planejo utilizar ele em projetos futuros, por isso quero entender como fazer isso sem utilizar o flexbox do bootstrap.
Comment: Apenas com Grid e CSS vc não vai conseguir. Talvez com algum JavaScript resolva, mas só com Grid acho que não dá, por isso sugeri o FlexBox, que mesmo sendo usado pelo BS4 também é amplamente usado na web sem demais problemas.
Comment: Entendo, imaginava que existia uma solução para o problema utilizando somente o Grid. Obrigado!
Answer: CSS grid sempre vai quebrar a row e colocar os itens em ordem de coluna.
Neste caso recomendo o uso de flexbox que faz exatamente o que quer com a propriedade justify-content: center


Where to start with statistics for an experienced developer

Question: During the first half of 2015 I did the coursera course of Machine Learning (by Andrew Ng, GREAT course). And learned the basics of machine learning (linear regression, logistic regression, SVM, Neuronal Networks...)
Also I have been a developer for 10 years, so learning a new programming language would not be a problem.
Lately, I have started learning R in order to implement machine learning algorithms.
However I have realized that if I want to keep learning I will need a more formal knowledge of statistics, currently I have a non-formal knowledge of it, but so limited that, for example, I could not properly determine which of several linear models would be better (normally I tend to use R-square for it, but apparently that is not a very good idea).
So to me it seems pretty obvious that I need to learn the basics of statistics (I studied that in uni but forgot most of it), where should I learn, please note that I don't really need a fully comprehensive course, just something that within a month allows me to know enough so I can get eager and learn more :).
So far I have read about "Statistics without tears", any other suggestion?
Comment: I don't see that this should be closed. I do see an argument for making it CW, though.
Comment: I would like to add one cautionary word. I feel sure you understand this already to some degree, but I just want to say it. I am an MD/PhD student. With my MD degree, I plan to practice internal medicine. For my PhD, I am studying biostatistics. I want you to know that you can no more get a mastery of statistics in 1 month than you can a mastery of medicine in one month.

I am by no means trying to discourage you from learning statistics. Quite the opposite, I hope you understand it magnificently. But just understand it is no less involved than wanting to be a developer, for instance.
Comment: For Statistics: Casella, G. and R. L. Berger (2002): Statistical Inference, Duxbury. For Econometrics: Hayashi, F. (2000): Econometrics, Princeton University Press. For another point of view: http://stats.stackexchange.com/questions/91863/what-to-learn-after-casella-berger
Comment: From my point of view, knowledge will be biased if you start learning statistics without the acquaintance of probability theories before.
Comment: Two years have passed, I'm curious to know where you're at on your road to ML?
Comment: I think you made a mistake, two years have not passed :)
Comment: I added the `references` tag. You might like to scan through the first page of [hits](http://stats.stackexchange.com/questions/tagged/references) on that topic.
Answer: I would suggest you a basic road-map about how to go about it:

You can brush up basic math and stats at Khan Academy, and/or take the Intro to Statistics course by Udacity.
Then, you can take these two nice courses of Udacity. Descriptive Statistics and Inferential Statistics
Then, you can dive into some Bayesian stats. And one of the best-related resource on the web which I have found is the Think Bayes free e-book
Then, dive into the basics of Machine Learning. Coursera's Andrew Ng's course is the perfect start.  And this resource: Machine Learning for developers is also very useful for skimming through the concepts quickly.
Then, you are on your own. You have enough resources and blogs on the internet for building up on these concepts.

Bonus:
A wonderful site for such road maps is Metacademy, which I personally would vouch as one of the best Data Science resources on the web.
Gitxiv is another beautiful site, which connects the Arxiv research papers on Data Science with the relevant open source implementations/libraries.
Comment: @Aksakal I have noticed it.  But, included it as a part of the road map.  Wouldn't really make a difference, so I thought including it would help others who are reading this post.
Comment: OP has already taken Ng's course, that's what prompted him to ask the question in the first place.
Answer: Have you checked out either Think Stats or Think Bayes--they are both (free) stats books geared towards programmers and with plenty of Python code.
Also, if you're interested in learning R then CRAN has a lot of (free) pdfs that you might want to check out, such as Introduction to Probability and Statistics Using R. There's also a Coursera course that uses R which a lot of people really love (they use this textbook, which you might want to check out as well, and have labs on DataCamp, I believe).
Also, if you want to brush up on a few Stats topics you can always watch a couple videos on Khan Academy.
Comment: I like Think Stats and Think Bayes but they deliberately avoid a lot of the formal statistical theory in favour of getting things done through code. Great for getting an intuitive grasp on the subject, but not as good if your goal is to understand the underlying theory.
Comment: @Marius: I know what you mean. I was thinking, however, that because he's already a programmer and also because he seemed to want "something small, simple and quick" that it might be more of what he's looking for.
Answer: If you were ever, even in distant past, able to solve problems in this list, then you should attempt to study applied stats "properly". I'll give you a simple two step algorithm.
First, get up to speed with probability theory. There are many great books. My favorite is the classic book by Feller. It's called "Introduction" but don't be fooled by the title, it's as deep as you wish to go, yet very well written and simple if you just want to skim the surface.
The second step is statistics. Again, there's a ton of great books. I'll give you one that I used, a decent intro text by Gujarati "Basic Econometrics", Fourth Edition. Econometrics is statistics applied to economics. For a reference, a guy who everyone thinks said that data scientist is going to be a sexiest job in next 10 years is Hal Varian, a Berkeley economist. A lot of machine learning stuff is based on basic statistics, regressions etc. All that is covered in this book, and you don't need to read it all, it's written in a way that you can pick chapters in your own order.
You'll be surprised to see how many gaps left open after Ng's class are filling out quickly while reading these texts.
As a practitioner, you don't need too much theory after these two steps. You can keep learning ML techniques specifically reading the books in this field. It's important not to get too deep in the beginning into probability and stats. Get your code going for ML first, and fill in the gaps as you go.
Answer: Everyone is recommending Casella & Berger, which is almost universally used in graduate statistics programs. It's not a bad reference book, but I'm not sure I'd do more than scan the first 4-5 chapters. I don't think you need the theory of how to construct a Neyman-Pearson type test before delving into "statistics" i.e. data analysis.
Instead, I would focus on learning methods. My graduate program used Applied Linear Statistical Methods for the frequentist tests, and it's a pretty decent comprehensive reference, but might not be the most approachable book from a self-teaching standpoint. A course or two from MIT or coursera might be a better way to start in on that, because you'll get a broader overview with more examples than you might from reading a book.
For Bayes, the book I've seen used most often is Doing Bayesian Data Analysis, which comes with puppy pictures (clearly, this makes the book superior to other Bayesian introductory textbooks). I've never used the book myself, but I've paged through it and it seems pretty decent - much better than Gelman's book, which I found somewhat incomprehensible AFTER two classes in Bayesian statistics - the explanations are terrible.
Comment: The first 5 chapters of C&B are not actually statistics at all, more like background ... The concept of a statistic is addressed in the beginning of chapter 6!

More to the point, learning methods will probably not help this specific person. it would help him apply statistics, not understand it, which is what he needs. if he has advanced mathematical training, he can probably skip it to some degree, but his answer suggests he is currently unable to understand the underpinnings of ML ... which strongly suggests his math is limiting (to me, at least). C&B might not be a bad place to start.
Comment: They may not be statistics, but the background on probability distributions is essential in order to do any sort of modeling - you need to know what a bernoulli distribution is and what its properties are before you can understand logistic regression, for instance.

I still reference C&B occasionally, but I don't think I've ever used anything beyond chapter 6 outside of the class I took that used that book.
Comment: i quite agree with what you said, but it relates to the digression instead of the major point - which is my fault for adding the digression in the first place.

at any rate, the main point is that as several others have suggested, what OP actually needs to do is get a better understanding of theoretical math and statistics.

no where in the post does it indicate he needs any help with applying more statistical tests. he can do that. he wishes to understand them more deeply. for this, C&B is better than learning more hands on application oriented preparation.
Answer: This is not intended to be a complete answer, it's just a suggestion.
If you want to learn more about statistics (the foundation), you could read:
Casella, G. and R. L. Berger (2002): Statistical Inference, Duxbury
This is a pretty standard book for statisticians and it has a lot of interesting results. You don't need to go through all the proofs of the theorems, but you might want to do some exercises in order to feel more secure with the results.
If you want to learn more about econometrics (models for data), you could take a look at:
Hayashi, F. (2000): Econometrics, Princeton University Press
Someone else actually asked something similar to what you asked and got a nice answer: What to do after "Casella & Berger".
Furthermore, if you really intend on reading these books, this syllabus of an econometrics course can give you a quite good direction and pace on what to read (CB & Hayashi) and when to read.
Comment: Casella and Berger will give you a chunk of the *theory* of statistics, but you'll learn very little about data analysis.
Comment: @JuanAntonioGomezMoriano how small were you after? I was always a fan of [How to lie with statistics](http://www.amazon.com/How-Lie-Statistics-Darrell-Huff/dp/0393310728) as a starting point.
Comment: He did say that he needed a more "formal" knowledge and basic knowledge about statistics.
Comment: (-1) Those sound like perfect choices for someone who prefers a mathematical or theoretical approach to statistics, pretty much the opposite of what the OP requested.
Comment: Thanks for the suggestion, however the first book you mention is around 660 pages... I have read bigger books, but is there something small, simple and quick so I can get a basic grasp of it?
Answer: I'd suggest a new book that came out since the original question: Statistical Rethinking: A Bayesian Course with Examples in R and Stan by Richard McElreath, CRC Press.
It's very well written and uses a Bayesian approach. It's very interactive, and you'll want to work the problems or you may get halfway through and begin to get lost.
It starts very basic and ends up with multi-level models, and it's aimed at fairly advanced scientists who have some statistical knowledge but don't feel comfortable overall with statistics as it was taught to them. So I can't exactly say it's a beginner's book, but it does start very simply and he has a wonderful arc and style.
The "Stan" part of the title is a general-purpose Bayesian sampling tool. Essentially, it's a programming language that compiles automatically to C++ and then gets compiled to an executable. (Bayesian inference is general, unlike alternatives, so you can have a generalized tool.)
Answer: Figured I'd throw this answer in for posterity, even if it's likely too late to be useful to you. Larry Wasserman's All Of Statistics was conceived as a course for people with a background in machine learning, other comp sci disciplines, or math  who didn't have any formal statistics training -- i.e., people in pretty much exactly your current situation. Having a similar lack of formal stats, a few friends and I formed a self-study group to go through it in grad school. I think I really benefited from that experience.
The extra topics Wasserman throws in beyond the typical "probability and statistical inference" course material, like graphical models and bootstrapping, are particularly relevant to someone working in machine learning. I should say that the book can be pretty terse compared to something like Casella & Berger, so if you want more detail or motivation for certain parts (especially proofs) you may have to supplement it with other reading material. That said, I also found the book to be clearly-written with a good number of practice problems, and it's an excellent quick reference.
One month is not a lot of time. If you set a very aggressive pace, though, I think you can certainly get a lot out of this text in one semester: we did our self-study group over the summer, for instance. That's especially true if you're mostly interested in linear modeling, which you'll hit by Ch. 13-14.


$f$ does not have extrema at the Lagrange multiplier value

Question: I have the function $2x^2+y$ and one constraint $x-y^2=1$ and want to find maximum value by lagrange multiplier. Intuitively, I see the point $(2,1)$ satisfies $c$ and have value of  $f(2,1)=9$.
Using Lagrange function $f(z)-\lambda c(z)$, I get $\lambda^3-4\lambda^2-1$ thus $\lambda=4.06$. However, when plug this into the derivatives of $x$ and $y$ I got different values in particular $x=\frac{4.06}{4}=1.015$ which is much lower than $2$. Am I missing something here?
Comment: Actually, $\lambda\approx-4.06$.
Comment: @MichaelHoppe Thanks. plugging $\lambda^3-4\lambda^2-1$ into the calc here http://www.1728.org/cubic.htm shows me 4.06
Answer: Nobody cares about the value of $\lambda$. Eliminating $\lambda$ yields $1+8xy=0$ and $x-y^2=1$, so solve $8y^3+8y+1=0$.  Good luck.
Comment: Sorry I didn't get what you mean by eliminating $\lambda$. I have $x=\frac{\lambda}{4}$ and $y=\frac{-1}{2\lambda}$. I need to find the value of $\lambda$ so I can substitute it in $x$ and $y$. I tried subtituting $\lambda=4x$ and $\lambda=\frac{-1}{2y}$ in $\lambda^3-4\lambda^2-1=0$.
Comment: Who cares about $\lambda$?  We want to find $x$ and $y$. So our goal is to get rid of $\lambda$, in our case $\lambda=-4x$ (note: $x=-\lambda/4$, not $x=\lambda/4$ as you stated.). Just substitute $\lambda=-4x$ in $1-2\lambda y=0$ to achieve $1+8xy=0$.  From the constrain we know $x=1+y^2$, hence solve $8y^3+8y+1=0$.
Comment: Thanks. I am multiplying the constraint by $-\lambda$ thats why $x=\lambda/4$. One final question, the resulted points are $(1.015,-.123)$ with $f(1.015,-.123)=1.9$. Clearly, these are not maximum points, is this mean they are minimum?
Answer: Note that your function is unbounded. Your constraint gives $x = 1+y^2$, and plugging this into the objective, you get $2\,(1+y^2)^2 + y$. Now, it is easy to see, that this can attain arbitrary large values. This means that your problem has no global maximum, but it may have a local one.
Further, since the gradient of your constraint is $(1, -2\,y)$, the LICQ is satisfied at every feasible point. This means that every local extremum (may it be a maximum or a minimum) can be found by the Lagrange multiplier method.
As you already found, there is only one solution to Lagrange's method. Moreover, it is easy to see that this is a local minimum (consider, e.g., the second derivative of the reduced objective $2\,(1+y^2)^2+y$ which is positive for $y = -0.123$.
Putting everything together, we find that your problem has no local maximum (and no global one).


Equivalence of two definitions of SUBSET-SUM

Question: Consider one version of the subset sum problem: given a target $W$ and positive integers $a_1, a_2,..,a_n$, decide whether there exists a nonempty subset $S \subset [n]$ so that $\sum_{i \in S} a_{i}=W$. Let us call this version $A$. The other version is: given integers $a_1, a_2,...,a_n$, decide whether there exists a nonempty subset $S \subset [n]$ so that $\sum_{i \in S} a_i=0$. Let us call this version $B$.
It is relatively easy to reduce version $A$ to version $B$. If $W = 0$, the reduction is immediate. Otherwise add $-W$ into the set of numbers and call version $B$.

Is there a "natural" way to reduce version $B$ to version $A$?

One approach is arguing that version $A$ is NP-complete and version $B$ is in NP, so the result follows from the definition of NP-Completeness, but this doesn't seem "natural" to me and seems to use more machinery (e.g., the Cook-Levin theorem) than needed. The problems should be similar enough that there is a natural correspondence between them.
Answer: Here is a polynomial-time reduction from version B to $n$ instances of version $A$.
Let $b_1,\dots,b_n$ be the integers in an instance of version B.

Choose an integer $M$ so that $|b_i| < M$ for all $1\le i\le n$.
Then choose an integer $B>(n+1)M$; note that this inequality implies that if $1\le t\le n$ then $(t+1)(B-M) > tB$ and $(t-1)(B+M) < tB$.

Now define $a_i=b_i+B$ for every $1\le i\le n$; note that $B-M \le a_i \le B+M$ for all $1\le i\le n$.
Use version A to determine whether there are solutions $S$ to $\sum_{i\in S} a_i=tB$, for every $1\le t\le n$.
Suppose we find a solution to a particular $\sum_{i\in S} a_i = tB$.

If $S$ had at least $t+1$ elements, then $\sum_{i\in S} a_i \ge (t+1)(B-M) > tB$, a contradiction.
Similarly if $S$ had at most $t-1$ elements, then $\sum_{i\in S} a_i \ge (t-1)(B+M) < tB$, a contradiction.
It follows that $S$ has exactly $t$ elements, whence $\sum_{i\in S} b_i = \sum_{i\in S} (a_i-B) = \sum_{i\in S} a_i - tB = 0$ is a solution to the original instance of version B.

And of coures, any solution $\sum_{i\in S} b_i = 0$ with $\#S=t$ immediately gives rise to the solution $\sum_{i\in S} a_i = tB$, so we are guaranteed to detect any solution of the version B instance in this way.
Comment: I don't think this is quite a polynomial time reduction. You can't compute the set of all sums of subsets in polynomial time. I should have specific we're looking for a polynomial time reduction; however this is usually implicit in complexity theory.
Comment: True enough. Are you looking for a reduction whose runtime is a polynomial in $n$, or in $\log n$? (in addition to being polynomial in the $\log a_j$)
Comment: Polynomial in $n$ and the $\log a_j$ is fine.


Computing the contour integral of a complex function

Question:
For $n \in \mathbb{N}$, evaluate $\displaystyle{\int_{|z|=1} \dfrac{e^{z}}{z^n}dz}$.

My intuition tells me that I can use the Cauchy Integral Formula since the function, $f(z)$ has $n$ singular points, being $z=0$ which lie entirely in the unit circle.
My solution is as follows:
$${\int_{|z|=1} \dfrac{e^{z}}{z^n}dz}=\int_{|z|=1}\dfrac{e^{z}}{(z_{1}-0)^n}+...+\int_{|z|=1}\dfrac{e^{z}}{(z_{n}-0)^n}  =n[2\pi i.f(0)]=2\pi nei,$$ where $f(0)= \dfrac{e^{0}}{(z-0)^0} = 1.$
Can someone tell me if i am on the right track and how can i correct my solution if i am wrong. Many thanks!
Answer: You are not using the  Cauchy's integral formula Theorem in the correct way.  Recall the statement and use it with $a=0$ and $f(z)=e^z$: for any $n \in \mathbb{N}^+$,
$$\int_{|z|=1} \dfrac{f(z)}{z^n}dz=2\pi i \cdot\frac{ f^{(n-1)}(0)}{(n-1)!}.$$
For $n=0$ the integral is zero by Cauchy's integral theorem.
Comment: Hi Robert, thanks for your hint. Could you kindly guide me further with some starting starting steps as i am rather new to this module on complex analysis.
Comment: You are not using Cauchy Integral Formula correctly. Recall the statement and try again. Note that the derivative of $e^z$ is again $e^z$.
Comment: Thanks again for your guidance. I've got it.


Cartan matrices in different books

Question: Cartan matrices in the books of (1) Humphreys (page 59) and of (2) Carter (page 82 -- 83) are different. Moreover, they are not transpose of each other. Which one is correct? Thank you very much.
Edit: Now I know the differences. In (1), $c_{ij}=2(a_i, a_j)/(a_j, a_j)$. But in (2), $c_{ij} = 2(a_i, a_j)/(a_i, a_i)$. Which one is standard? In particular, which Cartan matrices are used in the paper [V. G. Drinfeld, A new realization of Yangians and quantized affine algebras, Soviet Math. Dokl. 36 (1988), 212-216]? Thank you very much.
Comment: Well, $(a_i,a_j)=(a_j,a_i)$. This implies that the definitions in Humpreys and Carter's book are indeed transposed to each other. Isn't it? I guess you have in mind that the Cartan numbers $\langle a_i, a_j\rangle$ and $\langle a_i, a_j\rangle$ are not always the same and forgot that $(,)$ is a inner product.
Comment: Glad that you figured it out! If the information content is the same, why would we need to elevate one of the two alternatives to a status of a standard? In some cases that may be advisable or even necessary, but this is a relatively esoteric case, and simply calling it a *Cartan matrix* conveys the message clearly those who know. The only situation that I can think of, where it would matter, would be that if you are writing/using a piece of software, and are expecting a different  standard  convention than the user/author. Well, software should come with a document :-)
Answer: Here is a similar question with a great answer by Humphreys!

Cartan matrices in different books


Dúvida sobre atribuição de classes e ids

Question: Existe alguma boa prática que orienta a ordem que devo definir o id e a class de um elemento HTML? Sei que tanto faz a ordem para o navegador renderizar, mas existe algum guia de estilo de código para isso?
Comment: Possível duplicata de [Qual a prioridade do HTML? "id" ou "class"?](https://pt.stackoverflow.com/questions/39875/qual-a-prioridade-do-html-id-ou-class)
Comment: @Sorack Acho que não seja duplicata. Esta refere-se à ordem para se colocar os atributos no elementos, enquanto a que citou refere-se à ordem de prioridade que são aplicados os estilos. Está fortemente relacionada, mas acho que não chega a ser duplicata.
Comment: Isso deve responder, se não, acho que tem outras no site que responde, várias vezes o assunto foi tratado: https://pt.stackoverflow.com/q/39875/101. Veja também https://pt.stackoverflow.com/q/117922/101
Comment: Obrigado, @Maniero.
Answer: Segundo a documentação que está nesse Guia de Boas Práticas da Mozilla, o ID deve vir depois da class:

As classes são ótimos componentes reutilizáveis, então elas vêm em primeiro lugar. Os IDs são mais específicos e devem ser usados com moderação (por exemplo, para bookmarks in-page), então eles vêm em segundo lugar.

    Example link

Fonte: https://codeguide.co/#css-shorthand
Então, basicamente a Mozilla diz que como o ID é mais específico ele deve vir por último. Mas isso não é regra, é uma recomendação deles.
Já o Bootstrap por exemplo, que é um Framewrok gigante e super popular parece não ter um padão, algo estranho ao meu ver... Para eles o ID vem primeiro em alguns componentes, e depois em outros...
Por exemplo, repare que nas tags iniciais do Carroussel o ID vem primeiro, enquanto que na tag do Modal a Classe é que vem primeiro, e os dois são componentes do mesmo Framework.
Tag inicial do Carrossel https://getbootstrap.com.br/docs/4.1/components/carousel/:

Tag inicial do Modal https://getbootstrap.com.br/docs/4.1/components/modal/:

Eu não considero isso uma boa prática, o ideal seria adotar alguma regra para facilitar a manutenção e leitura do código.

Recomendação da Google: Não há recomendação :)
No Guia de Estilos da Google esse assunto de ordem dos atributos na tag nem é mencionado... https://google.github.io/styleguide/htmlcssguide.html
Comment: Obrigado, @hugocsl. Vou passar a colocar minhas classes primeiro, também acho que facilita a leitura do código ter um padrão. Estranho o Bootstrap não ter...
Comment: @ThiagoKrempser estranho mesmo o BS não seguir um padrão... eu fui lá justamente para ver o padrão que eles seguiam haha, mas logo percebi que parece não ter padrão... Eu meu ver em um FW tão grade deveria haver uma regra pra esse tipo de coisa...
Answer: No cenário do CSS, eu te recomendo fazer uso da class quando possível, já que são reutilizáveis, e fazer uso do ID com moderação, visto que são únicos e não podem ser reutilizados, perdendo muito dos benefícios de reutilização do CSS em múltiplos locais.
Também quando você começa a utilizar seletores com ID, você está automaticamente limitando aquele estilo a um único elemento.
Seja cauteloso ao utilizar IDs, validar de fato será necessário. Quando falamos sobre manipulação dos elementos do DOM, o ID de fato é melhor recomendado. Caso você vá utilizar, faça-o apenas em tags específicas e únicas do seu sistema para evitar conflitos.
Segue link para você conferir a especificação do Mozilla sobre selectores por classe ou ID: https://developer.mozilla.org/pt-BR/docs/Web/CSS/Getting_Started/Seletores
Manipulação do ID em js: (https://www.w3schools.com/jsref/prop_html_id.asp)
Comment: Mas ninguém falou em seletores. A recomendação de não utilizar ID para seletor até faz certo sentido, mas não neste contexto. Neste, para falar a verdade, ficou uma recomendação inválida, pois o ID tem sua função (importante) no DOM e deve ser avaliada dentro da necessidade e contexto adequados.
Comment: Ajustei minha resposta meu amigo. observei apenas o cenário comum do meu dia dia. Concordo quando a manipulação do elemento do DOM. Abraços.


Is there any way that adjusted R squared would be greater than R squared?

Question: Is there any way that adjusted $R^2$ would be greater than $R^2$? Including cases of extreme values of n and p and negative values of $R^2$.
Answer: No it can't. Check out this summary.
Edit: Just to flush out a bit more
The formula is $R^2_{adj} = 1 - \frac{(N-1)}{N-p-1}(1-R^2) $ where N = sample size, p = number of predictors, and $R^2$ is, well, $R^2$. So at best with an enormous number of samples and a small number of predictors, it can approach the original $R^2$ as $\frac{(N-1)}{N-p-1}$ approaches 1.
Comment: The argument is correct--but it's not quite general enough to address the situation implied by the question.  The suggestion that $R^2$ could be negative hints that a regression through the origin is contemplated, in which case the correct formula for adjusted $R^2$ is slightly different than the one given here.  The conclusion remains true--in fact, the adjustment is even greater in that case--but it might be worth pointing out that the *absolute value* of the adjusted $R^2$ easily could exceed that of $R^2$ (fwiw). In the most extreme cases $R^2=0$ whereas the adjusted value is $-1$.


Qual seria o tamanho padrão para criar botões no menu de websites, em diferentes resoluções?

Question: Gostaria de ter uma ideia do tamanho de botões para websites em suas respectivas resoluções, como botões do menu, botões de redes-sociais, botões de perguntas, entre outros...
Tem algum site de informação sobre esse tema?
Comment: Que eu saiba, não há padrão para isso. Depende do design do site.
Comment: Tem este artigo que dá para ter uma idéia. http://uxdesign.smashingmagazine.com/2012/02/21/finger-friendly-design-ideal-mobile-touchscreen-target-sizes/
Comment: Obrigada, Tony!!
Answer: Não existe um "padrão" de tamanhos. O que existe são estudos e recomendações, até porque variações de design entre sites comportam vários tipos de tamanhos e formas de botões.
Um artigo muito bom, o qual traduzo aqui, traz várias linhas guia para o desenvolvimento de interfaces:
Consistência ("princípio da menor surpresa")

Certos aspectos de uma interface deve se comportar de forma consistente em todos os momentos para todas as telas;
Terminologia deve ser consistente entre telas;
Ícones deve ser consistente entre telas;
Cores devem ser consistentes entre telas de função semelhante;

Simplicidade

Quebre tarefas complexas em tarefas mais simples;
Quebre sequências longas em etapas separadas;
Mantenha tarefas fáceis, usando ícones, palavras, etc.;
Use ícones / objetos que são familiares ao usuário;

Limitações de memória humana

Organize as informações em um pequeno número de "pedaços";
Tente criar seqüências lineares curtas de tarefas;
Não faça piscar informações importantes na tela por períodos consideráveis;
Organize os campos de dados para corresponder as expectativas dos usuários, ou para organizar a entrada do usuário (por exemplo, números de telefone de formatação automática);
Forneça pistas auxiliares / navegação para o usuário saber onde eles estão no software ou em que fase eles estão em uma operação;
Forneça lembretes ou avisos conforme apropriado;
Forneça feedback contínuo sobre o que é e / ou apenas aconteceu;
Permita que os usuários reconheçam em vez de recordar informações;
Minimize a trabalhar cargas de memória, limitando a duração das sequências e quantidade de informação - evitar ícone mania.

Direcionamento Cognitivo

Minimize as transformações mentais de informação (por exemplo, usando "Ctrl + Shift + esc +8' para recuar um parágrafo);
Use ícones significativos / letras;
Use pistas visuais adequadas, como setas de direção;
Use metáforas 'do mundo real', sempre que possível (por exemplo, metáfora da mesa de trabalho, metáfora da pasta, metáfora da lata de lixo, etc);

Feedback

Forneça feedback informativo nos pontos apropriados;
Forneça feedback adequado articulatório - feedback que confirma a operação física que você fez (por exemplo, digitei 'ajuda' e 'help' aparecer na tela). Isto inclui todas as formas de comentários, como feedback auditivo (por exemplo, emite um sinal sonoro do sistema, clique do mouse, clica-chave, etc);
Forneça feedback com semântica apropriada - feedback que confirma a intenção de uma ação (por exemplo, com destaque para um item a ser escolhido de uma lista);
Forneça indicadores de status apropriados para mostrar ao usuário o progresso com uma operação longa (por exemplo, a barra de cópia ao copiar arquivos, um ícone de ampulheta quando um processo está sendo executado, etc);

Mensagens do sistema

Forneça texto centrado no usuário em mensagens (por exemplo, "houve um problema em copiar o arquivo para o seu disco" ao invés de "erro de execução 159");
Evite mensagens ambíguas (por exemplo, presisone 'qualquer' tecla para continuar - não há 'qualquer' chave e não há necessidade de apertar uma tecla, reformular a dizer "pressione a tecla Enter para continuar);
Evite o uso de mensagens ameaçadoras ou alarmantes (por exemplo, erro fatal, execute abortado, matar trabalho, erro catastrófico);
Use palavras específicas, construtivas em mensagens de erro (por exemplo, evitar mensagens gerais, tais como "entrada inválida" e de uso específicos, tais como "Por favor, insira o seu nome");
Faça o sistema "assumir a culpa" por erros (por exemplo, "o comando ilegal" versus "comando não reconhecido")

Antropomorfização

Não antropomorfizar (ou seja, não atribuir características humanas a objetos) - evitar a mensagens do seu computador como por exemplo "Tenha um bom dia";

Modalidade

Use modos cautelosamente - um modo é um estado onde a interface que o usuário faz tem ações diferentes do que em outros estados (por exemplo, mudando a forma do cursor podem indicar se o usuário está em um modo de edição ou um modo de navegação);
Minimize os modos de preferência, modos de preferência especialmente irreversíveis - um modo preventivo é aquele em que o usuário deve completar uma tarefa antes de prosseguir para a próxima. Em um modo preventivo outras funções do software são inacessíveis (por exemplo, caixas de diálogo para salvar arquivos);
Torne as ações do usuário facilmente reversíveis - use 'desfazer' comandos, mas usá-los com moderação;
Permita rotas de escape de operações;

Atenção

Use técnicas chamam a atenção com cautela (por exemplo, evitar o uso excessivo 'pisca' em páginas da web, exibindo mensagens, 'você tem mail', cores fortes, etc);
Não use mais de 4 diferentes tamanhos de fonte por tela;
Usar fonte com ou sem serifa apropriadamente de acordo com a situação visual;
Não use todas as letras maiúsculas - uso e mistura letras maiúsculas / minúsculas;
Não use excessivamente áudio ou vídeo;
Usar cores de forma adequada e fazer uso de expectativas (por exemplo, não tem um botão OK de cor vermelha (usar verde para OK), amarelo para cautela e vermelho para 'perigo' ou 'pare');
Não use mais de 4 cores diferentes em uma tela;
Não use azul para texto (difícil de ler), o azul é uma boa cor de fundo;
Não colocar texto vermelho em um fundo azul (péssimo para daltônicos);
Utilize combinações de cores de contraste;
Usar cores de forma consistente;
Usar apenas 2 níveis de intensidade em uma única tela;
Use sublinhado, negrito, vídeo inverso ou outros marcadores com moderação;
Em telas de texto não use mais de 3 fontes em uma única tela;

Problemas de exibição

Manter exibição inércia - certifique-se a tela muda pouco de uma tela para a próxima tarefa dentro de uma situação funcional;
Organize a complexidade da tela;
Elimine informações desnecessárias;
Use frases concisas, sem ambiguidade, para instruções e mensagens;
Use ícones fáceis de reconhecer;
use um layout de tela equilibrado - não colocar muita informação na parte superior da tela - para tentar equilibrar a informação em cada quadrante da tela;
Use a abundância de "espaço branco" em torno de blocos de texto - utilize pelo menos 50% de espaço em branco para as telas de texto;
Agrupe informações logicamente;
Estruture a informação em vez de apenas apresentar um formato narrativo (compreensão pode ser 40% mais rápido para um formato estruturado);

Diferenças individuais

Acomode diferenças individuais na experiência do usuário (desde o iniciante até o alfabetizado computador)
Acomode as preferências do usuário, permitindo algum grau de personalização de layout de tela, aparência, ícones etc
Permita formas alternativas para os comandos (por exemplo, através de combinações da seleção de teclas de menu);
Answer: Até onde eu saiba, não tem um tamanho padronizado, irá depender mesmo do seu design.
Muitas vezes o botão não é nem um botão em si, mas sim uma palavra.
Essas coisas dependem muito de onde você quer chegar.
Recomendo você presquisar por palavras como User Xperience, User Interface, User Design assim você poderá enteder melhor quais os padroes que a Web utiliza.
O próprio StackExchange tem um forum dedicado somente a esse assunto, é o
UX StackExchange
Comment: Obrigada, Igor!


How do you deal with time series with long seasonality period?

Question: I have a few time series (20+) to be jointly forecasted. They are minute-level data with an obvious weekly seasonality. Therefore the seasonality is 7*24*60=10080.
Typical time series model can not handle such a long seasonality, since it requires a huge number of seasonality parameters (I tried DLM and some similar models).
Most time series models require deseasonality before feeding, is there any way to deal with this long seasonality?
Comment: [Here](https://robjhyndman.com/hyndsight/longseasonality/) is Rob J. Hyndman's blog post specifically on this topic. Search also for related threads on Cross Validated, something like [these](https://stats.stackexchange.com/search?q=long+seasonal+period).
Comment: Thanks @RichardHardy! That's definitely a good start point.
Comment: I'd be thinking about looking at trigonometric seasonality not dummy seasonality. You can probably get an adequate fit with only a few components. Do you seem to have stationarity across weeks?
Comment: @Glen_b Yes a fourier series seems to be able to capture the seasonality pretty well.
Answer: I would consider possibly using deterministic structure such as 6 dummies for day-of-the-week , 23 dummies for hour-of-the-day and arma structure for short term memory. How to build ARIMA model from my time series? might be of interest


How to change functions according to valued in numpy array

Question: I am trying to make a surface plot of a function that looks like this:
def model(param,x_1,x_2,x_3,x_4):
    est=param[0]+param[1]*(x_1+x_2*x_3+x_2**2*x_4)
    return est

The point is that according to the value of x_2, x_3=1 for x_2>=0 and x_4=1 for x_2<0 (else:0).
When I tried to make a surface plot, I was confused how to make the mesh-grid as there are 2 more variables in addition to x_1 and x_2.
To compute the z axis, I tried to modify function as:
def function (param,x_1,x_2):
    if x_2>0:
      est=param[0]+param[1]*(x_1+x_2)
    else:
      est=param[0]+param[1]*(x_1+x_2**2)
    return est)

However, it says the truth value is ambiguous. I understood it as python sees it whether all values in x_2 >=0 or not.
I also tried to use np.sign() but it doesn't act in a way I want this case.
Would there be any ways to change the function according to the value of elenemt in the array and/or solve this without manually computing z axis using for loop?
Comment: `x_2` is an array not a scalar value. What does it mean `[-2, -1, 0, 1, 2] > 0`? Use `if all(x_2 > 0):`
Comment: Is possible add some sample data and expected ouput?
Comment: You may try something like x_3[x_2>0] =1 and proceed
Comment: Object have truth value in python, a vector is a collection of object thus it is ambiguous to have a single truth value for a vector (see all and any). What you can do is `(X > 2).all()` to ensure all components are above 2.
Comment: @Tommy. I downvoted your question by error. I edited your post to fix this mistake. Sorry.
Answer: If you want to check all values greater than 0, use all:
def function (param,x_1,x_2):
    if all(x_2>0):
      est=param[0]+param[1]*(x_1+x_2)
    else:
      est=param[0]+param[1]*(x_1+x_2**2)
    return est

but if you want to apply the test on each value, use np.where:
def function (param,x_1,x_2):
    return np.where(x_2 > 0,
                    param[0]+param[1]*(x_1+x_2),
                    param[0]+param[1]*(x_1+x_2**2))

Answer: I think you need numpy.where:
def function (param,x_1,x_2):
    return np.where(x_2>0,
                    param[0]+param[1]*(x_1+x_2),
                    param[0]+param[1]*(x_1+x_2**2))

How it working:
param = [10,8]
x_1 = np.array([1,2,3])
x_2 = np.array([0,4,10])

If Trues in mask are used values from param[0]+param[1]*(x_1+x_2) else from param[0]+param[1]*(x_1+x_2**2):
print (x_2>0)
[False  True  True]

print (param[0]+param[1]*(x_1+x_2))
[ 18  58 114]

print (param[0]+param[1]*(x_1+x_2**2))
[ 18 154 834]

print (function(param,x_1,x_2))
[ 18  58 114]


Missing Exercises in Elementary Number Theory by Underwood Dudley.

Question: I'm a beginner in math and I just started studying Elementary Number Theory by Dudley. So far I'm impressed, but I've noticed that the book does not include all the solutions to the exercises they present in the chapters, namely those that require you to prove some property.
I would really like to find the worked out solutions to all the exercises. I've looked all over for a solution to all the exercises with no luck. Perhaps I'm missing something or perhaps someone knows a source I could use?
Thank You
Comment: Numerical questions will have a unique correct answer, but "prove" questions will have so many correct answers that providing one would be pretty useless. If your answer differed from the one provided, you would have no idea whether your answer was wrong, or just different.
Comment: ...or perhaps there are no online solutions to that book's exercises, so that the best source you could use is your brains.
Answer: [My comment has been well-received, so I'll risk elevating it to an answer]
Numerical questions will have a unique correct answer, but "prove" questions will have so many correct answers that providing one would be pretty useless. If your answer differed from the one provided, you would have no idea whether your answer was wrong, or just different.
Answer: There is a published instructors guide to go with Dudley's text, which includes some nice commentary as well as exercise solutions. Dover has it posted online: Instructors Guide to Elementary Number Theory


html com jquery (tabs)

Question: estou com um problema em colocar as tabs a funcionar.
Aparece-me os nomes das tabs mas não como deviam aparecer dentro de um rectangulo.
pois a seguir quero colocar os dados php lá dentro
http://jsfiddle.net/p3sfy/3444/
PS: Tenho esse codigo a cima mas falta-me um pedaço de codigo para funcionar a tabs
 $("#tabs").tabs();

Comment: Amigo, existe muio "lixo" no código que você adicionou, faça uma limpeza nele deixando evidente apenas a parte das tabs que terei prazer em ajudá-lo. Até mais
Comment: o que quero é colocar a funcionar é o php e as tabs e no fim dessa pagina quero que tenha a paginação. http://jsfiddle.net/J5Sx4/2/
Answer: Acho que o que você procura seria isso.
Cada tabs ira conter o conteudo que você precisa, quando for fazer o fecth, jã adicione em cada tabs o conteudo que precisa.
no link que abaixo segue sistema com TABS e CSS, para o meu inline e Jquery para quando clicar na TAB específica mudar o conteúdo.
Codigo com Jquery e CSS
Comment: Entao se é apenas dentro das tabs que coloco o php como posso fazer a paginação? Quando eu fiz a paginação ficou tudo dentro de um php só
Comment: fiquei com uma duvida. dentro desses tabs posso inserir php para mostrar dados ?
Comment: @user3253195, sim dentro das `TABS` você pode inserir o PHP para colocar o conteúdo, basta fazer como no outro código que fez, onde contem o `fetch`, para que o conteúdo apareça dentro da `TAB`que você deseja. A única coisa que precisa fazer é determinar qual `TAB` ira aparecer e quais ficarão escondidas.
Seu primeiro comentário não ficou muito claro, explique melhor. :-)
Comment: @user3253195 Seu `PHP` deve ficar [ASSIM](http://jsfiddle.net/Franckcf/PbZkV/1/).
Conforme ele buscar as informações no banco ele já coloca no `HTML` o que deve ser exibido em cada `TAB`. O `CSS` irá permanecer o mesmo, sendo assim exibindo o que deseja.

html com jquery (tabs)


Unable to POST to WCF service using Android client

Question: I have a self-hosted WCF web service running, and an Android client application. I am able to GET or retrieve data from the web service in json format, however I am unable to POST or send any data to the server.
Below is the code from the WCF service:
 [OperationContract]
 [WebInvoke(Method = "POST",
 UriTemplate = "/SetValue",
 RequestFormat = WebMessageFormat.Json,
 ResponseFormat = WebMessageFormat.Json,
 BodyStyle = WebMessageBodyStyle.Wrapped)]
 public string SetValue(TestClass someValue)
 {
     return someValue.Something.ToString();
 }

[DataContract]
public class TestClass
{
    [DataMember(Name = "something")]
    public int Something
    {
        get;
        set;
    }
}

Below is the code from the Android client:
 HttpClient httpClient = new DefaultHttpClient();
 HttpPost request = new HttpPost("http://xxx.xxx.x.x:8000/SetValue");
 List<NameValuePair> params = new ArrayList<NameValuePair>(1);
 params.add(new BasicNameValuePair("something", "12345"));
 request.setEntity(new UrlEncodedFormEntity(params));
 HttpResponse response = httpClient.execute(request);

The following is how I start the self-hosted service:
 class Program
 {
    static void Main()
    {
        Uri baseAddress = new Uri("http://localhost:8000/");

        using (WebServiceHost host = new WebServiceHost(typeof(ServerSideProfileService), baseAddress))
        {
            host.AddServiceEndpoint(typeof(ServerSideProfileService), new BasicHttpBinding(), "Soap");
            ServiceEndpoint endpoint = host.AddServiceEndpoint(typeof(ServerSideProfileService), new WebHttpBinding(), "Web");
            endpoint.Behaviors.Add(new WebHttpBehavior());

            // Open the service host, service is now listening
            host.Open();
        }
     }
  }

I only have an app.config which just has:
 <?xml version="1.0"?>
 <configuration>
 <startup><supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0"/></startup></configuration>

The response I'm getting when I run httpClient.execute(request) from the Android client includes:
 HTTP/1.1 400 Bad Request
 Request Error
 The server encountered an error processing the request. See server logs for more details.

And that's pretty much it. I am very new to WCF and don't know where this 'server log' would be, and am at a loss as to how to troubleshoot or debug this? (I have tried Fiddler2 but it doesn't seem to detect anything from the Android client.)
[EDIT]
I have also tried
 JSONObject json = new JSONObject();
 json.put("something", "12345");
 StringEntity entity = new StringEntity(json.toString());
 entity.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
 entity.setContentType( new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
 request.setEntity(entity);

which also results in the error.
I also noticed that if I change 'SetValue' to return a constant, such as "abcd", instead of someValue.Something.ToString(), then everything works?
Comment: Try this i hope that this is very help full.

[Android HTTPPost Returns Error "Method not allowed.](http://stackoverflow.com/questions/6272381/android-httppost-returns-error-method-not-allowed/6604491#6604491)
Answer: Your client code is sending a html form post formatted payload, but your server is expecting a json payload, you need the client to be something like
HttpClient httpClient = new DefaultHttpClient();
HttpPost request = new HttpPost("http://xxx.xxx.x.x:8000/SetValue");
StringEntity e = new StringEntity("{ \"something\":12345 }", "UTF-8");
request.setEntity(e);
request.setHeader("content-type", "application/json");
HttpResponse response = httpClient.execute(request);

Comment: Thanks for your suggestion, unfortunately I still receive the error. I've also tried:

     `JSONObject json = new JSONObject();
  json.put("something", "12345");
  StringEntity entity = new StringEntity(json.toString());
  entity.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
  entity.setContentType( new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
  request.setEntity(entity);`

which also results in the error.

I also noticed that if I change 'SetValue' to return a constant ("abcd") instead of someValue.Something.ToString(), then everything works?
Comment: Then it sounds like the request is making it ok to your code, but your code is throwing an exception.
Comment: Okay, you're right. I have added the following 'if statement' in SetValue(TestClass someValue):

  `if (someValue == null)
                    return "somevalue is null";`

and it returns this statement. It looks like the value "12345" specified on the client side is not being passed for some reason :s
Comment: I think you'll need to find out how the dataContract gets mapped to json.
Comment: well, if I change my SetValue definition to:
 SetValue( string something ) and then return this input string, I see "12345" as expected. At least it works now with simple types, though I am not successful with complex types (i.e. passing class objects) as in the original post.
Answer: I had the same problem, I resolved this by removing
BodyStyle = WebMessageBodyStyle.WrappedRequest

from my WCF method header
 [WebInvoke(Method = "POST", UriTemplate = "mymethod", RequestFormat=WebMessageFormat.Json,
            BodyStyle = WebMessageBodyStyle.WrappedRequest,
                ResponseFormat=WebMessageFormat.Json)]

Changed to
 [WebInvoke(Method = "POST", UriTemplate = "mymethod", RequestFormat=WebMessageFormat.Json,
                ResponseFormat=WebMessageFormat.Json)]

Answer:     [WebInvoke(UriTemplate = "crud/delete",
        ResponseFormat = WebMessageFormat.Json,
        RequestFormat = WebMessageFormat.Json,
        BodyStyle = WebMessageBodyStyle.WrappedRequest,
        Method = "POST"
    )]
    public SampleItem Delete(string id)
    {
        SampleItem item = new SampleItem();
        item.Id = 118;
        item.StringValue = id;
        return item;
        throw new NotImplementedException();
    }

var params  = '{"id":"sfs"}';

function postTest0(){
    $.ajax({
        url:'http://localhost/wcfrest/rest/crud/delete',
        //url:'http://localhost/wcfrest/rest/crud/create', //后台处理程序
        type:'post',    //数据发送方式
        dataType:'json', //接受数据格式
        contentType: "application/json",
        data:params, //要传递的数据
        timeout:1000,
        error:function(){alert('post error');},
        success:update_page //回传函数(这里是函数名)
    });
}

superfell 那个正解!
Comment: Please always try to write at least a small explanantion of your answer.
Answer: From what I have found Android converts the JSON string to a byte array stream and then posts it. Here is my own code as an example
HttpPost httpPost = new HttpPost(URL_Base + uri);
httpPost.setEntity(new StringEntity(sJSONOut));
httpPost.setHeader("Accept", "application/json");
httpPost.setHeader("Content-type", "application/json");
HttpEntity oHttpEntity = new DefaultHttpClient().execute(httpPost).getEntity();

In eclipse, when setting a break point on the second to last line and inspecting the httpPost object properties i find the value of my StringEntity is not a byte array [123. 43, 234 ...... even though I have confirmed that my string sJSONOut is correctly formatted json.
Another answer here suggested removing BodyStyle = WebMessageBodyStyle.WrappedRequest from the WCF method header. That gave me the clue I needed to change that line from WrappedRequest to Bare which is what ended up working.
BodyStyle = WebMessageBodyStyle.Bare


What is a safe alternative to wildcards in /etc/sudoers?

Question: In the /etc/sudoers file on my Red Hat server, I have this line:
%webdevgroup ALL=NOPASSWD: /bin/chmod * /home/http/*

This is clearly a bad idea, since someone could do something like this:
sudo /bin/chmod 777 /home/http/../../etc/sudoers

Is there a safer way to achieve this functionality without opening the server up to this security hole?
Comment: Use filesystem ACLs so users don't have to run `chmod 777`.  BTW, `chmod 777` is evil, you almost certainly don't want that, if want a half-way secure system.
Comment: Why don't you create several groups and add users to a certain group?
Comment: utrecht: That doesn't solve the problem of an untrusted user needing to run this command.
Answer: If I understand your problem correctly, you want to give rights to webdevgroup on the directory /home/http/*
ACL is a good option, but you can also have a look at setgid : What's the purpose of setgid directory?


Calculating the confidence interval or standard error of a PPV adjusted for prevalence

Question: I am trying to evaluate how well a disease test performs in a case-control study. In this example, the prevalence is 0.5%, and the results are below:

Disease +
Disease -

Test +
40 (TP)
10 (FP)

Test -
600 (FN)
5000 (TN)

As the sample is enriched for those with the disease, the standard PPV calculation $PPV = \frac{TP}{TP+FP}$ isn't accurate. I can calculate the PPV adjusted for prevalence using $ppv = \frac{p\cdot Sens}{p\cdot Sens + (1-p)\cdot(1-Spec)}$, as in this page, which here gives a PPV of 13.6%.
But given the low prevalence, I am concerned that a small change in the number of false positives could make a large difference to the PPV, so I want to calculate the 95% confidence interval on this PPV.
This question gives the standard error as $SE = \sqrt{ \frac{PPV(1-PPV)}{TP+FP}}$.
This would give a standard error of 4.8%, and if I then use $CI_{PPV} = PPV \pm 1.96*SE$, I get a CI of 4.1%-23.1%.
But:

Does this equation still apply when the PPV has been adjusted for prevalence?

I have read that as the uncertainty of a proportion is not symmetrical, using the above equation to calculate the CI is not very useful (e.g. in this question).

So, is there a better way to calculate the confidence interval on the PPV in this case?
Answer: After looking into this further I found that there are multiple possible ways of calculating PPV confidence intervals, but decided to use the standard logit confidence intervals explained in and recommended by this paper: Confidence intervals for predictive values with an emphasis to case–control studies


How Can I prevent a specific application from being run on a specific machine using Group Policy?

Question: I know this is possible to do and I am working on it with limited success. I believe the Group Policy I want is "Do Not Run Specified Windows Applications" - I can enable this and add the .exe I want to the list of programs not to be run.
I have tried this on my local machine by running gpedit.msc going to User Config > Admin Templates > System and then choosing that policy and editing and enabling it. Doing it this way verifies that it works as I could then not run the specified .exe (XenAppWeb.exe)
So this is great.
I have created a GPO to do the same thing in GP Management on my domain controller where we centralize this, enforced it, applied it to an OU, and put one of our machines into this OU to test it. I have let it sit there for 3 days, run gpupdate /force, and when I try to run XenAppWeb.exe on this machine, it still lets me run it fine.
What can I look at to troubleshoot this?
I should note that I am trying to enact this policy on Windows XP machines (Virtual Machines)
Thanks,
Mike
Answer: One alternative would be to use Software Restriction Policies (Computer Configuration -> Windows Settings -> Security Settings) rather than the "Do Not Run Specified Windows Applications" user policy.  This will also give you more flexibility around how you select the application to be blocked.
Keep in mind that any blacklisting approach can be worked around.  If you want to ensure that the restriction can't be bypassed, you'll need to use Software Restriction Policies in whitelist mode, i.e., specify those applications that are allowed to run rather than those that are not.
Comment: Thanks Harry, I played around with this and I think I got it to work. It doesn't give any sort of "Access denied" error when you try to run the program which would have been nice, but it doesn't run the program when you try to and that is the important thing
Answer: If you're setting the restriction policy on the User Configuration section of the GPO then this will have no effect unless the user account objects are in the OU that you've applied the policy to (or if you enable loopback processing).
Shift the settings to the Computer Configuration section of the policy, assuming you want the policy to apply regardless of who logs on to those systems.
Comment: Thanks Chris that makes a lot of sense, I do in fact have these settings under the User Configuration - The issue now is, when I go to edit the GPO, I don't have an option for "Do Not Run Specified Windows Applications" under Computer Config - It only exists under User Config - Is there some way to copy or move it?
Comment: Looks like that option isn't available under `Computer Configuration`. The easiest way would be to enable [Loopback Policy Processing](http://support.microsoft.com/kb/231287), which causes the `User Configuration` section of the policy to apply to any user logging on to those systems.


IE 8 stopped working during website loading

Question: When testing my site compatibility on IE8, the site load at once but the IE8 browser crashes. Please see the link http://labelco.staging.wpengine.com/. Can any body tell me what is causing the IE8 to stop responding. Thanks in advance.
Comment: Are there any errors in the console?
Comment: Add http://browsehappy.com/ to your website :) Seriously, who uses IE 8 anymore?
Answer: You have syntax errors that are being thrown and logged to console. If IE doesn't have a console open (your dev tools are open), log statements will crash your page. Firefox and Chrome are smart enough to deal with it. IE, unsurprisingly, is not.
Hit F12 to open your dev tools, and your app will finish loading. (Obviously you'll have to fix the underlying issue to get it to work properly.)


Jazz piano versus classical piano

Question: What are the main differences between a jazz Pianist and a classical Pianist, If there are any. If I play mainly songs of pop artists (e.g: The Beatles, David Bowie, Elton John, etc.) does this count as a jazz pianist? What is easier to learn when you start learning piano at an "old" age (20+)
Answer: Jazz and classical music have different traditions and points of focus.  In classical music the distinction between composer (or creator of music) and performer is highly divided - only in specific instances is the performer allowed to improvise (in the historical practice of music from the Renaissance, Baroque, classical piano concertos by Mozart and others, and certain 20th/21st century classical music). In jazz, the roles are much more closely integrated, and the main focus of this art is improvisation and embellishment upon standard tunes (this again discounts the most modern developments).  Accordingly, classical music has a much stronger focus on notated music, while jazz is more focused on using chords to describe a work.
Playing the music of pop artists falls somewhere in between - most performers in this style can play based on chords, but the sense of improvisation is usually not as rigorous or important - in fact, it's often important the melody remain largely the same.  In addition, jazz is very focused on extended tonal relationships, meaning that the piece can change keys in a single measure.  This rarely happens in pop music, which tends to focus on one or two related keys.
None is necessarily easier, but if you don't know a ton about theory, jazz might seem pretty daunting. Classical performance focuses less on this aspect, but technique is often very important. With that in mind, pop music is probably the best place to start.
Comment: cotroxell, I edited your answer to put in a reference to improvising in music from the Renaissance, Baroque, and Classical style periods.
Answer: Jazz is a collective, public and free art. You can train yourself alone, in private, up to a certain point, but a jazz pianist is someone who plays piano with other musicians (sometimes they are only there through their musical legacy): the improvisation component is the important point, not the themes or they origin.
In fact jazz artists use any theme from any source and transform them, reinterpret them, mock them, rock them or magnify them.  You can do jazz with a little excerpt of Beethoven or Chopin, the Beatles or the latest broadway musical, as well as your own musical ideas, pre-cooked or not.
There is a lot of material on the net, fabulous records, more and more jazz transcriptions and classical scores. But the best way to learn, jazz or classical, is to find people more experienced than you are (teacher or not) and interact with them.  It is perhaps easier to find official teachers for classical piano technique or around classical repertoire. More and more colleges and conservatories have jazz cursus. Looking at classified ads or going to local places where jazz pianists use to play you may find someone to help you.
Answer: This is an interesting question.
I learnt the nuts and bolts of playing the piano by doing 'classical' so I can read music etc, but now I play almost entirely jazz and 'popular' music.
Without going into too much detail I find that the two disciplines require you to think about your instrument -- and the music -- in very different ways. When I'm playing a jazz gig, I'm not really thinking about the mechanics of playing (ok, that might be partly becuase I haven't ingrained them already) but I'm more just concentrating on very deep listening -- on the moment and on what the other musicians are doing.
I do know that classical is probably better for raw technique, but for general playing in the real world -- in bands, playing by ear, and being able to comp along with virtually anything -- then the knowledge required to play jazz takes you into another place of freedom altogether. I no longer have to buy sheet music for anything - I can play virtually anything I want by ear. And properly, not just one-finger stuff. Within 10 or 15 mintues of getting it under my fingers, it's there. Only playing classical music will never give you that ability and it requires a completely different way of approaching the notion of 'competent' playing.
good post!

Jazz piano versus classical piano


Is there an alternative notation for polychords that won't be confused with slash notation?

Question: We have a terrific guide on slash notation, a notational practice in which, for example, Gm/D means a G-minor triad with a D in the bass (i.e., in second inversion). A polychord, though, is indicated by a horizontal slash (as opposed to the vertical slash of slash notation) to show a G-minor triad above a D-major triad.
But this distinction is tricky to typeset clearly, and sometimes it's downright unclear if the slash is vertical or horizontal.
Are there alternative methods for indicating polychords, especially in typed environments where the horizontal slash can be tricky to input?
Comment: Unfortunately I'm not aware of an alternate which is too bad because like you say typesetting a fraction is tricky at best. The shame is that a regular slash would work for all polychords with the exception of those that have a major triad on the bottom: A/C7 Cmaj7/Dm Bb/Gm are all understandable but G/C is just a bass note below instead of a triad. Maybe an alternate way to name a triad is the solution, C(tr) or Cmaj or C35. Any other ideas?
Comment: @JohnBelzaguy The Cmaj or CM idea does seem most straightforward, since those are already in use for triads.
Comment: Using John's idea, but a backwards rather than forwards slash would nail it. But it wouldn't be known world-wide. Although it would be pretty well self-explanatory - as in *this isn't a bog-standard slash chord*.  A\C7, C\Dm for examples. Gotta start somewhere!
Comment: I've only ever seen polychords notated with a perfectly horizontal line between the chords. I don't find it hard or ambiguous to separate between that and slash notation

https://musictheory.pugetsound.edu/mt21c/images/unit12/polychord-rite-chord.svg
Comment: What do you mean with typed environments? Are you using an old typewriter or do you have access to unicode or markup? (Side note, I think ampersand & is more common to find on keyboard than the union symbol and pretty close in meaning, or maybe | if you think of logical or)
Comment: @Aaron I like CM since Cm is minor. Who do we speak to about implementing this?
Comment: Something that might prove helpful here is the convention to use capital letters for chord symbols and minuscles for single note. So Gm over a D in the bass could be notated Gm/d, while Gm over a D major triad would be Gm/D.
Comment: You could try employing roman numerals partially to distinguish polychords from inversion notation. But that's functional-harmonic notation, which may or may not suit your case.
Comment: Some other ideas: As long as you're not using "+" to indicate raised (sharp) chord tones, you could have **Gm+D**.  Or, you could borrow the "union" symbol from set theory and use **Gm∪D**.
Comment: @Emil as long as we don't get too hung up on the strict mathematical meanings,  the **&** is probably a better option than **|** because it's more distinct from **/**.
Comment: Is it important, which program we talk about?
Answer: You could try to encapsulate the chord with brakets.  [G/B] .  I personally use standard notation sheet music instead of slash notation.  I've never ran into a situation where the player was still learning how to strum.  Mostly because an arpeggio sounds better than a strum.  And strums are indistinguishable to the audience unless it's supported by the drums.
Comment: With "[G/B]" written, I'd play an inversion, not polychord. Unusual notations have to be explicitly described, something like "[G/B] means a polychord with G and B".
Comment: O.I.C.  so Maybe something like GpB. Or G chord / B chord. No easy standard that I know of exists. Thank God for written music.
Answer: Some of the notation programs do offer options for slash/bass notation that are confusingly close to   the polychord 'fraction'. It behoves the engraver to choose styles that AREN'T ambiguous.  Sibelius, for one, makes a distinction that is perfectly  clear, and easy to achieve.
You could concoct your own notation for scores where slash chords are mixed with polychords, perhaps put a box around the polychords?  As I've done (unnecessarily) in the example below.
But this WOULD be your own private system, and would require explanation.   As far as I know there's no generally understood convention other than slash or fraction.
Comment: The whole polychord concept is so rarely used, it requires explanation, regardless of how it's notated, IMO. :)
Answer: Here (jazzpianosite) are a few approaches, perceiving or interpreting the polychord as an extended chord and/or change of scale:

garciamusic.com shows a few more alternative notations, following the same idea, for some more complex situations, still conveying, how the chord is built:


Coming up with a formula 100+100=100%

Question: I couldn't find the right phrases to google an answer to my question, but I am trying to come up with a formula and I have no idea how to.
So I have a soccer player who has a physical stat of 100 and a happiness stat of 100, which means he is going to perform at 100% of his attributes. If one of the stats or both of them go down to lets say physical is 97 and happiness is 85 he should perform at n%. Not sure what the formula could be... and one more thing happiness should affect his performance less than the physical. So a player with physical of 100 and happiness of 90 will play better than a player with physical of 90 and happiness of 100
Comment: Take a few more cases (maybe 6 or 7), and attempt an interpolation of some kind, maybe via polynomials, or just straight line. Check what happens to a player who has zero physical and zero happiness, for example.
Comment: That's all you know? Then there's pretty much nothing you can say about the function! But there are always two reasonable estimates: One is a linear weighted estimate, since physical matters more than happiness. Something like $0.6 * P + 0.4*H$, where $P$ is the physicality  and $H$ is the happiness. The other option, is to have some kind of an average of each quantity, say on an average $70$ physicality and $70$ happiness is expected, then we standardize this to $50$ performance, and nearby values to $70$ will produce identical performances, for example.
Comment: I will elaborate like this: In the band $60-80$, everybody's performance should be between $40$ and $60$. Then, below $60$ physicality/happiness you can have a linear graph of some kind, and above $80$ phy/happiness, you can have a very slowly increasing graph to $100$ performance.
Comment: Maybe take the product of those stats instead of the sum (equating $x%$ with $\frac{x}{100}$), if you want to add more weight to one factor, just put exponents. So for example if $p$ and $h$ are your physical and happiness stats (between $0$ and $100$), his performance might be given by $$ \frac{n}{100} =\left(\frac{p}{100}\right)^{a} \left(\frac{h}{100}\right)^{b}$$ with exponents $a < b$ to give a higher influence for $p$.
Answer: A simple way would be through a weighted average. Pick weights $w_1$ and $w_2$ between $0$ and $1$ such that $w_1 +w_2 = 1$, for example $w_1 = 0.7$ and $w_2 = 0.3$. Then
$$\text{Performance} = w_1\cdot \text{Physical} + w_2\cdot \text{Happiness}.$$
You can play around with the weights to get something you like. The higher the weight, the higher the corresponding attribute is valued.
This can be extended to any number of attributes, just create weights $w_1, w_2,...,w_n$ then the performance is given by
$$\text{Performance} = w_1\cdot \text{Attribute #1} + w_2\cdot \text{Attribute #2} + ... + w_n\cdot \text{Attribute #n}.$$

Coming up with a formula 100+100=100%


With Euler's method for differential equations, is it possible to take the limit as $h \to 0$ and get an exact approximation?

Question: I was recently watching a tutorial on Euler's method for approximating differential equations, and the whole time I was thinking "why can't you just take the limit of the step size $h$ as it goes to $0$, and get an exact or near-exact approximation of the differential equation?" So that is my question: is it possible to do that?
Comment: "exact approximation" is oxymoronic, yes?
Comment: It is a nice idea.  For an explicit solution of the DE, we would need to compute the limit explicitly. Even for nice functions, this can be quite hard. Works well for a few cases, for example $\frac{dy}{dx}=ky$, but that's pretty easy anyway. The same issue arises with the Riemann integral. It is defined as the limit of a certain sum, but apart from a few introductory examples, that's not how we find exact expressions for definite integrals, because finding the limit is too hard. Instead, we prove a result that connects the Riemann integral to antiderivatives.
Comment: In theory, yes. In practice, rounding error accumulates and this doesn't work.
Answer: Not really. Recall that the Euler method for $y^\prime=f(x,y)$ takes the form
$$\begin{align*}x_{k+1}&=x_k+h\\y_{k+1}&=y_k+hf(x_k,y_k)\end{align*}$$
for some stepsize $h$. Taking $h=0$ here is equivalent to not moving at all!
However, your idea can be made slightly more practical. Consider the application of the Euler method with stepsize $h/2$:
$$\begin{align*}x_{k+1/2}&=x_k+h/2\\y_{k+1/2}&=y_k+hf(x_k,y_k)/2\\x_{k+1}&=x_{k+1/2}+h/2\\y_{k+1}&=y_{k+1/2}+hf(x_{k+1/2},y_{k+1/2})/2\end{align*}$$
The value of $y_{k+1}$ from these two steps can usually be expected to be a bit more accurate that the value of $y_{k+1}$ from the $h$-step Euler method. We can keep playing the game, taking 4 steps with stepsize $h/4$, 8 steps with stepsize $h/8$, and so on, yielding a sequence of estimates for $y_{k+1}$ corresponding to decreasing $h$.
One way one might estimate the result of what happens when $h\to 0$ is to take all those estimates of $y_{k+1}$ along with the associated stepsizes, and then fit an interpolating polynomial to those. For example, taking $y_{k+1}^{(0)}$ to be the result for stepsize $h$, $y_{k+1}^{(1)}$ the corresponding result for stepsize $h/2$, and $y_{k+1}^{(2)}$ the result for stepsize $h/4$, one can fit a quadratic interpolating polynomial to the three points $\{(h,y_{k+1}^{(0)}),(h/2,y_{k+1}^{(1)}),(h/4,y_{k+1}^{(2)})\}$, and then estimate the limit as $h\to 0$ by evaluating the interpolating polynomial thus obtained at 0.

This scheme of using the interpolating polynomial to estimate the limit to 0 is called Richardson extrapolation. In practice, one certainly takes more than three points for the interpolation, and the order of the interpolating polynomial needed is estimated based on the behavior at past points. The idea of using Richardson extrapolation is due to Roland Bulirsch and Josef Stoer. The Bulirsch-Stoer method discussed here uses a slightly different method for integrating the differential equation (the modified midpoint method) from which the extrapolations are built (as well as a slightly modified extrapolation method), but is essentially the same idea as presented here.

Here's a tiny Mathematica demonstration of the Bulirsch-Stoer idea:
Table[(Apply[List,
     y /. First[
       NDSolve[{y'[x] == x - y[x], y[0] == 1}, y, {x, 0, 1},
        MaxStepFraction -> 1, Method -> "ExplicitEuler",
        InterpolationOrder -> 1, StartingStepSize -> 2^-k]]])[[4,
    3, -2]], {k, 4}] - 2/E

{-0.235759, -0.102946, -0.0485411, -0.0236106}
Here we tried the Euler method on the differential equation $y^\prime=x-y$ with initial condition $y(0)=1$ for the stepsizes $h=1/2,1/4,1/8,1/16$, and compared the result at $x=1$ with the true value $y(1)=2/e$. As you can see the accuracy isn't too good for any of these.
Here's what happens after Richardson extrapolation using those same results from Euler:
InterpolatingPolynomial[
  Table[{2^-k, (Apply[List,
       y /. First[
         NDSolve[{y'[x] == x - y[x], y[0] == 1}, y, {x, 0, 1},
          MaxStepFraction -> 1, Method -> "ExplicitEuler",
          InterpolationOrder -> 1, StartingStepSize -> 2^-k]]])[[4,
      3, -2]]}, {k, 4}], 0] - 2/E

0.0000823142
We end up with a result good to three or so digits, much better than even the result of Euler corresponding to $h=1/256$. Pretty good, I would say, considering that only $2+4+8+16=30$ evaluations of $f(x,y)=x-y$ were needed for a result with three-digit accuracy, while Euler with $256$ steps (and thus $256$ evaluations of $f(x,y)$) can only manage two good digits.
As an aside, Mathematica implements Bulirsch-Stoer internally in NDSolve[], as the option Method -> "Extrapolation".


Sometimes, HTTPS connection is too slow on Chrome

Question: I have trouble with some problem using HTTPS. Sometimes, HTTPS connection is too slow only Chrome. I couldn't find any problem on server.
It use load balancer with 2 web server(apache) on Amazon EC2. The certification for SSL is in the each server.
I don't know how to examine this problem. I tried to examine using TCP trace, Chrome diagnostic tool. It seems to look okay.
How can I examine this problem?
Thanks!
Comment: If you're using a load balancer, why don't you have the SSL certificate on it? i.e. A load balancing SSL proxy
Comment: @HTTP500 That'd violate some organizations' security policies, as the decrypted data would be travelling in-the-clear across Amazon's network after that.
Comment: @ceejayoz, Good point, I didn't know you STILL can't get a private VLAN with AWS. I'd go to another cloud provider that can offer.
Comment: You can with VPC.
Comment: @ceejayoz, Then I'd use VPC and put the SSL certificate on the LB SSL proxy.
Comment: Thanks, I already added certification on LB. Hm... I'll try to setup new LB tonight. I hope to fix it.
Comment: I've added new LB on EC2. It works well now. I think it might be had some bug on EC2 LB. Thanks guys!
Answer: Could be related to your CRL(*). AFAIK chrome does checks CRL while Firefox does not, and I don't know about IE.
Try with "check for server certificate revocation" enabled and disabled. I have no idea though how often chrome checks the CRL lists.
That's what I can think of. Could be something else as well.
--cut here--
(*) For those who happen to be new to SSL: CRL (Certificate Revocation List) - normally SSL certificate stores an address where it's possible to check if this certificate is not revoked. There's two protocols for such check - one is OSCP another one is CRL. Browsers once encounter SSL certificate may check if it isn't revoked (if they actually do it or not depends on browser and your settings). This check often disabled, but when it is enabled, browser may first contact revocation server and only then load the web page.
Comment: I've also tested with "check for server certificate revocation" But It looks same problem if I don't check it.
Comment: If so it's probably not CRL issue
Answer: If you own the SSL private key and certificate, you can take a tcpdump on your web servers and read the traces using wireshark.  You will want to configure wireshark to decrypt your ssl traffic, which you can then read as if they were http requests and responses.  You should be able to get a good idea on what Chrome is doing on those requests that take too long.
The wireshark wiki has a doc that provides all the information you need to set wireshark up to decrypt ssl and most of the downloadable wireshark binaries have already had this support compiled into it (so you don't need to worry about compiling your own version).  One thing to keep in mind is that you will want to download a copy of the private key(s) to your workstation and any modifications you need to make to those keys to strip out passwords should not be uploaded to your production keys on your servers.
Answer: It was just a problem on Amazone Load Balancer. After restarting, It works well.
Thanks All!


Why can't I get $(f)'*g = f*(g)'$?

Question: I am trying to show that the above equality holds when $f(t)=e^{at}$ and $g(t)=e^{bt}$. However, I get different values. So, I get that $f'(t) = ae^{at}$ and $g'(t)=be^{bt}$.
$$
(f')*g = \int_0^t f'(t-u)g(u) du \\
= \int_0^t ae^{a(t-u)}e^{bu} du \\
= a\int_0^t e^{at}e^{bu-au} du \\
= ae^{at} \int_0^t e^{u(b-a)} \\
= ae^{at} (\big(\frac{1}{b-a}\big)e^{bt}-e^{at}) \\
$$
Through a similar fashion I get $be^{bt}(\big(\frac{1}{a-b}e^{at}-e^{bt})$ for $f*g'$. Now, these two are unequal and I am not sure where I made a mistake. Any help would be greatly appreciated.
Comment: Your functions don't have compact support, i.e. the boundary integrals when doing integration by parts don't vanish.
Comment: Are you sure about your integration ? I would say $ae^{at} \int_0^t e^{u(b-a)} = ae^{at} \frac{1}{b-a}(e^{t(b-a)} - 1) = \frac{a}{b-a}(e^{tb} - e^{ta})$
Answer: There's a small typo at your final equality, but even if you fix it the two integrals will be different.
The equality $f'*g = f*g'$ holds for convolutions where the integral is taken from $-\infty$ to $\infty$.
You seem to be computing "causal convolutions", i.e. looking at the function $f$ where $f(t) = e^{at}$ for $t > 0$ and $f(t) = 0$ for $t < 0$ and similarly for $g$. In that case you need to take distributional derivatives (or something equivalent to that) for the formula $f'*g = f*g'$ to be correct.

Why can't I get $(f)'*g = f*(g)'$?


Does a run score if the batter is tagged for the 3rd out before he reaches first?

Question: There is a runner on third with two out. Batter hits a slow roller to first base. First baseman charges and picks up the ball. Runner from third crosses home. First baseman tags the runner running from home to first, does the run count ?
Comment: It seems relevant here to mention the fourth out rule, as described here : https://en.m.wikipedia.org/wiki/Fourth_out

In essence, if a runner scores prior to a third out which is not a force out, a force out can be subsequently made as a fourth out.  The fourth out then supercedes the third out and the run is nullified.
Answer: The run does not count. According to MLB rules:

4.09 HOW A TEAM SCORES.
(a) One run shall be scored each time a runner legally advances to and touches first,
second, third and home base before three men are put out to end the inning.
EXCEPTION: A run is not scored if the runner advances to home base during a
play in which the third out is made (1) by the batter-runner before he touches first
base; (2) by any runner being forced out; or (3) by a preceding runner who is
declared out because he failed to touch one of the bases.

Since the batter-runner does not make it to first base safely, the run does not count. Similar to a force out.