Como expandir a janela ao clicar num botão?

Question: É possível expandir uma janela com maiores informações quando o usuário clicar em um botão "Detalhes"? O comportamento é similar ao de algumas telas de erro, que mostram os dados de um erro, como demonstrado na imagem abaixo:

Minha janela tem um JButton que, ao ser clicado, deve expandir o JDialog e exibir o conteúdo de uma JTextArea ou ScrollPane.
Comment: Você no caso quer montar uma tela igual ao comportamento dessa...?
Comment: exato. A priori a tela vai está menor sem mostrar esse detalhes, e aí sim, quando eu clicar no JButton 'Detalhes', ela me expanda e me mostre os detalhes dentro de um JtexArea e tal...tem como ?
Comment: Eu não tenho tempo de testar a ideia no momento, e por isso não vou postar uma resposta. Mas se você simplesmente esconder/exibir o `JTextArea` no clique do botão, deve ser só questão de chamar o [método `pack`](http://docs.oracle.com/javase/7/docs/api/java/awt/Window.html#pack()) da janela.
Comment: Dê uma olhada no [tour]. Você pode aceitar uma resposta se ela resolveu seu problema. Você pode votar em todos os posts do site também. Alguma lhe ajudou mais? Precisa que algo seja melhorado?
Answer: Aparentemente esta caixa de mensagem apareceu por captura da exceção feito pelo próprio Java. Então não tem o que fazer.
O que você pode fazer é você capturar a exceção no local adequado - pode ser no main() - e tratá-la como quiser. Aí você mostra em uma tela que você tem controle para fazer como quiser programaticamente, provavelmente um JFrame.
Você poderá escolher o tipo de janela que deseja e poderá configurá-la como achar melhor.
Também é possível criar um manipular global, algo assim:
public final class ExceptionHandler implements Thread.UncaughtExceptionHandler {
    @Override  public void uncaughtException(Thread thread, Throwable throwable) {
        JOptionPane.showMessageDialog(null, "Erro: " + throwable.toString(),
            "Erro", JOptionPane.ERROR_MESSAGE);
    }
}

Coloquei no GitHub para referência futura.
É só um exemplo mostrando a captura global de exceções, claro que desta forma usando JOptionPane.showMessageDialog também há pouco controle.
Comment: Essa maneira eu sei fazer, porém, gostaria de algo mais sofisticado para o usuário como mostra a imagem acima. A ideia que eu quero é após clicar em um JButton a mesma me expanda o JDialog e me mostre o que eu quero dentro de um JTexArea/ScroolPane etc...
Comment: Então edite a pergunta e coloque o código do que você está fazendo e mostre a sua dificuldade. Você fez uma pergunta genérica e eu dei uma resposta genérica. Posso tentar ajudar com algo mais específico se entender o que você está fazendo.
Answer: Esta tela pode ser inteiramente construída na mão, caso você faça questão de tê-la em sua aplicação, segue um exemplo que desenvolvi, o código está com as devidas observações:
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;

import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextPane;
import javax.swing.JToggleButton;

/**
*
* @author diego.felipe
*/
public class DialogUnhandledException {

    // algumas IDE's podem reclamar de codificação de texto,
    // por causa destes simbolos, por isso deve-se manter
    // a codificação UTF-8 ou alterar os simbolos
    private static final String BUTTON_ARROW_NORTH = "▲";
    private static final String BUTTON_ARROW_SOUTH = "▼";
    private static final String MESSAGE_DEFAULT = "An unhandled exception has occurred in your application. "
            + "Click on Details for more information or click Quit to close the application immediately.";

    private DialogUnhandledException() {

    }

    public static void showException(String shortError, String strStackTrace) {

        // - fixedWith é um tamanho fixo para o frame não ficar redimensionando
        // ao abrir o JTextPane contendo a stacktrace.
        // - minHeight é o tamanho minimo do frame, quando o JTextPane da
        // StackTrace não estiver visível.
        // - maxHeight é a altura máxima do frame, comportando o JTextPane da
        // stracktrace aberto.
        int fixedWidth = 450;
        int minHeight = 135;
        int maxHeight = 300;

        JFrame frame = new JFrame();
        frame.getContentPane().setLayout(new BorderLayout());
        // obrigatório, para que o BorderLayout não redimensione automaticamente
        frame.setPreferredSize(new Dimension(fixedWidth, minHeight));
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        // painel principal que comportará os paineis de botoes
        // e da mensagem padrao
        JPanel principalPane = new JPanel();
        principalPane.setLayout(new BoxLayout(principalPane, BoxLayout.Y_AXIS));

        // painel onde será comportado o JTextPane com a mensagem
        // padrão mais a mensagem de erro sem o stacktrace
        JPanel messageDefaultPane = new JPanel(new BorderLayout(0, 5));
        messageDefaultPane.setBorder(BorderFactory.createEmptyBorder(3, 3, 0, 0));
        // componente onde será exibida a mensagem de erro padrao
        JTextPane tp_messageDefault = new JTextPane();
        tp_messageDefault.setBackground(frame.getBackground());
        tp_messageDefault.setEditable(false);
        tp_messageDefault.setText(MESSAGE_DEFAULT + "\n\n" + shortError);

        messageDefaultPane.add(tp_messageDefault, BorderLayout.CENTER);

        // scrollPane comportará o JTextPane que exibirá o stacktrace quando o
        // botao for clicado
        JScrollPane scrollPane = new JScrollPane();
        JTextPane tp_stackTrace = new JTextPane();
        tp_stackTrace.setBackground(frame.getBackground());
        tp_stackTrace.setEditable(false);

        // painel contendo os botoes Detais, Quit e Continue
        JPanel buttonPane = new JPanel();
        buttonPane.setLayout(new BoxLayout(buttonPane, BoxLayout.LINE_AXIS));
        buttonPane.setBorder(BorderFactory.createEmptyBorder(5, 0, 5, 10));

        // Como o estado do botão Details servirá para exibir ou ocultar
        // o JToggleButton faz mais sentido aqui
        JToggleButton btn_showDetails = new JToggleButton("Details " + BUTTON_ARROW_SOUTH);
        btn_showDetails.addItemListener(new ItemListener() {

            @Override
            public void itemStateChanged(ItemEvent e) {
                // quando o status do botao for "selecionado", a stacktrace será
                // atribuida no JTextPane, o frame terá sua altura alterada
                // para maxHeight e a posição da barra de scroll
                // ficará no topo do erro
                if (e.getStateChange() == ItemEvent.SELECTED) {
                    tp_stackTrace.setText(strStackTrace);
                    frame.setPreferredSize(new Dimension(fixedWidth, maxHeight));
                    tp_stackTrace.setCaretPosition(0);
                    frame.pack();
                    btn_showDetails.setText("Detalhes " + BUTTON_ARROW_NORTH);
                    // quando o status anterior do botao for desfeito, remove a
                    // stacktrace do componente de texto e redefine
                    // a altura minima para o frame
                } else if (e.getStateChange() == ItemEvent.DESELECTED) {
                    tp_stackTrace.setText(null);
                    frame.setPreferredSize(new Dimension(fixedWidth, minHeight));
                    frame.pack();
                    btn_showDetails.setText("Detalhes " + BUTTON_ARROW_SOUTH);
                }
            }
        });

        // funcionalidades não implementadas
        JButton btn_continue = new JButton("Continue");
        JButton btn_quit = new JButton("Quit");

        buttonPane.add(btn_showDetails);
        buttonPane.add(Box.createHorizontalGlue());
        buttonPane.add(btn_continue);
        buttonPane.add(Box.createRigidArea(new Dimension(10, 0)));
        buttonPane.add(btn_quit);

        scrollPane.setViewportView(tp_stackTrace);

        principalPane.add(messageDefaultPane);
        principalPane.add(buttonPane);

        frame.add(principalPane, BorderLayout.NORTH);
        frame.add(scrollPane, BorderLayout.CENTER);
        frame.pack();
        frame.setLocationRelativeTo(null);

        frame.setVisible(true);

    }

}

Seu uso é bem simples, e seguindo a resposta do @Maniero, pode ser usado em conjunto com a classe sugerida na resposta dele, mas para isso, é necessário antes converter as mensagens de erro e a stackTrace para string:
import java.io.PrintWriter;
import java.io.StringWriter;

public final class ExceptionHandler implements Thread.UncaughtExceptionHandler {

    @Override
    public void uncaughtException(Thread thread, Throwable throwable) {

        StringWriter strStackTrace = new StringWriter();
        throwable.printStackTrace(new PrintWriter(strStackTrace));
        DialogUnhandledException.showException(throwable.toString(), strStackTrace.toString());
    }

}

Para funcionar, basta configurar a classe como a manipuladora padrão de exceções não capturadas. A linha abaixo deve ser a primeira da aplicação:
public class Programa{

    public static void main(String[] args) {
        // registra nossa classe como manipulador padrao de
        // exceções não capturadas
        Thread.setDefaultUncaughtExceptionHandler(new ExceptionHandler());

            String a = null;
            System.out.println(a.equals(""));
            System.out.println(Integer.parseInt(a));
    }
}

Uma solução menos drástica(também já sugerido pelo @Maniero na outra reposta), é colocar no main, cercando a o trecho que inicia sua aplicação por um bloco try-catch:
public class Programa{

    public static void main(String[] args) {

        try {
            // define o look And Feel de acordo com o tema do SO em execução
            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());

            String a = null;
            System.out.println(a.equals(""));
            System.out.println(Integer.parseInt(a));
        } catch (Exception e) {
            StringWriter strStackTrace = new StringWriter();
            e.printStackTrace(new PrintWriter(strStackTrace));
            SwingUtilities.invokeLater(() -> DialogUnhandledException.
                    showException(e.getClass() + " " + e.getMessage(),strStackTrace.toString()));
        }
    }
}

O resultado para ambas as formas seria semelhante a imagem abaixo:

Lembrando que para ficar com esta aparência, é necessário que esteja rodando no Windows, se a aplicação Swing rodar no Linux ou OSX, a aparência será conforme o tema do sistema operacional em execução.


Como faço para fazer uma pesquisa entre vários db e apresentar o resultado na própria pagina?

Question: No MySQL tenho um banco de dados e dentro dele tenho a tabela student, e gostaria de pesquisar em outro banco que é idêntico ao primeiro, porém, com informações diferentes, e gostaria de saber em qual dos bancos o aluno está criado.
Essa pesquisa exibiria o resultado na própria página, e estou com essa dúvida e não estou conseguindo desenrolar isso.
Obs: esse código pode ser em php ou em JavaScript.
Comment: Crie duas conexões diferentes, na hora de executar a consulta especifique as repectivas conexões. Está usando o MySQLi ou o PDO?
Comment: o Mysql, mais teria outra forma, pois se caso tiver varias escolas ficaria varias conexões?
Comment: Todas as databases estão no mesmo servidor?
Comment: Não seria só usar o `mysqli_select_db` e selecionar outro banco de dados?
Comment: Tem diferença entre pedir ajuda e pedir pra fazer por você. **Poste o código**: [Manual de como NÃO fazer perguntas](http://meta.pt.stackoverflow.com/questions/5483/manual-de-como-n%c3%83o-fazer-perguntas).
Answer: Se as databases estiverem todas no mesmo servidor, basta informar o nome da database antes do nome da tabela.
Por exemplo, Supondo que você tenha duas databases, DB1 e DB2:
Exemplo de query consultando DB1:
SELECT * FROM DB1.Student WHERE ...

Exemplo de query consultando DB2:
SELECT * FROM DB2.Student WHERE ...

Exemplo de query usando as duas:
SELECT s1.nome, s2.nome FROM DB1.Student as s1
JOIN DB2.Student as s2 ON s2.id = s1.id

Comment: Obrigado leo_ap isso me deu uma luz de como resolver o meu problema


Joint CDF versus tail probabilities

Question: Is the following equation valid in general?
$$P(X>x,Y>y) \overset{?}= 1-P(X<x,Y<y)$$
Comment: That's very rarely true (with or without Silverfish's suggested fix).
Comment: I am fairly confident you intend the second probability to be $P(X<x, Y<y)$ and not $P(X<x,X<y)$?
Answer: For $P(X>x,Y>y) \overset{?}= 1-P(X<x,Y<y)$ to be valid in general, you'd need:
$$P(X>x,Y>y) + P(Y<x,X<y) = 1$$
In other words you'd need the events $X>x,Y>y$ and $X<x,Y<y$ to be complementary.
This is clearly not true in general, because those two events are mutually exclusive but may not be exhaustive: for instance, consider the event $X<x,Y>y$, or any of the other events labelled below.

If any probability lies outside the top right ($X>x, Y>y$) and bottom left ($X<x, Y<y$) quadrants, then those two events will not be exhaustive and the proposed equation will not hold.
There are many simple joint distributions for which this occurs: for example, let $X$ and $Y$ be independent Rademacher variables (i.e. either $+1$ or $-1$ with probability of $0.5$ for each) and take $x=y=0$. Then:
$$P(X>x,Y>y)=P(X>0,Y>0)=P(X>0)P(Y>0)=0.5 \times 0.5 = 0.25$$
$$P(X<x,Y<y)=P(X<0,Y<0)=P(X<0)P(Y<0)=0.5 \times 0.5 = 0.25$$
It is clear that $0.25 \neq 1 - 0.25$ so the equation fails to hold, and a quick inspection of the joint probability mass function reveals why: not all the probability is concentrated in those quadrants. Each of the four points has a probability mass of 0.25, so there is also a one quarter chance of $X>x, Y<y$ and a one quarter chance of $X<x, Y>y$.

In the comments Stéphane Laurent suggests another counterexample, where $X$ and $Y$ are independently ${\cal N}(0,1)$ and we take $x=y=0$. Once again, probability is spread across all four quadrants so the two quadrants selected in the equation are not exhaustive.

R code for plots

<code>require(ggplot2)

blank.df <- data.frame(x=0, y=0)
rademacher.df <- data.frame(x=c(1,1,-1,-1), y=c(1,-1,1,-1))
normal.df <- data.frame(x=rnorm(1e5), y=rnorm(1e5))

quadrants <- ggplot() + theme_bw() +
    annotate("rect", xmin=0, xmax=5, ymin=0, ymax=5, fill="red", alpha=0.2) +
    annotate("rect", xmin=-5, xmax=0, ymin=0, ymax=5, fill="blue", alpha=0.2) +
    annotate("rect", xmin=-5, xmax=0, ymin=-5, ymax=0, fill="grey", alpha=0.2) +
    annotate("rect", xmin=0, xmax=5, ymin=-5, ymax=0, fill="yellow", alpha=0.2) +
    annotate("segment", x=0, xend=0, y=0, yend=5, colour = "purple") +
    annotate("segment", x=0, xend=0, y=0, yend=-5, colour = "green") +
    annotate("segment", x=-5, xend=0, y=0, yend=0, colour = "steelblue") +
    annotate("segment", x=0, xend=5, y=0, yend=0, colour = "brown") +
    geom_point(alpha=0.01)

quadrants + geom_point(data=blank.df, aes(x=x, y=y), alpha=0.01) +
    scale_x_continuous(breaks=0, labels=c("x")) + xlab("X") +
    scale_y_continuous(breaks=0, labels=c("y")) + ylab("Y") +
    annotate("text", x=2.5, y=3, label = "X>x, Y>y", colour = "red") +
    annotate("text", x=-2.5, y=3, label = "X<x, Y>y", colour = "blue") +
    annotate("text", x=-2.5, y=-2, label = "X<x, Y<y", colour = "darkgrey") +
    annotate("text", x=2.5, y=-2, label = "X>x, Y<y", colour = "orange") +
    annotate("text", x=0, y=3, label="X=x, Y>y", colour = "purple") +
    annotate("text", x=0, y=-2, label="X=x, Y<y", colour = "green") +
    annotate("text", x=-2.5, y=0.5, label="X<x, Y=y", colour = "steelblue") +
    annotate("text", x=2.5, y=0.5, label="X>x, Y=y", colour = "brown") +
    annotate("text", x=0, y=0.5, label = "X=x, Y=y", colour = "black")

quadrants + geom_point(data=rademacher.df, aes(x=x, y=y)) +
    scale_x_continuous(breaks=0, labels=c("x=0")) + xlab("X") +
    scale_y_continuous(breaks=0, labels=c("y=0")) + ylab("Y")

quadrants + geom_point(data=normal.df, aes(x=x, y=y), alpha=0.01) +
    scale_x_continuous(breaks=0, labels=c("x=0")) + xlab("X") +
    scale_y_continuous(breaks=0, labels=c("y=0")) + ylab("Y")
</code>
Comment: I would add a simple counter-example to be more convincing, for example $X$, $Y$ independent ${\cal N}(0,1)$ and $x=y=0$.
Comment: @StéphaneLaurent I was intending to add the Rademacher as a counterexample, but the joint normal distribution might be more familiar so I decided to include it also, thanks.
Answer: Let $A = \{X \leq x\}$ and $B = \{Y \leq y\}$ denote events. Then,
$$\begin{align}
P\{X > x, Y > y\} &= P(A^c \cap B^c)\\
&= P\left((A \cup B)^c\right)&\scriptstyle{\text{apply DeMorgan's law}}\\
&= 1 - P(A\cup B)\\
&= 1 - \left[P(A) + P(B) - P(A \cap B)\right]\\
&= \left[1+P\{X \leq x, Y \leq y\}\right] - P\{X \leq x\} - P\{Y \leq y\}
\end{align}$$
whereas you ask whether
$P(X>x,Y>y) \overset{?}= 1-P(X<x,X<y)$. Clearly, the answer is No in general.
Indeed, what is true is that
$$P\{X \leq x, Y \leq y\}+ P\{X > x, Y \leq y\} +
P\{X \leq x. Y > y\} + P\{X > x, Y > y\}=1$$
and so, in order for $P(X>x,Y>y) \overset{?}= 1-P(X<x,X<y)$ to hold
for (continuous) random variables $X$ and $Y$, it must be that
$$P\{X > x, Y \leq y\} =
P\{X \leq x. Y > y\} = 0.$$

Joint CDF versus tail probabilities


JBoss 7 as deploys automatically

Question: I put my jboss on the linux server, exported the war file and placed it on the deployments folder and it automatically deployed. I didn't even had to do it via command line. How is this working?
My jboss has ssl to it.
Answer: From the Application Deployment documentation:

The standalone/deployments directory in the JBoss Application Server 7 distribution is the location end users can place their deployment content (e.g. war, ear, jar, sar files) to have it automically deployed into the server runtime.

So, if you put a war file in standalone/deployments, JBoss will detect it and act as if you had manually deployed it. The documentation page has a lot more info about configuration if you want to change the defaults.
Comment: @MДΓΓБДLL - I found a better page. The JBoss documentation is surprisingly hard to search through :\
Comment: Yes, it is. I've consistently found the JBoss documentation, at least for Community (read: free) edition, to be very frustrating.

JBoss 7 as deploys automatically


Use dll with different PublicToken property without recompilation

Question: I have .net dll, it use different .net dll with PublicToken set to null. Now I have to use the same version of different dll but with PublicToken set to some other value. Is there a way to use it without a need of recompilation of first dll (I do not have sources).
Answer: I don't think there is a clean way of doing this, mainly because what you are trying to do is defeat the very purpose of the Strong Naming concept. bindingRedirect only works on version, not the key. The only way that I can think of is to disable Strong Name Verification:
sn.exe -Vr TheAssembly

You can learn more about that here.
The problem with it is, it has to be done on every machine this is run.
Another alternative is to use a tool like Mono.Cecil to strip the Public Key Token from the Module's Assembly References so it no longer cares. If it is strong named itself, you'd have to remove that too. This option generally works, but will in most cases violate any form of EULA the assembly comes with if it is a commercial product.


A visual indicator for counting bars in 4/4

Question: I am helping a colleague out with a basic project. The project simply records bars tapped in a 4/4 time signature. There are two dynamic elements here. A beat indicator (in the screenshot, these are the 16 bars, 3 of which are filled in), and a bar counter (194 Bars Tapped). The Tap Beat button simply counts the beat.
Now my colleague and I are having a discrepancy with the visual elements. When should that bar counter increase to 195?! Once the 4th block is filled in? or once the first block in the NEXT bar is filled in? He says once the 4th block is filled in... I say once the first block in the next bar is filled in.
Additionally, do you feel there is ANY benefit to the visual element of the 16 blocks filling in?
If any of the above is confusing, please let me know and I will do my best to clarify further. Thank you.
Comment: What is the purpose of the visual indicator?
Answer: In a musical score bars begin to be counted at 1, there is no "measure 0". The first note of a piece is said to be in beat 1 of measure 1 (well, not when you have anacrusis, but that's not the issue here).
So if you wish to have consistency with the music notation convention I would say your friend is right, but you should change the caption to "Tapping bar #x" instead of "x-1 bars tapped", and start counting from 1.
Comment: It may be better to show the number of bars *and beats* tapped. This is commonly done with text notation like 1/1, 1/2, 1/3, 1/4 for the beats of bar 1. Unless the music is *always* in 4-bar phrases (which is probably too restrictive even for some "pop" music), what is the purpose of having groups of 4 and 16 bars in the graphics display?


Explain Multidegree of a polynomial

Question: Definition (The book Ideals, Varieties and Algorithms, Cox et al, pages 59-60 on 2008 edition):

Let $f=\sum_a a_a x^a$ be a nonzero polynomial in $k[x_1,\ldots, x_n]$ and let > be a monomial order.
The multidegree of f is $\quad\quad$ $multideg(f)=max(\alpha\in\mathbb Z^n_{\geq 0} : a_a\ne 0)$.
Example: $\quad\quad\quad\quad\quad\quad\quad$$multideg(f)=(3,0,0)$ for $f=4xy^2z+4z^2-5x^3+7x^2z^2.$

Please explain the definition: maximising each value in the n-tuple $\alpha$ but with respect to what is the multidegree calculated like in the case of $multidegree(f)$ above? With respect to exponents, monomial count, with respect to variable distribution -- thank you for any clarification!
Comment: What ordering is the maximum taken with respect to?
Answer: The definition of multidegree depends on a monomial ordering chosen. This is a total order on the set of all monomials that has the following aditional property:

For all monomials $m,n$ and $p$, $m < n$ implies $p\cdot m < p\cdot n$

In this case, we say that $<$ is an admissible order. A tipical example of a monomial ordering is the lexicographic order, defined as follows: for $\alpha, \beta\in \mathbb Z^n_{\geq 0}$, $\alpha < \beta$ if and only if the leftmost nonzero entry of $\beta - \alpha$ is positive.
Considering this ordering, $(3,0,0)$ is indeed the multidegree of $$f=4xy^2z+4z^2-5x^3+7x^2z^2,$$ but this may not be the case when you consider other orderings.
Comment: It's the "vector" representation of the monomial $x^3y^0z^0$.
Comment: How did you calculate the $(3,0,0)$? 3 for the sum of exponents in $4xy^2z$. What  are the zeros for?
Comment: And this uses monomial ordering in the example: (i) > is a total (or linear ordereing on $\mathbb Z_{\geq 0}^n$ (ii) your bullet point (iii) > is a well-ordering on $\mathbb Z_{\geq 0}^n$ i.e. every nonempty subset of $\mathbb Z^n_{\geq 0}$ has a smallest element under >. Thank you for the  comment +1, understood :)
Comment: @hhh I'm glad it helped ;)

Explain Multidegree of a polynomial


write a permutation as a product of permutations?

Question: I've been given the problem to write f = (1,2,3,4,5,6) as a product of permutation g of order 2 and a permutation h of order 3.
It doesn't make sense to me how a permutation of order 6 can be written as one of order 2 and one of order 3 because in doing this aren't we eliminating an element of f?
I understand what has to be done but I just don't get how I can break it down into two smaller order permutations without losing information?
Comment: Being a permutation of order $2$ or a permutation of order $3$ doesn't imply that only two or only three elements appear.  The permutation $(1,3,5)(2,4,6)$ for example is of order $3$.  Written in a different format, it is $\begin{pmatrix} 1&2&3&4&5&6\\3&4&5&6&1&2\end{pmatrix}$.  I agree that $f$ couldn't be written as a product of a disjoint $2$-cycle and a disjoint $3$-cycle, but that's not what the problem asks for.
Comment: @JMoravitz that definitely helps, thanks. So I something in the form of (x,y) and (a,b,c)(d,e,f) works since the first is order 2 and the second is order 3?
Comment: Or even something of the form (x,y)(u,v)(s,t) and (a,b,c)(d,e,f).  The order of a permutation is the least common multiple of the lengths of the cycles present when representing it as a product of disjoint cycles.  Since $2$ and $3$ are prime, that implies that $g$ will only have $1$-cycles (fixed points, which usually aren't written) and disjoint $2$-cycles.  Similarly for $h$.  The problem now is to find which ones work.
Comment: @JMoravitz ooooooh of course! so (1,2)(2,3)(3,4) and (4,5,6) would work?
Comment: actually no because we are doing the product of two... forget I said that!
Comment: (1,2)(2,3)(3,4) is of order four, not of order two, since these are not in fact *disjoint* cycles.  (a product of cycles in which no element appears in more than one cycle).  The useful thing about representing as disjoint cycles is that disjoint cycles (and their inverses) commute.
Answer: Hint: (expanded from those given in comments above)
$\sigma = \begin{pmatrix} 1&2&3&4&5&6\\3&4&5&6&1&2\end{pmatrix} = (1,3,5)(2,4,6)$ is of order three.
$\tau = \begin{pmatrix} 1&2&3&4&5&6\\4&5&6&1&2&3\end{pmatrix} = (1,4)(2,5)(3,6)$ is of order two.
See what their product is.  What is $\sigma\circ \tau$?  What about $\tau\circ\sigma$?  It won't be quite what you are looking for, but maybe it can be fixed.  Do you see how?

As $\tau$ sends $1\mapsto 4$ and $\sigma$ sends $4\mapsto 6$, you have $\sigma\circ\tau$ sends $1\mapsto 6$.  Similarly we see $\sigma\circ\tau$ sends $2\mapsto 1$, $3\mapsto 2$,... so we get $\sigma\circ\tau = \begin{pmatrix}1&2&3&4&5&6\\6&1&2&3&4&5\end{pmatrix} = (1,6,5,4,3,2)$  This should look very close to what you wanted.  What is wrong about it?

Being a product of two permutations doesn't require them to be written as the product of two cycles.  In the above, $\sigma\circ\tau = \left((1,3,5)(2,4,6)\right)\left((1,4)(2,5)(3,6)\right)$.
Comment: Need to search for all just good examples given by you here, or might be elsewhere (on other math sites). +1.
Answer: Hint:
$$(1\,2)f=(2\,3\,4\,5\,6).$$


Why does plt.cla() only work on one of the plots?

Question: I am trying to create a program that has two different plots at the same time:
import matplotlib.pyplot as plt
import numpy as np

plt.ion()

for i in range(100):
    x = np.arange(i, i + 50, 0.2)

    plt.cla()

    for subplotId in range(1, 3):
        plt.subplot(2, 1, subplotId)
        plt.ylim(-100, 100)

        y = np.tan(x)
        plt.plot(x, y)

    plt.pause(0.1)

However, plt.cla() only seems to work on the second plot.
The first plot seems to get 'squished':
How do I clear both plots?
Answer: The problem is that plt.cla() only works on the current subplot.
To fix the problem you need to run it after each subplot, like:
import matplotlib.pyplot as plt
import numpy as np

plt.ion()

for i in range(100):
    x = np.arange(i, i + 50, 0.2)
    #don't put plt.cla() here

    for subplotId in range(1, 3):
        plt.subplot(2, 1, subplotId)
        plt.cla() # put it here so that it runs for each subplot
        plt.ylim(-100, 100)

        y = np.tan(x)
        plt.plot(x, y)

    plt.pause(0.1)

I hope this helps.


Recuperar $_SESSION com Ajax

Question: É correto/seguro setar uma Session no PHP e recuperar esse valor utilizando AJAX?
Estou criando uma aplicação utilizando checkout transparente do PagSeguro e preciso passar um valor como Referência (Identificador). Porém, por se tratar de um dado restrito, eu não gostaria de deixá-lo no Front do HTML. Aí eu fiz da seguinte maneira (exemplo):
No FRONT-END
<?php
  session_start();
  $_SESSION['ref'] = 123;
?>

    <button type="button" id="btnSession">Testar Sessão</button>

SCRIPT JQUERY com chamada AJAX
$(function(){
  $("#btnSession").on("click",function(){
        $.get("backend.php",
        function (res){
            console.log(res);
        })
    })
})

No BACK-END
<?php
  session_start();
  echo $_SESSION['ref'];
?>

Isso está funcionando e me atende perfeitamente. Porém, eu gostaria de saber se isso é correto e seguro para minha aplicação ou se tem uma forma melhor/ mais segura/eficaz de fazer isso com AJAX.
O objetivo dessa aplicação é:
Tenho um formulário HTML, irei passar seus valores para um SCRIPT JQUERY que irá fazer conexão com o PAGSEGURO e enviar esses dados via AJAX para uma outra página PHP. Essa página irá receber os dados e validar a compra. Porém, eu preciso informar uma variável REFERENCE que trata-se do ID do usuário. E se eu colocar essa variável no meu HTML, ela corre o risco de ser alterada. Por isso pensei em setar a variável REFERENCE através de uma SESSION na página que está o HTML e depois retornar seu valor na página de validação em PHP.
Ficou claro agora?
Answer: Sobre a sessão, não há nenhum problema de segurança em si, apenas os problemas inerentes ao próprio sistema de SESSION (como Man-in-the-Middle, Session Prediction, Session Fixation e problemas relacionados ao XSS/CSRF, principalmente se está usando as configurações padrões no PHP).
Você pode ler algumas sugestões de segurança aqui, já que por padrão as configurações do PHP são completamente inseguras, como tudo no PHP. Adicionalmente recomendo ler isto.
O problema é no Ref. Você diz que ele é "um dado restrito", mas isto não define exatamente o que ele é. Bem, qualquer um analisando o trafego de rede (até pelo "Network" no navegador) terá acesso ao ref (devido ao echo $_SESSION['ref']), assim deixando de ser um dado secreto. Isso também pode ser um dado manipulado pelo cliente, como qualquer outro dado, já que o código do AJAX é controlado pelo cliente.

Além disso, pode existir problemas que não são relacionados à segurança. Por exemplo, o $_SESSION['ref'] PODE ser modificado se o usuário entrar em outra página, considere:

Pagina-1.php

$_SESSION['ref'] = 1

Pagina-2.php

$_SESSION['ref'] = 2

No seu código o ref não é alterado, só tem um e é único. Mas, considerando que ele possa ser alterado (existam mais de um produto, por exemplo). Se o usuário acessar o Pagina-1 terá o 1 como setado como o valor. Porém, se em outra nova aba/janela acessar o Pagina-2 o ref será alterado para 2. Agora vem o problema, se ele abrir a janela que está com o Pagina-1 aberta, quando executar o AJAX,   na Pagina-1, ele usará o valor 2 e não o 1.
Isto não é um problema de segurança, mas é um grave problema de usabilidade e um comportamento não-desejável.

Sobre uso JWT e Token, comentado pelo Fabio William Conceição, é desnecessário. Afinal o próprio session já possui um token (o PHP_SESSID é um token, se for analisar) e ele é utilizado para acessar os dados daquela sessão ("os arquivinhos lá no /tmp"). O JWT pode causar mais problemas, recomendaria o Paseto (ele não usa algoritmos arcaicos como o JWT, e nem permite facilmente altera-los, e força de algoritmos melhores como Ed25519, ChaCha20Poly1305 e Blake2), mas não recomendaria o uso neste caso. Isto seria útil apenas se pretende não salvar os dados no servidor. Lembre-se que tanto sua solução atual, como o JWT e quanto o Paseto não são capazes de defender contra o replay-attack.

Sobre ter melhores soluções: existe. Há melhores maneira de alcançar o mesmo objetivo. Mas, não há detalhes na pergunta (dê onde vem o ref, para que ele serve, se existe outra autenticação, porquê ele é secreto...) e nenhuma das soluções que pensei seria tão simplificado quanto ao que fez, somados isto impede de postar aqui uma "outra solução".
Comment: Entendi amigo, vou ler cada link que compartilhou comigo, obrigado. Em relação 3ª estrofe do seu comentário, o " echo $_SESSION['ref'] " foi apenas um exemplo... em relação a 4ª estrofe, o " $_SESSION['ref'] = 123; " foi outro exemplo também... O que preciso fazer é o seguinte: Preciso passar uma variável REF que identifica o usuário. Se eu colocar esse REF no html, o usuário poderá alterá-lo. Por isso pensei em setar uma Session com o REF dele e depois retornar esse valor na página que o AJAX irá acessar, dessa maneira fica tudo no PHP. Entendeu?
Answer: Isso não está incorrecto, mas não é de nem perto uma boa prática porque a $_SESSION e tudo que engloba dentro do objeto da mesma deveria ser acessada apenas pelo o escopo do próprio contexto que ela se aplica, traduzindo, apenas pelo backend.
Se você precisa manipular objetos ou qualquer coisa dentro do backend e precisa que algo seja mudado no contexto da $_SESSION você deveria ter um acessor a ela que não fosse implicatamente como você está fazendo, um token, JWT ou qualquer coisa parecida.
Mas considerando o estilo de script que você está fazendo aparentemente é algo que você ainda está aprendendo.
Mas no mundo do PHP tu tem que tomar cuidado com todas as superglobais (variaveis $_XXXX), pois basicamente essas variaveis podem (e fazem) um grande estrago na sua aplicação se alguém de fora mal intencionado tiver acesso a elas.
O PHP te da muita liberdade, mas essa liberdade tem um preço, que é bem alto na verdade, então tente tomar cuidado em relação a isso.
Comment: Interessante, teria algum link sobre o material que mencionou para eu dá uma estudada por favor?
Comment: O inicio dos estudos vem aqui -> https://www.php.net/manual/en/features.sessions.php
Answer: A session é um valor que deveria ser usado no lado servidor, manipular isso no frontend não é uma boa prática, não é seguro pois é muito mais fácil de ter acesso por outras pessoas.
Se está fazendo integração do PHP com PagSeguro, pode fazer todas as operações do lado server, tudo em PHP, evitando trafegar informações sensíveis para o cliente.
Na própria página do PagSeguro tem uma biblioteca com exemplos: https://m.pagseguro.uol.com.br/
Tem também o projeto no GitHub: https://github.com/pagseguro/php
Ou seja, evite trafegar essa informação, faça uma chamada ajax com o mínimo de dados sensíveis e deixe o código na parte server com o PHP.
Comment: Entendi. Estou me baseando na biblioteca do PagSeguro mesmo, porém lá eles passam essa Referência para o Front e eu não achei isso muito seguro. Aí eu queria fazer essa intermediação da página do formulário e a página de validação em AJAX. Se eu fizer sem o AJAX é tranquilo, mas via AJAX eu não encontrei um método seguro ainda.
Comment: Não entendi o "manipular isso no frontend não é uma boa prática". A manipulação ainda ocorre no PHP, portanto no servidor.
Comment: PS: Não fui eu quem dei negativo.
Comment: manipular no frontend eu quis dizer pegar o valor da session e trazer para o javascript, quis dizer que pode fazer isso tudo no PHP sem precisar desse valor no javascript ;)
bem não entendi o negativo, mas enfim
Comment: @Inkeliz eu havia pensado o mesmo... apesar de ser uma página HTML, acima eu coloco um PHP setando a SESSION, por isso achei que seria seguro e de boas.
Comment: @RicardoPontual eu não passo o valor da SESSION para o JavaScript. Eu justamente pensei em usar a SESSION para não fazer isso... na página HTML eu insiro a SESSION com o PHP no topo e depois retorno esse valor na última página PHP que será acessada via AJAX. Entendeu?
Comment: mas se executar `echo $_SESSION['ref']` está retornando o valor da session para a chamada ajax certo?

Recuperar $_SESSION com Ajax


Can these data be grouped?

Question: Whithin a certain population, I have selected three samples (in three different periods of time) and determined for each the frequency of individuals that present a specific characteristic. I want to determine if all these results can be grouped together or if there are differences between samples. Can I do it by performing a chi-square test for observed vs. expected frequencies and pooling the data if there are no significant differences?
If I do the sampling (three times also) in other populations, should I repeat the same procedure for each in order to determine if data from the same population can be pooled?
Answer: Question 1
If your dataset is something like this
Sample 1           Yes=200             No=180
Sample 2           Yes=156             No=130
Sample 3           Yes=300             No=320
You can use chi-squared test.
Question 2:
I am not sure if I understood your second question. What do you mean with other populations?  Please, give a practical example
Comment: Population 1 Sample 1 Yes=200 No=180;
Population 1 Sample 2 Yes=156 No=130;
Population 1 Sample 3 Yes=300 No=320;
Population 2 Sample 1 Yes=100 No=110;
Population 2 Sample 2 Yes=116 No=100;
Population 2 Sample 3 Yes=30 No=20. I want to know if I can pool together all data from the same population. Should I repeat the chi-square test for each population or there is a way to do the test for all at the same time?
Answer: I suggest three samples in different periods will not be usefully susceptible to sophisticated analysis.
Whether they might be grouped should most obviously depend on their similarity… here, handicapped by there being only three samples.
When you want to determine "if all these results can be grouped together or if there are differences between samples", what differences have you in mind?
To the extent they were similar - ideally, identical - grouping samples over different times might work.
In the same time, how could three samples suffice for a chi-square test for observed v expected frequencies, or pooling of data?
You should repeat the same procedure for anything you hope to compare but whether that would allow data to be pooled would depend on the details.

Can these data be grouped?


How to create a profile page?

Question: I'd like to create a profile page (visible for every visitor) for every user on my website. There should be displayed some personal information about the user (name, date of birth, bio...) and some things related to their activity on the website (favorite articles, own articles...).
I've already added a lot of fields to users (wich have to be filled in during the registration) in the People > Account settings > Manage fields section and created some views with the Views module in order to display their favorites etc.
I'm struggling with the next step. I'm not sure whether I should create a profile page myself or use the Profile2 module (wich is installed at the moment). First of all, I don't know how I can create a profile page myself. How can I set this up, assign it to a user...? Secondly, I'm not very convinced by the power of Profiles2: I managed to add fields to a user's profile page, but I can't find a way to add blocks or views to it. A nice feature is the 'private' field option, but I'm wondering if that can't be realised without the module.
Can you help me in finding a good solution?
Comment: please try to put 1 question at a time it will be easier in that way to give a better answer.
Comment: I agree and I try to do so, but in this case I thought that it would be more difficult for others to help, because they wouldn't see the 'big picture' (the reason for why I'm asking those questions).
Answer: You can consider using Panels module to override the user page.
UPDATE:
You must be knowing default user page has path of form 'user/[uid]'. Now to replace that with our new panels page, visit this link: "admin/structure/pages".
There, you can enable "user_view".
Now when you edit that, you choose layout and content (add the fields). Then when you visit user page at user/[uid], the new layout will take effect.
Comment: no need to have profiles2. Just add the required fields to the user object (like you said you have already done). Then enable the user page in panels, add the fields after choosing layouts.
Comment: Jeroen, you dont need to create a new page with user/[uid]. Once you enable 'user_view', that panels layout will take control of the user page. Then in that variant, you will find the tab for 'layout' and add 'contents'. After adding contents and shoosing layout, try to visit any user page and it will render the panels page and not the default one.

i strongly suggest you to learn Panels a bit, so that these steps will be easy for you. let me see if I can find some tutorials for you.
Comment: https://www.youtube.com/watch?v=_VIkE2ZS5oU

This shows how to override node view pages, but same concept applies to user page too.
Comment: So you mean I should use the Profiles2 page and then use the Panels module to override the 'My main profile' page? How can I do that?
Comment: Okay, but how can I assign the page to a user? In other words, how can I make sure that the user is redirected to his/her own profile page when he/she clicks the 'My profile' link? Same question when another user wants to visit someone else's profile page.
Comment: all you need is to allow view other user profile permissions on permission page
Comment: Updated my answer.
Comment: I enabled the user_view and created a new page with the url 'user/[uid]', but when I click on the 'My account' link or try to navigate to '/user/1', I get a 'Page not found'. What did I do wrong?
Comment: That's it! I had never worked with the user_view, so I didn't know how to use it. It's a really powerful tool. Thank you soo much for all your help!
Answer:
Create a profile using profile2 module
http://www.youtube.com/watch?v=jPbazpRCwP0
Do you need it here
I do not think so, what profile 2 module does is it separates user entity with a separate profile entity.Lets consider this with an example you have user on site with name,age fields but the user can have multiple profiles on the basis of Sports, Music  so fields on the profile goes in that way. You may have fields like compositions,favourites on music profile for the user and games.. etc.  fields on sports profile for the user but name and age will be on the user entity as it is common to both profiles
With fields you have mentioned you do not need profile2 module instead panels module will be good for you as neo has suggested before.
Make profile private without profile2 module
Again panels will make it doable.
https://insready.com/en/blog/3-lines-code-panels3-and-profile-modules-create-user-configurable-privacy-settings
User recent activity
To display the summary of user's recent activity, you can setup a view with a contextual filter of user id, set 'Content pane' display type for your view, and add it to user panel page.
Comment: Thanks for your help again @arpitr. Your tips will be handy in the future without doubt.

How to create a profile page?


Dropping any arguments from a string representing a command line in bash

Question: I need to write a bash function which, given a string that represents a command line, returns just the first token in the command line (i.e. the program being called, which may have spaces in its name), dropping any arguments. I want to do this without using sed or awk or anything but bash builtins and variable manipulation.
e.g.:
drop_args "ls" # prints "ls"
drop_args "ls -al" # prints "ls"
drop_args "spaces\ in\ name --bad-idea" # prints "spaces\ in\ name"

What I've tried is:
drop_args () { echo $1; }

and then I call drop_args ls -al, i.e. without quoting the string, and that works nicely for all cases that I can see except for drop_args spaces\ in\ name.
I'm not too terribly concerned if I can't do this in a way that correctly handles the spaces case with the restrictions I have stipulated, but I need to at least reliably detect that situation and display an appropriate error message, I guess.
This is related to my earlier question about dereferencing shell aliases; it's sort of a subproblem of what I am ultimately trying to accomplish there.
Comment: I don't see a problem with your function. It handles `spaces\ in\ name` without quotes nicely
Comment: hmmm.  Not sure what the problem is.  I created a script: "do it.sh".  The content of the script was simply "echo $0".  When I ran it, it echod "do it.sh".  Is this not what you were looking for?
Comment: @perreal Hmm, you're right that it does appear to work fine from the command line:
    `$ drop_args A\ Bad\ Program --terrible`
    returns `A Bad Program`
...but when called from within a shell script, I guess escaped spaces behave differently and it returns `A\\`. I need it to work within a script.
Comment: What's with the double quotes in your examples? I would expect `drop_args "foo bar"` to print `foo bar` and `drop_args foo bar` to print `foo`.
Comment: @tripleee it seems not to matter in the context of a script; `\ `  (backslash-space) just doesn't parse the way I want it to
Answer: drop_args()
{
  read cmd args <<< "$1"
  echo "$cmd"
}

This loses the backslashes, but they were never really meant to be "there" in the first place.
Comment: This doesn't seem to work properly within a script; the behavior of backslashes in strings is different.
Comment: Why are backslashes being put in arbitrary places?
Comment: What do you mean? They're there to "escape" the spaces as they might be escaped on the command line.
Comment: They're only escaped on the command line because the shell will split by words instead. This code makes sure it isn't split. Why do you believe that you still need them?
Comment: Because my program needs to parse the output of `alias`, which displays the values of aliases as they might be entered on the command line. (Why it needs to do this is not relevant or interesting.)
Comment: You already have the command so I don't know why you'd want to, but you could always replace the backslashes back in if you like.
Comment: I already have the command as it appears in the value of an alias, possibly with arguments, and from this string, which contains `A\ Bad\ Program --really-bad --why`, I need to pull out either `A\ Bad\ Program` or `A Bad Program`, don't care which.


Reflection: get invocation object in static method

Question: Is it possible to get an object that invoked static method in this method?
I have this code:
class A{
    static void foo(){
    }
}
A a = new A();
a.foo();

Can I get instance a in method foo() ?
Comment: Where is the constructor `A()`?
Comment: If you don't define a constructor the A() is the one used by default...
Answer: Firstly, your code isn't good as a programmer.
It is because static methods are class-level methods and should be called without any instance of class.
Recommended approach :
class A{
    static void foo(){
    }
}
A.foo();

Can I get instance a in method foo() ?

Nope, you can't. Because foo() is declared as static. So you can't use this inside that method, since this contains a reference to the object that invoked the method.
Answer: By definition, there is no instance object for a static method (static methods do not operate on a specific object, they are defined within a class purely for namespacing) -- so no.
Answer: No is impossible...the static method don't have the reference, you have to pass it reimplementing the method as:

class A{
    static void foo(A theObject){
    }
}
A a = new A();
A.foo(a);

and is better don't call the static method from the instance of the object
Answer: No; that's what static means.
The compiler actually completely ignores the instance.
Use an instance method.


How to insert temperature and precipitation data on a GEE or GLMM model

Question: I am analysing a data of number of aphids with variation over time (32 avaliations performed every week), area (two areas), and plant position (fixed factor), with 3 replications. Because of that, I am running both GEE and GLMM (to compare the results). The problem is that for each time in each area I have the data on precipitation and temperature. And these data are important because the aphid population is highly affected by these ambient conditions. I really want to study the effect of temperature and precipitation, and I am thinking of using them as fixed factors, but it does not sound correct because they are a range of values. I have thought about using the values as an offset in the model, but I don't know if it is right and probably I will not be able to make any conclusions on how the temperature and precipitation affected the data.
Here is a small example of the data set:

REP- repetition
posi - plant position
prec - precipitation
medt maxt mint - temperature information
area- area
cont- number of aphids
time- week of the count

<code>rep   posi prec   medt    maxt    mint   area cont time

1 s   11.03   21.60   28.20   15.10   1   22     1

1 m   11.03   21.60   28.20   15.10   1   0      1

1 i   11.03   21.60   28.20   15.10   1   0      1

2 s   11.03   21.60   28.20   15.10   1   2      1

2 m   11.03   21.60   28.20   15.10   1   0      1

2 i   11.03   21.60   28.20   15.10   1   0      1

3 s   11.03   21.60   28.20   15.10   1   1      1
.   .     .       .       .        .     .   .

.   .     .       .       .        .     .   .

1 s   143.70  22.66   26.24   19.09   2   0      32

1 m   143.70  22.66   26.24   19.09   2   23     32

1 i   143.70  22.66   26.24   19.09   2   18     32

2 s   143.70  22.66   26.24   19.09   2   0      32

2 m   143.70  22.66   26.24   19.09   2   0      32

2 i   143.70  22.66   26.24   19.09   2   0      32

3 s   143.70  22.66   26.24   19.09   2   3      32

3 m   143.70  22.66   26.24   19.09   2   0      32

3 i   143.70  22.66   26.24   19.09   2   3      32
</code>
Comment: Note that it does not make sense to compare a GLMM & a GEE model, as they are answering different questions. It may help to read [this](https://stats.stackexchange.com/a/32421/7290).
Comment: This is hard to follow. Can you provide a small example dataset to illustrate your situation?
Comment: I have edited this for English grammar based on my interpretation of what you are saying. Please ensure it still says what you want it to.
Answer: More of a too long comment.

I really want to study the effect of temperature and precipitation, and I am thinking of using them as fixed factors, but it does not sound correct because they are a range of values. I have thought about using the values as an offset in the model, ...

Offsets are mostly used for modeling rates, and temperature/precipitation are not involved in rates, so modeling them using offsets does not seem right. Apart from this, that temperature information is max/min-values, is a separate problem, but it is not solved by offsets! Maybe use max/min-temp as separete predictors?


Beginner to guitar playing with left-hand mobility issues - where should I begin?

Question: I'm right-handed but have had severe mobility issues with my left hand. I desperately want to learn the guitar. Should I buy a left-handed guitar? And if so, what should I start out with?
i have had problems weakness in my left arm since I was a child.I cannot move my fingers independently as you would normally I'm speaking specifically my left-hand thumb and fingers. I can make a fist sure no problem but intricate movement one by one each finger no. That's why felt using my right hand to hold down and change cords while strumming or picking with my left would be an appropriate choice.I apologize if i am not explaining this in a more eloquent way wish I could show you guys with a short video to explain. My left hand often was limp and lame as a kid looks fine but muscularly much weaker and not as defined as my right hand.for example something something as touching my thumb to my finger tips with my left hand when i try all fingers move not just  the one im trying to touch.
its a very frustrating experience but i want to overcome somehow and i though with the love of music and always wanting to play guitar i should make eforts
Comment: If you want to play just like someone with normal left-hand mobility, you'll get problems. But if you are willing to adapt your playing to what you _can_ do with your left hand, you might even develop your own style and sound, and you'll sound uniquely like yourself and nobody else. For some funk-soul-pop rhythm comping, even a couple of strings and frets can be made to sound awesome. But if you want to sound just like everyone else and if the joy of playing comes from performing exact note sequences like on records ... not going to happen.
Comment: Some specifics of the hand problem will make tailoring answers easier.
Comment: After your recent edit, it sounds to me like trying to learn to play left handed might be a good choice; you might find [thumb picks](https://www.guitarcenter.com/Finger-Picks-Thumb-Picks.gc) useful instead of regular picks. In any case, the _best_ thing to do would be to find a decent teacher and talk with them about it. They should be able to help you chart a course, and even if you only took lessons for a few months, that would be time and money well-spent.
Comment: I sincerely appreciate all of you taking your time and being so considerate and answering my questions It helps me a lot
Answer: Since you have no guitar experience it may not matter.  You have not provided enough data on your mobility issue to really make a determination.  For a guitarist both arms need to be mobile to some degree, especially for certain techniques.  I suspect you might think that the picking arm does not need to move as much as the fretting arm but that isn't necessarily the case.  For example, if you start doing finger tapping techniques you could be moving the picking hand more than the fretting hand.
You could help us by offering a little more data.  Is the mobility in the rotator cuff?  The wrist and fingers?  Or the elbow.  Les Paul (the inventor of the modern electric guitar), for example, shattered his right arm elbow in an accident.  Doctors were considering putting in a straight metal rod which would have destroyed his musical career.  They opted for fusing his arm at an angle.  Tony Iommi lost two fingers on his fretting hand and managed to adjust with home made prosthetics.  Django Reinhardt damaged his fretting hand in an accident and could only really use 2 fingers reliably but remained one of the greatest gypsy jazz guitarists in history even with the handicap.
My point with the above antecdotes is that even people who play guitar find ways to adjust when they lose mobility.  Since you have no frame of reference it may really not matter if you play right or left handed guitar.  You will hit blocks and you will work through them.  It feels uncomfortable to play guitar for almost all beginners in my experience so the lack of mobility might not be that big of an issue in comparison (again, just speculating since I don't know the exact nature of your issue).
Comment: there are even players with no arms who play with both feet
Comment: True, but I don't think the OP needs to use feet.  I would still like to know more about the severe mobility issue.
Answer: Several thoughts. It primarily depends on what mobility restrictions your left hand has. If it's grip, then it doesn't have to be a problem - you don't need to throttle the neck in order to play notes or chords!
If it's finger mobility, then you're better off using the right hand to finger notes and chords. If it's wrist/elbow mobility, then start with a standard guitar, as a lefty will need that mobility in order to strum chrds - something a guitar is made for.
What we often say is find a teacher. A good one will have some experience, possibly, to guide you, having been presented with your problems face to face. He will explain better than we can here, and give you far better guidance.
Comment: If it is grip, OP may want to set up the guitar in a special way (lighter strings, etc.)
Answer: For a guitar, both hands play an important role. The primary hand (normally right except for left-handers) plucks the strings while the other hand grips the chords in case of accompaniment.
In my opinion, if you just want to learn to pluck some chords for nice evenings at a campfire, you could really try your luck with a left-hand guitar. Notice that the strings will be inverted in contrast to normal right-hand guitars so you cannot just switch hands (unless you switch all strings).
In case you would like to learn how to play melodies and more complex stuff like rhythm patterns and pluck technique, you should consider to start with a right-hand guitar. Maybe your left hand is just untrained and gets used to the frets after some time. Actually it doesn't matter whether your untrained left hand would have to learn rhythmic pluck patterns or grips because both will be complex. - If after some weeks you should encounter big problems and not making progress, you could still switch to a left-hand guitar (or switch your strings at first).
Hope that helps you to find a decision.
Answer: Start with the chromatic scale. Depending on how severe your mobility issue is, keep in mind that you can play with a guitar pic.


Closest distance beetwen clothoid and given point

Question: I need formulas which let me compute closest distance beetwen given point and clothoid ("normal" to clothoid).
I have given point: P(x,y) and Clothoid parameters: BeginnigClothoid(x,y), EndClothoid(x,y), R (radius), A parmeter (clothoid parameter).
Comment: What is the typical range of the parameter ?
Answer: Let the parametric equation of the curve be $x=x(t),y=y(t)$. You need to minimize the (squared) Euclidean distance,
$$d^2=(X-x(t))^2+(Y-y(t))^2.$$
This is otained by canceling the first derivative on $t$,
$$\frac12\frac{d}{dt}d^2=(X-x(t))x'(t)+(Y-y(t))y'(t).$$
In the case of the Clothoid, this is a pretty difficult transcendental equation.
By studying the asymptotic behavior for large $t$, we can establish that the curve tends to hyperbolic spirals  around the two convergence points, and can be approximated by concentric circles. This can give reasonable starting points for iterative methods. I would recommend to try several starting points on neighboring circles to make sure to converge to the right arc.
Farther from the convergence points, it is probably reasonable to approximate the curve with a few line segments and project the given point onto them. This can give one or two starting points (in the overlap areas).
Comment: For numerical methods, it is especially useful to know that in the rotated and scaled coordinate system (as shown in your image), one can split $t$ into precalculated segments, and use a binary search within each segment to locate the (possibly local) distance minimum. Indeed, I wonder if the entire Cartesian plane could be divided into sectors for initial $t$ values (outside the attractor [is that the correct term?], that is: within the spiral passes near the attractor we need at least two local distance minima to be sure).
Comment: The number of curves to be considered will depend on the accuracy of the  flattening (decomposition in a polyline): the maximum deviation between the arc and the chord tells how many extra arcs in the neighborhood should be tried.
Comment: Thank you for answer. I need take a rest and analyze this formula tomorrow morning. Thank a lot once again!
Answer: The clothoid or Euler spiral or Cornu spiral can be defined as
$$\vec{c}(L) = \begin{cases}x(L) = \frac{1}{a} \int_0^L \cos(t^2) d\,t \\
y(L) = \frac{1}{a} \int_0^L \sin(t^2) d\,t \end{cases}$$
or, equivalently, as a power series,
$$\vec{c}(L) = \begin{cases}x(L) = \frac{1}{a} \sum_{i=0}^{\infty} \frac{(-1)^i}{(2 i)!}\frac{L^{4 i + 1}}{4 i + 1} \\
y(L) = \frac{1}{a} \sum_{i=0}^{\infty} \frac{(-1)^i}{(2 i + 1)!}\frac{L^{4 i + 3}}{4 i + 3} \end{cases}$$
and its tangent is
$$\vec{d}(L) = \frac{d\,\vec{c}(L)}{d\;L} = \begin{cases}\frac{d\,x(L)}{d\,L} = \frac{\cos(L^2)}{a} \\
\frac{d\,y(L)}{d\,L} = \frac{\sin(L^2)}{a} \end{cases}$$
The points $\vec{p}$ perpendicular to the spiral fulfill
$$\left ( \vec{p} - \vec{c}(L) \right ) \cdot \vec{d}(L) = 0$$
so one way would be to solve this for $L$, possibly leading to multiple values of $L \in R$, $L \gt 0$.
Another way is to find $L$ where the squared distance from point $\vec{p}$ to point $\vec{c}(L)$ reaches a minimum:
$$\min \left\lvert \vec{p} - \vec{c}(L) \right\rvert^2$$
In both cases, you need $\vec{c}(L)$, whose components are Fresnel integrals (which, as shown above, can also be described as infinite power series).
Because of this, I do not believe there are any algebraic solutions to this. (Even if there were, I suspect they would be basically unmanageably complex.)
This leaves us with numerical solutions.
The attractor for the spiral is at
$$\lim_{L=\infty} \vec{c}(L) = \left ( \frac{\sqrt{\pi}}{2 a \sqrt{2}}, \frac{\sqrt{\pi}}{2 a \sqrt{2}} \right )$$
Points near the attractor may be between the spiral passes, so one probably should take extra care there.
The power series yields an interesting option for finding the numerical solution: you can truncate the evaluation of the series early, based on either the squared distance divided by $a$ squared, or by the direction and length of the vector element iterations $i$ and $i+1$ add to $\vec{c}(L)/a$:
$$\begin{cases}
\frac{x_n(L)}{a} = \frac{L^{4 i + 1}}{(2 i)! \; (4 i + 1)} - \frac{L^{4 i + 2}}{(2 i + 2)! \; (4 i + 5)} \\
\frac{y_n(L)}{a} = \frac{L^{4 i + 1}}{(2 i + 1)! \; (4 i + 3)} - \frac{L^{4 i + 4}}{(2 i + 2)! \; (4 i + 7)} \end{cases}$$
Here is one algorithm for finding the $L \in \mathbb{R}$, $L \ge 0$, that globally minimizes the distance between $\vec{c}(L)$ and point $\vec{p}$:
Find two or three consecutive (in $L$) local distance minima for the squared distance to point $\vec{p}$. If the one with the smallest or middle $L$ has the smallest distance, then it is the solution; otherwise, you need to find the next local minima with a larger $L$, until you find the true minimum.
This should work, because if the point is near the initial part of the spiral, the first local distance minimum is the global distance minimum. If $\vec{p}$ is well outside the spiral attractor, the second local minima is the global distance minimum. Otherwise, $\vec{p}$ is inbetween spiral passes near the attractor, and you need to bracket $\vec{p}$.
Also note that it is easy to split $L$ into sections where $x(L)$ or $y(L)$ is monotonic, allowing for very fast binary searches. This is due to
$$\frac{d \, x(L)}{d\,L} = 0 \iff L = \sqrt{n \pi + \frac{\pi}{2}}$$
and
$$\frac{d \, y(L)}{d\,L} = 0 \iff L = \sqrt{n \pi}$$
where $n \in \mathbb{Z}$. In other words, if $n$ is some integer, range $L = \sqrt{n \pi / 2} .. \sqrt{(n + 1) \pi / 2}$ is one quadrant (one quarter turn) of the Euler spiral. In each such range there can be at most one local minimum in distance to some point $\vec{p}$. (Note that the distance squared is not a monotonic function; but since it only has one minimum in each range, you can still use a fast binary search in distance squared to find the local minimum in each range.)
I do suspect OP is not interested in numerical solutions, but it just strikes me (stroke me?) how realizing the geometric features allows for an efficient approach for numerical solutions. (By this I mean that understanding the geometric interpretation allows for short-circuiting the evaluation of the power series, but also an efficient overall approach for the global minimum distance search that avoids the issues normally associated with finding minima/maxima when dealing with a periodic function.)
Comment: "points near the attractor are the hardest to solve for": I wouldn't say that. The closer you get to the attractor, the better you can locally approximate the curve by a circle and find an easy starting point; at the same time, you know the distances to the neighboring circles and you can check if it is worth to try them.
Comment: @YvesDaoust: Very true. Definitely needs better wording. I was trying to convey the idea that there are many local minima in that region, making it easy to pick the wrong one if the numerical search was careless.


how do i print name key field inside a circle using d3.js

Question: I am very new to D3 so basically going through bunch of examples and problems to try it out. I have a json which looks like this
and the d3 stuff looks like this.

 var inNodes = getNodes();

var w = 600,
    h = 400,
    z = d3.scale.category20c();

var force = d3.layout.force()
         .linkDistance(100)
        .size([w, h])
        .charge(-430);

var svg = d3.select("#chart").append("svg:svg")
    .attr("width", w)
    .attr("height", h);

svg.append("svg:rect")
    .attr("width", w)
    .attr("height", h);

  var nodes = flatten(inNodes),
      links = d3.layout.tree().links(nodes);

  force
      .nodes(nodes)
      .links(links)
      .start();

  var link = svg.selectAll("line")
      .data(links)
    .enter().insert("svg:line")
      .style("stroke", "#999")
      .style("stroke-width", "1px");

  var node = svg.selectAll("circle.node")
      .data(nodes)
    .enter().append("svg:circle")
      .attr("r", function(d){return d.size*2})
      .style("fill", function(d) { return z(d.parent && d.parent.name); })
      .style("stroke", "#000")
      .call(force.drag);

  force.on("tick", function(e) {
    link.attr("x1", function(d) { return d.source.x; })
        .attr("y1", function(d) { return d.source.y; })
        .attr("x2", function(d) { return d.target.x; })
        .attr("y2", function(d) { return d.target.y; });

    node.attr("cx", function(d) { return d.x; })
        .attr("cy", function(d) { return d.y; });
  });

function flatten(root) {
  var nodes = [];
  function recurse(node, depth) {
    if (node.children) {
      node.children.forEach(function(child) {
        child.parent = node;
        recurse(child, depth + 1);
      });
    }
    node.depth = depth;
    nodes.push(node);
  }
  recurse(root, 1);
  return nodes;
}

I am getting a bit lost in the syntax here. So need some help with this. I am trying to print the name of each node inside the node.
function getNodes() {

var inNodes = {
    "name": "APP",
    "children": [
        {
        "name": "API 1",
        "size": 10
        },
        {
        "name": "API 2",
        "size": 10
        },
        {
        "name": "API 3",
        "size": 10,
        }
    ],
    "size":20
};

return inNodes;
}

I looked into whole bunch of examples but not really understanding how things are happening.
Answer: See: http://tributary.io/inlet/5809527
You need to append an svg text element for each data point. Then, in the tick() function, you set the "dx" (and "dy") attribute of the text to be the same as the "cx" (and "cy") attribute of the circle.


Chi-squared statistic applied on bacterial areas

Question: I read a tutorial on how to estimate the growth rate of E.coli by 1) assuming the growth is exponential, 2) computing the area using image processing techniques and 3) comparing the areas computed in these two different ways and doing some curve fitting.
Now, I was modeling a cell population and came up with a different area formula, namely:
$$A(t)=A_{\text{initial}} 2^{t/a_d},$$
where $a_d$ is the age at which the cells divide (in minutes). I want to follow the same procedure as in the tutorial, in order to estimate the age of division instead of the growth rate. I just replaced the formula. However, the graph of $\chi^2$ is always a curve that decreases, and the minimum is always the upper bound of the age range that I set, whichever that is. Not to mention that the curve fitting is completely messed up.
What am I doing wrong and how could I apply my formula to this method?
Answer: Congratulations, per this source on the 'Definition of Exponential Growth',
to quote:

Where a value increases in proportion to its current value. Such as always doubling.
The general formula is:
$y(x) = ab^{kx}$
Notice the variable "x" on the right hand side is part of the exponent (hence "exponential").
Example: $y = e^x $ is a simple exponential function.

You have managed to derive an exponential growth curve. Assuming that errors fitted are percentage in nature (like with a lognormal parent distribution), by taking say, a natural log transform (to the base e), you then have a linear regression model with normally distributed error terms.
Note, if you derive a prediction interval, upon reversing the ln values, you have a corresponding interval with center at the median (not mean) of the lognormal postulated percent error distribution (lookup properties for the parameters of the lognormal here).
[EDIT] The ln linearization of your model is:
$$ln(A(t))=ln(A_{\text{initial}}) + (1/a_d)ln(2)*t$$
So, the linear regression slope estimate, say m, equals the product of ln(2) divided by $a_d$. So, $a_d$ = ln(2)/m . Similarly, a stated confidence interval for m, centered at m, can be transformed to provide a confidence interval for $a_d$.
Comment: Thank you for your answer. I understand why it is an exponential growth curve and how to check that, but I am still not sure how to estimate a_d. The areas for each time step are computed using image processing, like in the tutorial, and now I want to sum the squares of the residuals and minimize the residuals across all data points. In the tutorial, they set up a range of values for the growth rate - I did the same for the age of division - was that maybe wrong? What I expect in real life is that the age of division becomes bigger over time, as it gets more and more crowded.


Um método estático pode ter o mesmo nome de uma propriedade?

Question: Já que um método estático não vai ser um método do objeto posso ter um método estático com o mesmo nome de uma propriedade definida dentro do construtor?
Answer: Sim, pode, não há confusão entre membros estáticos e membros de instância.

class Teste {
    static teste() {
        return 1;
    }
    constructor() {
        this.teste = 2;
    }
}

var x = new Teste();
console.log(x.teste);
console.log(Teste.teste());

Coloquei no GitHub para referência futura.
Answer: Isso é de facto possível, mas não podem por razões obvias ser acedidas ao mesmo tempo.
O método definido como propriedade estática deixa de estar acessível quando a classe é instanciada. E o método definido como propriedade/método da classe só é acessível depois de instanciado.

class MinhaClasse {
  constructor(nome) {
    this.nome = nome;
    console.log('Classe', nome);
  }

  static metodoEstatico(nome) {
    return 'Método estático de ' + nome;;
  }

  metodoEstatico() {
    return this.constructor.metodoEstatico(this.nome + '...');
  }
}

var Fulano = new MinhaClasse('Fulano');
console.log(MinhaClasse.metodoEstatico('Beltrano'));
console.log(Fulano.metodoEstatico());


How to display correctly this string on an alert javascript

Question: I have this string :
myString="Città"

and I'd like to display correctly (as Città) on an alert in Javascript. How can I do it from C# using Javascript/jQuery?
Here for the example
Comment: if I do alert(myString) I see Città
Answer: I think you don't need to use that notation in javascript. If you run alert('Città') the browser will show it correctly.
Comment: You think? Did you try? How is this helping the OP?
Comment: if I do alert(myString) I see Città
Comment: Yes, I tried and it shows perfectly. But I realized the problem he's having is that he gets the string with the HTML code for "à".
Comment: @Victor : yes, that's the problem!
Comment: Ok, so if you get this string from C#, I think you can use `HttpUtility.HtmlDecode` to get the original text, and then show the alert.
Comment: Yeah, that's will work ;) That's a bit dangerous if a user Insert some other javascript code, isn't it? :)
Answer: You need to use the Unicode character. This example uses the escaped form.
alert("Citt\u00e0");

This worked fine for me.
EDIT: see this page for reference (scroll down to "Encodings")
EDIT THE SECOND:
You might need to do a string replace on your returned value from the database.
var myString = "Città";
alert(myString.replace("à","\u00e0"));

Comment: @markzzz - Javascript does not have an HTML decode. Some libraries (jQuery for example) do have such functionality.
Comment: Regarding *"You need to use the Unicode character."* **a)** What you have is not a Unicode character, but the *escaped form* of it. **b)** JavaScript can perfectly cope with the literal Unicode character as long as the correct encoding and Content-Type header is used to transfer it.
Comment: I take the string from DB. I can't insert that string :)
Comment: This won't resolve the problem is my string will be é :) There isn't a sort of HTML decode on jquery? :)
Comment: You're absolutely right about point a, and I've edited my answer to reflect that.


function undefined reference c++

Question: I have a problem :
FPSlimiter.cpp :
#include <windows.h>
#include <mmsystem.h>
#include "FPSlimit.h"

FPSlimiter limiter;

void LIMIT_FPS(DWORD FPS_LIMIT)
{
static DWORD LAST_FRAME_TIME = 0;
limiter.CURRENT_FRAME_TIME = timeGetTime();
if ((limiter.CURRENT_FRAME_TIME - LAST_FRAME_TIME) < (1000 / FPS_LIMIT))
{
    return;
}
LAST_FRAME_TIME = limiter.CURRENT_FRAME_TIME;
}

FPSlimiter.h :
#include <mmsystem.h>
#include <windows.h>

class FPSlimiter
{
    public:
    void LIMIT_FPS(DWORD FPS_LIMIT);
    DWORD CURRENT_FRAME_TIME;
};

calling function from main.cpp :
DWORD MAX_FPS = 60;
limiter.LIMIT_FPS(MAX_FPS);

And i get error :
undefined reference to `FPSlimiter::LIMIT_FPS(unsigned long)'
Sorry for this bunch of code, but i can't find a solution. Thank you.
Comment: add `FPSLimiter::` before `LIMIT_FPS` in FPSLimiter.cpp
Answer: LIMIT_FPS is a member of FPSlimiter, so your definition has to be in the class' scope:
void FPSlimiter::LIMIT_FPS(DWORD FPS_LIMIT) { .... }
     ^^^^^^^^^^^^

Otherwise you are just definint a different, non-member function.

function undefined reference c++


Create Node and related Node at the same time?

Question: I have a content-type (Recipe) that is created by anonymous users and can be rated/reviewed with another content-type (Review).
Users should be able to write a Recipe and a Review related to that Recipe at the same time on the same Page. I think I'm searching for the wrong things but I can't find a solution for this Problem without the need to write a new module.
Thanks in advance.
Answer: The Inline Entity Form module will get you that functionality (assuming your reference field is provided by the Entity Reference module).

Provides a widget for inline management (creation, modification, removal) of referenced entities.
The primary use case is the parent -> children one (product display -> products, order -> line items, etc.), where the child entities are never managed outside the parent form.
Existing entities can also be referenced.
Comment: One little follow up question: Is it possible that other users can add a review after the initial node (Recipe/Review) is created?
Comment: Definitely, but that'll take a bit more work. Short version, enable comments on the node type and install the Fivestar module. With a bit of configuration you can get a good review system going without any code
Comment: Thanks for the reply Clive, but i think i didn't i didn't make clear what my question was =/. So I will try again and then stop bothering you.
I meant can another User add another Review (The Content-Type) to the Recipe. So that I can have one Recipe with x Reviews(Content Type) and the initial review was created during the Recipe creation.
Comment: Oh I get ya :) That would be more down to permissions, but yes, if those are set up right then any user will be able to edit the parent node and new child node(s). If you need that to be limited to one per user, or something, then things get more difficult
Answer: See also references_dialog:

This module extends reference fields like the user and node reference
  fields by adding links to add, edit and search for references through
  a dialog.


Get last row by timestamp in pig

Question: I have some slowly changing metadata that is stored in real-time onto HDFS.  I would like to write a pig job that condenses these rows down to the most recent row for each key.
For example, for these data (column headers added for clarity):
ts   meta   key
--   ----   ---
1    foo    id1
2    que    id2
3    que    id2
4    foo    id1
5    pasa   id2
6    pasa   id2
7    foo    id1
8    pasa   id2
9    pasa   id2
10   pasa   id2
11   pasa   id2
12   hombre id2
13   foo    id1
14   foo    id1
15   hombre id2
16   bar    id1
17   bar    id1
18   bar    id1
19   bar    id1
20   bar    id1

I would expect to get the output:
15   hombre id2
20   bar    id1

I am just starting to learn the ins and outs of Pig Latin - is there a built-in way to do this in pig or some library already, or should I look at writing a UDF?
Answer: This is a good place for a nested foreach:
A = LOAD '$input' AS (ts:int, meta:chararray, key:chararray);
B =
    FOREACH (GROUP A BY key) {
        byts = ORDER A BY ts DESC;
        newest = LIMIT byts 1;
        GENERATE FLATTEN(newest);
    };

Testing on your data (I converted it to be tab-delimited):
(20,bar,id1)
(15,hombre,id2)

With this method you're guaranteed just a single row for each key even if you have two lines with the latest timestamp (though this may not matter for your data).
Comment: Thanks, this worked well.  I'm a bit worried that sorting will not scale as well as the solution from @mr2ert, but ending up with a single result row is desirable, so I will wait until performance issues arise before trying to optimize.
Answer: One way you could do it is:
A = LOAD 'myinput' USING PigStorage(' ')
    AS (ts:int, meta:chararray, key:chararray) ;

-- Group by key, then find the newest ts for each key
B = FOREACH (GROUP A BY key)
    GENERATE MAX(A.ts) AS newest,
             FLATTEN(A) ;

-- Now that each line has the newest (appropriate) ts,
-- we can use it to filter the input
C = FILTER B BY newest == ts ;

Output:
(20,20,bar,id1)
(15,15,hombre,id2)

Note that if you don't want to have the duplicate ts, you can project it out now like:
C = FOREACH (FILTER B BY newest == ts)
    GENERATE A::ts AS ts, A::meta AS meta, A::key AS key ;

But it would be better to just leave the extra ts alone right now and project it out as part of a later FOREACH to limit the number of jobs.
Update: This method will return all lines with the greatest ts for each key.  For example, if the data is like this:
(11,nope,id1)
(20,foo,id1)
(20,bar,id1)

Then it will return both foo and bar.
Comment: This solution is nice too - I picked the one from @WinnieNicklaus since it ends up with a single row per key, although I don't really expect timestamp collisions anyway, so either one would probably work just fine.

Get last row by timestamp in pig


wenzhixin Bootstrap Table Editable: Show Error on server validation

Question: I am working on bootstrap table Editable. An extension of Wenzhixin Bootstrap Table.
Bootstrap Table Editable
I am using OnEditable to send data to the server (Using Laravel to handle the server request). I receive Error Codes in return about the outcome. But I can't seem to find a way to Show that Error on The Editable Popover OR prevent the new value to be replaced by old value. Like Error shows when We validate the Input.
I have checked the Editable->success but it only has NEW VALUE. Response parameter is always undefined.
Here is my code:
<code>var table = $('#table');
       table.bootstrapTable({
        columns: [
            {
                field: 'roomType'
            },
            {
                field: 'Mon',
                editable: {
                    type: 'number',
                    title: 'Update Rates',
                    validate: function (v) {
                        if (!v) return 'Please Enter Rate Value';
                        if (parseFloat(v) < 0) return 'Rate should be greater than 0';
                    }
                }
            }
        ],
        onEditableSave: function (field, row, oldValue, $el) {

            var data = {
                '_token': window.Laravel.csrfToken,
                'Field': field,
                'PK': row['_'+field+'_data'].pk,
                'oldValue': oldValue,
                'newValue': row[field]
            };

            $.post("Url", data)
                    .success(function(data, textStatus, xhr) {
                        if (data.success) {
                        }
                        else{
                            switch (data.code) {
                                case 400:
                                    return data.msg;
                                    break;

                                case 403:
                                    return data.msg;
                                    break;

                                case 401:
                                    return data.msg;
                                    break;
                            }
                        }
                    })
                    .fail(function(data, textStatus, xhr) {
                        return 'Something went wrong.';
                    });
        }
    });
</code>
I am expecting this kind of error to show:
Output To be Expected
Answer: I could not get the required output, to show the error on the popover. But I got a work around.
Sol: I am replacing the old value on error by $el[0].text = oldValue; and showing the error in some alert means.
Thanks
<code>                    $.post(URL, data)
                        .success(function(data, textStatus, xhr) {
                            if (data.success) {
                            }
                            else{
                                switch (data.code) {
                                    case 400:
                                        $el[0].text = oldValue;
                                        ShowError(data);
                                        break;

                                    case 403:
                                        $el[0].text = oldValue;
                                        ShowError(data);
                                        break;

                                    case 401:
                                        $el[0].text = oldValue;
                                        ShowError(data);
                                        break;
                                }
                            }
                        })
                        .fail(function(data, textStatus, xhr) {
                            $el[0].text = oldValue;
                            ShowError('Something Went Wrong');
                        });
</code>


EM Out/Headphones and amplifier recording

Question:
I have got this practice amplifier and as it is seen it has got an EM OUT/Phones output jack where you can directly listen to your guitar through headphones.
My question is If I would buy a male-to-male jack audio cable (like this one)  and then plug it into both amplifier and to computer's microphone/headphones jack will I be able to record my guitar directly?
I asked a similar question before and the answer I got was "You need to preamplify the guitar's signal". I suppose since it is coming directly from amplifier it is already amplified so I will be able to record this audio like it is coming from a microphone. Am I right?
Answer: The em. out/ phones jack will be 'preamplified', so you should be able to plug it in to your computer and get a strong enough signal to record. (I think em. Out stands for speaker emulation - i.e. they try to make it still sound like it's coming through a speaker cabinet).
However, whether that will be enough to do the recording jobs you want to do depends on some other factors. If you just want to record what you're playing solo and leave it at that, then this setup might be good enough, depending on the audio quality of your computer input. However, if you want to start making a song, laying down multiple tracks, you may need better monitoring / latency compensation, etc. Basically, there are reasons why people often buy a dedicated audio interface even if the signal level is good enough.
Comment: Thank you for your answer. Actually I am planning to build my own circuit to sample guitar's input at higher bit depth and sample rates. So If it is amplified enough to get sampled it is enough for me.


Equation in the paper "homotopy limits for 2-categories"

Question: I do not understand a step in the paper "Homotopy Limits for 2-Categories" by Nicola Gambino. The two longer calculations on page 22 together imply that
\begin{align}
\textrm{Ps}(\mathscr J,\textrm{Cat})(W, K(X,D-)) \cong \textrm{Ps}(\mathscr J,K)(W(-) \ast X,D)
\end{align}
when $K$ is a 2-category with copowers denoted by $\ast$. I do not see how the equation above follows from the universal property
\begin{align}
\textrm{Cat}(W,K(A,B)) \cong K(W\ast A,B)
\end{align}
of cotensors in $K$. Can somebody help me?
Comment: Probably you need to "expand" the category of transformations using some kind of end formula. It looks analogous to the same formula for enriched categories. See this [argument](https://math.stackexchange.com/a/4711372/5191) for the case of ordinary categories.
Comment: @ZhenLin Yes, that is what I was thinking too! But I am not aware of an end-formula for the weaker $\textrm{Ps}(\mathscr J,\textrm{Cat})$, though I would be down to believe that such a formula exists for the enriched $[\mathscr J,\textrm{Cat}]$
Comment: @ZhenLin you are right! i found https://arxiv.org/pdf/2210.01522.pdf which also speaks about "pseudo-ends", and with that it should work.
Answer: This is a very short computation with the help of pseudo-ends, whose theory is developed in the very recent text Notes on Lax Ends by Kengo Hirata. One can compute:
\begin{align*}
\operatorname{Ps}(\mathscr J,K)(W,K(A,D-)) &\cong \textstyle \int_X^{ps} \operatorname{Cat}(WX,K(A,DX)) \\
&\cong \textstyle \int _X^{ps}\operatorname{Cat}(WX*A,DX) \\
&\cong \operatorname{Ps}(\mathscr J,K)(W(-)*A,D)
\end{align*}


Discrete Random Variable vs Population Variance - Why Is Only The Latter Normalized?

Question: The formula for the variance of a discrete random variable $X$ with values $\{x_1,x_2, ...,x_n\}$ and probabilities $\{p_1,p_2,...,p_n\}$ is given as $\sum_{i=1}^{n}(x_i - \mu)^2p_i$ where $\mu = \sum_{i=1}^{n}x_ip_i$. On the other hand the formula for variance of a population with values $\{x_1,x_2, ...,x_n\}$ is given as $\frac{1}{n}\sum_{i=1}^{n}(x_i - \mu)^2$ where $\mu = \frac{1}{n}\sum_{i=1}^{n}x_i$. Why is the former variance not normalized while the latter is? I assume it has to do something with the inclusion of the $p_i$ term in the RV's mean, but I can't tease out why.
Comment: When I was a youngster, discreet materials arrived by mail in plain brown wrappers. ;-)  Maybe that's how discreet random variables are communicated, too?
Answer: You need to recognize the distinction between $x_i$'s in two formulas:
Random variable. First,
 $$Var(X) = \sigma_X^2 = \sum_{i=1}^{k}(x_i - \mu)^2p_i,$$
where $x_i$'s are $k$ discrete values that the random variable $X$ may take.
No two of these $x_i$'s may be alike.
Population. Second,
$$Var(X) = \sigma_X^2 = \frac{1}{N}\sum_{i=1}^N (X_i - \mu)^2,$$
where $X_i$'s are the $N$ values appearing in the population. Some
of these $X_i$'s may have the same value.
Urn example. Let's look at a specific example: Suppose an urn contains a population
of $N = 20$ numbered chips. One chip has the number 1; two chips
have the number 2, three have the number 3 and four have 4. That accounts for ten of the twenty chips. Also, one chip as 8, two have 7,
three have 6, and four have 5. That accounts for the rest.
Then the mean of the population is
$$E(X)=\mu_X = \frac{1}{20}\sum_{i=i}^{20}
x_i \\
=  \frac{1}{20}[1 + 2 + 2 + 3 + 3+ 3 +4+4+4+4\\+5+5+5+5+6+6+6+7+7+8]\\
= \frac{1}{20}[1 + (2+2) + (3+3+3) + (4+4+4+4)\\ + (5+5+5+5) + (6+6+6) + (7+7) + 8]\\
= \frac{1}{20}[1 + 2(2) + 3(3) +  4(4) + 4(5) + 3(6) + 2(7) + 8]\\
= \frac{1}{20}[1 + 4 + 9 + 16 + 20 + 18 + 14 + 8] = 90/20 = 4.5.$$
Similarly, the variance of the population is
$$Var(X) = \sigma_X^2 = \frac{1}{20}\sum_{i=1}^{20} (x_i - \mu)^2\\
= \frac{1}{20}[(1-4.5)^2 + 2(2-4.5)^2 + \cdots + (8-4.5)^2]\\
= \frac{1}{20}[12.25 + 3(6.25) + 3(2.25)+4(0.25)\\+4(0.25)+3(2.25) +2(6.25) + 12.25]\\
= \frac{1}{20}[65] = 65/20 = 3.25.$$
f = c(1,2,3,4,4,3,2,1)
x = 1:8
sum(f*(x-4.5)^2)
[1] 65
sum(f*(x-4.5)^2)/20
[1] 3.25

Then returning to the $k = 8$ values of the random variable $X$ we have probabilities $p_i$ taking values $1/20, 2/20, 3/20, 4/20, 4/20, 3/20, 2/20, 1/10$ for the respective values of $x_i,$ which are $1,2,3,4,5,6,7,8,$ respectively. Then
$$E(X) = \mu_X = \sum_{1=1}^8 x_ip_i\\
= 1(1/20)+2(2/20)+3(3/2)+4(4/20)\\+5(4/20)+6(3/2)+7(2/20) + 8(1/20)\\
= \frac{1}{20}[1 + 4 +9 +16+20+18+14+8] = 90/20 = 4.5,$$
as above.
Similarly,
$$Var(X) = \sigma_X^2 = \sum_{1=1}^8 x_ip_i\\
= \cdots = \frac{1}{20}[(1-4.5)^2 + 2(2-4.5)^2 + \cdots + (8-4.5)^2]\\
= \cdots = \frac{1}{20}[65] = 65/20 = 3.25,$$
as above.
Simulation. I can simulate drawing a large sample of chips from the urn with replacement, by using R. The sample procedure in R has three
parameters of interest to us. The first specifies he population,
the second specifies the sample size, the third rep=T indicates sampling with replacement.$
Simulation is cheap, so I will draw a million chips with replacement, and
then find the sample mean of the numbers on chips drawn and also find
the variance. With a million draws the sample mean should approximate
the population mean quite well; similarly, the sample variance should
match the population variance.
set.seed(2020)
pop = c(1, 2,2, 3,3,3, 4,4,4,4, 5,5,5,5, 6,6,6, 7,7, 8)
x = sample(pop, 10^6, rep=T)
mean(x)
[1] 4.500654   # aprx E(X) = 4.5
var(x)
[1] 3.245843   # aprx Var(X) = 3.25

cutp = (0:8) + .5
hist(x, prob=T, br=cutp, col="skyblue2", main="Numbers on Chips Drawn")
 k = 1:8;  p = c(1,2,3,4,4,3,2,1)/20
 points(k, p, col="red", pch=19)

The histogram below shows the proportions of chip numbers drawn.
With a million draws, these proportions should be similar to the
probability distribution of $X$ discussed above (shown as red dots).
Within the resolution of the graph, the match is essentially perfect.
Answer: These are two different $x_i$ in your formulas. The first one uses all possible values of the variable and $p_i$ denote the probabilities of the values. You could call the formula population variance as well as long as probabilities are known.
The second formula is for $x_i$ denoting the observations, in fact all existing observations. For instance, these could be every grade awarded to homework assignment. In this case you have the population. The grades obviously repeat. In the first formula the grades don't repeat because the x lists all possible grades and assigns probabilities to each


Difficult Time Series -Which forecast method?

Question: Following problem. I have a daily time series from 2017 to 2021. I want to forecast the time series for each product type and different categories. I have high autocorrelation for nearly 365 lags.
Any ideas for forecasting methods? Machine learning seems to be right. But as the only input is past data (no exogenous variables) Support Vector regression does not seem to be optimal.

Here some examples
Anyone any ideas where to look for forecasting models for such type of data?
Many thanks in advance
Comment: These look quite funky, what is the process creating these?
Comment: These are booking data for transmission capacities for energy.
Answer: I dont know anything about machine learning, except that it is a popular topic nowadays. You seem eager to apply machine learning techniques to this forecasting problem, but I think some good old fashioned econometric time series analysis is suited for this problem. Your question is about what method to use, but a method as I understand it should be seen in light of some model. So I dont think it is possible to suggest a method when there is no model. I would say that given you only have historical data on endogenous variable(s) with strong autocorrelation I would think applying (V)ARMA(p,q) type models is the way to go. Maximum likelihood estimation is typically the method to determine the model parameters given your data.
Comment: What you suggest IS machine learning, it's simply using a machine to learn parameters although a lot of more traditional stats practitioners reserve it for non-parametric methods like trees or neural nets. Time series especially has been quite resistant to the term, see this excellent answer: https://stats.stackexchange.com/questions/160382/why-time-series-analysis-is-not-considered-a-machine-learning-algorithm
Comment: I tried to model it with arima. But auto.arima in r run on error. Also acf showed high autocorrelation for more than 300 lags. The time series is not stationary and i am not sure how to make it so. Differencing might not be possible here
Comment: A colleague suggested the holt winters approach. But as I explained arima might not be working here due to the data being non stationary.


AWS iam policy for limiting access to only special folders

Question: I have a bucket "mybucket" in which there is a folder "myfolder".  In the same bucket there is also another folder "notmyfolder".
This is the policy that I think "should" work.
{
    "Statement": [
        {
            "Action": [
                "s3:GetObject"
            ],
             "Condition": {
                "StringLike": {
                    "s3:prefix": [
                        "myfolder",
                        "myfolder/*"
                    ]
                }
            },
            "Effect": "Allow",
            "Resource": [
                "arn:aws:s3:::mybucket"
            ]
        }
    ]
}

But testing with the policy simulator trying to do GetObject on a file in myfolder gets denied.
If I change it to
{
    "Statement": [
        {
            "Action": [
                "s3:GetObject"
            ],
            "Effect": "Allow",
            "Resource": [
                "arn:aws:s3:::pangea-configuration/myfolder/*"
            ]
        }
    ]
}

Now the simulator says I can access the file in myfolder.  But it also lets me access a file in notmyfolder.
what am I missing here?
Comment: Where exactly is `notmyfolder` located? In `myfolder`? Your question is unclear.
Comment: It would appear that _something else_ is granting permission to access `notmyfolder`. Try temporarily removing the above permissions and then try to access `notmyfolder` to determine what is happening.
Comment: @Marcin I modified the text to be more explicit.  They are both top level folders in the same bucket.
Comment: Second policy is correct. its not possible for you toaccess `notmyfolder` using it, unless you have other policies (not showed in the question) which allow that.
Comment: @JohnRotenstein might have been some kind of caching issue, cause now notmyfolder is correctly blocked in all cases.  So, one issue down.  Still no idea why the first policy doesn't work for the file in myfolder though.
Comment: @Marcin yeah, I couldn't figure that out either.  I think it was some kind of caching issue.  I repro'ed it 3 times before.  But now it won't allow access to notmyfolder, so that part is good.   But what is wrong with the first policy.  It is almost and exact match to what I found in the AWS docs.
Comment: Can you point us to where you saw `s3:prefix` being used? I suspect that it is used with `ListObject` but not `GetObject`.
Answer: The policy you've shown doesn't allow any access to objects because the resource you've indicated (arn:aws:s3:::mybucket) is a bucket ARN, not an object ARN. You've allowed an object-level action against a bucket ARN, which won't do anything useful.
The resource should be arn:aws:s3:::mybucket/myfolder/*. And you don't need any condition in the IAM policy because the default is to implicitly deny. The policy will not allow any access to objects under the notmyfolder prefix.
Answer: in the initial configuration you are omitting some permissions. Since in addition to the permissions on the prefix you must be able to list the objects inside the bucket, not just its folder.
You can check the step by step in the following link:
https://repost.aws/knowledge-center/iam-s3-user-specific-folder
Greetings


What does IV/IV signify in a chord progression?

Question: I have a chord progression here:

This is the verse of "Can You Feel the Love Tonight"
I have put a flame emoji over the spot I'm confused by.
The chord doesn't belong to the original key. From what I understand, this is an "applied chord". What does that mean? Why doesn't it sound out of key?
Comment: The IV is Eb, the IV of which is Ab. It's like a bVII chord. It doesn't sound out of key because it's a half step away from the vi.
Answer: These chords are called secondary chords, and they're read (in this case) as "IV of IV."
The concept is that the chord is best understood in relation to another chord which isn't tonic. In this case, you're in the key of B♭. "IV/IV" means that it is the IV chord of the IV of B♭. In other words, it's IV of E♭, and IV/E♭ is A♭.
As for why it doesn't sound of out key, that's partially opinion. Some will think it does, some will think it doesn't. But this IV/IV (or ♭VII) is a common feature in popular music. We can conceptualize it as part of the Mixolydian mode, or borrowed from the parallel minor, but it's so common that you might not think of it as being chromatic.
And, if I may say so, typically Roman numerals are best used to show how a chord is functioning. Not knowing the rest of the piece, I see no reason to label this chord as IV/IV; it could just as easily be labeled as ♭VII.
Comment: Agreed. bVII is more accurate and far more technically correct. Why break it if it doesn't need mending?
Comment: It's not, but the subdominant *of the subdominant* is secondary.
Comment: How is the Sub-Dominant chord secondary?
Comment: Secondary chords aren't just dominants. Anything labeled in relation to something other than tonic is a secondary chord.
Answer: It is the Sub Dominant chord of the Sub Dominant Key. So if the Tonic key is Bb then it is the Sub Dominant chord of Eb Major, so Ab / C / Eb. It is a modulation.
Comment: This probably partly due to the hooktheory (where it looks like the screenshot comes from) website.  I haven't used it for a while, but it gets very iffy and weird with how it interprets "modal" (aka not at all modal) songs, so you get the problem that if you include a bVII chord it says "OK so it's mixolydian then" and then other parts of the website reanalyse it in the "parallel major" key, which is... unhelpful to say the least.  Haven't used the site in a while but this was always a problem before and always lead to a lot of inappropriately labelled X/X chords as in this example
Comment: That's what this notation means, but in this case it's wrong (as it leads to a V).  An example when IV/IV would be appropriate would be hollywood boulevard https://youtu.be/rTJVclgwS5g .
Answer: The IV/IV would be called a "borrowed" chord. It's never followed by IV, so it is not technically functioning as a secondary subdominant. It is borrowing notes from another scale. We generically call this type of pre-dominant chord (precedes the Dominant) in a cadence a "substitute subdominant".
Answer: I agree with all the other comments. One thing I'll add is that, while this doesn't make sense in this context, secondary chords are very useful in cases like the "Hey Joe" progression (bVII IV I) or circle progressions (basically extended II V I sequences)