Levenshtein distance calculations

Question: What is the correct Levenshtein distance between the following strings?
<code>hahaha
ahahah
</code>
These sites report different values:
http://andrew.hedges.name/experiments/levenshtein/ (6)
http://planetcalc.com/1721/ (2)
The first site seems to be saying that you must compare each letter in place and change it to match the other string. (Full disclosure, I built the first site. I'm asking because someone emailed me telling me the calculation was incorrect.)
The second site (I think) is saying you can delete the first letter of either string, then add it to the end to get them to match.
Which is the correct algorithm? Thanks!
Answer: You are incorrect. You are allowed to edit, add, or remove any char at a cost of one source. You need to find the smallest value, so since (2)'s answer is smaller (and in fact, smallest) it is right.

Levenshtein distance calculations


Filter rows by field in Mysql

Question: I want if staff go to application page to view the list of application from student. it will only view the status of apply_status = 'PENDING' . status that already approved before will not view in the page.
................................................................................
This is my code if only the apply_status = 'PENDING' will only view in the page. ... I add the if else statement... but is not working. if there is several apply_status = approved. It will not showed the pending one. But if there is no apply_status = aprroved. It will view all the application.
<?php
    include("connection.php");
    $sql="SELECT * FROM application";
    $record = mysqli_query($con, $sql) or die ("error".mysqli_error($con));
    $apply = mysqli_fetch_assoc($record);

    $status1 = $apply["apply_status"];

    if ($status1 == "APPROVED") {
        echo "
";
        echo "No application from student yet.
";
        echo "
";
    }

    else {

    echo "

    Student ID
    Student Name
    Kelompok
    Block
    Level
    House
    Status

";
    $i=0;
    while ($ww=mysqli_fetch_array($query))
    {
        if ($i%2==0)
            $class="evenRow";
        else
            $class="oddRow";

        $id=$ww[0];
        $studentid=$ww[1];
        $name=$ww[2];
        $kelompok=$ww[8];
        $block=$ww[9];
        $level=$ww[10];
        $house=$ww[11];
        $status=$ww[14];

    echo '

        <input type="hidden" name="applyid['.$i.']" value="'.$id.'"/>
        '.$studentid.'
        '.$name.'
        '.$kelompok.'
        '.$block.'
        '.$level.'
        '.$house.'

            <input type="checkbox" name="status['.$i.']" value="approved" checked> APPROVED

';
    $i++;
    }

    echo '
';

    }

i think the error is at the if else statement but i dont know how to differentiate the apply_status = approved and apply_status = pending.
Comment: `print_r($apply);` and look into the printed output...
Answer: Try this,
Remember,
$status1 = $apply["apply_status"];

should be part of loop, there are may rows that has it.
    <?php
    include("connection.php");
    $sql="SELECT * FROM application";
    $record = mysqli_query($con, $sql) or die ("error".mysqli_error($con));
    $i=0;
    $number_of_rows = mysql_num_rows($record);

     if ($number_of_rows == 0) {
            echo "
";
            echo "No application from student yet.
";
            echo "
";
     } else {
      while ($ww=mysqli_fetch_array($record))
     {

    echo "

    Student ID
    Student Name
    Kelompok
    Block
    Level
    House
    Status

";

        if ($i%2==0)
            $class="evenRow";
        else
            $class="oddRow";

        $id=$ww[0];
        $studentid=$ww[1];
        $name=$ww[2];
        $kelompok=$ww[8];
        $block=$ww[9];
        $level=$ww[10];
        $house=$ww[11];
        $status=$ww[14];

    echo '

        <input type="hidden" name="applyid['.$i.']" value="'.$id.'"/>
        '.$studentid.'
        '.$name.'
        '.$kelompok.'
        '.$block.'
        '.$level.'
        '.$house.'

            <input type="checkbox" name="status['.$i.']" value="approved" checked> APPROVED

';
    $i++;
    }

    echo '
';

   }

Comment: thank you so much!!! its work!! but my output look like this -->                      " No application from student yet. and show table of student that apply_status = pending " it view this two result from if else. my table application has 2 student which is one apply_status = approved and another one apply_status = pending. so i want if all the apply_status = approved, so it will show "no application from student yet". but if there is another student that apply_status = pending, it will show only this student application.
Comment: I would limit directly on query  $sql="SELECT * FROM `application` WHERE `apply_status` = 'PENDING'"; then if MYSQL_num_rows return > 0 show rows else show "No application from student yet."
Answer: Im not found "staff" condition in your code,,
include("connection.php");

$sql="SELECT * FROM application";

if($staff){
$sql = $sql. " WHERE apply_status = 'PENDING'";
}else{
$sql = $sql. " WHERE apply_status = 'APPROVED'";
}

Filter rows by field in Mysql


Tensor products of infinite-dimensional spaces and other objects

Question: It has just occurred to me that most of my intuition for tensor products is derived from the special case of finite-dimensional vector spaces, so I'm wondering which properties I've taken for granted are true in general, and which are not.

Let $U$ and $V$ be $k$-vector spaces, possibly infinite-dimensional. Does it remain true that $U^* \otimes V \cong \textrm{Hom}(U, V)$ naturally in $U$ and $V$?
Let $A, B, C$ be objects in an abelian category, or better, a monoidal closed category. Is it true that $\textrm{Hom}(A, B \otimes C) \cong \textrm{Hom}(A, B) \otimes \textrm{Hom}(A, C)$ naturally in $A, B, C$? (Motivation: $\textrm{Hom}(A, -)$ preserves (cartesian) products.)
In the same context as above, is there a bifunctor $\mathscr{F}(-, -)$ such that $\textrm{Hom}(A, C) \otimes \textrm{Hom}(B, C) \cong \textrm{Hom}(\mathscr{F}(A, B), C)$ naturally in $A, B, C$? (Motivation: $\textrm{Hom}(-, C)$ maps coproducts to products.)
Comment: Well an element of $U^{\ast} \otimes V$ has finite rank as a linear map, no? For the other two: did you try to see what happens if you fix two variables and let the third vary, for instance in 2. take $A = \varinjlim A_i$ the functor on the left will then be $\varprojlim \operatorname{Hom}{(A_i, B \otimes C)}$ and on the right hand side you'd have to commute the tensor product with  limits, so no chance without finiteness conditions. Similarly for 3.
Comment: Of course, you still have a canonical isomorphism of $U^ *\otimes V$ onto the subspace of finite rank maps from $U$ to  $V$.
Comment: For 1: you only get the finite rank linear maps.
Comment: @Theo, Pierre-Yves: Thanks. Seems like I have a lot to (un)learn.
Comment: I noticed that the most modest persons are the ones who have the least reasons for being so.
Comment: Is there a positive answer to 2 even for finite-dimensional vector spaces over a field? I get the isomorphism part, but where does the canonicity come from?
Comment: @darij: Actually, I really didn't think through 2 and 3 very much at all. In the finite-dimensional case, for dimension reasons, 2 only works when $A$ is the base field, and even then it says something really trivial.
Answer:
No. As Theo says in the comments, the elements of $U^{\ast} \otimes V$ are precisely the finite-rank maps in $\text{Hom}(U, V)$.
This isn't even true in finite dimensions. The dimension of the LHS grows linearly in $\dim A$ but the dimension of the RHS grows quadratically in $\dim A$.
This also isn't even true in finite dimensions. The dimension of the LHS grows quadratically in $\dim C$ but the dimension of the RHS grows linearly in $\dim C$.

You seem to be under the mistaken impression that the tensor product is supposed to behave like a product. It isn't. Abstractly it comes from the tensor-hom adjunction
$$\text{Hom}(A \otimes B, C) \cong \text{Hom}(A, \text{Hom}(B, C))$$
and concretely it comes from wanting the free vector space functor $\text{Set} \to \text{Vect}$ to be (lax?) monoidal.
Working with naked infinite-dimensional vector spaces is asking for trouble. See topological tensor product for appropriate substitutes for topological vector spaces.
Comment: @Zhen: another way to think about tensor products is that they are really a way to describe [multicategories](http://en.wikipedia.org/wiki/Multicategory). In this case the relevant multicategory has morphisms given by multilinear maps.
Comment: Your last point is interesting: I think the properties I've been ascribing to the hom functor are in fact properties of the product functor! (Because, after all, $\mathbf{Set}$ is also a monoidal closed category.)
Comment: @Zhen: all the properties you've ascribed to the Hom functor are correct, but the product in $\text{Vect}$ and related categories is the direct product, not the tensor product.
Comment: And once again you show me that I should have thought a bit more before commenting...
Comment: @Qiaochu: Yes, I'm aware. My comment was informal: I was observing that, in some sense, $\textrm{Hom}(A, -)$ preserves products because of the product is defined to make it so. But it is a little distressing that the tensor product is neither a pure limit nor a pure colimit in most categories.
Comment: @Zhen: oh. That was a confusing way of saying that. Okay, but the tensor product is something better than a limit or colimit: it's an adjoint of an internal hom, and those are very natural functors.


Manipulação de matrizes em JAVA

Question: Bom dia, estou desenvolvendo um sistema bem simples de estoque onde os itens serao armazenados em uma matriz segue codigo:
package main;

import java.io.Console;
import java.util.Arrays;
import java.util.Scanner;

public class IncluirItem{
    public static void main(String[] args) {
        String[][] itens = new String[2][5];
        String[] campos = new String[7];
        int opcao = 0;
        int remover;
        int verificar = 0;
        int adcionar = 0;
        int tamanho = 2;

        Scanner sc = new Scanner(System.in);

        campos [1] = "Nome";
        campos [2] = "Codigo de barras";
        campos [3] = "quantidade";
        campos [4] = "validade";
        campos [5] = "data de entrada";

        do {
            System.out.println("\n\n### Sistema de estoque - simplificado ###");
            System.out.println("=========================================");
            System.out.println("      |     1 - Adcionar itens   |");
            System.out.println("      |     2 - Excluir itens    |");
            System.out.println("      |     3 - Mostrar itens    |");
            System.out.println("      |     0 - Sair             |");
            System.out.println("=========================================\n");

            System.out.println("Escolha uma opcao: ");
            opcao = sc.nextInt();
            System.out.print("\n");

            switch (opcao) {
            case 1:
                System.out.println("Cadastro de itens: ");
                //Adciona itens
                for (int i = 0; i <2; i++) {
                    System.out.println("Adcionar item? ");
                    System.out.println("1 para sim \n2 para nao: ");
                    adcionar = sc.nextInt();
                    if (adcionar == 1) {
                        System.out.printf("%d. item \n", (i+1));
                        verificar = verificar + 1;
                        for (int j=0; j < 5; j++) {
                            System.out.printf("%s ", campos[j+1]);
                            System.out.printf("= ", i,(j+1));
                            itens[i][j] = sc.next();

                        }
                        System.out.printf("\n");
                    }
                    else {
                        break;
                    }
                }

                break;
            case 2:
                //Remove itens
                System.out.println("Exclusao de itens: ");
                if(verificar > 0) {
                    for (int i = 0; i <2; i++) {
                        System.out.printf("%d. item \n", (i+1));
                        System.out.printf("ID do produto= 00%d \n", (i+1));
                        System.out.printf("\n");
                    }
                }
                else {
                    System.out.println("Nenhum item listado!");
                }
                System.out.println("\nEscolha o numero do item a ser removido: \n");
                remover = sc.nextInt();
                for (int i = 0; i <2; i++) {
                    if(remover == 2) {
                    itens[i] = itens[i-1];
                    }
                }
                break;
            case 3:
                //Mostra itens
                if(verificar > 0) {

                        for (int i = 0; i <2; i++) {
                            if (verificar == 2) {
                            System.out.printf("%d. item \n", (i+1));
                            System.out.printf("ID do produto= 00%d \n", (i+1));
                            for (int j=0; j < 5; j++) {
                                System.out.printf("%s ", campos[j+1]);
                                System.out.printf("= %s \n", itens [i][j]);
                            }
                            System.out.printf("\n");
                        }
                        else {
                                    itens = Arrays.copyOf(itens, tamanho - 1);
                                    verificar = 0;
                                    System.out.printf("%d. item \n", (i+1));
                                    System.out.printf("ID do produto= 00%d \n", (i+1));
                                    for (int j=0; j < 5; j++) {
                                        System.out.printf("%s ", campos[j+1]);
                                        System.out.printf("= %s \n", itens [i][j]);
                                    }
                                    System.out.printf("\n");
                                    break;
                            }
                    }
                }
                else {
                    System.out.println("Nenhum item listado!");
                }

                break;
            default:
                System.out.println("Opção Inválida!");
                break;
            }
        } while(opcao != 0);
    }
}

Minha duvida é a seguinte, eu quero excluir uma posicao da matriz, exemplo: registrei dois itens, na coluna um e coluna dois da matriz e gostaria de remover a coluna um da lista, como realizo essa função, e outra coisa, eu gostaria de quando eu inserisse pela segunda vez algum item a matriz começasse na proxima possicao vazia, atualmente se eu pedir para inserir um novo item a matriz começa da primeira posicao e assim apaga os elementos ja inseridos.
Answer: Arrays têm tamanho fixo e não existe uma forma de apagar uma posição específica do mesmo. O máximo que daria para fazer é setar a posição com null, mas aí você teria que verificar se a posição é nula antes de tentar usá-la.
Mas sinceramente, arrays não são a melhor forma de fazer o que você quer. Muito menos um array de strings. Mas vamos por partes.

Se um item pode ter várias informações diferentes, agrupe-as em uma classe. Algo assim:
public class Item {
    private String nome;
    private String codigoDeBarras;
    private int quantidade;
    private int validade;
    private String dataEntrada;

    public Item(String nome, String codigoDeBarras, int quantidade, int validade, String dataEntrada) {
        this.nome = nome;
        this.codigoDeBarras = codigoDeBarras;
        this.quantidade = quantidade;
        this.validade = validade;
        this.dataEntrada = dataEntrada;
    }

    public String getNome() {
        return nome;
    }

    // demais getters e setters, etc
}

Coloquei os campos como String e int só como exemplo. Não sei se a validade é de fato um número - como "30" para dizer que vale 30 dias, por exemplo - ou se deveria ser uma data), e a data de entrada poderia ser um Date, ou LocalDate, em vez de String. Mas o código acima é só para exemplificar mesmo.
Criei um getter para o nome, e você pode fazer o mesmo para os demais campos. Também é interessante ler isso para entender que nem sempre você é obrigado a criar getters e setters para tudo (mas no exemplo abaixo, vamos supor que criei todos os getters).

Agora que já temos uma classe que representa o item, podemos fazer o cadastro. Como ele é dinâmico (posso adicionar e remover itens à vontade), usar array não é uma boa opção, pois como já disse, ele tem tamanho fixo. Mas a lista de itens pode aumentar e diminuir conforme o usuário vai digitando as opções, então é melhor usar uma estrutura que possa ser modificada conforme a necessidade, como por exemplo um ArrayList. Ficaria assim:
public class CadastroItem {
    private List<Item> itens; // lista contendo os itens

    public CadastroItem() {
        // cadastro começa vazio - cria uma lista de itens sem nenhum elemento
        this.itens = new ArrayList<Item>();
    }

    public void adicionar(Scanner sc) {
        System.out.println("Adicionar item? ");
        System.out.println("1 para sim \n2 para nao: ");
        if (sc.nextInt() == 1) {
            sc.nextLine();
            System.out.printf("%d. item \n", itens.size());
            System.out.print("nome: ");
            String nome = sc.nextLine();
            System.out.print("código de barras: ");
            String codigoBarras = sc.nextLine();
            System.out.print("quantidade: ");
            int qtd = sc.nextInt();
            System.out.print("validade: ");
            int validade = sc.nextInt();
            sc.nextLine();
            System.out.print("data de entrada: ");
            String dataEntrada = sc.nextLine();
            // adiciona o item
            itens.add(new Item(nome, codigoBarras, qtd, validade, dataEntrada));
            System.out.println();
        }
    }

    public void remover(Scanner sc) {
        if (this.itens.isEmpty()) {
            System.out.println("Não há itens a serem removidos");
            return;
        }

        System.out.println("Itens existentes:");
        for (int i = 0; i < this.itens.size(); i++) {
            Item item = this.itens.get(i);
            System.out.printf("%d - %s\n", i, item.getNome());
        }
        System.out.println("\nEscolha o número do item a ser removido: ");
        int posicao = sc.nextInt();
        sc.nextLine();
        if (posicao < 0 || posicao >= this.itens.size()) {
            System.out.println("Posição inválida");
        } else {
            this.itens.remove(posicao);
        }
    }

    public void mostrar() {
        if (this.itens.isEmpty()) {
            System.out.println("Não há itens a serem mostrados");
        } else {
            System.out.println("Itens existentes:");
            for (int i = 0; i < this.itens.size(); i++) {
                Item item = this.itens.get(i);
                System.out.printf("%d - nome=%s, código de barras=%s, quantidade=%d, validade=%d, data de entrada=%s\n", i, item.getNome(),
                                  item.getCodigoDeBarras(), item.getQuantidade(), item.getValidade(), item.getDataEntrada());
            }
        }
    }
}

Em alguns casos eu chamei nextLine sem atribuir a nenhuma variável, porque os  métodos que lêem números, como nextInt, não consomem a quebra de linha (o ENTER), então ao chamar nextLine logo em seguida poderia não funcionar corretamente (leia aqui e aqui para entender melhor).
Repare que separei cada operação em um método, deixando as coisas um pouco mais organizadas. Assim, o main ficaria:
CadastroItem cadastro = new CadastroItem();
Scanner sc = new Scanner(System.in);
while (true) {
    System.out.println("\n\n### Sistema de estoque - simplificado ###");
    System.out.println("=========================================");
    System.out.println("      |     1 - Adicionar itens  |");
    System.out.println("      |     2 - Excluir itens    |");
    System.out.println("      |     3 - Mostrar itens    |");
    System.out.println("      |     0 - Sair             |");
    System.out.println("=========================================\n");

    System.out.println("Escolha uma opcao: ");
    int opcao = sc.nextInt();
    sc.nextLine();
    System.out.println();
    if (opcao == 0)
        break; // se for zero, sai do while (nem testa as demais opções)

    switch (opcao) {
        case 1:
            System.out.println("Cadastro de itens: ");
            cadastro.adicionar(sc);
            break;
        case 2:
            // Remove itens
            System.out.println("Exclusao de itens: ");
            cadastro.remover(sc);
            break;
        case 3:
            // Mostra itens
            cadastro.mostrar();
            break;
        default:
            System.out.println("Opção Inválida!");
            break;
    }
}

Claro que ainda dá para melhorar. Se não for digitado um número, nextInt dá erro e o programa para de executar. Então na classe CadastroItem você poderia ter um método que valida se foi digitado um número de fato:
public class CadastroItem {
    ...

    private int lerNumero(Scanner sc, String mensagem) {
        while (true) {
            System.out.println(mensagem);
            try {
                return Integer.parseInt(sc.nextLine());
            } catch (NumberFormatException e) {
                System.out.println("Não foi digitado um número, tente novamente");
            }
        }
    }
}

Assim, você não precisa mais ter as chamadas de nextLine logo depois de nextInt, e ficaria assim:
public void adicionar(Scanner sc) {
    System.out.println("Adicionar item? ");
    System.out.println("1 para sim \n2 para nao: ");
    if (sc.nextInt() == 1) {
        sc.nextLine();
        System.out.printf("%d. item \n", itens.size());
        System.out.print("nome: ");
        String nome = sc.nextLine();
        System.out.print("código de barras: ");
        String codigoBarras = sc.nextLine();
        int qtd = lerNumero(sc, "quantidade:");
        int validade = lerNumero(sc, "validade");
        System.out.print("data de entrada: ");
        String dataEntrada = sc.nextLine();
        // adiciona o item
        itens.add(new Item(nome, codigoBarras, qtd, validade, dataEntrada));
        System.out.println();
    }
}

public void remover(Scanner sc) {
    if (this.itens.isEmpty()) {
        System.out.println("Não há itens a serem removidos");
        return;
    }

    System.out.println("Itens existentes:");
    for (int i = 0; i < this.itens.size(); i++) {
        Item item = this.itens.get(i);
        System.out.printf("%d - %s\n", i, item.getNome());
    }
    int posicao = lerNumero(sc, "\nEscolha o numero do item a ser removido: ");
    if (posicao < 0 || posicao >= this.itens.size()) {
        System.out.println("Posição inválida");
    } else {
        this.itens.remove(posicao);
    }
}

Answer: Pra você remover a coluna um, deveria setar os valores dessa coluna como 'null' ou algo do tipo, servindo como indicativo pra você mesmo de que esta coluna esta excluída. Já para adicionar os valores na próxima coluna, é possível rodar a matriz pra descobrir o tamanho e inserir no próximo índice, é possível verificar se a próxima posição existe (try catch é importante nesse caso) Dentre outras soluções... Porém na minha opinião, você se encontra no momento perfeito pra expandir seus horizontes e compreender ArrayList, pois provavelment essas funções já são nativas.
Answer: Para você controlar a linha que já foi registrada um item é bem simples.
Faz uma variável contadora começando do 0, exp: int c = 0;
No case 1 tu coloca assim: for (int i = c; i < (número de linhas da matriz); i++) {.
E depois que sair desse for: "for (int j=0; j < 5; j++) {}" você coloca c++;
Assim sempre você vai pra uma nova linha que não foi registrado nada.
Comment: Essa solucao funcionou para mim, preciso agora excluir a posicao do vetor =(

Manipulação de matrizes em JAVA


Attempt to invoke virtual method

Question: Bom dia, estava fazendo uma classe genérica para utilizar o AlertDialog, mas me deparei com o seguinte problema:
05-28 10:11:16.323 19359-19359/com.example.vitordalmolin.abllock E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.vitordalmolin.abllock, PID: 19359
java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.res.Resources android.content.Context.getResources()' on a null object reference
    at android.content.ContextWrapper.getResources(ContextWrapper.java:92)
    at android.view.ContextThemeWrapper.getResources(ContextThemeWrapper.java:81)
    at android.support.v7.app.AppCompatActivity.getResources(AppCompatActivity.java:542)
    at com.example.vitordalmolin.abllock.additional.SystemStatus.alertDialog(SystemStatus.java:40)
    at com.example.vitordalmolin.abllock.activities.Main2Activity$2.onItemClick(Main2Activity.java:156)
    at android.widget.AdapterView.performItemClick(AdapterView.java:346)
    at android.widget.AbsListView.performItemClick(AbsListView.java:1577)
    at android.widget.AbsListView$PerformClick.run(AbsListView.java:3970)
    at android.widget.AbsListView.onTouchUp(AbsListView.java:6080)
    at android.widget.AbsListView.onTouchEvent(AbsListView.java:5839)
    at android.view.View.dispatchTouchEvent(View.java:10018)
    at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2833)
    at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2504)
    at android.widget.AbsListView.dispatchTouchEvent(AbsListView.java:5771)
    at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2844)
    at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2519)
    at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2844)
    at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2519)
    at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2844)
    at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2519)
    at android.widget.ScrollView.dispatchTouchEvent(ScrollView.java:733)
    at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2844)
    at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2519)
    at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2844)
    at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2519)
    at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2844)
    at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2519)
    at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2844)
    at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2519)
    at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2844)
    at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2519)
    at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2844)
    at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2519)
    at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2844)
    at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2519)
    at com.android.internal.policy.PhoneWindow$DecorView.superDispatchTouchEvent(PhoneWindow.java:2869)
    at com.android.internal.policy.PhoneWindow.superDispatchTouchEvent(PhoneWindow.java:1861)
    at android.app.Activity.dispatchTouchEvent(Activity.java:3061)
    at android.support.v7.view.WindowCallbackWrapper.dispatchTouchEvent(WindowCallbackWrapper.java:68)
    at android.support.v7.view.WindowCallbackWrapper.dispatchTouchEvent(WindowCallbackWrapper.java:68)
    at com.android.internal.policy.PhoneWindow$DecorView.dispatchTouchEvent(PhoneWindow.java:2830)
    at android.view.View.dispatchPointerEvent(View.java:10253)
    at android.view.ViewRootImpl$ViewPostImeInputStage.processPointerEvent(ViewRootImpl.java:5523)
    at android.view.ViewRootImpl$ViewPostImeInputStage.onProcess(ViewRootImpl.java:5359)
    at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:4804)
    at android.view.ViewRootImpl$InputStage.onDeliverToNext(ViewRootImpl.java:4857)
    at android.view.ViewRootImpl$InputStage.forward(ViewRootImpl.java:4823)
    at android.view.ViewRootImpl$AsyncInputStage.forward(ViewRootImpl.java:4964)
    at android.view.ViewRootImpl$InputStage.apply(ViewRootImpl.java:4831)
    at android.view.ViewRootImpl$AsyncInputStage.apply(ViewRootImpl.java:5021)

Esta é meu método:
public void alertDialog(int title,int mensage, int textPositiveButton, int textNegativeButton, int textNeutralButton){

    Resources res = getResources();
    String localTitle            = String.format(res.getString(title));
    String localmensage          = String.format(res.getString(mensage));
    String localPositiveButton   = "";
    String localNegativeButton   = "";
    String localNeutralButton   = "";
    if(textPositiveButton != 0){
        localPositiveButton   = String.format(res.getString(textPositiveButton));
    }
    if(textNegativeButton != 0){
        localNegativeButton   = String.format(res.getString(textNegativeButton));
    }
    if(textNeutralButton != 0){
        localNeutralButton   = String.format(res.getString(textNeutralButton));
    }

    //Cria o gerador do AlertDialog
    AlertDialog.Builder builder = new AlertDialog.Builder(context, R.style.DialogStyle);
    //define o titulo
    builder.setTitle(localTitle);
    //define a mensagem
    builder.setMessage(localmensage);
    //define um botão como positivo
    builder.setPositiveButton(localPositiveButton, new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface arg0, int arg1) {
            alertDialogOption(1);
        }
    });
    //define um botão como negativo.
    builder.setNegativeButton(localNegativeButton, new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface arg0, int arg1) {
            //Toast.makeText(BluetoothActivity.this, "negativo=" + arg1, Toast.LENGTH_SHORT).show();
            alertDialogOption(0);
        }
    });
    builder.setNeutralButton(localNeutralButton, new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            alertDialogOption(-1);
        }
    });
    //cria o AlertDialog
    alerta = builder.create();
    //Exibe
    alerta.show();
}

E estas são as biblioteca utilizadas:
import android.content.Context;
import android.content.DialogInterface;
import android.content.res.Resources;
import android.net.ConnectivityManager;
import android.net.ConnectivityManager;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.widget.Toast;

Comment: Poste o stacktrace da Exception também.
Comment: Acredito que seja porque a variável `res` não foi inicializada, não tenho como testar agora pra incluir como resposta
Answer: Context é nulo, você está chamando o método alertDialog(int title,int mensage...) cedo demais. Provavelmente você está chamando o método alertDialog antes do OnCreate (chamando pelo construtor, por exemplo), sendo que a instância da Activity não existe ainda

Attempt to invoke virtual method


xSpanner: how leader sync data to replicas?

Question: In Spanner: Google's Globally-Distributed Database, section 2.1, we read:

To support replication, each spanserver implements a single Paxos state machine on top of each tablet. (An early Spanner incarnation supported multiple Paxos state machines per tablet, which allowed for more flexible replication configurations. The complexity of that design led us to abandon it.)
The Paxos state machines are used to implement a consistently replicated bag of mappings.

Does this single Paxos state machine is similar as "Paxos Made Simple" mentioned Paxos state machine?
I'm curious about once a new leader elected how to learn all the data which is lost. Anyone can describe the detail implementation of Paxos group in Spanner?
Answer: No data is lost since Spanner uses synchronous replication. Leaders have no state that needs to be transferred if they fail or become unavailable. The worst that would happen is a transaction may need to be retried or fail, such as during an extended partition. Such partitions are incredibly rare due to the underlying infrastructure that Spanner is built on top of (its properties are derived from the union of software & hardware).
Leaders typically have 10 seconds leases that are extended if they prove to be healthy, which means leaders my be reelected every 10 seconds.
Answer: Cloud Spanner on Google Cloud Platform is the same Spanner from the whitepaper and it provides more details about it's custom Paxos implementation. Eric Brewer, the author of CAP Theorem, wrote up a whitepaper on it:
https://research.google.com/pubs/pub45855.html
==
To understand partitions, we need to know a little bit more about how Spanner works. As with most ACID
databases, Spanner uses two-phase commit (2PC) and strict two-phase locking to ensure isolation and
strong consistency. 2PC has been called the "anti-availability" protocol [Hel16] because all members must
be up for it to work. Spanner mitigates this by having each member be a Paxos group, thus ensuring each
2PC "member" is highly available even if some of its Paxos participants are down. Data is divided into
groups that form the basic unit of placement and replication.
==


Specify path for shared library on Linux in a C++

Question: I successfully compile my first Shared Library with the ld commannd. It is located in the following path.
/home/user/code/lib/libMy-lib.so
Although when I try to use it in a project I get the following error
<code>/usr/bin/ld: cannot find -lMy-lib
</code>
This it my compile line
<code>g++ SuperProject.cpp -o SuperProject -L/home/user/code/lib -lMy-lib -I/home/user/code/includes
</code>
I've been following these two tutorial and can't find what I'm doing wrong.

http://peon-developments.blogspot.ca/2011/07/creating-and-using-c-shared-libraries.html
http://www.javahotchocolate.com/tutorials/so.html
Answer: Set the path:
LD_LIBRARY_PATH=/home/user/code/lib
Comment: thx for the suggestion, but it does not work for me. This is what I have when I do printenv LD_LIBRARY_PATH=:/home/user/code/lib (note I have a colon before the first /)


Received Memory Warning when calling "SetNeedDisplay" method continously in Objective - c programming

Question: Facing memory warning issue due to calling setNeedsDisplay method. below is the process I have done:
Consider my application is to drawing line using CAShapeLayer in very large UIView (say: MyExampleView) say about (10000 * 8000). In this view am drawing the line by freehand using panGesture method. so in the pan gesture method am calling setNeedDisplay in "MyExampleView" every time so it receive the memory warning and leads to crash the app.
Could any one have suggestion kindly let us know
Code Added:
-(void)handlePan:(UIPanGestureRecognizer *)gesture
{
    exampleArea.currentX = someValue1;
    exampleArea.currentY = someValue2;
    // this someValue1 and someValue2 value keep on changing based on hand      moving;
   [exampleArea setNeedsDisplay]; // Here exampleArea - MyExampleArea class is subclass of UIView.
}

@implementation MyExampleArea
{
}

-(void)drawRect:(CGRect)rect
{
        CGMutablePathRef linePath = nil;
        linePath = CGPathCreateMutable();
        if(!lineShape)
        {
            lineShape = [QlineShapes layer];
        }
        lineShape.lineWidth = 2.0f;
        lineShape.lineCap = kCALineCapRound;;
        lineShape.strokeColor = [[UIColor blueColor] CGColor];
        CGPathMoveToPoint(linePath, NULL,100.0f,100.0f);
        CGPathAddLineToPoint(linePath, NULL, _currentX, _currentY);
        // _currentX, _currentY value will change
        lineShape.path = linePath;
        [self.layer addSublayer:lineShape];
        CGPathRelease(linePath);
}

Comment: please share ur code
Answer: In every call to drawRect:, you are adding a new sublayer without removing any old sublayers. This is quickly going to overwhelm the system with layers.
In any case, you shouldn't be adding layers in drawRect:. You should do that in handlePan: if anywhere. drawRect: is for redrawing the current state, not for modifying the state. drawRect: could be called at any time. If it were called repeatedly, your current code would add layer after layer for the same x,y.


Extract continuous sections of text from txt file

Question: I have a text file that has continuous sections of questions and answers. For example:
Q1: some lines of text.
Answer: some lines of text.
Q2: some lines of text.
Answer: some lines of text.

I want to extract the questions and answers from the text file, and put them in a csv file with two columns (Questions and Answers), where the questions and answers go into their respective columns.
This is the code I have now (still rudimentary):
for line in file:
    if line.strip() == 'Answer :':
       print(line)
       break
for line in file:
    if line.startswith('Q'):
       break
        print(line)

But this prints out only the first instance of the Answer. What do I do?
This is an example of the file:
Q1: What is the piston rod and the connecting rod?
Answer:
Piston Rod
A rod which is connected to the piston and the connecting rod is called piston rod.
Connecting Rod
The intermediate element between piston rod and crankshaft is the connecting rod.

Q2: State the constructional features and material requirements of connecting rod.
Answer:
1. The cross-section of connecting rod is I-section and the rods should be designed long, inorder to satisfy our need and
requirement.
2. The rods should have high strength and should not fail, when axial loads are applied on them.

This is a screenshot of part of the file:

This is an example of the question and answer format in the text file:
Q1.
What is the piston rod and the connecting rod?
Answer :
Piston Rod

A rod which is connected to the piston and the connecting rod is called piston rod. It transmits gas pressure developed by
the fuel or steam to the crankshaft through connecting rod. One end of piston rod is attached to the piston by a tapered rod with a
nut and the other end is joined with the connecting rod, through a crosshead by a cotter-pin. These ends are having no revolving
movement and hence, they are considered as fixed ends.
Connecting Rod

The intermediate element between piston rod and  crankshaft is the connecting rod. It consists of a small end which acts as
a connection for piston rod and a big end, that is usually split to accommodate the crank pin bearing shells. When the fuel force
is transmitted from piston rod to crankshaft, the connecting rod is also subjected to alternate tensile and compressive forces. The
compressive load is taken as the design load for the connecting rod, similar to the design of piston rod.
Q2.
State the constructional features and material requirements of connecting rod.
Answer :
1.
The cross-section of connecting rod is I-section and the rods should be designed long, inorder to satisfy our need and
requirement.
2.
The rods should have high strength and should not fail, when axial loads are applied on them.
3.
Connecting rods are made up of carbon steels or alloy steels of molybdenum and chromium, as these materials have high
tensile and compressive strengths.
Q3.
Write about the forces acting on the connecting rod.
OR

Explain the various types of stresses induced in the connecting rod.

Comment: Can you please edit your post to include an example of the text file? A series of two questions and answers would really help. There a lot of nice ways to breakup a text file, but it will depend largely on the formatting of your text file.
Comment: Which is the format of the text file? Plain text files do not have bold characters.
Comment: It was actually a pdf file that I converted to text using PyMuPdf library. But the screenshot was from the pdf file.
Answer: Let's assume your text file as:
Q1 : What is your name?
Answer: Joe

Q2: What is your last name?
Answer: Joe Joe

Now to create a dictionary we can do:
df = open('myfile.txt', 'r')
df = df.readlines()
ques = []
ans = []
for items in df:
    if "Q" in items:
        ques.append(items)
    elif "Answer" in items:
        ans.append(items)
dictionary = {q:v for q, v in zip(ques, ans)}

print(dictionary)
> {'Q1 : What is your name?\n': 'Answer: Joe\n',
 'Q2: What is your last name?\n': 'Answer: Joe Joe'}

I am also assuming that each question is followed by it's answer. If not this might need some update
Comment: When I tried your code, { 'Q1. \n': 'Answer : \n', 'Q2. \n': 'Answer :  \n'}. And I don't know if I'm going about this the wrong way, but what I really intend to do is to classify all the questions and answers and insert it into a database (e.g mongodb). I read that that's usually done by inserting as json, that's why I decided to use this method. If there was a better method, please I would like to know.
Comment: Also, some of the questions and answers are contained in more than one line. But your code seems to print the questions and answers next to them.
Answer: I think using the full question text as a key dictionary is not needed. Then you need to know it in advance to recover the answers.
You could use two separate lists or dictionaries, one for questions, one for answers. If you use lists, just be sure that question and corresponding answers are at the same index. If you use dictionaries, use the same key (could just be a progressive number) in each dicitionary for the question and the corresponding answer.
Here an example with two dictionaries:
import re

questions = {}
answers = {}

c = 1
scanquestion = True
with open("myfile.txt", "r") as ff:
    for line in ff:
        if re.search(r"^Q\d+", line) is not None:
            scanquestion = True
            questions[c] = line
        elif 'Answer' in line:
            scanquestion = False
            answers[c] = ""
            c += 1
        elif line == '\n':
            pass
        else:
            if scanquestion:
                questions[c] += line
            else:
                answers[c-1] += line

print(questions)
print(answers)

questions[1] is the first question, answers[1] is the corresponding answer.
EDIT after comments and edit of question
After seeing the screenshot and reading the comments, I think you do not have any new lines between answers and questions.
I've edited my answer. I use regex to search for "Q1", "Q2" at the beginning of a line to identify a new question, and do not make any assuptions on presence / absence of empty lines (if present, they are skipped).
Comment: I'm getting: KeyError: 1 (pointing at the line: questions[c] += line)
Comment: Do all your questions start with "Q1", "Q2", etc? If not, that's the reason. I've edited my answer to be more general.
Comment: All the questions started with "Q1", "Q2", but they're in a string format, and your edit no longer gave the error. But it's not giving me the result I want. For example, when i tried to print(questions[1]) and print(answers[1]), it gave me the whole text in the file, just not in a dictionary format. Thanks for your help though.
Comment: That's strange. I tried it and it separates questions and answers correctly. Are you sure your `myfile.txt` follows the format you posted in the question? Is there one empty line between each question-answer couple?
Comment: I guess. Let me add a screenshot of part of the file. I edited my original question and added it there.
Comment: Sorry, you tried to edit my answer. Better edit the original question.
Comment: Oh I'm sorry. I did not notice.
Comment: I'm sorry for being this clumsy. I've edited the original question now.
Comment: @adomzy I've edited again after seeing the screenshot.
Comment: I'm getting the same "KeyError: 1" error I was getting before. I'm sorry for disturbing this much.
Comment: Could you copy paste in your question the content of the the text file converted? It's likely that there is ore or more extra characters before the "Q" and the regex does not match.
Comment: I have added an example of the way the questions and answers look in my text file.
Comment: I tried using the updated text file, I do not get the KeyError. Could you tell me where exactly the KeyError happens? (which line of code). I'm very curious now to understand what is going on.
Comment: It happens on this line: "questions[c] += line".
Comment: I tried changing it to "questions[c] = line", and it started working. But some of the questions with more than one line had some lines missing. For example, Q3 (in my question above), showed only the last line that starts with "Explain...". The other lines of that question were missing in the dictionary.
Comment: Yes, that is expected. `+=` concatenates the line to the previous ones. What I cannot understand is why it misses the first line. The only explanation I can give is that in some cases the beginning of the question does not follow the pattern "Q" plus number. Try to `print(c)` to the console just before `questions[c] += line` You can understand which question fails to be recognized and see in the text file if there are, for example, other characters before the Q.
Comment: I think the code only prints out the line in a question that's just before the Answer. I tried adding another line to Q2, and it printed out just the new line I added. I need it to print out everything between the question and answer.
Comment: That is because you changed `questions[c] += line` to `questions[c] = line`. Leave the `+=`. You need to understand why it fails to recognize the beginning of the question. As far as I understand, it does not enter in the first `if` statement when it should. But on my machine, with the sample code you provided, my code works.
Comment: I just found out why it was not working. The beginning of the text file I'm using was not the beginning of the text I gave as example (I just copied the important part). So when I deleted that part from my text file (so that Q1 was the actual first line), it started working perfectly. Thanks so much man! I really appreciate you taking the time to help me.
Comment: Ah! That's it! Glad to help.


Modify part of a Texture Map that is in use in OpenGL ES 2.0

Question: I have a texture which I use as a texture map. Its a 2048 by 2048 texture divided in squares of 256 pixels each. So I have 64 "slots". This map can be empty, partly filled or full. On screen I am drawing simple squares with a slot of the sprite map each.
The problem is that I have to update this map from time to time when the asset for the slot becomes available. These assets are being downloaded from the internet but the initial information arrives in advance so I can tell how many slots I will use and see the local storage to check which ones are already available to be drawn at the start.
For example. My info says there will be 10 squares, from these 5 are available locally so when the sprite map is initialized these squares are already filled and ready to be drawn. On the screen I will show 10 squares. 5 of them will have the image stored in the texture map for those slots, the remaining 5 are drawn with a temporal image. As a new asset for a slot is downloaded I want to update my sprite map (which is bound and used for drawing) with the new corresponding texture, after the draw is finished and the sprite map has been updated I set up a flag which tells OpenGL that it should start drawing with that slot instead of the temporal image.
From what I have read, there are 3 ways to update a sprite map.
1) Upload a new one with glTextImage2D: I am currently using this approach. I will create another updater texture and then simply swap it. But i frequently run into memory warnings.
2) Modify the texture with glTextSubImage2D: I cant get this to work, I keep getting memory access errors or black textures. I believe its either because the thread is not the same or I am accessing a texture in use.
3) Use Frame Buffer Objects: I could try this but I am not certain if i can Draw on my texturebuffer while it is already being used.
What is the correct way of solving this?
This is meant to be used on an iPhone so resources are limited.
Edit: I found this post which talks about something related here.
Unfortunately I dont think its focused on modifying a texture that is currently being used.
Answer:
the thread is not the same

OpenGL-ES API is absolutely not multi-threaded. Update your texture from main thread.
Because your texture must be uploaded on gpu, glTextSubImage2D is the fastest and simplest path. Keep this direction :)
Render on a Frame Buffer (attached on your texture) is very fast for rendering data which are already on gpu. (not your case). And yes you can draw on a frame buffer bound to a texture (= a frame buffer which use the texture as color attachment).
Just one contrain: You can't read and write the same texture in one draw call (The texture attached to the current frame buffer can't be bound to a texture unit)
Comment: having it bind on a different tread was part of the issue, this along with having my texture coordinates inverted.


What is the default MySQL JOIN behaviour, INNER or OUTER?

Question: So I've been looking through the internet the last hour, reading and looking for the definitive answer to this simple question.
What is the default JOIN in MySQL?
SELECT * FROM t1 JOIN t2

Is that the same as
SELECT * FROM t1, t2

OR

SELECT * FROM t1 INNER JOIN t2

Also a related question, when you use "WHERE" clauses, is it the same as JOIN or INNER JOIN ?
Right now I'm thinking a stand-alone JOIN is identical to using commas and WHERE clauses.
Answer: In MySQL writing JOIN unqualified implies INNER JOIN. In other words the INNER in INNER JOIN is optional. INNER and CROSS are synonyms in MySQL. For clarity I write JOIN or INNER JOIN if I have a join condition and CROSS JOIN if I don't have a condition.
The allowed syntax for joins is described in the documentation.

Right now I'm thinking a stand-alone JOIN is nothing more than (identical to) using commas and WHERE clauses.

The effect is the same, but the history behind them is different. The comma syntax is from the ANSI-89 standard. However there are a number of problems with this syntax so in the ANSI-92 standard the JOIN keyword was introduced.
I would strongly recommend that you always use JOIN syntax rather than the comma.

T1 JOIN T2 ON ... is more readable than T1, T2 WHERE ....
It is more maintainable because the table relationships and filters are clearly defined rather than mixed together.
The JOIN syntax is easier to convert to OUTER JOIN than the comma syntax.
Mixing the comma and JOIN syntax in the same statement can give curious errors due to the precedence rules.
It is less likely to accidentally create a cartesian product when using the JOIN syntax due to a forgotten join clause, because the join clauses are written next to the joins and it is easy to see if one is missing.
Comment: @Quang: This for example will fail: `SELECT * FROM t1, t2 JOIN t3 ON t1.x=t3.y WHERE t1.a = t2.b`
Comment: Sweet, thanks for clarifying up this simple question for me :)  In the past I've always used commas+where clauses... but will be converting to using JOINs per your advice. Thanks
Comment: Hey Mark, what do you mean by mixes of JOIN and commas. Mix queries like this, SELECT * FROM t1 LEFT JOIN (t2, t3, t4)
ON (t2.a=t1.a AND t3.b=t1.b AND t4.c=t1.c) ?
Answer: These are all equivalent, and also equal to, CROSS JOIN.
There are some differences between using comma and [INNER | CROSS] JOIN syntax, which might be important when joining more tables. Pretty much all you need to know is described here in the MySQL JOIN documentation.
Comment: ^--- answer to question is JOIN (standalone) basically is the same thing to INNER and comma+where clauses


Qual a diferença ao criar um projeto class libray (.net framework) e class library(.net standard) no VS2017?

Question: Quais as diferenças e usos desses tipos de projetos?
Answer: Imagina que você queira que sua aplicação tenha portabilidade para criação de quaisquer tipos de API's, como .NET Framework, .NET Core, Xamarin e etc. Neste caso você utilizaria o .NET Standard, porém seus recursos seriam bem limitados, afinal, você teria acesso somente a API's que seriam compatíveis para todas as plataformas.
Já o .NET Framework, você teria acesso a todas as API's do .NET Framework, porém você só poderia criar aplicações para plataformas que suportem o .NET Framework.
Caso tenha mais dúvidas, de uma olhada neste link da Microsoft que explica quando utilizar ou não o .NET Standard.
Espero ter ajudado.
Abraço!
UPDATE 1
Achei este post bastante interessante sobre o assunto e em português pra ficar mais claro.
Comment: Obrigado, ajudou sim!!
Answer: Se escolher o .NET Standard só poderá usar os recursos listados nessa especificação. Qualquer coisa que não esteja nele gerará um erro. Note que ele só tem a lista de componentes, não tem os códigos mesmo, os códigos ele pega de outro lugar. Não existe de forma concreta um .NET Standard, é abstrato para você se garantir que só usurá coisas que funciona em todo .NET compatível com o Standard.
Se escolher o .NET Framework poderá usar o que está dentro dele e aí só poderá usa biblioteca em projetos para o .NET Framework. Não poderá no .NET Core, no Xamarin, no Mono, etc.


Exponential form for matrices

Question: I'm trying to prove that for two commutative matrices $N$ and $M$, that $e^{N+M}=e^Ne^M$.
I wrote using the binomial expansion and commutativity:
$$e^{M+N}=\sum_{k=0}^{\infty}\frac{1}{k!}(M+N)^k=\sum_{k=0}^{\infty}\frac{1}{k!}\left(\sum_{i=0}^{k}\frac{k!}{i!(k-i)!}M^{i}N^{k-i}\right)$$
Now I'm stuck, as I don't know if I can use commutativity of double sums considering the second sum depends on the first, although the result looks somewhat promising, since I can kind of make out what I'm trying to prove.
Comment: The key step is in Marc van Leeuwen's answer below: the double sum you have is equivalent to summing over all non-negative $i,j$.
Answer: I think the easiest approach is to show that $\exp(X+Y)=\exp(X)\exp(Y)$ is an identity in the ring $\Bbb Q[[X,Y]]$ of formal power series in commuting variables $X,Y$. The necessary transformations of sums are now trivially satisfied, as long as the sums make sense for formal power series, notably:
$$\exp(X+Y)=
\sum_{k=0}^{\infty}\left(\sum_{i=0}^{k}\frac{1}{i!(k-i)!}X^{i}Y^{k-i}\right)
=\sum_{i,j=0}^\infty\frac{X^i}{i!}\frac{Y^j}{j!}=\exp(X)\exp(Y).
$$
Then since in the series $\exp$ the coefficients tend to zero faster than exponentially with the degree, the series have infinite radius of convergence, so the identity remains valid after substitution of any pair of commutaing values for $X,Y$.

Exponential form for matrices


Conditional expectation of Poisson process given number of events

Question: Let $\{N(t), t\geq 0\}$ be a Poisson process with rate $\lambda$, $S_n$ the instant of the $n$-th arrival and $T_n$ the $n$-th interarrival time, that is, $T_n = S_n - S_{n-1}$, $n \geq 1$.
Now consider the following result:

Theorem. Given that $N(t) = n$, the $n$ arrival times $S_1, S_2, \dots, S_n$ have the same distribution as the order statistics corresponding to $n$ independent random variables uniformly distributed on the interval $(0,t)$.

I would like to know how to calculate $\mathbb{E}[S_4 | N(1) = 2]$ using the theorem above.
I have already solved it using the memorylessness property of the exponential distribution, since $T_i \sim Exponential(\lambda)$, and it went like: you can call $S_4 = 1 + T_3 + T_4$, then
\begin{align*}
 \mathbb{E}[S_4 | N(1) = 2] &= \mathbb{E}[1 + T_3 + T_4] \\
 &= 1 + \mathbb{E}[T_3 + T_4] \\
 &= 1 + \frac{2}{\lambda},
\end{align*}
since $(T_3 + T_4) \sim Gamma(2, \lambda)$, so I know the result I should get.
My attempt: we can write $S_4 = (T_1 + T_2) + T_3 + T_4 = S_2 + T_3 + T_4$, so it follows
\begin{align*}
   \mathbb{E}[S_4 | N(1) = 2] &= \mathbb{E}[S_2 + T_3 + T_4 | N(1) = 2] \\
   &= \mathbb{E}[S_2 | N(1) = 2] + \mathbb{E}[T_3 + T_4] \\
   &= \frac{1}{2} + \frac{2}{\lambda},
\end{align*}
since increments are independent, $(S_2|N(1) = 2) = \max \{U_1, U_2\}, U_i \sim Uniform(0,1)$, and $(T_3 + T_4) \sim Gamma(2, \lambda)$.
What have I done incorrectly? I'd get the correct result if I wrote instead $S_4' = S_1 + S_2 + T_3 + T_4$, but that's absurd since
\begin{align*}
   S_4' &= S_1 + S_2 + T_3 + T_4 \\
   &= (T_1) + (T_1 + T_2) + T_3 + T_4 \\
   &= T_1 + (T_1 + T_2 + T_3 + T_4) \\
   &= T_1 + S_4.
\end{align*}
In addition to that, in these MIT freely available online class notes from a "Discrete Stochastic Processes" course, on page $92$, we have equation $(2.46)$:
\begin{align}
   \mathbb{E}[S_i|N(t) = n] = \frac{it}{n+1},
\end{align}
which in my attempt would yield a completely different result:
\begin{align}
   \mathbb{E}[S_2|N(1) = 2] = \frac{2}{3}.
\end{align}
How to proceed?
Answer: Your mistake lies in the transition between this statement:
$$\mathbb{E}[S_4 | N(1) = 2] = \mathbb{E}[S_2 + T_3 + T_4 | N(1) = 2]$$
and this statement (the next line):
$$\mathbb{E}[S_4 | N(1) = 2] =\mathbb{E}[S_2 | N(1) = 2] + \mathbb{E}[T_3 + T_4]$$
in which you have disappeared the time gap between $S_2$ and $1$.  You need to make $\mathbb{E}[T_3 + T_4]$ conditional upon $S_2+T_3\geq 1$, otherwise, the time calculation includes the possibility that the third (and fourth) arrivals will occur before $t=1$, but we know they can't, as $N(1) = 2$.  Once you do that, the memoryless property will come into play, and you'll get your missing time back, as it's the expectation of the time between the second arrival and $1$.
Note also that $\mathbb{E}[S_2 | N(1) = 2] \neq 1/2$, so the line "$=1/2 + 2/\lambda$" is also incorrect.  You can see this intuitively by noting that the maximum should have a larger expected value than that of (maximum + minimum)/2, which is evidently $1/2$ (the expectation of a $U(0,1)$ variate.) As you have in your final line, it equals $2/3$.  We can calculate this easily enough by noting that the cumulative density function of a $U(0,1)$ variate is $F(u) = u$, so the c.d.f. of the maximum of two independent $U(0,1)$ variates, label it $z$, is $F(z) = z^2$, so $f(z) = 2z$, and work from there.  (See the answers to Distribution of extremal values)
for the derivation of the c.d.f. of the maximum.)
Comment: No idea what was that comment about. Thank you for the answer!


Advice for first harmonica

Question: Please tell me: for a beginner, which type of harmonica I should buy? Without knowing I have bought a Walther Harmonica, and both side has 48 holes. One side has a written C, and the other side G.
Can I practice with this Harmonica? Thanks.
Answer: I would recommend starting with a more beginner-friendly harmonica (that is, with fewer holes) for now, just to get the basics down. I've always heard great things about the Hohner 20, but of course everyone will have different opinions on where to start.
Starting with a harmonica like the Hohner 20 has multiple advantages, but the two biggest ones (as I see it) are:

A wealth of learning material designed explicitly for someone starting on an instrument like this.
The ability to play actual music much more quickly. In other words, it'll be more fun, and sooner!

With that said, you can certainly keep the Walther; you can come back to it once you've mastered the basics on a more beginner-appropriate instrument.
Of course, you're welcome to just "jump right in" and start learning on the Walther, but the process will probably take a little longer. It will also probably be difficult to find learning materials for that harmonica, since most material will assume an understanding of the basics learned on something like a Hohner 20.
Answer: I found references to a Walther Chromatic 48.  Does yours have a button or slide on the side that changes pitch of the notes?  It should make every note sharper.
If so, then any instruction for a chromatic harmonica should work.  I believe the note layout is the same for every chromatic; they just differ in how many octaves they cover.
Or maybe it's a tremolo; I found a Swan 'Double sided C/G 48 hole tremolo harmonica'.  Americans don't know much about tremolo harmonicas.  They mostly play 10 hole diatonics.  But tremolo is more popular in Asia.
Blues harmonica to start
There are few other questions about tremolo harmonicas.

Advice for first harmonica


AHCI - Will be two HDDs (SSDs) two times faster?

Question: Lets take common numbers:
<code>SATA HDD - 120Mb/s read, write speed heavily depends on gaps in sequence
SATA SSD - 550Mb/s read, 500Mb/s write
PCIe SSD - 2500Mb/s read, 1500Mb/s write
</code>
Lets assume they are connected to AHCI controller (not RAID controller). If we connect two identical drives to AHCI (not RAID-0) and use two-threaded application running on two CPU cores to read/write sequental data, will be speed doubled?
Comment: theoretically yes, practical anything from actually beeing slower to nearly close to 2x the speed is possible.
Comment: Very likely true, if your application is well written for that situation.
Answer:
will be speed doubled?

Yes, No, Maybe - anywhere in between - it entirely depends on the actual configuration and the nature of the use case. In real terms yes you should see some benefit but the only way to know is to test it as you need.


From beta distribution to Dirichlet: Estimation of the concentrantion parameters

Question: Searching at least 3 hours about the connection between beta distribution and dirichlet. My problem is:
I have a collection of random variables $X_i \sim Beta(a_i, b_i)$. The parameters $a_i$ and $b_i$ are known, $\forall i=1,2,...K$. From $\{X_i\}$, I want the dirichlet distribution $(X_1,X_2,...,X_k) \sim Dir(a)$. However, I cannot find a connection between the scale parameters and the concentration vector $a$. The individual distribution of $X_i$ does not provide useful information, but through the dirichlet, the marginals give me the answer.
Any suggestion?
Comment: The [characterization of the Dirichlet distribution in terms of Gamma distributions](https://stats.stackexchange.com/questions/36093/) may be instructive.  Its [merging property](https://stats.stackexchange.com/questions/244996) helps (inductively) to relate Dirichlet to Beta distributions by eliminating one parameter at a time.  Note that neither of the Beta parameters is a scale parameter: they are both *shape* parameters.
Answer: Beta distribution has $(0, 1)$ support, same as each of the variables jointly distributed as Ditichlet. Given $X_i \sim \mathsf{Beta}(a_i, b_i)$, if you wanted to have something like $(X_1, X_2, \dots, X_k) \sim \mathsf{Dir}(\alpha)$, you would need to force $X_1 + X_2 + \dots + X_k = 1$, because Dirichlet distribution has such constraint. For each draw from the distribution, you would need $x_2 < 1-x_1$, $x_3 < 1 - (x_1 + x_2)$ etc., finally with $x_k = 1 - (x_1 + x_2 + \dots + x_{k-1})$ being deterministic rather then random. This means, that the beta distributions would not be independent any more. What follows, independent beta variables do not jointly follow Dirichlet distribution.
There is however the reverse relation, if
$$
(Y_1, Y_2, \dots, Y_k) \sim \mathsf{Dir}(\alpha)
$$
then given $\alpha_0 = \sum_{i=1}^k \alpha_i$, marginally $Y_i$'s follow beta distributions
$$
Y_i \sim \mathsf{Beta}(\alpha_i, \alpha_0 - \alpha_i)
$$
So if your variables jointly follow Dirichlet distribution, their marginals are beta distributed. However if the variables are independent and follow beta distributions, then they do not jointly follow Dirichlet distribution, because you wouldn't be able to guarantee the constraint that they sum to unity.
Example
To illustrate this, let's simulate three independent $X_i \sim \mathsf{Beta}(1, 2)$ random variables, and $(Y_1,Y_2,Y_3) \sim \mathsf{Dir}(1, 1, 1)$ variables
library("extraDistr")
n <- 50000
X <- data.frame(V1=rbeta(n, 1, 2), V2=rbeta(n, 1, 2), V3=rbeta(n, 1, 2))
Y <- as.data.frame(rdirichlet(n, c(1, 1, 1)))

If you look at their marginal plots, they all follow the $\mathsf{Beta}(1, 2)$ distribution.

However if you look at the sums of the samples taken from the beta distributions, they clearly do not sum to unity:
range(rowSums(X))
## [1] 0.07868429 2.56876122

Also if you'll compare the scatter plot (with n = 1000 to make it more readable) of the joint distribution of the beta variables, and Dirichlet, you will see that the independent beta variables are less uniformly distributed then Dirichlet.
Comment: Instead of having $X_i \sim Beta(a_i,b_i)$, which similar distribution would enable retrieving the dirichlet distribution? My problem is that $X_i$ can not be interpreted, but a joint distribution constrained to $\sum X_i=1$, would allow me to get the marginals
Comment: @AlexandrosB what do you mean by retrieving? Why can't you model those variables as a Dirichlet distribution? The problem in here is that with independent distributions you cannot fit the constraint, as the values would need to depend on each other to meet it. So you need a distribution that models the dependence between the variables.
Comment: Is it correct, given the fact that the marginals of the dirichlet follow the beta distribution, to estimate the concentration vector by mapping $X_i \sim beta(a_i,b_i) \to beta(m_i , m_0-m_i)$, where $m_0=\sum m_i $ and $m=[m_1 m_2 … m_k] $ the concentration vector.
Comment: @AlexandrosB I'm not sure if I understand your comment, but if you take three *independent* beta distributions, then (no matter of the parameters) you have no guarantee that their sum would be one, and this is the constraint in Dirichlet distribution.
Comment: OP never specified the Betas were independent to begin with, so it's strange to say they cannot be independent "any more." Given the information in the OP, it follows immediately that the components of $\alpha$ are the $a_i$'s, assuming they satisfy the restriction that $b_i = \sum_{j\ne i} a_j$, otherwise the necessary Dirichlet does not exist.
Comment: @guy maybe my wording was imprecise (fixed this). What I meant is that if you have independent beta variables, they are not jointly Dirichlet.


Promise always returns the initial value

Question: having a bit of a problem with promises in angularjs.
My promises 'get cached', meaning they always return the initial value they got called with. I'm pretty familiar with promises from other places, but new to angularJS, so please help me shed a light on my problem, I'm probably not understanding something very basic here
I am using a factory:
.factory('Traffic', function ($http) {
    var trafficUrl = 'some url';
    var httpPromise = $http.get(trafficUrl, {cache: false} );
    var invalidateCache = function() {
        return $http.get(trafficUrl, {cache: false} );
    }

    return {
        all: function () {
          httpPromise = invalidateCache();
            return httpPromise
              .then(function (response) {
                //parsing the response and returning stuff (not promise)
        }

    }
})

which is sending a request, and parsing it for the first time.
now invalidateCache was suggested by someone to avoid exactly my problem (assign a new $http.get each time to avoid it referring to the same, initial promise).
now my controller:
.controller('TrafficCtrl', function ($interval, $ionicLoading, $scope, Traffic) {
var getJams = function () {
      var traffic = Traffic.all();
      traffic.then(function (response) {
            //doing stuff with the response
        })
    };

    $scope.refresh = function () {
      getJams();
    }
})

now, each time I invoke $scope.refresh method, I see the items getting 'refreshed' (console.log gets called inside getJams) but the values stay as the first called getJams().
Thanks.
Comment: Can you turn on your network traffic and see what it is capturing? I wonder if the $http response is being cached even though you are telling angular not to. Is it making subsequent network requests? Is browser saying response was cached when it returns?
Comment: just to clarify - is the ajax call executing and reaching to the server? are you sure about it ? please check that and inform us.
Comment: @Patrick seems like you were right, the response is `from cache`, so the problem is not here. so my new question is, how do I disable this cache ?
Answer: From your comment, it sounds like the browser is caching your response, so you will want to update the server logic to set Cache specific headers.
You will probably want to add the following Cache-Control header to your response:
Cache-Control: no-store, no-cache
A little more info about the cache headers here.
Should be able to find plenty of examples to set this in your server side language of choice.
Also, you can clean up the code much more:
.factory('Traffic', function ($http) {
    var trafficUrl = 'some url';

    return {
        all: function () {
          // don't need the invalidate call anymore
          return $http.get(trafficUrl).then(function (response) {
                //parsing the response and returning stuff (not promise)
        }

    }
})

And your controller:
var getJams = function () {
      // No need to store the initial promise call, just chain them.
      Traffic.all().then(function (response) {
            //doing stuff with the response
        })
    };


How to configure Apache so all requests go to single CGI file

Question: I'm porting a CGI application from an embedded web server to run under Apache. In the effort of changing the least amount required I'm trying to figure out how to configure Apache so any requests coming in go to my CGI program, which then will use the QueryString environmental variable to determine which file needs to be created.
I have Apache working now to where it will process my CGI file if it's requested directly i.e. localhost/cgi-bin/cgi_test.out
but I need to figure out how to get my application to be called whenever any file is requested:
localhost/ -> call my application with QueryString set to "" or "/"
localhost/thisFile -> call my application with QueryString set to "/thisFile"
etc.
I have been doing all of my configuration testing under /etc/apache2/sites-available/mysite, which has been enabled and the default disabled.
Thanks for any help.
I've tried the recommendation from here: Configure apache to handle all requests via single index.php but I keep getting circular redirects.
EDIT: I have tried a few different variations of mod-rewrite but they have not worked yet.
I have an index.cgi file under /usr/lib/cgi-bin (default location) and the default index.html under /var/www/.  I've reverted everything back to default settings so I'm ready to start fresh with any new ideas.
Comment: are you using mod-rewrite? if so, could you post your rewrite rules for debugging
Comment: As Roy said, mod_rewrite is the solution.
Answer: Are you averse to mod_rewrite?  You could easily setup a RewriteRule like so:
<code>RewriteCond %{REQUEST_URI} ^(.*)$
RewriteRule ^(.*)$ /mycgi.cgi [L,E=QUERY_STRING:$1]
</code>
Comment: I finally got the rewrite rule to work, turns out by default the AllowOverride None is configured and must be commented out.
Comment: Where should I be putting this?  What file?  I'm slightly confused on the purposes for the different configuration files.

I'm not opposed to mod_rewrite at all.
Comment: This would be in your Apache config, where it goes depends on your configuration, e.g. if this is for a single vhost it'd go in the configuration for the vhost.

Documentation for mod_rewrite is available at http://httpd.apache.org/docs/2.0/mod/mod_rewrite.html


check for respective elements in arrays in powershell

Question: I have two arrays with three elements(file name parts) each. I need to join first element of first array and first element of second array and test if is not null and if the combination(file name) exists and like wise i need to do it for other two elements in a same manner.
$file_nameone_array = ( table, chair, comp)
$file_nametwo_array = ( top, leg , cpu)
foreach ($input_file in $file_nameone_array) {
foreach ($input_rev in $file_nametwo_array) {
$path = "D:\$input_file-$input_rev.txt"
    If (test-path $path -pathtype leaf) {
        write-host "$path exists and not null"}
    else{
        write-host "$path doesnot exist"
        exit 1}

I expect to test for "table-top.txt", "chair-leg.txt" , "comp-cpu.txt"
whereas my code checks for "table-leg.txt" and exits saying table-leg.txt doesnot exist.
Comment: Your declaration of array is wrong. It has to be defined with `@`
Answer: This sounds like a coding problem for a homework assignment (i.e. something you should figure out), so I'll just give you hints instead of the answer.

Your elements of array need to be wrapped in quotes.
Use Write-Output $path to see what you're actually checking for.
Use a regular for loop
This is the syntax to write output of the first element in the array: Write-Output "$($file_nameone_array[0])"

Hopefully you can get this answer from this.
Answer: You can try this way :
$file_nameone_array = ( "table","chair", "comp") # INITILIZING ARRAY
$file_nametwo_array = ( "top", "leg", "cpu") # INITILIZING ARRAY

if ($file_nameone_array.Count -ne $file_nametwo_array.Count )  # CPMPARING BOTH ARRAY'S SIZE
{
    Write-Error "Both array must have same size..." # THROW ERROR
    exit # EXIT
}

for($ind = 0 ; $ind -lt $file_nameone_array.Count ; $ind++) # FOR LOOP 0 TO ARRAY'S LENGTH - 1
{
    $path = "D:\\" + $file_nameone_array[$ind] + "-" + $file_nametwo_array[$ind] + ".txt" # COMBINING BOTH ELEMENTS
    If (test-path $path -pathtype leaf) # CHECKING PATH EXIST OR NOT
    {
        write-host "$path exists and not null" # PRINT PATH EXIST
    } # END OF IF
    else # ELSE
    {
        Write-Error "$path doesnot exist" # THROW ERROR : FILE NOT EXIST
        exit 1 # EXIT SCRIPT
    } # END OF ELSE

} # END OF FOR LOOP

Answer: If you change your example slightly to just display the $path variable ike this:
$file_nameone_array = @( "table", "chair", "comp" )
$file_nametwo_array = @( "top", "leg" , "cpu" )
foreach ($input_file in $file_nameone_array) {
    foreach ($input_rev in $file_nametwo_array) {
        $path = "D:\$input_file-$input_rev.txt"
        write-host $path
    }
}

you get this output
D:\table-top.txt
D:\table-leg.txt
D:\table-cpu.txt
D:\chair-top.txt
D:\chair-leg.txt
D:\chair-cpu.txt
D:\comp-top.txt
D:\comp-leg.txt
D:\comp-cpu.txt

so you can see why it's looking for "D:\table-top.txt" as the first file.
what you can do instead is this:
$file_nameone_array = @( "table", "chair", "comp" )
$file_nametwo_array = @( "top", "leg" , "cpu" )
for( $index = 0; $index -lt $file_nameone_array.Length; $index++ ) {
    $input_file = $file_nameone_array[$index];
    $input_rev  = $file_nametwo_array[$index];
    $path       = "D:\$input_file-$input_rev.txt"
    write-host $path
}

and now you get this output
D:\table-top.txt
D:\chair-leg.txt
D:\comp-cpu.txt

You can replace the write-host with your original file checking logic and you should get the behaviour you were after.
Note - This requires your arrays to be exactly the same length, so you might need to put some error handling in before this bit of code in your script.


Normalizar valores separados por virgula para nova tabela

Question: A ideia é deixar de ter a coluna com os valores separados por virgula e passar os mesmos para uma tabela intermédia:
Tabela origem
Assumindo uma tabela com o nome press com os seguintes campos:
id, tag_id

Contendo registos tipo:
┌───────────┬──────────────┐
│ press_id  │  tag_id      │
├───────────┼──────────────┤
│  1        │  1,2,3       │
├───────────┼──────────────┤
│  2        │  2,6,5       │
├───────────┼──────────────┤
│  3        │  10,450      │
└───────────┴──────────────┘

Tabela Destino
Pretende-se realizar uma consulta para ler os mesmos e escrever os valores numa nova tabela press_tags que vai estabelecer a relação entre a press e a tag:
┌──────┬────────────┬──────────────┐
│  id  |  press_id  │  tag_id      │
├──────┼────────────┼──────────────┤
│  1   │  1         │  1           │
├──────┼────────────┼──────────────┤
│  2   │  1         │  2           │
├──────┼────────────┼──────────────┤
│  3   │  1         │  3           │
├──────┼────────────┼──────────────┤
│  4   │  2         │  2           │
├──────┼────────────┼──────────────┤
│  5   │  2         │  6           │
├──────┼────────────┼──────────────┤
│  6   │  2         │  5           │
├──────┼────────────┼──────────────┤
│  7   │  3         │  10          │
├──────┼────────────┼──────────────┤
│  8   │  3         │  450         │
└──────┴────────────┴──────────────┘

Pergunta
Como selecionar todos os registos da tabela de origem e por cada tag_id que existe separado por virgula, inserir um registo na tabela destino?
Answer: MySQL não tem nenhuma função que nos permita dividir um string em múltiplas linhas, pelo que o trabalho torna-se um pouco complexo:
SQL Fiddle
INSERT INTO press_tags (press_id, tag_id)
SELECT
    press.press_id,
    SUBSTRING_INDEX(SUBSTRING_INDEX(press.tag_id, ',', n.n), ',', -1) tag_id
FROM press
CROSS JOIN
(
    SELECT a.N + b.N * 10 + 1 n
    FROM
    (SELECT 0 AS N UNION ALL SELECT 1 UNION ALL SELECT 2 UNION ALL SELECT 3 UNION ALL SELECT 4 UNION ALL SELECT 5 UNION ALL SELECT 6 UNION ALL SELECT 7 UNION ALL SELECT 8 UNION ALL SELECT 9) a,
    (SELECT 0 AS N UNION ALL SELECT 1 UNION ALL SELECT 2 UNION ALL SELECT 3 UNION ALL SELECT 4 UNION ALL SELECT 5 UNION ALL SELECT 6 UNION ALL SELECT 7 UNION ALL SELECT 8 UNION ALL SELECT 9) b
    ORDER BY n
) n
 WHERE n.n <= 1 + (LENGTH(press.tag_id) - LENGTH(REPLACE(press.tag_id, ',', '')))
 ORDER BY press_id, tag_id

Explicação

A sub-consulta com um pseudônimo de n vai gerar em tempo real uma sequência de números de 1 a 100, neste caso em particular, utilizando [UNION ALL][4] e CROSS JOIN.
No SELECT experior, no SUBSTRING_INDEX() interior, vamos obter tudo até ao enésimo elemento em uma lista.
O SUBSTRING_INDEX() exterior vai extrair a porção mais à direta após o último delimitador, conseguindo assim receber a informação do enésimo elemento.
CROSS JOIN permite-nos produzir um conjunto de linhas que é um produto cartesiano (de 100 linhas em n, e todas as linhas da tabela press).
A condição na cláusula WHERE vai filtrar todas as linhas desnecessárias do conjunto de resultados.

Esta consulta vai dividir até 100 tag_id por cada registo na tabela de origem. Para o caso em mãos é suficiente, mas se for necessário, pode-se ajustar as sub-consultas.

Cenário comum
Um cenário comum com valores separados por um delimitador numa coluna é a inserção da combinação valor + delimitador, resultando em algo tipo:
valor;valor;valor;

Onde a presença do último delimitador, com a solução supra citada, vai gerar um registo em branco na tabela de destino:
┌──────┬────────────┬──────────────┐
│  id  |  press_id  │  tag_id      │
├──────┼────────────┼──────────────┤
│  1   │  1         │              │
├──────┼────────────┼──────────────┤
│  2   │  1         │  2           │
├──────┼────────────┼──────────────┤
│  3   │  1         │  3           │
└──────┴────────────┴──────────────┘

Este problema pode ainda refletir-se num erro tipo:

Incorrect integer value: '' for column 'tag_id'

Para evitar isto, podemos fazer uso de um outro SELECT para selecionar os campos onde a tag_id não seja '' ou NULL:
INSERT INTO press_tags (press_id, tag_id)
SELECT
  result.press_id,
  result.tag_id
FROM (
  # consulta aqui
) AS result
WHERE result.tag_id > ''

O que resulta em:
SQL Fiddle
INSERT INTO press_tags (press_id, tag_id)
SELECT
  result.press_id,
  result.tag_id
FROM (
  SELECT
      press.press_id,
      SUBSTRING_INDEX(SUBSTRING_INDEX(press.tag_id, ',', n.n), ',', -1) tag_id
  FROM press
  CROSS JOIN
  (
      SELECT a.N + b.N * 10 + 1 n
      FROM
      (SELECT 0 AS N UNION ALL SELECT 1 UNION ALL SELECT 2 UNION ALL SELECT 3 UNION ALL SELECT 4 UNION ALL SELECT 5 UNION ALL SELECT 6 UNION ALL SELECT 7 UNION ALL SELECT 8 UNION ALL SELECT 9) a,
      (SELECT 0 AS N UNION ALL SELECT 1 UNION ALL SELECT 2 UNION ALL SELECT 3 UNION ALL SELECT 4 UNION ALL SELECT 5 UNION ALL SELECT 6 UNION ALL SELECT 7 UNION ALL SELECT 8 UNION ALL SELECT 9) b
      ORDER BY n
  ) n
  WHERE n.n <= 1 + (LENGTH(press.tag_id) - LENGTH(REPLACE(press.tag_id, ',', '')))
  ORDER BY press_id, tag_id
) AS result
WHERE result.tag_id > ''

Grande parte desta solução é proveniente das respostas no SOEN nesta pergunta.
Answer: Olha parabéns pela sua resposta @Zuul da p/ ver que tem muita experiência no MySql.
Eu consigo chegar no mesmo resultado, mas de uma maneira mais humilde, talvez até seja considerada uma gambiarra, mas é o que sempre usei como solução para casos deste tipo.
PREPARAR DADOS

Eu faço um sql que irá gerar um "script":

select concat('insert into press_tags (press_id,tag_id) select ',press_id,',tag_id from (select NULL tag_id union select ', replace(tag_id,',',' union select '),') A where tag_id IS NOT NULL;') 'query' from press;

Esta instrução irá gerar uma saída assim:

insert into press_tags (press_id,tag_id) select 1,tag_id from (select NULL tag_id union select 1 union select 2 union select 3) A where tag_id IS NOT NULL;
insert into press_tags (press_id,tag_id) select 2,tag_id from (select NULL tag_id union select 2 union select 6 union select 5) A where tag_id IS NOT NULL;
insert into press_tags (press_id,tag_id) select 3,tag_id from (select NULL tag_id union select 10 union select 450) A where tag_id IS NOT NULL;

EXECUTAR SCRIPT

Pego essa saída e executo como instrução sql:

mysql> insert into press_tags (press_id,tag_id) select 1,tag_id from (select NULL tag_id union select 1 union selec
t 2 union select 3) A where tag_id IS NOT NULL;
Query OK, 3 rows affected (0.04 sec)
Records: 3  Duplicates: 0  Warnings: 0

mysql> insert into press_tags (press_id,tag_id) select 2,tag_id from (select NULL tag_id union select 2 union selec
t 6 union select 5) A where tag_id IS NOT NULL;
Query OK, 3 rows affected (0.04 sec)
Records: 3  Duplicates: 0  Warnings: 0

mysql> insert into press_tags (press_id,tag_id) select 3,tag_id from (select NULL tag_id union select 10 union sele
ct 450) A where tag_id IS NOT NULL;
Query OK, 2 rows affected (0.03 sec)
Records: 2  Duplicates: 0  Warnings: 0

Como disse é uma forma mais simples, utiliza-se apenas de comandos mais básicos, mas é uma alternativa que funciona ;)
Comment: +1 Esse método revela-se de simples implementação e flexibilidade para inúmeros cenários.


Quadratics/Algebra word Problem (based on physics)

Question: There is a problem from an old high school math book I have.
It appears in a chapter on quadratics and polynomials.
It uses constant velocity, so hence it is physics based type of problem.
Over the years I have come back to this problem, and could never figure it out. I once took this problem to a university Masters student studying "Algebraic Geometry", but he gave me a very convoluted answer, or I should maybe say he gave me an abstract method to solve this, which later I could not figure out.
So here is the question:

Two runners start at the opposite sides of a $60$ meter field. One person runs at $4$ m/s, the other person runs at $5$ m/s. If they run back and forth for $12$ minutes, how many times with they pass each other.

Answer in the book is: They pass each other $54$ times.
I have no idea how to model this problem.
Hope someone knows how to figure this problem out.
Regards,
P
Comment: Though I do not have an answer (yet), I was able to graph this problem in Desmos, having all the crossings visible. You might be interested: https://www.desmos.com/calculator/pgsbyry5c9
Comment: Hi Mark, I really like what you did with Desmos.com, its a nice way to illustrate this problem. I liked the fact that you created algebraic functions here, because i believe that is what the problem is looking for.
Comment: @Palu Please, if you are ok, you can accept the answer and set it as solved. Thanks! cdn.sstatic.net/img/faq/faq-accept-answer.png
Answer: Relative to one of the runners, the other runner approaches their next meeting at a speed of $4+5=9$m/s. So if you imagine one of the runners is stationary from the beginning, the other runner is doing all the running at $9$m/s.
In $12$ minutes this runner will cover a distance of $9\times 12\times 60$ metres and he meets the stationary runner every $120$ metres, so the number of times they meet is $$\frac{9\times 12\times 60}{120}=54$$
Comment: Hi David Quinn, I really like your answer, to me its solved closer to a physics based way, which I do like, but since the book is a math book, i believe its expecting a very algebraic way of solving this, while thru physics principles you were able to reduce this to an arithmetic problem. I think your way of doing it is pure genius. BUT i think its not the approach expected.
Comment: Hi Palu. There are probably lots of ways of doing this problem but I bet there are no simple solutions involving quadratics and polynomials. You have your own views on what constitutes a physics solution as opposed to a maths solution. For me there is no difference. For me the best solution is one which is simple to understand.
Comment: Yes, I agree  David with what you say as well. The thing that made it more Physics is making one of the runners stationary, because that is looking at things from a particular Frame of Reference, (ie. Galilean transformation ideas), and in the highschools in my country, they teach this kind of way of thinking in physic class and not in math class. So that is where my ideas of what is math and what is physics comes from.
Answer: In the first minute the faster runner runs the field 5 times while the slower runners runs the field 4 times, thus they cross 4 times + 1 time and after a minute the start toghether from the same side. In the second minute they cross again 4 times and then at the end of the second minute the are again at opposite sides. Since the same cicle of 2 minute repeates 6 times,they cross $9\times6=54$ times.
Comment: Hi gimusi, as I commented to David, i thought Davids answer was very very good, but I am looking for an algebraic way, with functions etc to do this. Your answer is a word based explanation, and I have a bit difficulty following it. Your explanation makes claims without real proof. But even if you did, like I mentioned I am looking for an algebraic solution.
Answer: The faster runner crosses the field 60 times, and the slower runner 48 times.  Since they each cross the field an even number of times, they end up where they started.  Since the faster runner crosses the field more often, he must overtake the runner sometimes.  (This is not counted as a cross.)  In order for him to overtake a second time, the runners must first cross.  So, the $12$ extra laps consist of $6$ overtakes and $6$ crosses, and there are $48 + 6 = 54$ crosses in all.


In Perl, would keeping a reference to Catalyst's $c in an attribute cause a memory leak?

Question: I started off writing some Perl code using Catalyst that looked like this:
package My::Controller;
extends 'Catalyst::Controller';

sub handler :Path :Args(0) :Location( some/url )
    my ($self, $c) = @_;

    $self->do_something_with_arguments($c);
    $self->make_a_decision($c);
    $self->another_method($c);
}

Then I thought . o O ( Why pass $c around all the time? ), and I changed to this:
package My::Controller;
extends 'Catalyst::Controller';

has c => (is => "rw", isa => "Catalyst");

sub handler :Path :Args(0) :Location( some/url )
    my ($self, $c) = @_;
    $self->c($c);

    $self->do_something_with_arguments;
    $self->make_a_decision;
    $self->another_method;
}

There is only one entry point to the handler, so $self->c will always be set correctly.
My colleagues said that if this was how Catalyst was meant to be used then, well, everyone would use it like that. They were worried that doing it this way would cause a memory leak because the reference to $c would persist after the request was over. Is that true?
Answer: This isn't a "memory leak" in the exact sense that most people think of, since it won't result in unbounded memory growth, but yes, you're keeping a request context around longer than its ordinary lifetime. It'll be freed the next time you make a request that sets $self->c to something else, but not any sooner. More importantly though, it's pretty much just wrong design. Either continue passing the context as an argument; or turn your controller methods into private actions and call them with ->forward (which passes the context automatically); or move things into the model if appropriate, and have the model ACCEPT_CONTEXT.


Polynomials - getting wrong answer using Euclidean algorithm

Question: I am finding the GCD of $a = x^3 + 11/3x^2 + 17/4x + 3/2$ and $b = 3x^2 + 22/3x + 17/4$ using the Euclidean algorithm. So I divide $a/b$ and get $q$ and $r$ such that $a = qb + r$. Then, according to Wikipedia, I set the new $a = b$, $b = r$, and repeat until $b = 0$, at which point the GCD of the original $a$ and $b$ will be the current $a$ value.
Iteration 1:
$$a = x^3 + \dfrac{11}{3}x^2 + \dfrac{17}{4}x + \dfrac{3}{2}$$
$$b = 3x^2 + \dfrac{22}{3}x + \dfrac{17}{4}$$
$$x^3 + \dfrac{11}{3}x^2 + \dfrac{17}{4}x + \dfrac{3}{2} = \left(\dfrac{1}{3}x + \dfrac{11}{27}\right) \times \left(3x^2 + \dfrac{22}{3}x + \dfrac{17}{4}\right) - \dfrac{25}{162}x - \dfrac{25}{108}$$
Iteration 2:
$$a = 3x^2 + \dfrac{22}{3}x + \dfrac{17}{4}$$
$$b = -\dfrac{25}{162}x - \dfrac{25}{108}$$
$$3x^2 + \dfrac{22}{3}x + \dfrac{17}{4} = \left(-\dfrac{486}{25}x - \dfrac{459}{25}\right) \times \left(-\dfrac{25}{162}x - \dfrac{25}{108}\right) + 0$$
Then I set $a = b = -\dfrac{25}{162}x - \dfrac{25}{108}$ and $b = r = 0$. Since $b$ is zero, the GCD is $a$.
Wolfram|Alpha gives the GCD as $1/6x + 1/4$. So what did I do wrong? (I'm sure it's simple, but I just can't figure out what I'm doing wrong...)
Comment: Don't forget that the GCD is only defined up to a constant factor.  This doesn't completely explain your discrepancy though (459 has a factor of 17 which is nowhere to be found in $1/6 x + 1/4$).
Answer: Note that:
$$-\frac{25}{162}x - \frac{25}{108} = -\frac{25}{27}\left(\frac 1 6 x + \frac 1 4\right)$$
The GCD of 2 polynomials is determined up to a constant (aka a unit).
Comment: Is there any particular rule as to which constant should be used? Wolfram|Alpha certainly seems to be using some sort of rule... I have heard that you should take the monic version, or that you should take the primitive parts, but neither of these yield the 1/6 and 1/4 coefficients. Or should any scaling of the polynomial work for squarefree, distinct degree, equal degree, etc. factorization (which is what I need this for)?
Comment: Monic is nice. Or else a version with integer coefficients ($2x+3$). I'm surprised as well that W|M didn't do that. I do not believe there is any particular rule though.


Database Polling using RxScala

Question: TableEntriesI'm starting out with RxScala and I'm trying to come up with a polling mechanism that checks the database for every interval (say 20 seconds), to check if there was any change in some of the rows in the table.
object MyDatabaseService {

  def getAllEntries: List[MyTableEntries] = ???
}

I would need to start out with an Observable that will emit List[MyTableEntries]. So I started out with the following:
class MyDBObservable(service: MyDatabaseService, observer: Observer[Seq[MyTableEntries]]) extends Observable[Seq[MyTableEntries]] {

  val o = Observable.interval(10.seconds).map { _ => service.getAllTableEntries }
  o.subscribe(observer)
}

In my Observer that I pass in to the function, I have the onNext, onError and onCompleted implemented! There are a couple of questions however:

What happens if my database takes more than 30 seconds to respond
What happens if my database is completely down?

Is this a valid approach what I have done? Suggestions?
Answer:
What happens if my database takes more than 30 seconds to respond

Assume the first service.getAllTableEntries needs 30 seconds, the second and the third service.getAllTableEntries need 1 seconds.
Then in your example, the first service.getAllTableEntries happens at 10 seconds, the second one happens at 40 seconds, the third one happens at 41 seconds.
Basically, the events won't be skipped because of the long-running actions. Instead, just delay the events.

What happens if my database is completely down?

If so, I think service.getAllTableEntries will throw an exception, and you will receive it in onError.

Database Polling using RxScala