Ansible: Add IPs from inventory to /etc/hosts of all nodes

Question: I am deploying a small 3 node cluster and I want to add the public IP addresses as defined in my inventory to the /etc/hosts files of all of the nodes.
I am trying to use the following, but it is giving me an error:
- name: Add IP address of all hosts to all hosts
  lineinfile:
    dest: /etc/hosts
    line: '{{ hostvars[item]["ansible_host"] }} {{ hostvars[item]["ansible_hostname"] }} {{ hostvars[item]["ansible_nodename"] }}'
    state: present
  with_items: groups['all']

The error is:

fatal: [app1.domain.com]: FAILED! => {"failed": true, "msg": "the
field 'args' has an invalid value, which appears to include a variable
that is undefined. The error was: 'ansible.vars.hostvars.HostVars
object' has no attribute u"groups['all']"\n\nThe error appears to
have been in '/Users/k/Projects/Ansible/roles/common/tasks/main.yml':
line 29, column 3, but may\nbe elsewhere in the file depending on the
exact syntax problem.\n\nThe offending line appears to be:\n\n\n-
name: Add IP address of all hosts to all hosts\n  ^ here\n"}

Any ideas on what I'm missing?
Answer: The previous answer simply does not work because it adds a new line for the same host instead of modifying the existing line when an IP Address for a host changes.
The following solution takes into account when the ip address changes for a specific server and handles it well by only modifying the line instead of adding duplicate entries.
---
- name: Add IP address of all hosts to all hosts
  lineinfile:
    dest: /etc/hosts
    regexp: '.*{{ item }}$'
    line: "{{ hostvars[item].ansible_host }} {{item}}"
    state: present
  when: hostvars[item].ansible_host is defined
  with_items: "{{ groups.all }}"

Comment: Hi Basil, this is a better solution. I haven't considered IP changing. Thanks
Answer: Looks like you have errors in your syntax. Also what version of ansible are you using? The variable names may be different. On version 2.2 this works for me:
- name: Add IP address of all hosts to all hosts
  lineinfile:
    dest: /etc/hosts
    line: "{{ hostvars[item].ansible_host }} {{ hostvars[item].inventory_hostname }} {{ hostvars[item].inventory_hostname_short }}"
    state: present
  with_items: "{{ groups.all }}"

UPDATE
Basil has thought about situations when the IP changes. In that case it is better to use his suggested solution:
- name: Add IP address of all hosts to all hosts
  lineinfile:
    dest: /etc/hosts
    regexp: '.*{{ item }}$'
    line: "{{ hostvars[item].ansible_host }} {{item}}"
    state: present
  when: hostvars[item].ansible_host is defined
  with_items: "{{ groups.all }}"

Comment: on `regexp: '.*{{ item }}$'`, what if we have two hosts named `s1` and `ss1`?
Comment: had to add following: `unsafe_writes: true` otherwise got error on docker-provisioned hosts
Comment: This answer does not take into account when the ip address changes.
Comment: My problem was needing quotes around the groups['all'] / groups.all section. Every example I'd found online didn't have quotes around it, but that was definitely my issue. Thanks
Comment: yea when using variables you need double quotes (except in `when` clause). Out of curiosity, what version of ansible are you using? also what does your inventory file look like?
Comment: Using ansible 2.2. Inventory file is super basic right now.
[app]
app1.us.com ansible_host=192.168.1.1
app2.us.com ansible_host=192.168.1.2
app3.us.com ansible_host=192.168.1.3
Comment: for me following worked (ansible_host was not recognized by Ansible)        line: "{{ hostvars[item].ansible_ssh_host }} {{ hostvars[item].inventory_hostname }} {{ hostvars[item].inventory_hostname_short }}"
Answer: I had the same issue and here is my solution for anyone who is interested.
hosts/dev.ini
[controller]
controller1 ansible_ssh_host=10.11.11.10
controller2 ansible_ssh_host=10.11.11.11
controller3 ansible_ssh_host=10.11.11.12

[compute]
compute1 ansible_ssh_host=10.11.11.13
compute2 ansible_ssh_host=10.11.11.14
compute3 ansible_ssh_host=10.11.11.15

[block]
block1 ansible_ssh_host=10.11.11.16
block2 ansible_ssh_host=10.11.11.17

[haproxy]
haproxy1 ansible_ssh_host=10.11.11.18

[nginx]
nginx1 ansible_ssh_host=10.11.11.19

[deployment]
deployment ansible_ssh_host=10.11.11.20

[all:vars]
ansible_python_interpreter=/usr/bin/python3

tasks/main.yml
---
- name: Update /etc/hosts
  become: true
  blockinfile:
      path: /etc/hosts
      create: yes
      block: |
        127.0.0.1 localhost

        # The following lines are desirable for IPv6 capable hosts
        ::1 ip6-localhost ip6-loopback
        fe00::0 ip6-localnet
        ff00::0 ip6-mcastprefix
        ff02::1 ip6-allnodes
        ff02::2 ip6-allrouters
        ff02::3 ip6-allhosts

        {% for item in ansible_play_batch %}
        {{ hostvars[item].ansible_ssh_host }}   {{ item }}
        {% endfor %}

Notes:

python 3.7.5 ansible 2.9.0
I decided to go with blockinfile instead of using templates because hostvars context was not getting updated inside the template. Plus I was in a hurry :-).
Answer: I've combined gbolo's solution and this solution with addition to add local hostname to /etc/hosts and also make sure not to mistake hostnames like s1 and ss1 with each other
- name: add hostname to /etc/hosts
  vars:
    comment: '# added by ansible'
  lineinfile:
    dest: /etc/hosts
    regexp: "127[.]0[.]0[.]1.*"
    line: "127.0.0.1 localhost.localdomain localhost {{ ansible_hostname }} {{ comment }}"
    state: present
    backup: yes
- name: add IP address of all hosts to /etc/hosts
  vars:
    comment: '# added by ansible'
  lineinfile:
    dest: /etc/hosts
    regexp: ".* {{ item }} {{ comment }}"
    line: "{{ hostvars[item]['ansible_env'].SSH_CONNECTION.split(' ')[2] }} {{ item }} {{ comment }}"
    state: present
    backup: yes
  when: ansible_hostname != item
  loop: "{{ query('inventory_hostnames', 'all') }}"

Answer: In Ansible2.5 this is a working solution and I have used ansible_env.SSH_CONNECTION variable to get the remote server ip and ansible_host is not defined in the gathered facts.
- name: Update the /etc/hosts file with node name
      tags: etchostsupdate
      become: yes
      become_user: root
      lineinfile:
        path: "/etc/hosts"
        regexp: "{{ hostvars[item]['ansible_env'].SSH_CONNECTION.split(' ')[2] }}\t{{ hostvars[item]['ansible_hostname']}}\t{{ hostvars[item]['ansible_hostname']}}"
        line: "{{ hostvars[item]['ansible_env'].SSH_CONNECTION.split(' ')[2] }}\t{{ hostvars[item]['ansible_hostname']}}\t{{ hostvars[item]['ansible_hostname']}}"
        state: present
        backup: yes
      register: etchostsupdate
      when: ansible_hostname != "{{ item }}"
      with_items: "{{groups['app']}}"

Comment: why are you duplicating `hostvars[item]['ansible_hostname']`?
Comment: also you need to remove `hostvars[item]['ansible_env'].SSH_CONNECTION.split(' ')[2]` from `regexp` section in order to handle ip changes
Answer: An addition to all the other great answers:
---
- name: test
  hosts: all
  tasks:
  - name: generate file
    blockinfile:
      backup: yes
      path: /etc/hosts
      block: |
        {% for host in groups['all'] %}
        {{ hostvars[host]['ansible_facts']['eth1']['ipv4']['address'] }} {{ hostvars[host]['ansible_facts']['fqdn'] }} {{ hostvars[host]['ansible_facts']['hostname'] }}
        {% endfor %}

You should change the nic name in hostvars[host]['ansible_facts']['eth1']['ipv4']['address'] according to your available nics. Also this is valid assuming your nic names are uniformly distributed accross your environment.
Answer: The solution from Basil A is quite flexible, but it can leave redundant entries if you make hostname changes or remove hosts from inventory. For this reason, I created a slightly refined version of the solution by Vipul HK, using blockinfile instead of lineinfile:
- name: Add Ansible inventory mappings to /etc/hosts
  become: true
  blockinfile:
    path: /etc/hosts
    block: |
      {% for host in groups['all'] %}
      {{ hostvars[host].ansible_host }} {{ host }}
      {% endfor %}

This solution ensures that the host mappings in /etc/hosts always matches the ones in the inventory file.
Answer: Building on @arkantos' answer. If you have multiple network interfaces and want to fine tune which IPs you add, then you should do the following:
In your inventory file, further add a hv_net_ife for the interface you want to use. I also add for hv_hostname since I use it elsewhere to set the hostname of the machine.
[master]
xxx.xxx.xxx.xxx hv_hostname="controller-node" hv_net_ife="enp7s0"

[node]
xxx.xxx.xxx.xxx hv_hostname="staging-node" hv_net_ife="ens10"
xxx.xxx.xxx.xxx hv_hostname="prod-node" hv_net_ife="ens10"

- name: Add the IP addresses of all hosts to each other
  ansible.builtin.lineinfile:
    dest: '/etc/hosts'
    regexp: ".*\t{{ hostvars[item]['ansible_hostname'] }}\t{{ hostvars[item]['ansible_hostname'] }}"
    line: "{{ hostvars[item]['ansible_' + hv_net_ife]['ipv4']['address'] }}\t{{ hostvars[item]['hv_hostname'] }}"
    state: present
    backup: true
  when:
    - hostvars[item]['ansible_' + hv_net_ife] is defined
    - hostvars[item]['ansible_hostname'] != hv_hostname
  with_items: '{{ groups.all }}'

For example, this was very useful since I created two virtual machines as part of the same private network (they both use the NIC ens10) but then I added another one. My cloud provider decided to give it enp7s0 so I had to scratch my head a little to get it to work.
Oh also you need the when condition - hostvars[item]['ansible_' + hv_net_ife] is defined else you will get an error since Ansible tries to look for all interfaces.


Atualizar JTable após cada alteração de dados em uma célula

Question: Estou usando java swing onde tenho uma janela e nela uma JTable.
Executo um método onde lerá os dados desta Jtable e atualizará uma coluna, célula a célula, desta Jtable. O problema é que ele executa o método normalmente,rodando o looping, mas atualiza a coluna(todas as células) somente no final. Gostaria que atualizasse a célula linha a linha e não tudo somente no final.
Segue código:
 private void BtnEnviarActionPerformed(java.awt.event.ActionEvent evt) {

        SMSMultiploBean smsb = new SMSMultiploBean();
        SMSMultiploDAO smsd = new SMSMultiploDAO();

        int i;
        int linha = 0;
        int totenviados = 0;

        for(i = 0;i<TblDadosSMS.getModel().getRowCount();i++){

            smsb.setDdd((String) TblDadosSMS.getValueAt(linha, 4));
            smsb.setTelefone((String) TblDadosSMS.getValueAt(linha, 5));
            smsb.setMensagem((String) TblDadosSMS.getValueAt(linha, 6));
            smsb.setLinha((int)TblDadosSMS.getValueAt(linha,8));

            Date data= JData.getDate();
            Format ff = new SimpleDateFormat("ddMMyyyy");
            String datastring = ff.format(data);

            smsb.setData(datastring);

                try {

                    String retorno = smsd.EnviaSms(smsb);

                     //retorno falando se o SMS foi enviado ou não

                    TblDadosSMS.setValueAt(retorno, i, 7);

                    //TblDadosSMS.firePropertyChange(retorno, i, i);

                    Pbar.setMinimum(0);
                    Pbar.setMaximum(Integer.parseInt((LblTotal.getText())));
                    Pbar.setValue(i+1);

                    if (retorno.equals("Enviado")){
                      totenviados += 1;
                      LblEnviados.setText(Integer.toString(totenviados));
                    }

                 } catch (Exception ex) {
                     Logger.getLogger(FrmSMSSimultaneo.class.getName()).log(Level.SEVERE, null, ex);
                     JOptionPane.showMessageDialog(this, "Erro: "+ex);
                 }
                     linha++;

       }

    }

Janela antes de executar o método:

Janela depois de executar o código:

Segue abaixo código para popular tabela:
private void CarregaDadosPlanilha() throws SQLException, IOException, ParseException, Exception {

    ExcelBean eb = new ExcelBean();
    ExcelDao ed = new ExcelDao();

    //data convertida para String
    Date data = JData.getDate();
    SimpleDateFormat formatador = new SimpleDateFormat("dd/MM/yyyy");
    String novadata = formatador.format(data);

    //conversão String para date
    String texto = novadata;
    String formato = "dd/MM/yyyy";
    Date dataobjeto = new SimpleDateFormat(formato).parse(texto);

    //System.out.println("Data tratada date: "+dataobjeto);

    eb.setData(dataobjeto);

    List<ExcelBean> ListaDadosPlanilha = new ArrayList<ExcelBean>();

           // ListaDadosPlanilha = ed.CarregaExcel(eb);
     ListaDadosPlanilha = ed.LeExcel(eb);

            DefaultTableModel tbm = (DefaultTableModel) TblDadosSMS.getModel();

            //zera as linhas da tabela
            for (int i = tbm.getRowCount() - 1; i >= 0; i--) {
                tbm.removeRow(i);
            }
            int i = TblDadosSMS.getRowCount();
            /*
             * preenche a tabela
             */
               for (ExcelBean eb2 : ListaDadosPlanilha) {
                tbm.addRow(new String[1]);

                TblDadosSMS.setValueAt(eb2.getNome(), i, 0);
                TblDadosSMS.setValueAt(eb2.getServico(), i, 1);

                //data convertida para String
                Date dataexcel = JData.getDate();
                SimpleDateFormat f = new SimpleDateFormat("dd/MM/yyyy");
                String datastring = f.format(dataexcel);

                TblDadosSMS.setValueAt(datastring, i, 2);
                TblDadosSMS.setValueAt(eb2.getHorario(), i, 3);
                TblDadosSMS.setValueAt(eb2.getDdd(), i, 4);
                TblDadosSMS.setValueAt(eb2.getTelefone(), i, 5);

                eb2.setMensagem("Prezado(a): "+eb2.getNome()+
                    " , nao se esqueca que tem o servico: "+eb2.getServico()+" marcado para: "+novadata+
                    " as: "+eb2.getHorario());

                TblDadosSMS.setValueAt(eb2.getMensagem(), i, 6);

                TblDadosSMS.setValueAt(eb2.getLinha(),i,8);

                System.out.println("Linha célula form: "+eb2.getLinha());

              //System.out.println("linha jtable: "+eb2.getLinha());

                i++;
            }

               LblTotal.setText(Integer.toString(tbm.getRowCount()));
}

Comment: Você está usando um TableModel próprio ou está usando defaultTableModel nessa tabela?
Comment: Rodrigo, quando você criar uma pergunta e precisar complementar ela, clique em [edit] na pergunta e adicione diretamente as informações nela. O campo abaixo é para respostas.
Comment: Desculpe Diego, ainda estou pegando o jeito.
Comment: Desculpe pela intromissão, mas você já tentou utilizar um método que envia um por um, lendo esse um em seguida após a alteração e deixar automaticamente alterar (update) de um segundo método e assim sucessivamente até terminar todos?
Answer: Isso acontece porque você está executando o loop e incrementando o progresso dentro do Event Dispatch Thread(EDT),  e essa Thread vai executar todo o código que estiver nela antes de atualizar o container(JFrame, Jpanel, etc) e seus componentes.
Para atualizar a tabela e o progresso a cada linha, você precisa a atualizar o TableModel em uma Thread paralela, e a melhor forma de fazer isso junto com a EDT é usando SwingWorker.
Elaborei um exemplo simples somente pra demonstrar o funcionamento do SwingWorker com a EDT, está comentado os principais trechos referente ao funcionamento do progresso:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.table.*;
import java.util.List;

public class ProgressWithSwingWorker extends JFrame {

    private JButton btnChecar;
    private JProgressBar progressBar;
    private JScrollPane ScrollPane;
    private JTable tabela;

    public ProgressWithSwingWorker() {
        initComponents();
    }

    private void initComponents() {

        ScrollPane = new JScrollPane();
        btnChecar = new JButton();
        progressBar = new JProgressBar();

        String[] columns = {"coluna 1", "coluna 2", "coluna 3", "coluna 4"};
        Object[][] data = new Object[][]{
            {null, null, null, null},
            {null, null, null, null},
            {null, null, null, null},
            {null, null, null, null},
            {null, null, null, null},
            {null, null, null, null}
        };

        DefaultTableModel model = new DefaultTableModel(data, columns) {
            @Override
            public Class<?> getColumnClass(int columnIndex) {
                if (columnIndex == 3) {
                    return Boolean.class;
                } else {
                    return super.getColumnClass(columnIndex);
                }
            }
        };

        tabela = new JTable(model);

        ScrollPane.setViewportView(tabela);
        btnChecar.setText("Checar");
        //A "mágica" acontece na classe ChecarComSwingWorker
        btnChecar.addActionListener(new ChecarComSwingWorker());

        this.setLayout(new BorderLayout());
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.add(ScrollPane, BorderLayout.NORTH);
        this.add(btnChecar, BorderLayout.CENTER);
        this.add(progressBar, BorderLayout.SOUTH);

        pack();
    }

    public static void main(String args[]) {

        EventQueue.invokeLater(() -> new ProgressWithSwingWorker().setVisible(true));
    }

    class ChecarComSwingWorker implements ActionListener {

        @Override
        public void actionPerformed(ActionEvent e) {

            final int totalRows = tabela.getModel().getRowCount();
            progressBar.setMaximum(totalRows);
            progressBar.setMinimum(0);
            //passei parametros para facilitar o entendimento
            //- o primeiro é o retorno do doInBackground(não foi necessario uso neste exemplo)
            //- o segundo é o tipo do valor usado entre o publish e o process
            SwingWorker<Object, Integer> worker = new SwingWorker<Object, Integer>() {

                //este método é que executa em uma Thread paralela
                //todo processamento pesado que deve ser executado
                //fora da EDT, deve ser executado aqui
                @Override
                protected Object doInBackground() {
                    for (int i = 0; i < totalRows; i++) {
                        try {
                            Boolean status = (Boolean) tabela.getModel().getValueAt(i, 3);
                            status = status == null ? true : !status;
                            tabela.getModel().setValueAt(status, i, 3);
                            //este método é que atualiza a barra de progresso
                            //passando cada iteração para o método process
                            publish(i);
                            Thread.sleep(400);
                        } catch (Exception ex) {
                            ex.printStackTrace();
                        }
                    }
                    return null;
                }

                //este método é que recebe o que é passado no publish
                //e atualiza a barra de progresso na EDT
                @Override
                protected void process(List<Integer> chunks) {
                    int valueRecent = chunks.get(chunks.size() - 1);
                    progressBar.setValue(valueRecent + 1);
                }

                //só é executado quando o doInBackground termina
                //o processamento
                @Override
                protected void done() {
                    progressBar.setValue(0);
                }
            };

            worker.execute();
        }
    }
}

E o resultado é:

Segue abaixo alguns links relativos ao uso do SwingWorker:
11.5 - Dificuldades com Threads e concorrência - Caelum
Trabalhando com SwingWorker em Java - DevMedia
Capturar exceções na execução do swingworker
Passar a execução de um determinado método para outro como argumento
Comment: Diego, ao escrever TblDadosSMS.getModel().fireTableDataChanged(); o NETBEANS identifica como erro.  Estou usando estas bibliotecas  "import javax.swing.table.AbstractTableModel;
import javax.swing.table.DefaultTableModel;"
Comment: segui o tutorial do devmedia e funcionou perfeitamente. Obrigado. Problema resolvido
Comment: @RodrigoStortideOliveira se a resposta lhe ajudou, seria interessante marcá-la como aceita, assim,servirá de referencia para outros usuarios. :)


C# Sentiment Analysis

Question: Does anyone know of a (preferably open source) C# library that can be implemented to calculate the overall sentiment of some given text?
Answer: Take a look at an open source sentiment analysis engine based on Naive Bayes classification at https://github.com/amrishdeep/Dragon.
Comment: did  you use it in real world? do you know best getting started - *step by step guide* about it?
Answer: http://rapid-i.com/content/view/26/84/
maybe not c# but I guess you can call it from c#, will it does the job for you?
Comment: did  you use it in real world? do you know **best getting started** - *step by step guide* about it?

C# Sentiment Analysis


Nested radical and rationality

Question: I did not found it on the forum so :
$$S=\sqrt{1+\frac{1}{2}\sqrt{1+\frac{1}{2^2}\sqrt{1+\frac{1}{2^3}\sqrt{1+\frac{1}{2^4}\sqrt{\cdots}}}}}=1.25$$
I try to denested the radical but I'm really stuck to get wich follows .
Maybe a generalization could be give the result.
Furhtermore I have a question is 2 the only number such that :
$$\sqrt{1+\frac{1}{k}\sqrt{1+\frac{1}{k^2}\sqrt{1+\frac{1}{k^3}\sqrt{1+\frac{1}{k^4}\sqrt{\cdots}}}}}$$
is rational ?
Where $k\geq 2$ is a natural number
Thanks a lot for your answer and your time .
Comment: I can see this generalization only:
$$\sqrt{1+x\sqrt{1+\frac{x}{2}\sqrt{1+\frac{x}{2^2}\sqrt{1+\frac{x}{2^3}\sqrt{\cdots}}}}}=1 + \dfrac{x}{2}.$$
Comment: Wonder if we could generalise it for $x/n$
Answer: Consider the unique power series in $\,t\,$ that satisfies
$$ f(t,q) = \sqrt{1 + tf(t\,q,q)}. \tag{1} $$
We can express it as a continued square root
$$ f(t,q) = \sqrt{1 + t\sqrt{1 + t\,q\sqrt{1 +
t\,q^2 \cdots}}}. \tag{2} $$
The first few terms are
$$ f(t,q) \!=\! 1 \!+\! (1/2)\,t^2 \!+\!
 (-1/8\!+\!1/4q)\,t^3 \!+\! \\
(1/16q\!-\!1/8q\!-\!1/16q^2\!+\!1/8q^3)\,t^4
 \!+ \cdots .\tag{3} $$
A special case closed form formula is
$$ f(1/2^n,1/2)=1+2^{-(n+1)}, \tag{4} $$
proven by induction using equation $(1)$ and the
identity $$(1 + r/2) = \sqrt{1 + r(1 + r/4)}\;\;
\text{ where } \;\; r = 2^{-n}. \tag{5} $$
The question asked about
$\,f(\frac12,\frac12) = \frac54\,$ using equation $(4)$
with $\,n=1.$
NOTE: In equation $(2)$ the continued square root is
the limit of a sequence
$$ x,\; \sqrt{1\!+\!t\,x},\;
 \sqrt{1\!+\!t\sqrt{1\!+\!t\,q\,x}},\;
 \sqrt{1\!+\!t\sqrt{1\!+\!t\,q\sqrt{1\!+\!t\,q^2x}}},\;\cdots $$
which converges at least for
non-negative $\,t,q,x\,$ which needs some kind
of proof in general.
Comment: Well by Vigaraghavan's take on the Herschfeld's theorem, we have, $\sqrt{a_0+\sqrt{a_1+\sqrt{a_2+...}}}$ converges if and only if $$\lim_{x\rightarrow \infty}\frac{\log{a_n}}{2^n}<\infty$$ Then using this to check out the convergence for Eq $2$, we get the radical converges iff, $$2(\log(t)+\log(q))<\infty$$$$=\log(tq)<\infty$$. So as long as $q,t$ are both finite quantities, the radical will surely converge.
Comment: Do we have to worry about convergence in equation (2) (since we have infinitely many terms)?
Comment: @rzkrd Thanks for that helpful comment! I knew that there was a theorem about continued square roots such as this.

Nested radical and rationality


Perturbation Problem (ODE)

Question:
Need answers to question 5a(iv), I'm confused whether it is regular perturbation or singular perturbation.
Also, 5b also.
Thank you.
Answer: If setting $\epsilon=0$ changes the character of the equation, then it is a singular perturbation. Thus a(iv) is singular, the order of the ODE changes from 2 to 1, while (iii) is regular, the ODE stays at order 2.
for b) one would need to know what techniques you know of. You can solve this via characteristic polynomial, via inner and outer solutions, via WKB approximation,...
The boundary layer is at $x=0$, the outer solution is $e^{(x-1)/2}$ which has value $e^{-1/2}$ at $x=0$, the inner solution would have to deliver this jump, the proposed formula does not seem to give that,...
Comment: Thanks a lot @Lutz Lehmann

Perturbation Problem (ODE)


Sticks moving in my hands (weak grip?)

Question: I've been playing drums for a while and there's something bothering me. I've watched a lot of "how to hold your drumsticks properly" videos for the 'matched grip' style (the one i use) to try to improve my 'matched grip'. I try to be relaxed and not apply too much force when holding my drumsticks, but when I start to play a little bit faster, they start to move in my hands. My thumb and index finger are being used to find the fulcrum point but from time to time I have to move my index finger to find the fulcrum point again.
Do I have to put more force when I'm holding my sticks? I've watched a lot of videos on YouTube but they seem all the same to me when it comes do the matched grip. I've tried the traditional grip too. Should I invest more time and effort on improving it?
Answer: There is some certain uncertainty that makes it difficult to answer this question. The easiest solution would be to record yourself while speeding on a practice pad.
I had a similar problem when I was a beginner and the problem was that I tend to make a rotation and some forward translation while I was hitting the drums. The net effect of course is that stick gains some momentum forward and tends to slip out of your hand.
So you need to make sure that your index finger is not slipping under your thumb which creates a forward motion. The idea of a fulcrum point is to make the stick bounce in a steady motion such that you can bring it back (in theory by just applying some torque with your grip fingers)
I recommend anything JoJo Mayer says :) Especially, the Moeller technique description should clarify your concerns and pay attention for an alternative fulcrum grip with two middle fingers.

Speaking of who, use Jim Chapin's books. They have been very useful to me.
Comment: Hmm....that's really different...I've only known the fulcrum point with the thumb and index finger...i'll definitely check this out at home...

But could you explain what you said before? About the "rotation and foward translation"? And which Jim Chapin books do you recommend? I'm really inexperienced when it comes to drum theory and techniques...are they too complex?
Comment: @JoaoVictor Suppose you are holding with index and thumb only. Then you perform a hit movement by pushing your thumb forward and your index finger slides below the thumb. Do it without holding a stick, you'll see what I mean. If that is performed incorrectly the thumb pushes the stick forward sliding over the index finger. So in the next stroke you will be holding the stick at a slightly further point to the butt of the stick. Is that a little clearer?
Answer: Drum sticks are basically 'sticks'!!!! Instructing new students in the Art of Stick Fighting, I find that new students most often act as though a 'stick' is a 'club' - They hang on to it like there is no tomorrow and bang it against your stick as hard as they can. After you explain to them that your stick is there to help them, and that there really is no need to flog it unmercifully, they begin to relax. Tension is usually equated with power, speed, or force. This is an unfortunate assumption.If you are more relaxed you will have more speed. If you are relaxed you will have more control. If you are relaxed you will have more accuracy. If you are relaxed you will have more energy, and power. The phrase 'float like a butterfly, sting like a bee' comes to mind. You only need the power at the moment of the 'strike'. With drum 'sticks', we need to learn that if you allow it, the 'stick' will bounce up again without you doing anything other than initiating the first 'strike'. The art is in controlling the bounce by not stifling it. Let the 'stick' do the work. Allow the wrist to do what it does naturally. Do not grip the 'stick'. Do not let it go. The 'stick'must be able to move, that's what 'sticks' do. You have but to guide, and thus control it's action.
Answer: it happens to the best (Here Joe Morello loses it at about 3:30 and you have to actually watch the video to notice).  Of course the stick will not stay put: with time you'll learn how to make it creep back to where it belongs.
The actual fulcrum the stick rotates around shifts when holding/moving your thumb differently and depending on just how you move your wrist, so you can let it "overtake" the center of weight of the stick if that is in danger of "escaping".  Once this becomes semiautomatic, most of the creep will be in check without requiring conscious/explicit action.  And earlier than that you'll notice in time for clawing it back.
Of course, this does not protect against an accidental jerk or fumble.  But even if you aren't blind like Morello, you'll have to just sense where your stick is at without looking.
Answer: It's ok if the stick moves. It's supposed to. What you are experiencing is called "Stick Creep" We all get it. Over time you learn to make little mico adjustments. I saw Tommy Igoe say If your stick is not moving you are griping too hard. He demonstrated in a constent flow of 1/8 notes with his right hand how the stick actually rotates in his hands. Meaning the "logo" of the stick spins.
Answer: The best advice I had as I begining to play drums is to grab well the sticks between thumb and index finger. It should be a good gripper that allows the stick to move while holding it and letting other fingers push it.
Practice and relearn all you know while doing this. Bounce the sticks, do singles, doubles, play with only one hand, everything counts.
Check out this other answer of mine, about drum hand technique. With a lot of information and videos.
Answer: If you can not simply look down and see sticks rotating slowly in your hand as you play, you are not holding them correctly.

Sticks moving in my hands (weak grip?)


How does cardinality map a finite set to $(\{0\} \cup \mathbb{N})$?

Question: In reading Kevin Houston's "How to Think Like a Mathematician", there's a line stating the following:
Let $X$ be the set of finite sets. Then the cardinality of a set is a function on $X$, that is $|.|: X \to \{0\} \cup \mathbb{N}$. Note that we need $0$ in the co-domain as the set could be the empty set.
What does this mean exactly? From my understanding, this would imply that any finite set is mapped exactly to one natural number. For example, a finite set of $5$ elements would be mapped to the natural number $5$. However, is it possible to map the set itself to a value?
Comment: Unless I'm mistaken, $0 \in \mathbb N$, so $\{0\} \cup \mathbb N = \mathbb N$.
Comment: @eyeballfrog that's a matter of convention/definition.
Comment: @eyeballfrog Whatever $0\in \mathbb{N}$ or not is debatable. [See this post about it](https://math.stackexchange.com/questions/283/is-0-a-natural-number)
Comment: @eyeballfrog If $0$ was natural then why isn't there a Roman numeral for it?
Comment: @eyeballfrog: See [this answer of mine](https://math.stackexchange.com/a/1029623/1508) from four years ago:-)
Comment: Yes. In this case the elements of $X$ are sets so a function on $X$ maps those members of $X$ to values. You could even have a set of functions as your domain and map those to individual values.
Answer: It means what you think it means.
The domain of definition for this function is the "set of all finite sets".
Thus every element here is a "finite set".
Consider for a simpler example: $A=\{\{1,2\}, \{1,2,3\},\{5,7,8,12\}\}$
This is a set whose elements are the sets $\{1,2\}$ and $\{1,2,3\}$ and $\{5,7,8,12\}$.
If you define a function on $A$ then you assign a value to each of $\{1,2\}$ and $\{1,2,3\}$ and $\{5,7,8,12\}$  yet not to $1,2,3, 5,7,8,12$.
Tangential remark: there is a problem with the idea of a set of all finite sets, but this is not relevant in this context.
Comment: The function is defined as assigning to $\{1,2\}$ the number of elements in it, that is $2$. And for $\{5,7,8,12\}$ it would be $4$. To ask for the number of elements in the number $13$ does  not make sense, thus the function you consider is defined for sets only.
Comment: But then how would you infer the cardinality of the set from that? What "number" is assigned to each of {$1,2$} etc.?
Answer: You understood wrong. According to this definition, any finite set is mapped exactly to a set whose cardinality is a natural number or zero.
Comment: @Jakobian sure, and the set of all finite sets does not even exist. Please, don't confuse the poster. In any case the definition in OP has as image the natural numbers. (And of course we can consider a natural number as a set, but that's besides the point here.)
Comment: That seems incorrect to me.
Comment: The above comment or my understanding? If that's true, then what does the above mentioned statement imply about the elements in the set that $X$ is being mapped to?
Comment: @quid Every cardinal number is a set.
Answer: For every finite set, its function value is its cardinality.
So $\{1,2,3\}$ is mapped to $3$ just as $\{2,4,8\}$ is, as both have the same cardinality $3$. $\emptyset$ is mapped to $0$ (as the only set with that property).
I don't quite see what the problem is: there is a class of all finite sets and we can define a function with those sets as input.
Comment: You don't see the problem because you probably don't remember not knowing this. Anya is a beginner who was taught that functions map elements from one set to another. Anya has probably never considered how complex those sets can be.
Comment: @JohnDouma a set of sets is perfectly valid. I was taught that at age 13 in high school..
Comment: That's my point. You have known this for a long time and this is easy for you. It is easy for me too, but not for everyone.


AbstractMethodError when overriding a Java method with vararg parameter from Scala

Question: I need to override a Java method from a Java interface which makes use of a vararg parameter:
public interface Function<T> {
    T apply(Object... var1);
}

When I try to implement the method apply in Scala like follows
class ScalaFunction extends Function[String] {

  override def apply(args: Object*): String = args.toList match {
    // impl
  }

}

I get a "java.lang.AbstractMethodError: null" error during run-time.
This is what I already tried:

using @varargs args Scala annotation which should generate a Java-friendly delegate method => resulted in the same error
using a self-provided delegate method
def apply(args: Array[Object]): Unit = apply(args: _*)
which was actually successfully called, but I'm not able to use    String as return type because then the compiler yields a

Error:(13, 7) double definition: def apply(args: Array[Object]):
  String at line 20 and override def apply(args: AnyRef*): String at
  line 13 have same type after erasure: (args: Array[Object])String

The calling Java code looks like this:
Object[] args = //...
Object returnValue = function.apply(args);

Any ideas?
See this Gist for an example: https://gist.github.com/mrueegg/f191e547bee6a24a6bcf
Thanks,
Michael
Comment: No solution (sorry) but have you tried getting your IDE to override the method for you? I would imagine it's a standard process and they should do it correctly for you.
Comment: That looks like a bug to me.
Comment: IntelliJ suggests override def apply(objects: AnyRef*): String = ??? which is what I already have...
Comment: Can't reproduce this on Scala 2.11.6 - what version are you on?
Comment: Sorry, forgot to mention that: Scala 2.11.7
Comment: did you use the interface type (Function) to call apply or the implementation (ScalaFunction)?
Comment: "using a self-provided delegate method" you could just give it a different name.
Comment: I don't think so. Because that is the method that is called by function.apply(args) above. Or am I overlooking something?
Answer: This issue. I haven't followed it closely, but maybe someone wants to add info.
Comment: Thanks, this must be the right issue I think. By the way, with my Gist from above I was able to verify that it worked with Scala 2.10.4 while I now get a java.lang.AbstractMethodError with Scala 2.11.7!
Comment: I'd at least comment on the ticket with the test case. Or maybe ask on gitter.


How to modify local variable within Invoke-Command

Question: I am trying to modify a variable within Invoke-Command in order to get out of a loop, however I'm having trouble doing that.
In the sample script below, I'm connecting to a host, grabbing information from NICs that are Up and saving the output to a file (Baseline). Then on my next iteration I will keep grabbing the same info and then compare Test file to Baseline file.
From a different shell, I've connected to the same server and disabled one of the NICs to force Compare-Object to find a difference.
Once a difference is found, I need to get out of the loop, however I cannot find a way to update the local variable $test_condition. I've tried multiple things, from Break, Return,  $variable:global, $variable:script, but nothing worked so far.
$hostname = "server1"
$test_condition = $false

    do {
        Invoke-Command -ComputerName $hostname -Credential $credential -ScriptBlock{

            $path = Test-Path -LiteralPath C:\Temp\"network_list_$using:hostname-Baseline.txt"

            if ($path -eq $false) {
                Get-NetAdapter | Where-Object Status -EQ "Up"  | Out-File -FilePath (New-Item C:\Temp\"network_list_$using:hostname-Baseline.txt" -Force)

            } else {
                Get-NetAdapter | Where-Object Status -EQ "Up" | Out-File -FilePath C:\Temp\"network_list_$using:hostname-Test.txt"
                $objects = @{
                    ReferenceObject = (Get-Content C:\Temp\"network_list_$using:hostname-Baseline.txt")
                    DifferenceObject = (Get-Content C:\Temp\"network_list_$using:hostname-Test.txt")
                    }
                $test_condition = (Compare-Object @objects).SideIndicator -ccontains "<="
                $test_condition #this is returning True <-----

            }

        }
    } until ($test_condition -eq $true)

Any tips? What am I doing wrong?
TIA,
ftex
Comment: Try adding this `$test_condition = Invoke-Command -C........`, your invocation is returning a boolean to stdout, you need to capture it in the variable to test it against the `until (....)` condition
Comment: Thanks @SantiagoSquarzon. It worked. I appreciate the help.
Comment: No problem :) Steven did all the hard work tho, thank him
Answer: You can pass variables into a remote script block with the $Using:VarName scope modifier, but you can't use typical $Global: or $Script to modify anything in the calling scope.  In this scenario the calling scope isn't the parent scope.  The code is technically running in a new session on the remote system and $Global: would refer to that session's global scope.
For example:
$var = "something"
Invoke-Command -ComputerName MyComuter -ScriptBlock { $Global:var = "else"; $var}

The remote session will output "else". However, after return in the calling session $var will output "something" remaining unchanged despite the assignment in the remote session.
Based on @SantiagoSquarzon's comment place the assignment inside the Do loop with a few other modifications:
$hostname = "server1"

do {
    $test_condition = $false
    $test_condition =
    Invoke-Command -ComputerName $hostname -Credential $credential -ScriptBlock{

        $path = Test-Path -LiteralPath C:\Temp\"network_list_$using:hostname-Baseline.txt"

        if ($path -eq $false) {
            Get-NetAdapter | Where-Object Status -eq "Up"  | Out-File -FilePath (New-Item C:\Temp\"network_list_$using:hostname-Baseline.txt" -Force)

        } else {
            Get-NetAdapter | Where-Object Status -eq "Up" | Out-File -FilePath C:\Temp\"network_list_$using:hostname-Test.txt"
            $objects = @{
                ReferenceObject = (Get-Content C:\Temp\"network_list_$using:hostname-Baseline.txt")
                DifferenceObject = (Get-Content C:\Temp\"network_list_$using:hostname-Test.txt")
                }

            (Compare-Object @objects).SideIndicator -contains "<=" # this is returning True <-----
        }

    }
} until ($test_condition -eq $true)

I don't know why you were using -ccontains considering "<=" has no casing implications.  Also it's very unusual to capitalize operators.
Notice there's no explicit return or assignment.  PowerShell will emit the Boolean result of the comparison and that will be returned from the remote session and end up assigned to the $test_condition variable.
An aside:
I'm not sure why we want to use -contains at all.  Admittedly it'll work fine in this case, however, it may lead you astray elsewhere. -contains is a collection containment operator and not really meant for testing the presence of one string within another. The literal meaning of "contains" makes for an implicitly attractive hazard, as demonstrated in this recent question.
In short it's easy to confuse the meaning, purpose and behavior on -contains.
This "<=" -contains "<=" will return "true" as expected, however "<==" -contains "<=" will return "false" even though the left string literally does contain the right string.
The answer, to the aforementioned question says much the same. My addendum answer offers a some additional insight for the particular problem and how different operators can be circumstantially applied.
So, as a matter of practice for this case wrap the Compare-Object command in the array sub-expression operator like:
@( (Compare-Object @objects).SideIndicator ) -contains "<="

Given the particulars, this strikes me as the least intrusive way to implement such a loosely stated best practice.
Comment: Yep, great answer as always. I'm so not used to `Compare-Object` honestly, never find a good use case for it vs a more classic approach, maybe i'm too old lol. I would recommend OP using a `PSSession` for this use case too and `-Session` instead of `-ComputerName` on `icm`.
Comment: Thanks! Yes now that you mention it, as written amd considering it's a loop we should indeed use a PSSession.  Moreover, we should probably introduce a `Start-Sleep` command.  However, It doesn't look like there's a good reason to outside `Invoke-Command`, instead we could probably move it in to the script block.  That would diminish the case for PSSessions, not having to setup/teardown repeatedly.  I think I'll wait for comment before amending.
Comment: Nicely done; note that you never need `@(...)` in order to use `-contains` - even a _scalar_ LHS will do; e.g.; `1 -contains 1` works just fine.
Comment: @mklement0 Thanks. I edited the answer, hopefully to better convey the intended message.  I included a recent question that shows what I think is a common point of confusion with the `-contains` operator. In any event, your feedback is always welcomed; do let me know what you think.
Comment: Thanks for updating, Steven (you already had my +1). I assume you're saying that use of `@(...)` with `-contains` isn't a _technical_ necessity but _signals to the reader_ that the LHS of `-contains` is a _collection_ operator. However, even `-match` and `-like` can situationally act like collection operators, namely if the LHS is a collection, whereas `-contains` always acts _always_ treats its LHS as a collection. To me, the `@(...)` therefore suggests the opposite of what you're trying to convey, namely that _situationally_ `@(...)` is necessary - which it isn't.
Comment: Also note that with _expression_ output such as `(Compare-Object @objects).SideIndicator` (member enumeration on a command's outptut), `@(...)` results in (in this case unnecessary) construction of an _additional_, always `[object[]]`-typed array. Try `@([int[]] (1..5)).GetType().Name`, for instance.
Comment: Your interpretation of my intent is correct.  However, now I'm genuinely concerned I may be sending the wrong message.  I did talk about the situational behavior of other operators in the the referenced answer.  And, I struggled with if I should expound on them here as well.  Note: I had already double checked the enumeration, and `(Compare-Object $array $array2).SideIndicator.GetType()` where `$array` has exactly 1 element more `$array2` returns a string not `[Object[]]`.  This was consistent across 5.1 & 7.1.3...
Comment: Only just happened to see this, @Steven. On a meta note: you as the post owner are automatically notified of follow-up comments, but in the absence of @-mentioning commenters, they aren't notified of your responses. The exact notification rules are complex, and I wish that the site showed you _who will be notified_ before submitting a comment (there is a hard limit on only being able to @-mention _one_ user).
Comment: Yes, the `.GetType()` behavior is as expected, but my point was that `@() -contains ` and ` -contains ` are _equivalent_, so that bringing `@(...)` into the mix may cause confusion.
Comment: A follow-up to the meta conversation:
A who-will-be-notified preview feature was requested in 2011(!) in https://meta.stackexchange.com/questions/99261/tell-the-user-who-will-be-notified-of-a-comment, but the feature never materialized.
Comment: Thanks @Steven for your help and everyone involved in this thread. I do appreciate it.

PS: The -ccontains was a mistake of mine, part of a tab complete. I was looking for -contains only.


Shedding two toms and still sound the same?

Question: At some stage after the conclusion of the tour to support the Black Album Lars Ulrich shed two toms from his kit. I'm referring to the toms at chest level not the two floor toms which I think he's retained.
The question is how can you do this and still sound the same? Surely there are pre-existing songs that demand the use of these (now missing) toms?
Comment: Took me a moment to realize "shed" meant "remove" and not "[woodshed](http://en.wiktionary.org/wiki/woodshed#Verb)".
Comment: I came across this video where he explains when, how and why (if anyone's still interested ~6.5 years later) https://youtu.be/uI07pAt34i0
Answer: Very simply, you can't. Unless those two toms were not being used in the first place, which may very well have been Lars Ulrich's reason for shedding them.
But more realistically speaking, it's possible that he simply wanted to create a different sound. Many musicians agree that sometimes you can make your music better by limiting your resources. For instance, arrangers decide which instruments they'll use before starting to arrange a song, and then they'll adapt the song to this limitation they have imposed on themselves.
In drumming, it can be similar. I'm guessing that Lars Ulrich wanted to experiment with a completely different sound, by using a more limited drum kit. Of course, he'll have had to adapt his parts in all songs so that they'd work this way.
If you'd like to hear to what extent you can make a drum kit sound different by removing pieces, I suggest you have a listen to Alt-J's album, called An Awesome Wave. The drummer doesn't have a single cymbal other than the hi-hat, and also makes very limited use of his bass drum. In my personal opinion, it sounds very unique.
Comment: Ulrich's style has changed throughout his career. For the first 4 Metallica albums the style would have been fast, aggressive thrash beats. From the "Black Album" onwards (until Death Magnetic) he appears to have simplified his drum rhythms in order to fit the simplification in Metallica's overall musical style. It still doesn't explain though how, for example, the fill from the intro to Creeping Death from the 1990s live albums (4 toms) can (to my musically unsophisticated ears) still sound the same as the current live performances (2 toms)
Answer: If he went from six to four toms, the simple answer might be that few fills required all six toms, and those that did, didn't utilize them in a significant way. In metal, more is more and that goes double for drummers. Not many drummers with more than 3 or 4 toms utilize all their toms in my experience. Perhaps L. Ulrich came to the same conclusion.
In contrast to metal drummers, jazz drummers have quite stripped down sets, and manage to get a lot of different sounds out of their kits. Four toms are not stripped down (unless you're Neil Peart or Terry Bozzio), and that is likely the reason the shedding is not very noticeable.


How to evaluate ensemble models using independent data

Question: I am creating species distribution models using the popular R package biomod2. I am using biomod2 functionality to create ensemble models. Ensemble models combine individual models based on their weight of evidence (statistical performance).
Traditionally, model averaging or multi-model inference was performed using likelihood techniques (i.e., AIC). More recently, techniques have been developed to average models that are not likelihood based, such as Random Forests. This is accomplished by using cross-validation or split sample validation to assess statistical performance and then combine models using measures of statistical performance like ROC, kappa, TSS, etc.
My question is how can individual models be assessed for statistical accuracy using cross-validation or split sample, then be combined into an ensemble weighted based on performance, and then the ensemble model be assessed for accuracy using cross-validation or split sample again with independent evaluation data? The issue here is that when you create different partitions of calibration and evaluation data to assess the individual models, there ends up not being any independent data left to evaluate the ensemble model.
The only way that I can think that this would work is to use cross-validation and ensemble within runs. Each run of cross-validation would have the same partition of data for all models (i.e., if you were doing 5-fold cross validation on 3 models, in Run 1 the three models would use the same 20% of data as evaluation and 80% as calibration, in Run 2 the three models would use the same 20% of data as evaluation and 80% as calibration, etc.). That way, all three models in each run can be combined, and the resulting ensemble model could be assessed using the same 20% of evaluation data that was used for the individual models.
The issue with this arrangement is that it results in 5 separate models, one for each run of the cross-validation. That isn't a very satisfying result.
Any recommendations for best practices on creating ensemble models and then evaluating them? I realize people are probably going to say a dataset that is truly independent in space and time that is saved for assessment of the final ensemble model. Any alternatives to this for people with data that isn't independent in space and time and small dataset that aren't big enough to have a portion left out for a final evaluation?
Answer: Ensemble learning works as follows:
For each candidate estimator obtain the cross-validated predictions. That is: construct 10 disjoint validation sets, train the estimator 10 times on the training sets, obtain all validation predictions, stack the validation predictions together to obtain a prediction vector for all samples.
Next, one can plug the cross-validated prediction vector of each estimator into risk functions (e.g. least-squares risk) to get an unbiased estimate of performance. Choosing the best one would be cross-validation selection.
Alternatively, one can look at every linear/convex/nonnegative combination of the cross-validated prediction vectors across the estimators. For each combination, you can plug it in the least-squares risk function to obtain an unbiased risk estimate. You can then choose the best linear/convex/nonnegative combination based on these risk estimates. This is equivalent to fitting linear regression/nonnegative least-squares with the cross-validated predictions as covariates/features. This is called stacking.
To evaluate the ensemble learner, one should perform nested/double cross-validation to get a fair risk estimate of the ensemble/stacked learner itself and then compare this risk estimate to the risk estimates of the individual learners/estimators. In other words, treat the ensemble learner as an estimator in-and-of-itself and use (nested) cross-validation to compare it to the non-stacked learners. If you do 10-fold cross-validation then you should have enough data to do the nested cross-validation. Alternatively, you can increase the folds to ~15-20 if you have very little data. Also, using hold-out data to evaluate the ensemble model is a very inefficient method.
For references, google "SuperLearner"
Comment: I have attempted to give you reputation points. Once I reach 15 point you will receive those. The methodology you outlined is very informative. I am going to wait to accept the answer for 1-2 days in hopes of hearing from someone from the biology/ecology field that might have an answer more closely related to species distribution modeling and [tag:biomod2], as the methodology you outlined is quite different than what is typically done in this field.
Comment: No need for that. I am just glad this was helpful!


Fit h1 div Height to Font Size

Question: I edited the font size of my h1 tag, but it looks like the height of the div doesn't automatically fit it:

I tried manually setting the height, but then the div just extends below instead of encasing the text:

Is there any way to make the div fit to the font size?
Here's my css:
h1 {
    background-color: red;/* TEST */

    font-family: Lobster;
    font-size: 66px;
    font-style: normal;
    font-variant: normal;
    font-weight: 500;
    line-height: 26px;
}

Comment: line height 26 on a font size 66 and asking why it won't fit? C'mon ...you had only two things to change and play with in your CSS...
Comment: Maybe he don't understand relation between Line-height and font-size, also the questionable is concept of line height. Don't be hard on him :D
Answer: Set the line-height and font-size to the same value:
font-size: 66px;
line-height: 66px;

Comment: Using `line-height: 66px` will mean that you'll always need to change the `line-height` value according to the `font-size`.By setting `line-height` to 1 though,  you are basically saying the same thing but in a dynamic way, since 1 will be multiplied (based on docs) to the font-size and the result will be the same.

`font-size: 66px; line-height: 1;`
Answer: Change:
h1{
    background-color: red;/* TEST */

    font-family: Lobster;
    font-size: 66px;
    font-style: normal;
    font-variant: normal;
    font-weight: 500;
    line-height: 1;/*Change is here, don't put px at the end*/
}

See if that works for you.

Fit h1 div Height to Font Size


Proving the existence of a detailed balanced stationary distribution

Question:
Consider $$P = \begin{pmatrix}
0 & a & 0 & 1-a\\
1-b & 0 & b & 0\\
0 & 1-c & 0 & c\\
d & 0 & 1-d & 0\\
\end{pmatrix}$$ with $S = \{1,2,3,4\}$, and show that there is a stationary distribution satisfying the detailed balance condition if $$0 < abcd = (1 - a)(1 - b)(1 - c)(1 - d).$$

I know that the detailed balance condition requires $\pi_i p(i,j) = \pi_j p(j,i)$ for all $i, j \in S$. Thus, my initial idea was to rewrite the equality as follows: $$abcd = p(1,2) p(2,3) p(3,4) p(4,1)$$ and $$(1 - a)(1 - b)(1 - c)(1 - d) = p(2,1) p(3,2) p(4,3) p(1,4)$$ However, I'm unsure where to go from this point. I tried thinking about properties of the stationary distribution ($\sum_{i \in S} \pi_i = 1$, $\pi_2 p(1,2) + \pi_3 p(1,3) + \pi_4 p(1,4) = \pi_1$), but have thus far not been able to transform this into the detailed balance condition. Any advice is greatly appreciated!
Answer: We can think of the four states of this Markov chain as being arranged in a cycle. We go clockwise from $i$ to $(i+1)\bmod 4$ with probabilities $a$, $b$, $c$, $d$ respectively, and counterclockwise from $i$ to $(i-1) \bmod 4$ with probabilities $1-a$, $1-b$, $1-c$, $1-d$, respectively.
Any time the detailed balance conditions are satisfied, if we start at one value of $\pi_i$, we can deduce the values of all others connected to it. In this example, we can write down $\pi_2$, $\pi_3$, and $\pi_4$ in terms of $\pi_1$:
\begin{align}
  \pi_1 a = \pi_2 (1-b) &\implies \pi_2 = \frac{a}{1-b} \pi_1 \\
  \pi_2 b = \pi_3 (1-c) &\implies \pi_3 = \frac{b}{1-c} \pi_2 = \frac{ab}{(1-b)(1-c)}\pi_1 \\
  \pi_3 c = \pi_4 (1-d) &\implies \pi_4 = \frac{c}{1-d} \pi_3 = \frac{abc}{(1-b)(1-c)(1-d)}\pi_1.
\end{align}
With just these three equations, which are the detailed balance equations for $(1,2)$, $(2,3)$, and $(3,4)$, we've solved for $\pi_2, \pi_3, \pi_4$ in terms of $\pi_1$.
But there's one more equation we haven't used yet. It says that $\pi_4 d = \pi_1(1-a)$ and since we already know both sides, we can write it as
$$\frac{a b c}{(1-b)(1-c)(1-d)}\pi_1 d = \pi_1 (1-a) \iff a b c d = (1-a)(1-b)(1-c)(1-d).$$
(We canceled $\pi_1$ from both sides, but that's okay: if we had $\pi_1 = 0$ then the equations above would tell us $\pi_2 = \pi_3 = \pi_4 = 0$ as well, which wouldn't be any good.)
In other words, starting with an arbitrary $\pi_1$, we can force detailed balance at $(1,2)$, $(2,3)$, and $(3,4)$ to hold by choosing $\pi_2, \pi_3, \pi_4$ appropriately. (We could now also work out $\pi_1$ by using the fact that $\pi_1 + \pi_2 + \pi_3 + \pi_4 = 1$, but we don't need to.) But we no longer have the freedom to force detailed balance to hold at $(1,4)$, since $\pi_1$ and $\pi_4$ are fixed. We can just hope that the equation turns out to hold anyway, and the above calculation shows that it does hold exactly when $a b c d = (1-a)(1-b)(1-c)(1-d)$.
(Once that's true, we have a solution that satisfies detailed balance, and therefore it must also be a stationary distribution.)
Comment: Interesting - I think I was having trouble getting this logic through my head but you've done a great job in helping me understand. Thank you!


How to improve my technique while learning Yann Tiersen's "Pern"?

Question: I'm a self learner, unfortunately I did not have any lessons. I try to work on scales, keys, articulation, tempo, etc. myself. And I also try to curve my fingers whenever I can.
I can't read notes super-fast yet, but I can sight-read from low to high C, with chords, sharps & flats. I know some music theory, all types of chords, inversions, etc.
In my 2 years experience I was able to memorize and can play the following tracks:

Nuvole Bianche, Ludovico
I love you, RIOPY (still have some trouble)
Angels, Robbie Williams
My Heart Will Go On
Comptine d`un autre ete - Yann Tiersen (still have some trouble)
plus some basic 4-chords songs like The Scientist

All of the above in their original keys and hopefully the correct fingering :)
I've learned a lot from them, especially various left-hand patterns.
Now I'm trying to learn Pern by Yann Tiersen.
I noticed I have 3 problems with my playing right now and I'm looking for some help or guidance that would help me overcome this.

I find it incredibly difficult to play arpeggiated Bflat chord in the left hand (see image below). I don't even know what fingering I should use here. Should I lift the whole hand? It goes like: Bflat -> F -> Bflat -> C (then it goes back) -> Bflat -> F -> Bflat and then it repeats but the highest note is D not C. I've played this pattern in My Heart Will Go On, but not on Bflat. It's incredibly difficult for me to not to accidentally press some keys when "pivoting" on my finger 2 (on the F key).

To add to the above problem in this piece Pern by Yann Tiersen I have to "wait" with the left hand because the tempo in the left hand is twice slower. Im not sure what should I do. Should I keep the keys pressed (pivot on them) or should I lift them and immediately try to jump on the next key?

And lastly, the piece repeats the intro pattern on 2 octaves in the right hand (it just moves to 1 octave higher). I find it really troubling too (same thing happens in his other piece Comptine dun autre ete). The weight of the keys is smaller and my hand just goes crazy and I feel like I have to learn it twice... (but the notes are identical, just the wrist position and the weight of the keys change).

I know this is a broad question, but I'd appreciate any advice on how to improve on the above. I already know half of this piece, it's pretty easy. Just the intro and outro are killing me... :)
Comment: A couple of points come to mind, thus not a complete answer. On an upright or grand piano, the weighting of the keys shouldn't vary by very much at all moving an octave - what piano is it? It should be possible to pedal your way through rather than holding notes - especially if your hands are small. But pedalling is quite a difficult technique to acquire by yourself - a lot of players overpedal, and it all goes muddy. Lessons with a teacher will be a great help.
Answer:
I find it incredibly difficult to play arpeggiated B♭ chord in the left hand.

Notice that in the first three-note grouping, the final note, B♭ is marked staccato. This means that the first grouping can be played 5-2-1 (some might prefer 5-3-1), and then the staccato allows the entire hand to move, since a legato connection to the following C is not necessary.
The same idea holds for the second three-note grouping. Those are marked portato (staccato and tenuto), which means to allow some separation between each note. A fingering of 1-2-5 (or 1-2-4, or even 1-2-1) will work well here, again since a legato connection to the following low B♭ is unnecessary.
B♭ arpeggios can also lead to hand-position problems. Please see this post for tips, particularly the final picture, which shows almost exactly the hand position needed for the beginning of this passage.

Should I keep the keys pressed (pivot on them) or should I lift them and immediately try to jump on the next key?

As indicated above, it's okay to lift where the notes are marked staccato or portato. For the others (from low B♭ to F, and from F to the upper B♭), each note should be held until the next note is played.
There should not be any pivoting or twisting needed (especially because such movements, done frequently, can lead to injury). The combination of the above fingering plus the hand position given in the linked post should eliminate any rotational movements.

The weight of the keys is smaller and my hand just goes crazy

The most common cause of this is that when you play, you play by moving your fingers only, holding your arm in place. This over-control of movement actually leads to less control in one's playing. Relaxation is essential, and when achieved, the small differences in key weighting — or even bigger differences between different pianos — will be fairly insignificant.
Again, the post linked above given some basic tips for establishing and maintaining a relaxed hand and arm. Similar points are also made in this post about curved fingers. A post about arpeggios contains a list of relevant tips. There is also a post on seating position, which might be relevant for you.


Angular directive receiving object as attribute using Typescript

Question: I am developing using Angular 1.5.8 and Typescript
I have a directive which is used under the scope of another directive (and another controller of course). Let's say Directive1, Controller1 and Directive2, Controller2.
Given the Controller1 already has the user information, I would like to pass this user information to the Controller2 through the Directive2, to prevent from fetching the information again from the backend.
I am not sure if this can be done, but it would be nice if that's the case :)
Below is the code to help my explanation:
Directive1 HTML:

    ...
    <directive2 user="{{ctrl.loggedUser}}"></directive2>
    ...

loggedUser is loaded in Controller1 constructor through a call to the backend.
Directive2 and Directive2Ctrl Typescript code:
class Directive2 implements ng.IDirective {
    controller = "Directive2Ctrl";
    controllerAs = "d2Ctrl";
    bindToController = {
        user: "@"
    };
    restrict = "E";
    templateUrl = "directive2.html";

    static factory(): ng.IDirectiveFactory {
        const directive = () => new Directive2();
        return directive;
    }
}
angular
    .module("app")
    .controller("Directive2Ctrl", Directive2Ctrl)
    .directive("directive2", Directive2.factory());

class Directive2Ctrl implements IDirective2Ctrl {
    public user: User;

    constructor(user: User) {
         // user is undefined
    }

    $onInit(user: User): void {
        // user is undefined
    }
}

I couldn't find a way of passing the user object to the Directive2Ctrl (not even sure if it is possible).
Comment: It should be `user="ctrl.loggedUser"` in the view (no curly braces) and `user: "="` in bindToController definition (instead of @)
Comment: Should I use the scope within the controller or the directive? Or should it work without the need of using the scope?
Comment: No, you don't need to use the scope explicitly if you're using bind to controller syntax
Answer: Use "scope" property instead of "bindToController" property, and replace your "@" with "=".
Then I use an interface for my specific scope to get autocompletion.
export interface IMyDirectiveScope extends ng.IScope {
    user: any;
}

export class Myirective {
    public restrict: string = 'E';
    public templateUrl = "/mytemplate.html";
    public link: (scope: IMyDirectiveScope, element: ng.IAugmentedJQuery, attrs: ng.IAttributes, ngModel: ng.INgModelController) => void;
    public scope = {
        user: "="
    };

    constructor() {
        var context = this;
        context.link = (scope: IMyDirectiveScope, element: ng.IAugmentedJQuery, attrs: ng.IAttributes, ngModel: ng.INgModelController) => {
           //INSERT YOUR CODE
           //console.log(scope.user);
        };
    }

    public static Factory() {
        var directive = () => {
            return new MyDirective();
        };

        return directive;
    }
}

In your html, remove your curly braces.

    ...
    <directive2 user="ctrl.loggedUser"></directive2>
    ...

Comment: I tryed to create a plunker, but not sure how to compile typescript on plunker.
Comment: In order to compile, you need to add your imports in your .ts file.
Answer: If you want to share data between different locations in your application, just put it in a service and use DI wherever you need the data.
That is, fetch the data, store it in a service and use DI to make the data available in different locations. There is no need to pass data through  bindings over several layers, much easier to use a service.

var mod = angular.module('testApp', ['ngRoute']);

mod.config(['$routeProvider',
  function($routeProvider) {
    $routeProvider.
      when('/intern', {
        template: '
{{User.firstName}}
{{NestedUser.lastName}}<test-dir></test-dir>

',
        resolve: {
          userResolve: function($q, $timeout, User) {
            var deferred = $q.defer();

            // mock server call, which returns server data
            $timeout(function() {
              var mockUserResp = {
                firstName: 'John',
                lastName: 'Rambo'
              };
              User.setUser(mockUserResp);

              deferred.resolve();
            }, 1000);

            return deferred.promise;
          }
        }
      }).
      otherwise({
        redirectTo: '/intern'
      });
  }]);

mod.factory('User', function() {
  var _user = null;
  return {
    setUser: function(user) {
      _user = user;
    },
    getUser: function() {
      return _user;
    }
  }
});

mod.controller('InternController', function($scope, User) {
  $scope.User = User.getUser();
});

mod.controller('NestedController', function($scope, User) {
  $scope.NestedUser = User.getUser();
});

mod.directive('testDir', function(User) {
  return {
    restrict: 'EA',
    scope: {},
    template: '
{{firstName}} is a cool guy.
',
    link: function(scope) {
      scope.firstName = User.getUser().firstName;
    }
  };
});
.outer {
  border: 1px solid green;
}

.nested {
  border: 1px solid blue;
}

.dir {
  border: 1px solid orange;
}

Comment: But I don't want to fetch the data again. Because Controller1 has already fetched the user data and the directive I am using is inside Controller1 HTML, so I would like to just pass it as parameter. I think that the $scope is used for this purpose, but I am not clear how to make it work on my Typescript implementation.
Comment: Ah, maybe I missunderstand you.. You mean pulling the data from the backend once and then make it available for any controller through a service? I think that would be much better. Have you got a sample of that?
Comment: Exactly, I've added a short code snippet, which demonstrates a common problem in angular apps. Usually, for some state data has to be fetched from the server (mocked with $timeout call). Then, this data is often shared in multiple locations. Hope this example helps.
Answer: It should be like this. But if it's still not working for you, you can create a simple plunker and I will fix it there. Cheers!

    ...
    <directive2 user="ctrl.loggedUser"></directive2>
    ...

`
class Directive2 implements ng.IDirective {
    controller = "Directive2Ctrl";
    controllerAs = "d2Ctrl";
    scope = {},
    bindToController = {
        user: "="
    };
    restrict = "E";
    templateUrl = "directive2.html";

    static factory(): ng.IDirectiveFactory {
        return () => new Directive2();
    }
}
angular
    .module("app")
    .controller("Directive2Ctrl", Directive2Ctrl)
    .directive("directive2", Directive2.factory());

class Directive2Ctrl implements IDirective2Ctrl {
    public user: User;

    $onInit(user: User): void {
        // user should be available
        console.log(this.user);
    }
}

Comment: I created this plunker although it is not working yet (I don't know how to compile typescript in Plunker).
Plunker
Answer: Sorry, I wonder if you still need to set scope = {}
Comment: Directive2 does not require Directive1. It requires a user. In this case it is being used under the scope of a controller which has a user, but it doesn't necesarily has to be Controller1.
Comment: I guess, I am slightly confused, could you not set your scope to be user:"=", instead of  user:'@', on your bind to controller
Comment: I already tried the scope = { }; as well as changing the @ with = but still no success.
Answer: To do what I asked in the first place, the scope needs to be correctly used.
Here is another question which is nicely explained which uses the scope correctly:
How can I define my controller using TypeScript?


Dynamically add input field using #ajax

Question: As the question says, im not clear on how to go about adding new input fields depending on values of certain fields in the form.
I got as far as setting a callback and a wrapper, but i just can't seem to rebuild the form, i can do basic returns of values from the callback, but that's about it.
If anyone could show me a clean, simple way where i could go from, that would be great!
<?php

//Create raffle form
function raffle_create_form($form, &$form_state)
{

    //Basic raffle info
    $form['raf_raffle_name'] = array(
        '#type' => "textfield",
        "#prefix" => "
Raffle information

",
        "#title" => "Raffle Name:",
        "#required" => TRUE
    );

    $form['raf_allowed_number'] = array(
        '#type' => "textfield",
        "#title" => "Number of allowed members",
        "#required" => TRUE,
        '#element_validate' => array('element_validate_number')
    );

    $form['raf_start_now'] = array(
        "#type" => "checkbox",
        "#title" => "Start raffle now?"
    );

    $form['raf_end_date'] = array(
        "#type" => "date",
        "#title" => "When to close this raffle?",
        "#required" => TRUE
    );

    $form['raf_prize_type'] = array(
        '#type' => "select",
        "#options" => array('gift' => 'Steam Gift', 'hardware' => 'Gaming peripherals'),
        "#title" => "Prize type",
        "#ajax" => array(
            'callback' => 'raffle_create_form_type_steam',
            'wrapper' => 'steam_options',
        ),
    );

    if(isset($form_state['values']['raf_prize_type']))
    {
        $form['raf_steam_options'] = array(
            '#type' => 'textfield',
            '#title' => 'Added div',
            '#prefix' => '
',
            '#suffix' => '
'
        );
        $form['raf_steam_options']['#description'] = 'configure some steamy steam steam';
    }

    $form['raf_prize_name'] = array(
        '#type' => "textfield",
        "#title" => "Prize name",
        '#prefix' => '

',
    );

    $form['raf_prize_about'] = array(
        '#type' => "textarea",
        "#resizeable" => true,
        "#title" => "Prize description"
    );

    $form['raf_prize_thumb'] = array(
        '#type' => "file",
        "#title" => "Prize thumbnail"
    );

    $form['raf_prize_link'] = array(
        '#type' => 'textfield',
        '#title' => "Link to product"
    );

    $form['raf_raffle_create'] = array(
        '#type' => 'submit',
        '#value' => "Create Raffle",
    );

    $form['#submit'][] = 'raffle_create_form_submit';

    return $form;
}

function raffle_create_form_validate($form, &$form_state)
{

}

function raffle_create_form_submit($form, &$form_state)
{
    dsm('i printed');
}

function raffle_create_form_type_steam($form, &$form_state)
{
    dms('hi');
    return $form['raf_steam_options'];
}

Answer: You should do something like this
$form['raf_prize_type'] = array(
        '#type' => "select",
        "#options" => array('gift' => 'Steam Gift', 'hardware' => 'Gaming peripherals'),
        "#title" => "Prize type",
        "#ajax" => array(
            'callback' => 'raffle_create_form_type_steam',
            'wrapper' => 'steam_options',
            'event' => 'change',
           'method' => 'replace',
        ),
    );

$form['raf_prize_name'] = array(
        '#type' => "textfield",
        "#title" => "Prize name",
        '#prefix' => '
',
        '#suffix' => '
'
    );

And your callback function should be
function raffle_create_form_type_steam($form, $form_state){

    return $form['raf_prize_name'];
}

Comment: 'raf_steam_options' is the form to be appended.

This is the current source code, there is no change. Nothing is appended, the 'raf_steam_options' is built without a change being triggered.

http://notey.it/n/dDN3
Answer: The trick was to:

Define ajax method as append.
Append keeps adding the input field on change, replace works swifter in this case.
Set a prefix on any of the input field to create a div. CLOSE THE DIV ON THE PREFIX FIELD AND NOT ON THE SUFFIX FIELD. E.g.
'#prefix' => "

"

Then set the callback function to return required input
   <?php

//Create raffle form
function raffle_create_form($form, &$form_state)
{

    //Basic raffle info
    $form['raf_raffle_name'] = array(
        '#type' => "textfield",
        "#prefix" => "
Raffle information

",
        "#title" => "Raffle Name:",
        "#required" => TRUE
    );

    $form['raf_allowed_number'] = array(
        '#type' => "textfield",
        "#title" => "Number of allowed members",
        "#required" => TRUE,
        '#element_validate' => array('element_validate_number')
    );

    $form['raf_start_now'] = array(
        "#type" => "checkbox",
        "#title" => "Start raffle now?"
    );

    $form['raf_end_date'] = array(
        "#type" => "date",
        "#title" => "When to close this raffle?",
        "#required" => TRUE
    );

    $form['raf_prize_type'] = array(
        '#type' => "select",
        "#options" => array('gift' => 'Steam Gift', 'hardware' => 'Gaming peripherals'),
        "#title" => "Prize type",
        "#required" => TRUE,
        "#ajax" => array(
            'callback' => 'raffle_create_form_type_steam',
            'wrapper' => 'steam_options',
            'event' => 'change',
            'method' => 'append',
        ),
    );

    $form['raf_prize_name'] = array(
        '#type' => "textfield",
        "#title" => "Prize name",
        "#prefix" => "

",
        "#required" => TRUE
    );

    $form['raf_prize_about'] = array(
        '#type' => "textarea",
        "#resizeable" => true,
        "#title" => "Prize description"
    );

    $form['raf_prize_thumb'] = array(
        '#type' => "file",
        "#title" => "Prize thumbnail"
    );

    $form['raf_prize_link'] = array(
        '#type' => 'textfield',
        '#title' => "Link to product"
    );

    $form['raf_raffle_create'] = array(
        '#type' => 'submit',
        '#value' => "Create Raffle",
    );

    $form['#submit'][] = 'raffle_create_form_submit';

    return $form;
}

function raffle_create_form_validate($form, &$form_state)
{

}

function raffle_create_form_submit($form, &$form_state)
{
    dsm('i printed');
}

function raffle_create_form_type_steam($form, &$form_state)
{
    return  $form['raf_steam_options'] = array(
            '#type' => 'textfield',
            '#title' => 'Added div',
            '#prefix' => '
',
            '#suffix' => '
'
        );
}

Answer: Please note that form function should contains all form variant. So the way stated by @Haider Ali did is not acceptable because $form['raf_steam_options'] is appended in the #ajax callback.
The code in question is not working because there is no

 printed in page in the very beginning.
Please check below for the reference.
/**
 * Create raffle form.
 */
function raffle_create_form($form, &$form_state) {
  $form = array();
  $values = &$form_state['#values'];

  // ...

  $form['raf_prize_type'] = array(
    '#type' => "select",
    "#options" => array(
      'gift' => 'Steam Gift',
      'hardware' => 'Gaming peripherals'
    ),
    "#title" => "Prize type",
    "#required" => TRUE,
    "#ajax" => array(
      'callback' => 'raffle_create_form_type_steam',
      'wrapper' => 'steam_options',
      'event' => 'change',
      'method' => 'append',
    ),
  );

  if (isset($values['raf_prize_type']) && !empty($values['raf_prize_type']) {
    $form['raf_prize_name'] = array(
      '#type' => "textfield",
      '#title' => "Prize name",
      '#prefix' => '
',
      '#suffix' => '
',
    );
  } else {
    $form['raf_prize_name'] = array(
      '#prefix' => '
',
      '#suffix' => '
',
    );
  }

  // ...

  return $form;
}

/**
 * Ajax callback.
 */
function raffle_create_form_type_steam($form, $form_state){
  return $form['raf_prize_name'];
}

Dynamically add input field using #ajax


How to remove all and add some new elements with config transforms

Question: I have the following block in my web config
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <rules>
        <logger name="*" minlevel="Trace" writeTo="dev" />
        <logger name="*" minlevel="Debug" writeTo="file" />
        <logger name="*" minLevel="Info" writeTo="growl" />
    </rules>
</nlog>

I would like it to transform it by removing all rules and adding a new one
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <rules>
        <logger name="*" minlevel="Debug" writeTo="graylog" />
    </rules>
</nlog>

I've tried this
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <rules>
        <logger xdt:Transform="RemoveAll" />
        <logger name="*" minlevel="Debug" writeTo="graylog" />
    </rules>
</nlog>

but that merely clears out the <rules> element.
Whats the correct transform?
Comment: Don't you need to specify `xdt:Transform="Insert"` on the new element?
Comment: @lc. Indeed! Would be swell if their documentation mentioned that, huh? Want to put that as an answer so I can accept it?
Comment: Tell me about it. I've included a link to the documentation too, in the hopes this helps fill in the gaps for the next person.
Answer: You need to also specify a transform action for the new record:
<logger name="*" minlevel="Debug" writeTo="graylog" xdt:Transform="Insert" />


Amplifier settings for Epiphone Standard Pro Top

Question: Hello Ive been struggling with my amp settings for quite a bit now. My amp happens to be a Roland cube 40 and I'm still intermediate at playing so I still don't have a processor or any other effect pedal. So my problem is that I dont get the long lasting smooth distortion tone. For example consider the solo of wither by Dream Theatre or Farewell Ballad by Zakk Wylde. Do I need to put the gain at its max (I usually get a rough sound with that)?
Could anyone suggest me good settings for the amp without the need for processor or any other effect pedal.
Thanks
Comment: Sustain originates in the string and guitar construction itself, you mention an Epiphone. I have the same guitar and can tell you the sustain is not that great. All I can think of for you to get is some sort of e-bow device. Opinions differ on what makes sustain greater/shorter but novice/intermediate guitars aren't typically built for sustain.
Comment: Actually I think its not about the sustain coz' when my amp is in JC Clean it has a very long and good sustain but I dont find that when distorting it.
Comment: In that case the distorted patch in the Cube may have a gate element to it cutting off any signal below a certain dB threshold.
Comment: So do I need to decrease gain and increase volume can you suggest me where the gain and volume should be set in that case?
Comment: Yeah, set the gain at 0 and go from there. It's all a matter of personal taste and experimentation really, gain shouldn't generally be maxed out unless you're going for a ridiculous tone :D
Comment: Ill definitely try that but in most cases (all till now) my lower strings sound very heavy making the notes I play 'not crispy' or clear.
Answer: Typically, increasing the gain will improve your sustain - and taking gain up so far it dramatically clips the input signal will act as a compressor and increase gain.
Petrucci also uses a dynamics processor and a range of very good valve amplifiers and effects...Some pictures from that site:

These allow greater sustain and controlled feedback without excessive noise.
With your current guitar and amp you may just not be able to achieve the same tone.
Here's a logical structure for Petrucci's rig - this can also help you understand just how different your kit is from his:
Comment: Of course there are many sounds that need processors, but get your guitar and amp combo right first.
Comment: My guitar seems to make noise at lower strings its just not thin and crisp. Cant I adjust my amp so that atleast I get a good tone? Or atleast close to many guitarists on youtube
Comment: Once you find the guitar and amp that work for you, stick with it - all guitarists struggle to find 'their' tone. After 28-ish years gigging, I have finally found the amp that gives me the tone I like, and I have played everything under the sun. Some amps just won't do what you need.
Comment: Im just curious that are there some sounds that actually need processor and cannot be made without them?
Comment: and maybe thats the reason why I dont get specific sounds?


How to pass a parameter from docker-compose to service runned in docker image?

Question: My docker-compose.yml, among other images, uses official mongo docker image:
mongodb:
    container_name: mongodb
    image: mongo:3.2
    volumes:
        - mongo_data:/data/db
    ports:
        - "57017:27017"
    restart: always

The problem is that I need mongo deamon to run with --httpinterface option. How can I change my docker-compose.yml to pass this parameter to the final CMD ["mongod"]?
Is it possible without touching the mongo image? Forking this image to only add one parameter would be an overkill.
Answer: You can use command option of docker-compose.yml
mongodb:
    container_name: mongodb
    image: mongo:3.2
    command: mongod --httpinterface
    volumes:
        - mongo_data:/data/db
    ports:
        - "57017:27017"
    restart: always

Comment: Note that MongoDB 3.6 removes the deprecated HTTP interface. You can see from [here](https://docs.mongodb.com/manual/release-notes/3.6-compatibility/#http-interface-and-rest-api)


How to throw ball straight up in tennis's serving?

Question: I observed players of different skills and I noticed that one repeating mistake is in the fact that it is hard to throw the ball straight up, I have the same mistake. When serving with the ball going straight up, serving becomes far more consistent (not hitting the net and not going over). I simplified the serving to the serve like in Pesäpallo (i.e. you go down in your feet while your hands are at the constant height, not to get the release of the ball in circular path so only trying to get vertical velocity). Now my couch said it does not look like tennis even though the shots became far more consistent. So:

How to throw the ball straight up in tennis's serving?
Answer: As you probably know - one of the most important things about your serve in tennis is a consistent toss. One that produces the ball following the same height and trajectory each time. You can even just practice your toss by itself, without actually hitting the ball (you might have done this). The goal should be that the ball lands between a foot or two inside the baseline if you let it drop.
Another thing to do in order to have a consistent toss is to pay attention to the position of your hand relative to your shoulder when you let go of the ball. You want to let go and toss the ball into the air when your hand is level with your shoulder.
If you let go of the ball before your hand is level with your shoulder, you are likely to have a toss that does not go high enough and that goes too far forward into the court. If you let go of the ball too late (when your hand is above your shoulder) you are likely to have the ball go too far back behind your head which will lead to you hitting the serve long.
If you pay attention to those things and practice your toss by itself, it should improve. Keep in mind that a good serve can take a lot (thousands) of serves. Whenever I try to work on mine I take a basket of balls to the court with me so I can practice the motion repeatedly and focus on my service motion without worrying about having to pick up balls very often.
Comment: Is the flight path a parabola (my first risky serve) or straight (my second less risky serve) in ideal serving? I can serve more solidly with the high straight serving but serving with a parabola path (ball going slightly in front of you, first serve) is far more errorsome for me. **How are serves different between the first serving and second serving?**
Comment: Agree and love [Djokovic tips](https://www.youtube.com/watch?v=R0dldQUtRbo&t=0m16s) about serving, I always try to have the ball as high as possible so I have more time during the serving. One thing I cannot notice in your answer is **a solid stance (legs solidly apart from each other)**: a solid stance where you are not in a wobbling position.
Comment: If you're just starting out (only been playing a year or two) I would recommend just keeping the same toss for both serves. If you develop a kick serve for your second serve then you would end up tossing the ball a little further back over your head but I wouldn't worry about that until you have solid technique for a normal serve.
Comment: As far as your toss goes - a flight path like a parabola would not be recommended - I'd say you want to learn how to hit a toss that is straight up before anything else. If the ball going slightly in front of you is errorsome then try adjusting your timing and how far in front of you your toss ends up. If your toss has the ball landing more than about a foot (12 inches) inside the court, your problem might be that you're tossing it too far out.


JQuery Slider - stop function - what if a user doesn't 'stop'?

Question: I have this code which uses JQuery UI to create a slider. It calls a function when the slider is stopped (when you stop moving the slider) and creates a hidden form field with the value contained in the slider (so that it can be POST'ed once the form is submitted.)
This works perfectly except for one minor bug:
If the user doesn't move the slider, stop: is never triggered and therefore, a hidden form field is never created.
What's the best way to fix this?
 $(function() {
    $( "#slider8" ).slider({
     orientation: "horizontal",
     range: "min",
     min: 0,
     max: 100,
     value: 50,
     stop: function(event, ui) {
        var $s1 = $('<input/>', {type: 'hidden',id:'slider8',name:'slider8', value: ui.value});
        $s1.appendTo('.form-horizontal');
     }
  });
 });

Comment: why not add the hidden form field always and have it contain a default value, that way there is always a value there. Then simply overwrite the value if the user does use your slider?
Comment: Change your ux logic?
Comment: Doh. Why didn't I think of that? :>
Answer: Edit:
My initial suggestion was to attach the jQuery UI slider to a range input type, but jQuery UI doesn't support that - it only gets attached to divs, not input elements. My mistake.
Here's a complete jsFiddle example of what you wish to achieve. You need to create your hidden element in the create event, and update it in the change event, like so:
HTML:

jQuery:
 $(function() {
    $( "#slider8ui" ).slider({
     orientation: "horizontal",
     range: "min",
     min: 0,
     max: 100,
     value: 50,
     create: function( event, ui ) {
        $('<input/>', {type: 'text',id:'slider8',name:'slider8', value: 50}).appendTo('#slider8ui');
     },
     change: function(event, ui) {
        $("#slider8").val(ui.value);
     }
  });
 });

Here's the complete jsFiddle:
http://jsfiddle.net/TdpX9/
Comment: Sorry, my mistake, seems like you can't attach jQuery UI slider to an input element. I've just rewritten my reply, including a complete working example


Find ZFS metadata from raw disk/partiton

Question: So, I've come across a lone disk with a ZFS partition on it. Clearly this is out of place.
How can I pull some metadata off it (like the GUID or what zpool it belongs to), so I can figure out where this thing belongs.
Google give me tons of information on how to get stats on devices that are part of an imported pool, and how to identify which disk in a tray is the bad one, but I'm coming up dry on this.
Answer: zpool import will dump information about the pool to which the disk belong.
Use zpool import -a to import all pools found.
For destroyed pools, try zpool import -D
Comment: Still nothing, but I was able to find the information out directly by using hexedit. The beginning of the partition is pretty easy to read.
Comment: It just says 'no pools available to import', so I'll take that to mean that it's had its metadata destroyed. I find it a bit odd that there is no dedicated command for this (like LVM's pvdisplay).
Comment: You can see metadata even of destroyed pool. See the updated answer.


Interpret Pearsons correlation output from R

Question: I have conducted Pearson's correlation in R and need help interpreting the results.
<code>Pearson's product-moment correlation

data:  A.C$Average.tortuosity and A.C$Area
t = -0.6168, df = 14, p-value = 0.5473
alternative hypothesis: true correlation is not equal to 0
95 percent confidence interval:
 -0.6092369  0.3622606
sample estimates:
       cor
-0.1626531
</code>
I am interested in reporting the r and p values. Would it be fair to say based on the the above output that:

There was a non-significant correlation between the two variables, r (14) = -.16, p > .05.
Comment: Yes, you're right. The p value that's greater than 0.05 failed to reject the alternative hypothesis and the conclusion is that there is no significant correlation, namely accept the null hypothesis where correlation is equal to zero.
Answer: I think it would be better to say that the correlation of the two variables was statistically non-significant. Thus you can't conclude that the correlation is not equal to 0. The p-value is in fact 0.5473.
You can also see that the 95 percent confidence interval has the number 0 which also shows the non-significance of the result.
I never like the wording "non-significant correlation" because it says that there both is a correlation and that it's *non-significant". That's a contradiction -- either there is a statistically significant correlation or (by the properties of a hypothesis test) you fail to show a significant result. If you fail to show the result, you can't conclude that your correlation is different from 0.
Hope that helps!
Comment: (+1) although the interpretation in the OP could be read as 'the sample correlation is 0.16. Based on the p value of 0.55, we cannot say anything about the true correlation'. This would not be a contradiction.
Answer: You better say that there is no Linear association (or correlation) between the two variables.
By the way I cannot see you r value ?
Comment: Your answer is very short and is rather like a comment. Can you extend your answer please?


Rotation slerp to unity quaternion

Question: The context: A graphic application in which the user rotates an object around the origin and then can press a button to reset the rotation to its reset state. The reset should be appear smooth and not just jump.
I'm using a quaternion to represent the current rotation of the object at any time and when the user presses the button I want to slerp() between the current rotation and the reset one. This works fine if the reset rotation is a real rotation with Theta and an Axis but it breaks down if the reset state is has theta=0.
The slerp starts with a standard rotation quaternion
q1 = sin(theta/2) + (xi + yj + zk)cos(theta/2)

and supposed to end at the rotation quaternion with theta=0:
q0 = sin(0/2) + (xi + yj + zk)cos(0/2)

which turns out to be the the unit quaternion:
q0 = 1+0i+0j+0k

The problem I'm facing is that to do the rotation, slerp calcs the angle alpha between q0 and q1 by just taking their vector parts and doing arccos(), but the unity quaternion's vector is (0,0,0) so it can't do that.
Is there a standard way to solve this issue?
Comment: Please don't use codeblocks for something which is not actual code. [MahJax](http://meta.math.stackexchange.com/questions/5020/mathjax-basic-tutorial-and-quick-reference) should be used to typeset equations and mathematical text.
Comment: For what reason do you need to compute the angle $\alpha$ between the vector parts of $q_0$ and $q_1$?
Answer: Yes, you can do it... First of all your definition of a quaternion is wrong.  The correct expression is:
$$q_1 = \cos(\theta/2) + (xi + yj + zk)\sin(\theta/2)$$
and
$$q_0 = \cos(0/2) + (xi + yj + zk)\sin(0/2) = 1 $$
where $x^2 + y^2 +z^2 = 1$.
Since $q_1$ represents the forward rotation, then the inverse is just the conjugate (i.e. negate the vector part).
$$q_1^{-1} = \cos(\theta/2) - (xi + yj + zk)\sin(\theta/2)$$
We can then divide the reverse rotation into N steps by dividing the angle by N yielding
$$q_{slerp} = \cos(\frac{\theta}{N}/2) - (xi + yj + zk)\sin(\frac{\theta}{N}/2)$$
This rotation is then applied to all of the points in your rotated shape object N times to bring it to the reset position.

Rotation slerp to unity quaternion