Inner product vs. vector triad form

Question: This program involves the matrix-vector computational primitive $y \leftarrow Ax$ where $x,y\in\mathbb{R}^n$ and $A\in \mathbb{R}^{n\times n}$. A is taken to be dense and banded in the two parts of the problem. Recall, there are many ways to implement the primitive. Two standard approaches are:
$$\eta_i = e_i^{T}y = e_i^{T}Ax = \tilde{a}_i^{T}x, 1\leq i\leq n \ \ \text{inner product form}$$
$$y = \sum_{1}^{n}(Ae_i)(e_i^{T}x) = \sum_{1}^{n}a_i\xi_i, \ \ \text{vector triad form}$$
Note: $e^T$ is the standard basis vector.
I know that when implemented these two approaches will produce the same result but I do not understand what the two forms are doing. I believe the inner product form is just multiplying every value in each row of $A$ to the values in $x$ and summing. Any suggestions are greatly appreciated, I will be programming these in C++.
Answer: There are many, many different ways to do matrix vector multiplication or the more general matrix matrix multiplication. Mathematically, they return the same result, but their run times differs significantly depending on the size and type of the relevant matrices as well as details of the underlying architeture. The goal is acheive an implementation which minimizes the runtime by making the best possible use of the available resources.
You mention two different ways of computing the matrix vector product $y = Ax$.  Let us assume that matrix is $n$ by $n$ for the sake of simplicity. Let $r_i$ denote the $i$th row vector of $A$ and let $c_j$ denote the $j$ th column vector. Then
\begin{equation}
y = Ax = (r_1 \cdot x, r_2 \cdot x, \dotsc, r_n \cdot x)^T = \sum_{j=1}^n c_j x_j.
\end{equation}
The first method access the matrix $A$by rows, whereas the second method access the matrix by columns. The performance of the method depends on how the matrix is stored. In Fortran matrices are stored by columns by default. This is called column major format. This format favors the second method because it ensures that the matrix is accessed with stride $1$. This reduces the number of cache misses and improves performance. If the first method is used for a matrix in column major format, then the matrix would be accessed with stride $n$. This would dramatically increase the number of cache misses and significantly reduce the rate at which flops can be executed. Many C programmers prefer to store their matrices by rows, using an array of pointers to point to the beginning of each row. Here the situation is reversed. One should at all times use an algorithm which is compatible with the memory layout.
Banded matrices are normally stored in a special format, imaginatively called banded format. This is implemented in LAPACK and described here http://www.netlib.org/lapack/lug/node124.html. This format compresses the matrix into a wide rectangle which allow the columns to be accessed with stride 1. The corresponding matrix vector multiplication routine is called DGBMV (Double precision General Band Matrix Vector multiplication) and is documented here http://www.netlib.org/lapack/explore-html/d2/d3f/dgbmv_8f_source.html. In reality, the routine is nothing but a special case of the second method which takes the unique sparsity patterns of the matrix into account.
Comment: Ok, just to make sure that I understand. For the first method (inner product) I take the rows of $A$ and multiply by the elements of $x$. And for the second I take the columns of $A$ and multiply by the elements of $x$?
Comment: Your understanding is correct. This is precisely how you should view the two methods.
Comment: by the way do you code in C++?
Comment: No, I get by C and Fortran 95 as needed and develop ideas in MATLAB. I only need a small subset of these languages.
Comment: I see I assume your doing a PhD in computational mathematics?
Comment: Close, but those days are behind me :) I finished my Ph.D. in mathematics some years ago, but my specialization was certainly in computational science.
Comment: nice I am first year PhD in financial mathematics. Thanks again for your help, your a boss!
Comment: Good luck with your studies and remember to do something else as well :)
Comment: Indeed, thank you I do just this course in computational mathematics is really hard. If you do tutoring by the way I could totally use one for this class come test time. I assume your not in the states so we could skype if your interested not sure if you have the time
Comment: I am sorry to turn you down, but I do not have the time. I have considerable commitments both to local students and two different research projects. The time that I spend on MSE goes out of my spare time which is in short supply already.
Comment: ok, no problem just thought I would ask good luck with your research projects

Inner product vs. vector triad form


How do you use GitHub's primer and octicons?

Question: I'm trying to use GitHub's primer and octicons. After using npm to install both I started using the css classes defined by GitHub by including the build.css file in my html document. How would I point the project towards all the svg icons that octicons gives me?

    <!DOCTYPE html>

        <meta charset="UTF-8">
        <title>Hello Primer</title>
        <link rel="stylesheet" href="node_modules/primer-css/build/build.css">

        <form>

                <input class="form-control" type="text" placeholder="Username">

          <button class="btn">

                </button>

        </form>

Answer: [edit] short answer: include node_modules/octicons/build/font/octicons.css
This works, without svg icons. If you want to use the svg icons, you should probably include the images using  tags. However, using a font makes this a lot easier.
<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>Hello Primer</title>
    <link rel="stylesheet" href="node_modules/primer-css/build/build.css">
    <link rel="stylesheet" href="node_modules/octicons/build/font/octicons.css">

    <form>

            <input class="form-control" type="text" placeholder="Username">

                <button class="btn">

                </button>

    </form>

Edit
And if you really feel the need for it, here is an version using svg's:
<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>Hello Primer</title>
    <link rel="stylesheet" href="node_modules/primer-css/build/build.css">
    <link rel="stylesheet" href="node_modules/octicons/build/octicons.css">

    <form>

            <input class="form-control" type="text" placeholder="Username">

                <button class="btn">

                </button>

    </form>

Comment: As of this writing, `npm install octicons` does not include a `font` directory or an `octicons.css` file. Not sure what's up with that.
Comment: What does "building route" mean in this context? Is there any other way to create a web font from the collection of svg files?
Comment: @shacker They switched to building route so they will not provide the fonts anymore last version with fonts is v4
Comment: Why did you include the `src: url('node_modulles/octicons/build/font/octicons.woff') format('woff')` lines? it seems like `node_modules` is misspelled, I commented it out and everything still worked, so are those lines not required?
Comment: Good catch. They are also included in `octicons/build/font/octicons.css` so are not needed. I guess I included them because I first used the wrong css file.
Answer: Why don't we just use cdn link, or download from there?
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/Primer/3.0.1/css/primer.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/octicons/3.5.0/octicons.min.css">

Comment: This answer seems deprecated, no? It seems Octicons changed in the way of how to use it.
Answer: Use Bower to install Octicons.
bower.json:
{
    "name": "my-app",
    ...
    "dependencies": {
        "octicons": "4.3.0",
    }
}

Then link to wherever your bower libraries are being held:
<link href="/libs/octicons/build/font/octicons.css" rel="stylesheet">

Comment: This worked for me. The Octicons package available on the website as of 2019 is missing the fonts, but the one in bower has all the necessary files.
Answer: Update for those reading in 2023:
I faced a similar issue and was annoyed by how, in spite of using Bootstrap icons and Devicon as CDN-distributed CSS, I had to resort to importing Octicon SVGs individually. For this reason, I created my own little build pipeline that bundles the SVGs in a CSS distribution. Here is the project repository, and if you want to include it using CDN:
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/octicons-css/octicons.min.css">


DataSet relation with multiple joins in query

Question: I'm filling dataset from multiple tables using relation on this way:
<code>private void UcitajZahtjeve()
    {
        string query1 = "SELECT tblrezgo.IDRadnik, CONCAT(tblradnik.Ime, ' ', tblradnik.Prezime) AS ImePrezime, tblrezgo.EmailRadnik, tblrezgo.creationTime, tblrezgo.IDUnos ";
        query1 += "FROM tblrezgo ";
        query1 += "LEFT JOIN tblradnik ON tblradnik.IDRadnik = tblrezgo.IDRadnik ";
        query1 += "LEFT JOIN tblrezgolog ON tblrezgolog.IDUnos = tblrezgo.IDUnos ";
        query1 += "WHERE (tblrezgolog.OdobrenoN=1 AND tblrezgolog.OdobrenoHR=1) ";
        query1 += "ORDER BY tblrezgo.creationTime ASC";

        string query2 = "SELECT IDUnos, DatumGO, OdobrenoN, OdobrenoHR FROM tblrezgolog";

        gridZahtjevi.DataSource = dbTwoTableRelation(query1, query2, "Detalji", "IDUnos", "IDUnos").Tables[0];
        gridZahtjevi.LevelTree.Nodes.Add("Detalji", gridDetails);
    }

private DataSet dbTwoTableRelation(string query1, string query2, string relationName, string fieldName1, string fieldName2)
        {
        MySqlDataAdapter table1;
        MySqlDataAdapter table2;

        DataSet myDataSet = new DataSet();

        table1 = new MySqlDataAdapter(query1, this.connection);
        table2 = new MySqlDataAdapter(query2, this.connection);

        table1.Fill(myDataSet, "mainList");
        table2.Fill(myDataSet, "subList");

        myDataSet.Relations.Add(relationName, myDataSet.Tables["mainList"].Columns[fieldName1], myDataSet.Tables["subList"].Columns[fieldName2]).Nested = true;

      return myDataSet;

    }
</code>
The queries work fine but if I run this code I get error even application is loaded grid is empty.

A first chance exception of type 'System.ArgumentException' occurred
  in System.Data.dll

If I remove from query1 one join clause then everthing is ok.
I don't understand what causes problem, whay two joins are problem?!
Answer: Just fetch the constructed query1 at runtime and try to execute in your database,
Then it will be easy to findout the error
Comment: I've already do that. Query works fine. I think that problem is in method DataSet dbTwoTableRelation() on line myDataSet.Relations.Add(relationName, myDataSet.Tables["mainList"].Columns[fieldName1], myDataSet.Tables["subList"].Columns[fieldName2]).Nested = true;

But I don't know why...
Answer: Use Query Like this. It should work.

<code>     string query1 = "SELECT tblrezgo.IDRadnik, CONCAT(tblradnik.Ime, ' ',
                     tblradnik.Prezime) AS ImePrezime, tblrezgo.EmailRadnik,
                     tblrezgo.creationTime, tblrezgo.IDUnos ";
                     query1 += "FROM tblrezgo ";
                     query1 += "LEFT JOIN tblradnik ON tblradnik.IDRadnik =
                     tblrezgo.IDRadnik , tblrezgo  ";
                     query1 += "LEFT JOIN tblrezgolog ON tblrezgolog.IDUnos =
                     tblrezgo.IDUnos ";
                     query1 += "WHERE (tblrezgolog.OdobrenoN=1 AND
                     tblrezgolog.OdobrenoHR=1) ";
                     query1 += "ORDER BY tblrezgo.creationTime ASC";
</code>
Comment: There is error like Not unique table/alias: 'tblrezgo'


Latex algpseudocode IF with multiple conditions

Question: I'm trying to write a pseudo code with Latex in my paper where I need to put a IF condition which has multiple conditions. I'm trying this but doesnt seem to work as the \Or command is not recognized:
<code>\begin{algorithmic}

\While{$condition$}
    \State $do-something$

    \If {$condition-1$ \Or $condition-2$ \Or $condition-3$}
        \State $break$
    \EndIf

\EndWhile
\end{algorithmic}
</code>
I'm using the algpseudocode package. Also I need to put a "space" within the conditions, but latex just discards it and connects the two words together, any way to do this?
Cheers,
Comment: (La)TeX-related questions are better suited on [TeX.SE](http://tex.stackexchange.com). Since you've "figured it out", you could type up your own solution as an answer, and then flag this for migration to TeX.SE. Alternatively, this would be considered "too localized".
Answer: Nevermind guys, found out. This is the correct way
<code>\begin{algorithmic}

\While{$condition$}
    \State $do-something$

    \If {$condition$ $1$ OR $condition$ $2$ OR $condition$ $3$}
        \State $break$
    \EndIf

\EndWhile
\end{algorithmic}
</code>
Comment: Try \If {$condition$ {\bf or} $condition$}


Problemas de lentidão com AJAX no ASP .NET MVC C#

Question: Estou com um problema de lentidão na resposta do meu AJAX. Utilizo o seguinte código para fazer a busca e retornar uma lista de resultados:
Javascript
function enviaBusca(url) {
    var resultado = $('#resultados'),
        mensagem = $('#mensagem'),
        palavras = $('input[type=hidden][name=palavrasTemp]').val(),
        palavraChave = $('#txt_palavra_chave').val(),
        valorMinimo = $('input[type=number][name=valor_minimo]').val(),
        valorMaximo = $('input[type=number][name=valor_maximo]').val(),
        buscaPublicado = $('')
    param = { 'buscaTermo': encodeURIComponent(palavraChave), 'palavrasBuscadas': palavras, 'buscaTipoImovel': get_lista_tipos_marcados(), 'buscaEstado': get_lista_estados_marcados(), 'buscaCidade': get_lista_cidades_marcadas(), 'buscaBairro': get_lista_bairros_marcados(), 'buscaCaptador': get_lista_captadores_marcados(), 'buscaPretensao': get_lista_pretensoes_marcadas(), 'buscaFinalidade': get_lista_finalidades_marcadas(), 'buscaSituacao': get_lista_situacoes_marcadas(), 'buscaValorMinimo': valorMinimo, 'buscaValorMaximo': valorMaximo, 'buscaPublicado': get_lista_publicados_marcadas() };

    $('#loading').removeClass('invisivel');
    resultado.empty();
    mensagem.addClass('invisivel');

    $.post(url, add_anti_forgery_token(param), function (response) {
        if (response) {
            if (response.length > 0) {
                resultado.removeClass('invisivel');
                for (var i = 0; i < response.length; i++) {
                    resultado.html(response);
                }
            }
        } else {
            resultado.addClass('invisivel');
            mensagem.html('Nenhum resultado foi encontrado com os filtros selecionados.').removeClass('invisivel');
        }
        $('#loading').addClass('invisivel');
    });
}

Controller
[AllowAnonymous]
        [HttpPost]
        public ActionResult Resultados(string buscaTermo, string palavrasBuscadas, List<int> buscaTipoImovel, List<int> buscaEstado, List<int> buscaCidade, List<int> buscaBairro, List<int> buscaCaptador, List<int> buscaPretensao, List<int> buscaFinalidade, List<int> buscaSituacao, int buscaValorMinimo, int buscaValorMaximo, List<int> buscaPublicado)
         {
            var palavrasTemp = palavrasBuscadas;
            if (palavrasTemp != "")
            {
                palavrasChave.Add(palavrasTemp);
            }
            palavrasChave.Add(buscaTermo);

            if (!Request.IsAuthenticated)
            {
                buscaSituacao.Clear();
                buscaSituacao.Add(1);
                buscaPublicado.Clear();
                buscaPublicado.Add(1);
            }

            var lista = ImoveisModel.RecuperarListaBusca(palavrasChave, buscaTipoImovel, buscaEstado, buscaCidade, buscaBairro, buscaCaptador, buscaPretensao, buscaFinalidade, buscaSituacao, buscaValorMinimo, buscaValorMaximo, buscaPublicado);
            ViewBag.TermoBuscado = palavrasChave;
            ViewBag.ListaImoveis = lista;
            ViewBag.QuantidadeRegistrosEncontrados = lista.Count();
            return PartialView(lista);
        }

JSON enviado
param = { 'buscaTermo': encodeURIComponent(palavraChave), 'palavrasBuscadas': palavras, 'buscaTipoImovel': get_lista_tipos_marcados(), 'buscaEstado': get_lista_estados_marcados(), 'buscaCidade': get_lista_cidades_marcadas(), 'buscaBairro': get_lista_bairros_marcados(), 'buscaCaptador': get_lista_captadores_marcados(), 'buscaPretensao': get_lista_pretensoes_marcadas(), 'buscaFinalidade': get_lista_finalidades_marcadas(), 'buscaSituacao': get_lista_situacoes_marcadas(), 'buscaValorMinimo': valorMinimo, 'buscaValorMaximo': valorMaximo, 'buscaPublicado': get_lista_publicados_marcadas() }

A consulta roda até que rápido, o tempo varia de 20 a 600ms dependendo da quantidade de resultados obtidos mas o problema é o retorno do AJAX, leva alguns minutos para montar a tela e esconder a div loading ... O que pode ter de errado?
Comment: Bem vindo Cristiano. Você checou se o problema não está no loop do response? Não parece necessário esse loop, não sei oque tem no response, mas independente do tamanho ele está substituindo o html N vezes mas sempre pelo mesmo valor (response).
Comment: Então George, o loop é exatamente para preencher a lista de resultados (neste caso lista de imóveis encontrados com os filtros). Com poucos resultados até retorna rápido mas a partir de 10 resultados leva muito tempo para retornar, até congela a tela impedindo a navegação ou seleção de outros filtros para a busca.
Comment: Ficaria mais fácil conseguir ajuda se você postar o código da controller também e dar um exemplo de como é o retorno. Mas avalie se a resposta abaixo já não atende suas necessidades.
Comment: Adicionei o código do Controller, como disse ao amigo abaixo o meu retorno é uma List.
Answer: Pelo que estou vendo a consulta não te retorna apenas um JSON, mas todo o HTML já propriamente formatado. Quando você disse que a consulta era rápida, isso inclui a formatação do HTML, ou só a consulta no banco de dados?
Formatar strings da maneira errada pode ser muito custoso. Strings geralmente são imutáveis, o que significa que ao se concatenar 2 strings, o compilador precisa realocar toda a memória da variável.
Em C#, a forma correta de se construir longas strings, é com o objeto StringBuilder.
Se você já está fazendo isso no seu servidor, e a lentidão é toda do JavaScript, não há muito o que fazer, recomendo você substituir o
for (var i = 0; i < response.length; i++) {
    resultado.html(response);
}

por
resultado.html(response.join(''));

Comment: Na realidade o meu retorno é uma List, ai no resultados.cshtml eu monto o html. Quando me referi ao tempo de carregamento é justamente o model retornado pelo JSON.
Comment: Já trabalhei com tabelas que eram grandes demais para serem renderizadas de uma só vez. Quando você chega a esse ponto o melhor a se fazer é renderizar 50-100 itens de cada vez, e colocar um eventListener no scroll da window para renderizar mais itens quando o usuário rolar a barra de navegação até o final.
Comment: Entendo, mas neste caso não acredito ser problema com a quantidade de registros pois mesmo uma consulta que retorne 10 registros demora uns 5 minutos para completar, isso quando não dá timeout. Eu tenho uma lista que traz todos os imóveis registrados que não usa AJAX e carrega rapidinho. Na busca preciso do AJAX para que o usuário aplique filtros para diminuir a lista sem ter que ficar trocando de página toda hora.
Comment: Mas então você está usando AJAX apenas para filtrar os resultados de uma lista que você já tem em tela? Não seria melhor usar JavaScript para filtrar esses resultados?
Comment: Não é bem isso, acho que não ajudou minha resposta. O que eu disse sobre ter uma lista é em outra sessão do site, na busca eu carrego os filtros e a partir do momento em que eu seleciono o primeiro filtro eu carrego a primeira lista. A partir dai a cada interação do usuário com os filtros (click em um checkbox) a consulta AJAX é feita novamente aplicando o filtro selecionado. Adicionei na resposta o JSON que envio para o Model.
Answer: depois de quebrar bastante a cabeça tentando achar o problema no AJAX eu parei e pensei no óbvio: qual o retorno? É uma lista, sendo uma lista não preciso percorrer o objeto "response" para montar uma lista então resolvi removendo o for e deixando assim:
Código antigo
$.post(url, add_anti_forgery_token(param), function (response) {
    if (response) {
        if (response.length > 0) {
            resultado.removeClass('invisivel');
            for (var i = 0; i < response.length; i++) {
                resultado.html(response);
            }
        }
    } else {
        resultado.addClass('invisivel');
        mensagem.html('Nenhum resultado foi encontrado com os filtros selecionados.').removeClass('invisivel');
    }
    $('#loading').addClass('invisivel');
});

Código novo
$.post(url, add_anti_forgery_token(param), function (response) {
    if (response.length > 0) {
        resultado.removeClass('invisivel');
        resultado.html(response);
    } else {
        resultado.addClass('invisivel');
        mensagem.html('Nenhum resultado foi encontrado com os filtros selecionados.').removeClass('invisivel');
    }
    $('#loading').addClass('invisivel');
});

Obrigado a todos pelas respostas e deixo aqui a solução para que se alguém mais tiver problemas parecidos possa resolver.
Comment: É exatamente oque comentei pra você la na sua pergunta. hehehe
Que bom que achou a solução! :)


Can you break down relative MySQL load by "source" of query?

Question: I am trying to improve server performance, and it is clear that MySQL is a major contributor to the problem.  Troubleshooting it, however, is very hard.  I am using the slow query log to target specific kinds of queries, but the real issue is that MySQL is used by Java processes, PHP processes, and cron jobs (which are typically also PHP processes, but run through the command line versus via Apache)
Usually when the server gets slow, I will run some commands like "ps" or "top" to try to find the culprit, but even if I know MySQL is to blame, I don't know which of the three "realms" I mentioned might be actually causing slowdown.  In other words, I'd love to somehow break it down and see that, for example, 80% of the demands placed on MySQL at that moment are due to queries from PHP, while only 20% come from Java.  Since I have automated tasks and periodic events triggered from both "realms", it is hard to isolate their effects through trial-and-error alone.
Everything resides on one server, so all MySQL queries come from localhost.  Could I also maybe "tag" queries, add comments to them, or otherwise add some kind of meta-data so I could analyze those tags later for relative load?
I doubt there is a way to get info quite like that, but if anyone can help provide a way to further breakdown MySQL load in a way that helps identify the source of those queries (process IDs might work too), it would help immensely.  Thanks!
Comment: It's not clear from your description, but are all these processes running on the same server?
Comment: Yes, all on the same machine.
Answer: I'd suggest using MySQL Proxy. With MySQL Proxy you can intercept and log every query going into your server.
A simpler approach would be running mysqlbinlog to analyze the binary log files generated by MySQL (see man mysqlbinlog).
Anyway, if you haven't done this already, it would be a good idea to run mysqltuner to see if there are any obvious problems or bottlenecks (like for example, an unusual number of queries performing JOINs without indexes).
Answer: Have you tried logging into the mysql service and issuing a SHOW FULL PROCESSLIST or using mytop to see which queries are running?
SHOW FULL PROCESSLIST provides a list of all queries and tasks the MySQL is currently doing.  It needs to be run as a user with either 'PROCESS' or 'SUPER' priveleges in the database.  mysqladmin has a processlist argument as well.
mytop is very good for showing what the server is doing on an ongoing basis.  Think of it as something like top for MySQL.
Both of these will tell you what commands are running, where they are coming from and how long MySQL has been trying to service them so far.
Once you are armed with that information you can go about deciding what to do.  If the the system is write bound you may need to partition your data.  If you are read bound, there are things that can help.  Indexing tables properly can give a significant boost to read performance in many cases.  If you have a lot of identical queries adding a cache may help.  Adding read slaves can also improve performance.  Caching and adding slaves will increase performance but will add some additional complexity to your network and application.
Answer: One possibility is to make sure the different processes use different credentials to connect to mysql. I'm pretty sure mysql logs the username that executed the query in the query log.
Answer: Yes you can, but profiling without using a client-based profiler requires that you pass the requests through something that can catch them -- In this case, that's going to be MySql-Proxy. There's instructions on their website on how to set it up to snag and profile queries, and then you can run explains and other operations against the ones that seem to be spending a long time.
Another method that's not so complicated but may work is to set your slow-query timeout to a very low value, and then make sure you turn the slow query log on. That way you'll see anything that takes longer than a few seconds. This won't help you if the developers (or their ORM) makes a bunch of basic queries and then summarizes the data in the application, of course.
Answer: SHOW FULL PROCESSLIST;
That shows you the processes and runtimes. To differentiate the source, you can use different logins for each 'realm', OR prepend the realm in all queries. eg, this is a valid query:
/* php */ SELECT * FROM items;
as is:
/* java */ SELECT * FROM items;
etc.
But you still can't see system load caused by the queries. Can be helpful anyway, and you could hack your monitoring tools to graph the data to look for correlations with your performance.
Answer: Maatkit's mk-query-digest script won't classify by source but it will give you a lot of insight into which queries are hogging resources the most.
http://www.maatkit.org/doc/mk-query-digest.html
Answer: We mark queries with comments, as mibus suggested above. We then regularly write the FULL PROCESSLIST output to files. When we have performance problems, we import these files into the database and munge the data to see long queries. For us at least, these cause the most load.
I would be careful with running MySQL Proxy on a production system. I have found it to lock up occasionally. Additionally you have a further piece of infrastructure you need to monitor.
Answer: Have you looking into using mysql profiling?
http://dev.mysql.com/tech-resources/articles/using-new-query-profiler.html
mysql>set profiling=1;
<run your queries with profiling enabled>
mysql>show profiles;

The output of this will be a table with QueryID, Duration of Query, and Query string.  Similar to this:
mysql> show profiles;
+----------+------------+-----------------------------------------------+
| Query_ID | Duration   | Query                                         |
+----------+------------+-----------------------------------------------+
|        0 | 0.00007300 | set profiling=1                               |
|        1 | 0.00044700 | select count(*) from client where broker_id=2 |
+----------+------------+-----------------------------------------------+

From here, you can break that query further down with
mysql>show profile for query <QueryID>;

This will give you a breakdown of how much time the query spent at each stage of execution.  You can further delve into the specifics of how much CPU time is spent on a query as well:
mysql> show profile cpu for query 4;
+----------------------+------------+------------+------------+
| Status               | Duration   | CPU_user   | CPU_system |
+----------------------+------------+------------+------------+
| (initialization)     | 0.00002900 | 0.00000000 | 0.00000000 |
| checking permissions | 0.00000800 | 0.00000000 | 0.00000000 |
| init                 | 0.00004000 | 0.00000000 | 0.00000000 |
| Opening table        | 0.00009400 | 0.00100000 | 0.00000000 |
| System lock          | 0.00000500 | 0.00000000 | 0.00000000 |
| Table lock           | 0.00000700 | 0.00000000 | 0.00000000 |
| setup                | 0.00004200 | 0.00000000 | 0.00000000 |
| creating table       | 0.00195800 | 0.00000000 | 0.00100000 |
| After create         | 0.00010900 | 0.00000000 | 0.00000000 |
| copy to tmp table    | 0.52264500 | 0.55591600 | 0.04199300 |
| rename result table  | 0.11289400 | 0.00199900 | 0.00000000 |
| end                  | 0.00004600 | 0.00000000 | 0.00000000 |
| query end            | 0.00000700 | 0.00000000 | 0.00000000 |
| freeing items        | 0.00001300 | 0.00000000 | 0.00000000 |
+----------------------+------------+------------+------------+

I suggest reading the information page to find out exactly what information you would like as the tool is fairly verbose, but this should help you in finding your bottlenecks within the mysql daemon.
Comment: I should add that the way to go from your offending query to finding out who requested it would be using general_log.  Where this may be a hassle to find the culprit it will also show you where you are spending all your time.  I would think refining your processor hungry query is going to be the end solution.
Answer: First step is to not have all your processes use the same user. Especially if all of them are coming through 'localhost'. Even for queries coming from the same tool (as in php), have the ones in cron use a separate user from the ones running through apache.
Once that is done, you can use mysqlbinlog to parse the slow logs (it has some great fields to order the queries/normalize the queries) or even use something more advanced like a profiler to find the slower queries
Comment: also, innotop is a very good tool that shows each query running at a given time and can do explain on it and also allows you to check on locks (deadlocks are one big reason for bad performance). I actually find it more informative than mytop


hg-git clone from Github gives "abort: repository is unrelated"

Question: I have a project whose main (Mercurial) repository is on SourceForge, but there are clones on Bitbucket (Mercurial) and Github (Git).
Now I have been using hg-git to push the Mercurial repository to Github and from what I understand of the procedure, some metadata is kept in the Mercurial repository in the process.
Now, when cloning the Bitbucket repository anew and cloning the Github repository anew as well, and if I issue a hg pull ../github-repo I get:
pulling from ../github-repo
searching for changes
abort: repository is unrelated

Why is that and how can I convince Mercurial that indeed they are related? Or do I have to rely on the original repository from which I pushed to Github originally? I still have that, but suppose I lost it, what would be the options I have, short of manual changeset transplantation?

Note: the Github repo was changed (new changeset) due to a pull request. But the SourceForge and Bitbucket repos still recognize each other as related. The mission now is to pull the changeset from the Github Git repo into a local one and push them back up to SourceForge and Bitbucket respectively.
Comment: Can you `hg pull git://github.com/you/githubrepo.git` from inside the new Mercurial bitbucket clone?
Comment: @EmilSit +1, but it should be `hg pull git+ssh://github.com/you/githubrepo.git`, if I'm not mistaken.
Comment: @EmilSit: no. All interaction between the two Hg repos works, but when you try to pull from the Git one (which was based on the Hg one originally) it won't work with either and the above error message.
Comment: Can you include the output of `hg pull -v --debug ../github-repo`?
Answer: The related or non-related bit basically comes from whether two repositories share a common root, i.e. initial changeset.
To force the pull, you could do something evilish with the graft or transplant extensions, but this could have ripple effects, and you seem adverse to such a solution – I would be too!
To understand why you're having a problem, you need to understand a little bit about how Hg-Git works.
How Hg-Git works
Tl;dr
The real problem is that Hg-Git basically creates a new repo dynamically. Thus, the two repositories aren't related for the same reason that the product of hg convert some-existing-hg-repo isn't related to the original repository. You hadn't noticed it thus far because Hg-Git does this in the other direction as well – when you start from a Mercurial repository, it creates the necessary Git repository. When you first started cloning to GitHub, you created a bare Git repository on their servers, which for all intents and purposes is related to every repository. Thus, your push the new Git repo created by Hg-Git is related and everything works, no problem. Afterwards, you were pushing from that same repo, so again no problems – Hg-Git tracks the relationship between the local Git and Hg repositories and thus your relationship was maintained. But when you start afresh, you create a new Git and/or Hg repo (depending on which direction you're going in) and the correspondence is broken.
Slightly less oversimplified
Hg-Git works by creating a hidden Git repository and establishing a correspondence between commits of the Git and the Hg repositories. Hg-Git is a two-way bridge, that is, it is capable of taking Git commits and producing Hg commits and vice versa. Hg-Git achieves its bilingualism by using a Git-library written in Python (dulwich) and linking into Mercurial as an extension. This means that Hg-Git reads and writes Git repositories without needing a git binary / the Git reference implementation installed. However, Hg-Git is a Mercurial extension and as such depends on system Mercurial for the Mercurial end of the transaction as well as the user interface. This is why there are efforts to create the reverse interface (Git-Hg and the like) so that Git users can use the Git to interact with Mercurial.
Now, whether the Git, or the Hg repository is created depends on how the hybrid repository was created in the first place. Since you're coming from the canonical Mercurial side, we'll start there.
When you create a repository on GitHub or Bitbucket, it is initially bare and commitless and thus related to every repository – this is part of the motivation for the default of no initial commit on repository creation. (This is true for both Git and Mercurial.) Repository relatedness is based on the root node. Thus, any repository can pushed to this new repository. When you run hg push ssh+git://firstname.lastname@example.com/user/some-git-repo for the first time, Hg-Git creates a new, hidden Git-repository in your local folder, then uses the Git protocols to communicate and push the changes to the remote. From then on, you should have no problem communicating between the two repositories – from the initial conversion of the root node and parent-child relationships, it is possible to achieve a one-to-one mapping between the changesets of the two repositories. (This isn't quite 100% true, especially if you use more advanced, idiomatic features of Git or Mercurial, but it'll suffice for now.) Hg-Git tracks a tad bit more information than this, I'm pretty sure, if for no other reason than to speed things up with successive pushes and pulls. So, when you start from a Mercurial clone, your "proto-root" is the Mercurial root and the Git repository is created and maintained as need be.
Now, if you aren't starting from a local Mercurial clone, but rather from a remote Git clone, then you do actually wind up creating a Mercurial clone from the Git one – the "proto-root" is the Git root. More precisely, when you run hg clone ssh+git://email@example.com/user/some-git-repo, Mercurial starts up, checks to make sure it can interface with the remote (which it can with Hg-Git's help), then creates the directory and calls the necessary extension (s), i.e. Hg-Git. Hg-Git then creates a hidden .git folder in your .hg folder, performs a Git clone, then converts the Git repo to a Mercurial one; once that clone is complete, it calls hg update, which operates directly on the Mercurial repo without every knowing about the Git repo.
This, I suspect, is what went wrong in your case. When you did a new clone from GitHub, you in effect created a new Mercurial repository, which of course isn't related to your original repository – much in the same way that the product of hg convert isn't related to the original, even if the mutated commits don't include the initial one. (This is sort of like when you translate something to another language and back again, you don't always get the original form back.) For various reasons, I suspect that Hg-Git performs its conversions in a time-independent and deterministic way (almost definitely the latter, but it might add extra meta data about the conversion itself, which would mean not the former). If this is the case, then you should be able to start from a canonical Hg clone and recreate the connection to the Git repository. (Yes, it is somewhat problematic that the directionality of the initial conversion makes a difference, but the pros, and cons of the design decisions leading up to that are best discussed with the developers themselves.)
Back to the structure of a hybrid Hg-Git repository. There are two interesting things here:

Mercurial is more or less completely oblivious to the extra translation going on when it communicates with Git remotes and

There is a full-fledge Git repository hidden from view and occasionally synchronized to the Mercurial repository.

Importantly, you can actually operate directly on the hidden Git repository via system Git. If you use Hg-Git, then the Git repository is synchronized only on pushes to and pulls from remote Git clones, which means that those local direct Git changes will get out of sync with the Mercurial repository – in the worst case, you commit a few times to Git, then commit to Mercurial without synchronizing and effectively create two separate branches because the Hg commit and the Git commits share a common ancestor but don't build upon each other. However, Hg-Git provides a mechanism for manually forcing a sync between the repos via hg gimport [git-repo-to-import-from-if-not-local-hidden] and hg gexport (exports by default to local hidden copy, creating it if need be). Forcing this synchronization should also provide you a way deal with the issues you've noticed. You could namely use Git to pull (or in Git terminology, fetch – git pull is equivalent to hg pull --update; git fetch is hg pull, which makes the Mercurial fetch extension's name really unfortunate) the new changesets into the Git repository, then use hg gimport to import those changesets into the Mercurial repository.
Now, if you did something like editing history or the like, then all bets are off. I'm not sure how Hg-Git would handle this – I suspect it would wind up creating doubles. The new commits in the Mercurial clone would be added to Git, but the deleted changesets are still in the Git repo and would probably be imported back into the Mercurial repository. (This is a direct result of Hg-Git's method of offline synchronization of changesets.) In this case, I suggest picking a canonical repository, wiping all clones, and doing a new push with an apology to everybody whose clones were invalidated by this mess. (This is, incidentally, part of why the Mercurial community is so wary of editing history.)
Potential Solutions

@EmilSit suggested that you run hg pull git+ssh://github.com/you/githubrepo.git directly from the canonical (non GitHub clone) Mercurial repository. This has a decent chance of working, assuming that Hg-Git's method of creating the initial Git clone is completely time-independent and deterministic. (The latter is almost assuredly true, but I'm not sure of the former, see text above for more detail.)

You can do the local variant of this: use git clone  ssh://github.com/you/githubrepo.git to get a local pure Git clone, then do hg pull ../githubrepo. (This requires that you have Git installed.) Hg-Git should automatically kick in and do the conversion. The conversion is also dependent on Hg-Git doing the conversion in a deterministic, time-independent way.

You can operate directly on the hidden Git repository in the original hybrid repository. Use git fetch (you may potentially first have to cd into the .git folder hidden in the .hg folder first). Then run hg gimport && hg update to import the changes from the Git repository and update. (You may have specify the path for gimport – either . or the path to the hidden Git repo. I suspect you could also specify the GitHub path.)

You can use various methods of dumb transplanting – exporting a patch series, etc. – and manually committing them. If you want to give another developer credit when doing manual commits, then you can use the -u option to set the user on a per-commit basis.

You can do smart transplanting with either the graft or transplant extensions. First, use Hg-Git to do a new Mercurial clone of the GitHub repository. Then use one of those extensions to pull bring the two Mercurial repositories together.

At least one of the non-transplanting methods should work because, unless Hg-Git does its magic time-dependently, then it should be possible to find a common root. Even if a common root is found though, you may wind up with two basically duplicate (unnamed) branches, which you then have to merge back together.
Answer: I'd add that you can even get a "repository unrelated" error when you push a hg repo to git, then clone the git repo from hg and then you try to pull in changes from the original hg repo. Since now we have a hg repo locally created from a git repo that was created from the original hg repo I suppose the local and the original hg repo should be related, but sometimes aren't.
Due to the differences in how hg and git handle author names and e-mails if your original hg repo had anything different for authors than Name <firstname.lastname@example.com>-style ones you'll see this issue. The reason is that hg-git tries to convert authors to the strict git-style (that uses the mentioned name-email pairs) and will fill in the blanks if this is not the case (see the explanation in hg-git's Readme: https://bitbucket.org/durin42/hg-git).
Thus it can happen that the author for a changeset in the original hg repo is not exactly the same than in the git repo; and as a result, authors in the hg repo created from the git repo won't match the ones in the original hg repo, e.g.:

Changeset A in the original hg repo has the author set as firstname.lastname@example.com.
Since this doesn't conform to git's standard hg-git will convert this to firstname.lastname@example.com <firstname.lastname@example.com> in the git repo.
Now when you clone the git repo to hg the changeset will have the author as email@example.com <email@example.com>.

Since for two repos to be related the initial commit should match exactly you'll get the "repository unrelated" error even if the hash, commit message, datetime matches, but the author is different. Quite a pain to experience (argh, now I'm punished because I forgot to set the author properly three years ago!) but completely reasonable.


Central limit theorem maximum

Question: $ξ_1, ξ_2, ξ_3....  ξ_n.... $ they are equally distributed, independent, and have a single expectation and a single variance. Let $M_n = max(ξ_1, ξ_1 + ξ_2,...,ξ_1 + ξ_2 + ... + ξ_n) $ .
Is it possible to find for every ${x}$ where $\lim \limits_{n\to\infty}\mathbb{P}(M_n \leq n + x\sqrt n)$ ?
There was a tip: Central limit theorem would help
Seems that it is simple trick, but I have no idea =( I would be very grateful for help!
Comment: Your question is unclear: you want to find every $x$ such that $\mathbb{P}(M_n \leq n + x\sqrt n)$ verifies what ?
Comment: Sorry for that, I edited my question. I'm looking how to find $\lim$ for any x
Comment: [Wiener process](https://en.wikipedia.org/wiki/Wiener_process#Running_maximum)
Answer: Have a look at the Darling Erdos Theorems. They are reviewed for example in this paper:
https://projecteuclid.org/journals/annals-of-probability/volume-26/issue-2/Darling-Erd%c5%91s-theorems-for-normalized-sums-of-iid--variables/10.1214/aop/1022855652.full
Comment: Is this my case? `In the case when the distribution of ξ is close to a stable(α) law for some α ϵ(0,1)⋃(1,2)`
Comment: I think your case corresponds to the first paragraph.
Answer: The running maximum formula in Wikipedia only works if there is no drift. If the mean is not 0, use equation (1.5) from Shepp, Lawrence A. "The joint density of the maximum and its location for a Wiener process with drift." Journal of Applied probability (1979): 423-427. First integrate over $x$ to get the bivariate density. There doesn't seem to be a closed form for the marginal density of $Y$ unless the drift parameter ($c$) is $0$.
This R program will evaluate the distribution function by numerical integration. I include an example where the random variables are iid normal with mean 0.5 and standard deviation 2. Then, the graph shows the empirical distribution function (black) from the simulated values and the distribution evaluated by numerical integration (red).
<code>
library(pracma)
library(cubature)

fYth=function(x,c1,sig) {
  y=x[1]
  th=x[2]
  res= (
    2*exp((c1^2*(1 - th + 2*th^2))/(2*sig^2*(-1 + th)) + (y*((2*c1)/(-1 + th) + y/th))/(2*sig^2) -
            (c1^2*th^3 - c1*(-2 + th)*th*y + (-1 + th)*y^2)/(sig^2*(-1 + th)*th))*sig*y-
      (c1*exp((c1^2*th*(1 + th))/(2*sig^2*(-1 + th)) + (y*((2*c1)/(-1 + th) + y/th))/(2*sig^2) - (c1^2*th^3 - c1*(-2 + th)*th*y + (-1 + th)*y^2)/
                (sig^2*(-1 + th)*th))*sqrt(2*pi)*sqrt(1 - th)*y)+
      c1*exp(-((c1^2*th^3 - c1*(-2 + th)*th*y + (-1 + th)*y^2)/(sig^2*(-1 + th)*th)) + ((2*c1*th^2*(c1 + y))/(-1 + th) + (-(c1*th) + y)^2)/
               (2*sig^2*th))*sqrt(2*pi)*sqrt(1 - th)*y*erf((c1*sqrt(1 - th))/(sqrt(2)*sig))
  )/(2*pi*sig^3*th*sqrt((1 - th)*th))
  return(res)
}

FY=function(y,c1,sig) {
  a1=adaptIntegrate(fYth,lowerLimit=c(0,0.000001),upperLimit =c(y,0.999999),
                    c1=c1,sig=sig,maxEval=10000)
  if (is.na(a1$integral) | a1$integral>1) print(c(y,a1$returnCode,a1$integral))
  return(a1$integral)
}

n=1000
nsim=10000
mu=0.5
sig=2
x=matrix(rnorm(n*nsim,mu,sig),ncol=n)
y=apply(x,1,function(x1) max(cumsum(x1)))
plot(ecdf(y))
pts=FYs=c(350:700)
for (i in 1:length(pts)) FYs[i]=FY(pts[i],mu*n,sig*sqrt(n))
lines(pts[!is.na(FYs)],FYs[!is.na(FYs)],col="red")

</code>

Central limit theorem maximum


The variable in element nth-child using jquery

Question: I'm stuck and I can't overflow counting children using variable and jquery. What I do:

First

Second

Third

and

I want to click a particular child from the list, and that changed class in the same line of the table.
Something like:
$('ul li:nth-child(' + count + ')').click(function() {
    $('table tr:nth-child(' + count + ')').addClass('active');
});

But I do not know how to properly use the variable 'count'.
Answer: You can use $.fn.index to get current index of the LI and use it to highlight curresponding table row:
$('ul li').click(function() {
    $('table tr:eq(' + $(this).index() + ')').addClass('active');
});

With nth-child you need to add +1: 'table tr:nth-child(' + ($(this).index() + 1) + ')'.
Answer: Click li first remove active class and addClass, then will be dynamic for click
$('ul li').click(function() {
    $('.active').removeClass('active');
    $('table tr:eq(' + $(this).index() + ')').addClass('active');
});

Demo


Como vocês calculam (com facilidade) total e subtotal no Django?

Question: Estou usando Django 1.7.8
Eu tenho o models.py
class SaleDetail(models.Model):
    quantity = models.PositiveSmallIntegerField(_('quantidade'))
    price_sale = models.DecimalField(

    def get_subtotal(self):
        return self.price_sale * self.quantity

    subtotal = property(get_subtotal)

./manage.py shell
>>> from vendas_project.vendas.models import SaleDetail
>>> from django.db.models import Sum, F, FloatField
>>> q = SaleDetail.objects.values('price_sale', 'quantity').filter(sale=1)
>>> q.aggregate(Sum(F('price_sale') * F('quantity')), output_field=FloatField())

Gera o erro:
field_list = aggregate.lookup.split(LOOKUP_SEP)
AttributeError:
    'ExpressionNode' object has no attribute 'split'

Como vocês calculam subtotais e total no Django?
Eu preciso do resultado, exemplo:
price_sale quantity subtotal

10.50      2        21.00

9.55       3        28.65

total = 49.65

Comment: Isso que você quer [está disponível no Django 1.8](https://code.djangoproject.com/ticket/14030), mas não no 1.7 ou anterior. Mais de dois anos atrás eu tive um problema semelhante (no sentido de ter a mesma causa raiz), e postei [essa pergunta no SOen](http://stackoverflow.com/q/15453662/520779), até hoje sem resposta. Infelizmente, não conheço nenhuma solução pré 1.8 que não envolva usar `extra` (posso dar mais detalhes numa resposta, se quiser).
Answer: Na versão 1.8 para gerar o subtotal você deve utilizar annotate e para gerar o total você deve usar aggregate.

É necessário utilizar ExpressionWrapper quando estiver realizando
  cálculos com diferentes tipos de valores.

Exemplo:
>>> from django.db.models import F, DecimalField, ExpressionWrapper
>>> q = SaleDetail.objects.filter(sale=1).values('price_sale', 'quantity')
>>> q_com_subtotal = q.annotate(subtotal=ExpressionWrapper(F('price_sale') * F('quantity')), output_field=DecimalField())
>>> q_com_subtotal[0].subtotal
21.0
>>> calculo_total = q_com_subtotal.aggregate(total=Sum('subtotal'))
>>> calculo_total.total
49.65

Referências:

https://docs.djangoproject.com/en/1.8/ref/models/expressions/#query-expressions
https://docs.djangoproject.com/en/1.8/ref/models/expressions/#django.db.models.ExpressionWrapper
Comment: primeiro deuo seguinte erro: django.core.exceptions.FieldError: Expression contains mixed types. You must set output_field. Dai eu coloquei qs = q.annotate(subtotal=(F('price_sale') * F('quantity')), output_field=FloatField())
qs[0].subtotal
E o erro passou a ser: AttributeError: 'FloatField' object has no attribute 'resolve_expression'
Comment: @RegisdaSilva já atualizei o código.
Answer:
Para o Django 1.8 ou mais recente, ver a resposta do Orion.

Na versão 1.7 do Django ou anterior não é possível utilizar F como parâmetro de annotate, aggregate ou values (ver ticket #14030), de modo que a única maneira de fazer isso é utilizando SQL puro (via extra). Não sei se é possível calcular total e subtotal em uma única query. Um exemplo (testado no SQLite) é:
>>> SaleDetail.objects.extra(select={
...   'subtotal':'round(price_sale * quantity, 2)',
... }).values('price_sale', 'quantity', 'subtotal')
[{'subtotal': 21.0, 'price_sale': Decimal('10.5'), 'quantity': 2},
 {'subtotal': 28.65, 'price_sale': Decimal('9.55'), 'quantity': 3}]

>>> SaleDetail.objects.extra(select={
...   'total':'round(sum(price_sale * quantity), 2)',
... }).values('total')
[{'total': 49.65}]


Computed value on multipage Webform

Question: I have multipage webform. I want to compute the value of the component (Hidden -type) which is on the second page based on the data submitted on the first page.
I'm using hook_form_alter and added my client_submit handler:
function mymodule_client_submit(&$form, &$form_state)

I can read there submitted data from the first page and I can do the calculation. But I cannot set the value of the component from the second page. I can see the structure of the form in $form or $form_state parameter. But I do not know how to set the value of the component from the second page as it was not submitted yet.
Answer: I can suggest you a simple way to do this. You can pass the calculated value stored in a variable to the next form function.
Like I had two step form & at first step of the form user select some name from given name(checkboxes), I store them in array & pass them to the next form function like --
function MYMODULE_form($names)//Use your module name instead of MYMODULE.
{
  $return_form = drupal_get_form('MYMODULE_get_form', $names);
  return drupal_render($return_form);
}
function MYMODULE_get_form($form, &$form_state, $names)
{
  $form = array();
  $i = 0;
  foreach($names as $name)
  {
    $form['item']['name'.$i] = array(
      '#type' => 'markup',
      '#value' => $name,
    );
    $i++;
  }
}

Try something like this, if it solves your problem. Use simple variable if you don't have multiple values.
Comment: You can use hook_form with passing your own variable too. Here MYMODULE_form is the function which will be called in next step of your form.
Comment: I tried your code, but it's not working: any markup fields are rendered on the second page.
Comment: I found the `function MYMODULE_form($names)` is not called. Even I use function signature like `function MYMODULE_form($form_id, &$form_state)` it is not called.
Comment: @PetrFelzmann - Paste your full code somewhere & link it here..
Comment: I created module called mt_booking and inside mt_booking.module file I have this code:
    ``
No message is displayed.

Computed value on multipage Webform


Page where I can see my user's managed files

Question: Is there a page in Drupal that lists all of the files in file_managed that the logged in user owns?
Answer: I do not think there is a pre-made page for this, but you can make one using Views.  Create a new view of type Files.  Under the Advanced section, add a Relationship for the user who uploaded the file.  Then add a filter "User: current" using this relationship.
Comment: Thanks, but I'm looking for a pre-made page. :)


dumping assets via assetic in prod using sass filter

Question: Im trying to dump the assets (assetic:dump  --env=prod --no-debug) for my Symfony 2.5 app for the production env.
I use the sass filter for including the .scss files:
    {% stylesheets filter="sass"  ...
I get the following error:
An exception has been thrown during the compilation of a template ("There is no "sass" filter.")
Is it required that you have all the filters (in this case sass) set up in your production environment? because I remember reading somewhere that in the prod environment symfony automatically does not use assetic.
I also tried dumping the assets locally (for prod) and then uploading them to the production server including the cache files (since my guess was symfony somehow must know which assets to look for, where) without any success.
Any thoughts on this are highly appreciated.
Comment: Well does your production environment have the sass filter?
Comment: No it does not.. There is no ruby installed
Comment: Im not positive on this but i believe that you still have to define the filter in the production config, even if you are not going to be using it. As long as you have the definition it should continue as expected.
Answer: You should be able to run the assetic:dump --env=prod command on your development environment, which will compile / dump the files as static css / js /etc. Those should then copied to the production server as part of the deployment process. On production, the Assetic Twig helper just resolves the assets to the proper filename, the compiled / static asset is served by your webserver as usual.


If a pager is missing, then appears when using another theme, does that narrow the problem to the original theme?

Question: I have a pager missing from one page, while visible on another. These pages are generated by my custom module. I'm working with a custom theme that's been hacked together (wasn't me!) When I switch the theme to Bartik everything works as expected.
Here is the query function:
function query_activities($tid = NULL, $did = NULL) {
  $record_count = variable_get('promo_list_count');
  $query = db_select('node', 'n')->extend('PagerDefault');
  $query->fields('n', array('nid', 'title'));
  if ($tid) {
    $query->leftJoin('taxonomy_index', 'ti', 'ti.nid = n.nid');
    $query->condition('ti.tid', $tid);
  }
  $query->condition('n.type', 'activity_promo_list');
  $query->condition('n.status', 1);
  $query->groupBy('n.nid');
  $query->orderBy('n.sticky', 'DESC');
  $query->orderBy('n.promote', 'DESC');
  $query->orderBy('n.changed', 'DESC');
  $query->orderBy('n.created', 'DESC');
  $query->limit($record_count);
  $results = $query->execute()->fetchAll();
  return $results;

I have a function that wraps the query results in theme arrays and can post the whole thing if needed (it's 120 lines) but I think the only relevant part is:
  $content['pager'] = array(
  '#theme' => 'pager',
  '#weight' => $count,
  '#quantity' => 5,
  );
  krumo($content['pager']);
  return $content;

The krumo() dump shows the pager array populated on both pages (pager visible & pager missing).
Does this narrow the problem to theme layer?
What should I look for to fix or diagnose the missing pager?
Comment: It's (almost) definitely a theme layer problem, does the hacked-together-theme contain a function called `THEMENAME_pager`?
Comment: No, I saw a few other questions refer to THEMENAME_pager, so I searched for this (actually searched pager) and nothing out of the ordinary came up.
Comment: How does your module generate and pass the pager to the page?
Comment: @sheena_d I updated the question to include some code :)
Comment: have you looked at the HTML source of the page as outputted to a browser? Is the pager markup there? .. just thinking it could be as simple as a CSS rule.
Answer: I stumbled on tostinni's answer in Pager disappears when adding "GROUP BY" in the SQL query.

Your query with the GROUP BY is incorrect, MySQL is lax enough to let you write this kind of queries but it is by no way recommended. When you use a GROUP BY clause you should group all the columns without a aggregate function.

I then fixed two queries that have poorly formed GROUP BYs, but my pager was still missing. I bust out Devel's query logging feature; the offending SQL query resulted to be used by the Nodequeue module. I checked the bug reports for that module, and found the one about that query: Grouping error" when creating a simple queue (PostgreSQL).


proof verification of $\frac{1}{n}\sum \sin nx$ having a limit

Question: I have to prove that $b_n=\frac{1}{n}\sum\limits_{i=1}^n \sin ix$ has a limit.
I'm using the result of an already solved problem which implies the following:
$$\sum_{i=1}^n \sin ix=\frac{\sin{\frac{n+1}{2}x}\sin{\frac{n}{2}x}}{\sin{\frac{x}{2}}}$$
Having that we see that $\sum\limits_{i=1}^n \sin ix$ is a bounded sequence since $\sin{x}$ is bounded by $-1$ and $1$.
Using the property that multiplying a bounded sequence by a sequence converging to $0$ we get a sequence converging to $0$, i.e.
$\lim\limits_{n\to\infty}\frac{1}{n} \sum\limits_{i=1}^n \sin ix=0$.
Is my reasoning correct and if not how do I prove this?
Answer: One needs to be careful here since we are dividing by $\sin(x/2)$ and that can be $0$ for $x\in2\pi\mathbb{Z}$. If $x\not\in2\pi\mathbb{Z}$, then $\sin(x/2)\ne0$ and your argument works fine.
However, if $x\in2\pi\mathbb{Z}$, then $\sin(ix)=0$ for all $i\in\mathbb{Z}$, and so the sum is $0$. This case needs to be handled.
Therefore, we get a pointwise limit, but we have not shown whether this limit is uniform or not.
Answer: View the sum as the imaginary part of
$$\sum_{k=1}^{n}e^{ikx} = e^{ix}\frac{e^{inx} - 1}{e^{ix} -1}.$$
That's bounded if $x\in (0,2\pi).$ If $x=0,$ the imaginary part of the sum is simply $0.$
Answer: Yes, you did it very well. In a formal way, one would write it perhaps as follows: Since we showed that $\sum_{i=1}^n sin(ix)$ can be written by the above formula, it is  $-1 \leq \sum_{i=1}^n sin(ix) \leq 1$, so also
$$ \frac{-1}{n} \leq b_n \leq \frac{1}{n}.$$
Since both the sequences $\frac{-1}{n}$ and $\frac{1}{n}$ converge to $0$ for $n \to \infty$, by the "Sandwich criterion" (or however you want to call this criterion with upper and lower bounds), also
$$ \lim_{n \to \infty} b_n = 0. $$

EDIT: After looking at the other answer, I just realized that $\sum_{i=1}^n \sin(ix)$ is not bounded by $1$! The denominator in your expression can be extremely small, making the fraction as large as you like. But as long as it does not get zero, the argument can be still performed since you still get a finite bound, and $x$ is fixed throughout the argument.
Comment: If $x=2 \pi + \pi/n$ the sum can be arbitrarily large.


Tossing two dices with indications of $X$ and $Y$ respectively. Probability questions around $S=X+Y$.

Question: Exercise :

We toss two dices. Let $X$ be the indication of the result of the first one and $Y$ the indication of the result of the second one. If $S=X+Y$, find the following :
(a) The probability mass function $p(s_j)$ of the random variable $S$.
(b) The mean value $E[S]$ of the random variable $S$.
(c) The variance $V[S]$ of the random variable $S$.

Attempt :
(a)
So, $S$ is the summation of the indications of the two dices, which means that the value of $S$ will rely in $[2,12]$, which is obvious. How would one continue to finding the probability mass function though ?
For (b) and (c), I do not know how to continue (I think you need (a) for those as well).
This is not a homework question, as it is an exam question which I'm trying to figure out in order for the upcoming semester tests. I would really appreciate any help on understanding the problem and the questions asked.
Comment: For a) the general method is called convolution. In this particular example when you adding two i.i.d. discrete uniform, you obtained a triangular distribution. For b) and c), you do not need to rely on the result of a). You just need to know how to calculate for individual dice and then sum them up (expectation is linear; by independence assumption there is no covariance term)
Comment: @BGM For (b) and (c) I will work through : $$E[X+Y] = E[X] + E[Y]$$ and $$V[S] = E[S^2]-E[S]^2$$ But how would I proceed in (a) though ? I didn't get it.
Comment: Concerning c) it is more handsome to follow the instruction of @BGM and to go for $V[S]=V[X]+V[Y]+Covar[X,Y]=V[X]+V[Y]$. Concerning (a) note that e.g. $P(S=5)=\sum_{k=1}^4P(X=k\wedge P(Y=5-k)=\sum_{k=1}^4P(X=k)P(Y=5-k)$ since $X$ and $Y$ are independent.
Comment: The way to visualize the counting: You make a $6$ by $6$ table, and write the support of $X, Y$ i.e. $1, 2, \ldots, 6$ on the two margins respectively. So each cell $(x, y)$ represent the event that $X = x, Y = y$ and by independence and uniform assumption, the probability of each happening is equally likely, i.e. $1/36$. Next, sum the coordinates and write it down for all the cells. Note the pattern appear on the table and count the number of cells with values $2, 3, \ldots 12$. Sum the corresponding probabilities (i.e. multiply the count by $1/36$ in this case) will be your required pmf.
Answer: Hint:
The pdf of $X$ (or Y) is a uniform distribution on support set $\{1,2,3,4,5,6\}$ so the distribution of $S$ using convolution operator over its support set $\{2,3,4,5,6,7,8,9,10,11,12\}$ is $$\dfrac{1}{36},\dfrac{2}{36},\dfrac{3}{36},\dfrac{4}{36},\dfrac{5}{36},\dfrac{6}{36},\dfrac{5}{36},\dfrac{4}{36},\dfrac{3}{36},\dfrac{2}{36},\dfrac{1}{36}$$Can you finish now?
Comment: IE . $~p(s_j) =\begin{cases} \frac 1{36} &:& s_j=2 \\ \frac 2{36} &:& s_j=3 \\ ~\vdots &\vdots &~ \vdots\end{cases}$
Comment: This would imply that : $$p(s_j) = \frac{1}{36}$$ ?
Comment: What is $s_j$? It is a triangular distribution over the support set of $S$.
Comment: The probability mass function as described in the question form.
Comment: Yes....The numbers I wrote there are CDF values of $S$
Comment: Yes that's right...
Comment: PDF, not CDF. $ $
Comment: [Checking that link here](https://onlinecourses.science.psu.edu/stat414/node/104), seems like the correct answer is that the probability mass function is equal to $1/36$. I still don't get something here regarding the answer and everything people have written (which is not clear).


call function when leaving scope

Question: What is the most elegant solution for calling a function automatically when leaving a scope?
My current approach (see below) works but I guess there should be something more general as writing a custom class for this.
#include <iostream>
#include <functional>

using namespace std;

class DoInDtor
{
public:
    typedef function<void()> F;
    DoInDtor(F f) : f_(f) {};
    ~DoInDtor() { f_(); }
private:
    F f_;
};

void foo()
{
    DoInDtor byeSayerCustom([](){ cout << "bye\n"; });

    auto cond = true; // could of course also be false
    if ( cond )
        return;

    return;
}

int main()
{
    foo();
}

Sure, one could abuse std::unique_ptr and its custom deleter, but since I am not really acquiring a resource here, that does not sound great to me either in terms of code readability. Any suggestions?
Comment: As a side note, you generally should not do this if the function that you want to be called when leaving the scope can throw an exception!
Comment: You might want to check out [(Loki's)](http://loki-lib.sourceforge.net/) [(ScopeGuard)](http://loki-lib.sourceforge.net/html/a00667.html) class.
Comment: In the future, we might get this: [Scoped Resource - Generic RAII Wrapper for the Standard Library](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2014/n3949.pdf).
Comment: This probably belongs on Code Review.
Comment: When leaving a function or leaving a scope? Because, there are two different things. Not that it matters a lot. But sounds heavy work to put this `DoInDtor` object in _each_ scope. What are you trying to achieve?
Comment: @KerrekSB: OK, sorry. I will post it there is no answers will be posted here.
Comment: @KirilKirov: Any scope, nur just function scope. I edited my example to make this clearer.
Comment: @anderas: Yes, dtors sould of course never throw.
Comment: @Angew: Thanks, this looks interesting.
Comment: @CassioNeri: That sounds nice, thanks.
Answer: Angew and Cassio are pointing you in the right direction here with ScopeGuard. Using std::function can incur dynamic memory allocation and is not the most efficient solution. The ScopeGuard-based implementations avoid that by encoding the type of the function object to invoke into the ScopeGuard class itself as a template parameter. With a helper function template, you never have to explicitly state that type, the compiler deduces it for you (and has to in the case of a lambda being used as the function object to invoke).
Rather than repeating all the details here, I recently wrote two articles about this very area:

Let your compiler do your housekeeping
OnLeavingScope: The sequel

The first article focuses on simplicity and starts from a similar place as your original question, including a motivating example. The second one goes through all the steps to evolve that to an efficient and robust implementation which results in concise, very readable code. The second article also explains how the material presented relates to Andrei's work with ScopeGuard and the C++ standards proposal for scope_exit mentioned by Cassio.
Answer: Using a constructor/destructor in this way is a common way to solve this sort problem. I have used it for both locks (constructor takes lock, destructor releases it) and logging purposes (constructor prints something on construction, and destructor prints on destruction, giving a nice callgraph of a project - in the latter case, using macros to also get __FILE__ and __LINE__ store in the object, so we can see where the constructor was called [it's almost impossible to do this for the destructor, but typically it's possible to see the constructor and make out where the destructor gets called]).

call function when leaving scope


Violin Tuning- shouldn't the the A-string be tuned to A5? Why A4?

Question: G3 up by a perfect fifth is D4, D4 up by P5 is A5!! A5 up by P5 is E5. It's all good except that the A string is tuned to A4, which is 440Hz. Why should not be tuned to A5?! Why is the tuning G3, D4, A4 and E5 instead of G3, D4, A5 and E5?
Comment: A5 is higher than E5. The lowest letter name for any octave number is C, so  the perfect fifth above D4 is an A within the same octave number.
Comment: Thanks, Pat, Aaron, User25119, Todd and Phil. . Needless to say, I am still to attend a class with a teacher. Curiosity got the better of me. I have been reading the notes are arranged from A to G and assumed the octave number changes at the G/A boundary. My mistake. Thanks.
Comment: Please "accept" one of the answers by clicking on the tick mark below the answer. That's equivalent to a "thank you".
And you're always welcome to ask more (constructive) questions on StackExchange :-)
Comment: Please don't add "thank you" as an answer. Instead, vote up the answers that you find helpful. - [From Review](/review/low-quality-posts/23058)
Answer: If the comment and existing answer still don't make it clear, maybe a picture:

As user25119 wrote, the octave numbers change when you go from B to C. So that means the D and the A highlighted below should have the same octave number.

The octave starting with middle C has octave number 4, so the octave from middle C up to the B above middle C is C4 D4 E4 F4 G4 A4 B4.
The octave above that, of course, is octave number 5, which is why the high E on the violin is E5.

Image Source
Comment: I love that picture. How to tune a Violin using a piano: Twiddle the knobs until they sound completely wrong. Weep. Smash the violin until the bottom half falls off. Then, with a peculiar smile, take some green string and tie the pegs to the nearest piano and walk slowly away. There, I tuned the violin, and it's with the piano.
Answer: D4 up by a perfect fifth is A4.  The octave number in the scientific note naming system only advances when crossing the B/C boundary, so the C major scale notes available on the violin (notes on open strings marked) are
G3(open) A3 B3 C4 D4(open) E4 F4 G4 A4(open) B4 C5 D5 E5(open) F5 ...


If statement isn't working while using dictionary or list

Question: I have a form with student ID and pages of slides that students have read.
Now I need to print out those students who read more than 200 slides and calculate how many of them. I've tried to import csv to list and dictionary.
I found it's not possible to use if and while loop as I learned in C language.
<code>#1
import csv
f = open('student_example.csv','r')

for row in csv.reader(f):
     with open('student_example.csv', mode='w') as outfile:
         writer = csv.writer(outfile)
         [k,v] = row
         f[k] = v
         k = 0
         print (f[2])
         while k < 71:    #There are 71 students
            k += 1
            if f[k] >= 200:
                print (f[k])
#2
import csv

with open('student_example.csv', mode='r') as infile:
   reader = csv.reader(infile)

   with open('student_example_new.csv', mode='w') as outfile:
       writer = csv.writer(outfile)

       mydict = {rows[0]:rows[1] for rows in reader}
       print(len(mydict))
       k = 200
       for rows[1] > k in reader:
            print(rows[1])
</code>
Sample output should be:
There are 13 students passed: dict_keys(['B046060035', 'B064020028', 'B064020052', 'B064030002', 'B065040041',
'B066060019', 'B066090002', 'B073040038', 'B074020003', 'B074020024', 'B074020043', 'B074020053', 'B074020055'])
Answer: Using your first try, you can do this in this way.
You want to open you outfile and then iterate through the students.
check for each student how many slides they read and write to outfile if > 200
<code>import csv
f = open('student_example.csv','r')

with open('student_example.csv', mode='w') as outfile:
    writer = csv.writer(outfile)
    for row in csv.reader(f):
        [student_id, slides] = row
        if slides > 200:
            writer.writerow(student_id)
            print (student_id)
</code>


Solving $3^n-2^m=1$ by proving the inequality $3^n - 2^{[n \log3/\log2]}>1$

Question: I know one way to find all the integer solutions of $3^n-2^m=1$ is to consider cases about $n$ (odd or even) and proceed consequently. But I would like to prove the above just in a different way:

$m$ cannot be bigger than $n \log_{2}3$ otherwise $3^n-2^m$ would be negative, so $m\le [n \log_{2}3]$

$m$ cannot be less than $n$ otherwise $3^n-2^m$ would be bigger than $1$

As between the integers $2^m$ and $2^{m+1}$ should be one prime then we must have $m+1> n \log_{2}3$

From 1., 2. and 3. we get that $m= [n \log_{2}3]$
So in order to prove that the only solutions are $n=1$ and $m=1$ or $n=2$ and $m=3$, it suffices to prove:
$$3^n-2^{[n \log_{2}3]}>1$$ for every integer $n>2$.
But I have difficulty here and I need some advise please.
Comment: Maybe someone can prove me wrong, but I think viewing it as an inequality in terms of $\lfloor n \log_2 3 \rfloor$ is very unlikely to be a useful approach.  You'd need some very specific estimates on e.g. the continued fraction expansion of $\log_2 3$.  Seems like a lot of work to avoid using modular arithmetic.
Comment: I think that would be very hard to prove analytically.
Comment: @Mike Click on the clock icon above-left to see the post activity timeline.
Comment: I see now how this question got bumped, thanks!
Comment: Since you accepted an answer using a different proof, the question is now a dupe.
Answer: Note that $3-2=1$ and $3^2-2^3=1$. Those are the only solutions.
ETA: I have no idea how one would prove it along the lines that you are trying to, showing that there are no integers $N$ and $M$ s.t. $0<M-\frac{N \log 2}{\log 3} \le \frac{1}{3^M}$ via some sort of analytic method [i.e., $2^N = 3^{\frac{N \log 2}{\log 3}}$ is an integer, and
$\frac{N \log 2}{\log 3}$ comes so close to another integer $M$ from below that in fact $3^M-3^{\frac{N \log 2}{\log 3}} = 1$]. It probably would involve some pretty deep mathematical results.
Are you aware of the other proof first: First note that the equation $$3^M-2^N=1$$ has no solutions for $M>1$ odd. Indeed if $M$ is at least 3 then $N$ must also satisfy $N>3$. However, $3^M \equiv_8 3$ for all odd $M$ while $2^N \equiv_8 0$ for all $N \ge 3$.
We now show that the equation $$3^{M}-2^N=1$$ has no nontrivial solutions either
for any even integer $M>2$.
Indeed doing algebra this becomes
$$(3^{\frac{M}{2}}-1)(3^{\frac{M}{2}}+1)=2^N.$$
Then this implies that there exists nonnegative integers $n_1$, $n_2$ such that both (a): $3^{\frac{M}{2}}-1=2^{n_1}$ and (b): $3^{\frac{M}{2}}+1 = 2^{n_2}$, and $n_1+n_2=N$, and [as $3^{\frac{M}{2}}-1<3^{\frac{M}{2}}+1$] the strict inequality $n_1<n_2$. So then, on the one hand $2^{\min\{n_1,n_2\}}=2^{n_1}=3^{\frac{M}{2}}-1$ divides both $3^{\frac{M}{2}}-1$ and $3^{\frac{M}{2}}+1$ by Equations (a) and (b), so (c): $2^{n_1} =3^{\frac{M}{2}}-1$ is a factor of $\gcd(3^{\frac{M}{2}}-1,3^{\frac{M}{2}}+1)$, and thus (c$'$): $\gcd(3^{\frac{M}{2}}-1,3^{\frac{M}{2}}+1)$ $=$ $3^{\frac{M}{2}}-1)$. On the other hand, $3^{\frac{M}{2}}-1$ and $3^{\frac{M}{2}}+1$ differ by precisely 2 so this implies (d): $\gcd(3^{\frac{M}{2}}-1,3^{\frac{M}{2}}+1) \in \{1,2\}$.  So (c$'$) and (d) together give $3^{\frac{M}{2}}-1$ must be in $\{1,2\}$ if there is a solution, which is impossible for even $M \geq 4$.
Comment: This is a correct proof (and the right way to approach the problem, in my opinion); however, the OP specifically said this is not what they're looking for.
Comment: All I can say to the OP is good luck.  $\log_2 3$ is of course irrational and $n$ can be any integer and to show we *can't* squeeze a value of $M=n\log_2 3$ so that $2^M=3^n$  is never within $1$ of a power of $2$.... It can only have things to do with nature of integers and therefore number theory.
Comment: Well it is probably extremely difficult. I don't think I've yet to see on here a Diophantine Equation solved in the way the OP suggested.
Comment: Thanks for the answer! +1, As I said in my question,  I know the way to prove such an equation with modular arithmetic.  What I was actually,  looking was a way to prove that the sequence $a_n=3^n-2^{n [\log_{2}3]}$ is bigger than $1$ when $n>3$. This is obvious just checking up to $n=1000$, and furthermore it seems that $a_n$ is increasing.
Comment: I have tried some ways like: $3^n=(2+1)^n>2^n+3 •2^{n-1}+2 •2^{n-2}+...+3 •2+1$ but it did not help.... Furthermore the subsequent function is not even continuous so I ran out of methods...
Comment: Please don't duplicate common proofs (to FAQs), esp. when the OP asks for a different proof.


Out of PAT range

Question: Now that the point after touchdown attempt in the NFL makes for a challenging kick, has successive offensive penalties ever taken a team out of range for the PAT?
Answer: "Out of range" is subjective, so I will leave it up to the reader to decide.
During the first week of the 2015 season, the Browns converted a 48-yard PAT. According to ESPN, this was the longest PAT since 2001, in which the Cardinals converted a 37-yard PAT.
According to ForTheWin, the Redskins converted a 40-yard PAT in 1987 and is believed to be the longest PAT conversion prior to the rule changes implemented in 2015.

Out of PAT range


Tuning peg tight on a guitar (possibly slipping, too)

Question: So my guitar's G-string peg is feeling tight. I'm a newbie, but I think that the peg is slipping, since I can hear a click sound when I try tuning it up. The G string is now around 2 whole steps behind G, yet it feels tight. Please tell me what I should do now?
Edit 1: Sorry for posting this late, but... https://vimeo.com/467097345
If you watch the video you'll hear the sound. It's a fender squier acoustic guitar.
Edit 2:
Comment: Adding a picture or two of your headstock would answer some questions we have, so we can answer yours more easily?
Comment: Do your tuners have exposed gears or are they sealed? If they are exposed make sure that the gear is seated properly on the shaft and that the screw that holds it in place is not loose.
Comment: Without relevant information, such as what sort of guitar, what sort of strings, this is not going to get a good answer.
Comment: They're sealed, but i took them out and checked what was wrong. They're normal pegs. I'm not sure what the problem is. Please check out the link which I've added. You might under the issue then.
Comment: They're not pegs, they're geared tuners. Different behaviors.
Comment: Oops okay Sorry. Thanks! Understand* Also, please check out the video which shows the issue.
Answer: Without more info we can only guess:

If the string is slipping it will go down in pitch quickly while tuning or playing. If that happens, the best thing to do is to unwind it, remove the string from the peg, and put it back properly. If you're not sure how to do that, look online for some instructional videos on how to install strings correctly, so they can't slip.

Could it be that the wrong string is there? If a thicker strings ended up there by mistake, it may be impossible to tune, it will either break or not go beyond a certain point.

If the machine heads are old and worn, or cheap and poorly made, hardness and imprecision are to be expected. One thing you can try is to loosen it up, put a couple of drops of oil in it, make it go back and forth one time to spread the oil everywhere, and then try to tune the string again.

If it's a classical guitar, there'll be a screw that keeps the gear head locked into the white plastic pin, and (in some models) it also controls how tight the peg is when you turn it. So make sure it is tight enough to keep the gear solid with the plastic peg, but not so extremely tight that it makes the machine head impossibly hard to use.

Some electric guitar pegs have a locking screw or metal gear that you can tighten with your hands to keep the tuning locked in place for a longer time than usual. In such a case you may have to loosen the locking screw/gear a bit, before you can tune the string normally again.
Comment: I have uploaded a video which shows what the issue is. The peg is too tight and i can hear the sound from the video often.


Crumbs is not showing parent of taxonomy term

Question: I'm using Drupal 7.5.2 and am attempting to use the Crumbs module (version 7x-2.5) to show parent and child paths in the breadcrumbs trail and it's not working.
My URL alias structure—which I am attempting to recreate in the breadcrumbs—is as follows:

My Great Node Pile: A view page that is neither taxonomy term or a node.
Category: A view page that is connected to the parent taxonomy term.
Category Child: A view page that is connected to the child taxonomy term.
Node: The node associated within that parent category and child category.

Only one category—child or parent category—can be associated to a node at any given time.
My "Entity Parent" settings for all node content types is as follows; note all content is based in the path of my-great-node-pile/ which is a stand-alone view that is simply the "home base" for this stuff; it is neither a taxonomy term parent item or a child item:
my-great-node-pile/[node:field_category:parent]/[node:field_category]

So if I have a node that resides in the aliased area of "My Great Node Pile" titled "Cool Stuff" that has this parent/child taxonomy term URL structure; using Pathauto for that so do not take this pseudeo-example 100% literally:
my-great-node-pile/field-category/field-category-child/cool-stuff

Then I would expect my breadcrumb trail to be this:
My Great Node » Category » Category Child » Cool Stuff

But with the default Crumbs settings, this is the bizarre breadcrumb trail I am getting:
My Great Node » Category Child » My Great Node » Cool Stuff

What? If the entity parent is [node:field_category:parent]/[node:field_category] then why is it apprarently rendering as [node:field_category]/My Great Node?
Example Note: The names of items here—including tokens—are neutralized to protect anonymity of the project, but I assure you all tokens and examples here are proven to have the values they should have via the output of the Devel (version 7.x-1.5) module.
Comment: A said below, imo the goal of stackexchange should be to produce Q/A content that will be useful to more people than just the original poster. If people get here from google, they should be provided with useful information that is generic enough to apply to their case.
Comment: Hi! I am about to write an answer to this, which I hope will clarify things for other readers too. Maybe you could add more information to the question and use example names that allow a better distinction of nodes vs terms? E.g. in your example "Parent stuff" and "Child thing" are a terms, but "Cool stuff" is a node? And "My great node" is possibly a views page which is neither a term nor a node? Also if you can, specify urls or paths for each breadcrumb item.
Comment: And what is `[node:category]`? I imagine you have a taxonomy term reference field, so it would rather be sth like `[node:field-category:1:tid]`.
Comment: @donquixote Sorry, but while I appreciate your effort—and your notes have helped me clarify the question—this is ultimately a self-answered question where doing [what I outline in my answer](http://drupal.stackexchange.com/a/222054/36892) is what ultimately solved the problem outlined which is simply stated: If I have a parent/child taxonomy term structure, why does it behave oddly and render incorrectly when using Crumbs via default settings? Simply adding `path` from Crumbs from "Disabled by default" to "Enabled" is what solved the problem.
Answer: After spending more time than I wanted to to dealing with this—exploring solutions and Googling seemingly forever—I came across this post on the official Drupal site titled "Crumbs not working" and specifically this answer from 'donquixote' which states:

are these system paths or node aliases? If they are node aliases, do you have the "path" plugin enabled? (*)

Okay, so that seems like an idea. So I went into the Crumbs settings area under "Structure > Crumbs" and dragged the path setting—which describes itself as "Chop off the last fragment of the path alias, consider the result as the parent path."—from "Disabled by default" to the second position of "Enabled" (see attached screenshot), hit "Save configuration" and… et voilà… It works! Parent and child taxonomy terms are being rendered in the breadcrumb path as expected.
Comment: This does not answer the "why does it behave oddly and render incorrectly" part of your question - just saying.
Answer: One important thing to notice is that Crumbs trail-finding works recursively.
Every rule in "Entity parent" or in the main plugin configuration page is only there to specify the direct parent page.
The rest of the trail, like the grandparent, grand-grandparent etc are determined via recursion.
About your example

My "Entity Parent" settings for all node content types is as follows;
  note all content is based in the path of my-great-node-pile/:
my-great-node-pile/[node:category:parent]/[node:category]

I suspect that the token string does not work.
First, [node:category] should probably be something like [node:field_category] if you are using a taxonomy term reference field.
Secondly, I recommend to specify the system path of the node's category, not the alias: taxonomy/term/[node:field-category:1:tid]. Notice the - instead of _. This is just how tokens work, apparently.
Thirdly, what you really should do instead, is use the already-existing plugin for taxonomy.termReference.field_categories.node.*.
Proposed solution
On admin/structure/crumbs:
First, enable the taxonomy.termReference.field_categories.node.* (replace field_categories with the field name of your choice). This tells Crumbs that the parent page of a node should be the category.
Then, enable taxonomy.termParent.* or leave it in the "Inherit" section. This tells Crumbs that the parent page for a category should be the parent category.
Finally, go to admin/structure/crumbs/entity-parent/taxonomy-term and set my-great-node-pile as the parent path for categories.
Alternative I: The "path" plugin.
If you sure that your aliases are all perfect, you could simply work with the "path" plugin alone, as you already proposed.
If you do this, you can remove the "Entity parent" token strings.
But beware that this requires your aliases are all working correctly. E.g. if for some reason you have one node with the wrong alias, then your breadcrumbs will break down for this node.
Alternative II: "Easy breadcrumb" module
Basically, Easy breadcrumb is equivalent to Crumbs with ONLY the "path" plugin.
If you are sure your aliases are perfect, and you are not interested in any of the other functionality in Crumbs, then Easy breadcrumb can be for you.
It does not give you the deep recursion like Crumbs. E.g. if you visit a node/123 which has an alias, and then go to node/123/edit, which does not have an alias, then Crumbs will preserve the beginning of the breadcrumb, while with Easy breadcrumb you will lose most of the breadcrumb on the node edit page.
Troubleshooting: Crumbs "Debug" tab
Notice that the "Debug" tab is there for a reason..
Comment: The main intent of my reply is not primarily to help you personally, but to make this a useful Q/A for other readers. Your answer might work for you, but I think it might be misleading to other readers in some cases, and it does not explain the background and why this works.
Comment: Your answer doesn't solve a problem; this is a self-answered question where I present an answer that works 100% fine for the situation presented. Perhaps my example—in which I have attempted to neutralize personal details of naming schemes from the client's site with new names—needed to be more carefully setup to avoid confusion, but I assure you the scenario I provide as an example is saved perfectly by my answer.
Comment: @donquixote I take you are the maintainer of the module the question is about? This is important, because in that case you are objectively more prepared to answer this question.
Comment: Yes, I am the maintainer, and I am following the "breadcrumbs" tag to get feedback and better understand how people use the module, and in the hope that I can educate people.
Comment: And I am often annoyed on stackexchange sites if I find "worksforme" answers that do not help anyone else. Or issues on drupal.org that were closed for this reason.
Comment: On the other hand this means I am obviously biased, so I want to avoid advertising it too much. So i always want to propose alternatives when applicable.


How to align Two image view in same bottm line in android?

Question: I have two imageView with two different size image. anyone one have idea how to align two image from baseline?
Comment: What's you effort , you should share your layout code to get assistance or help.
Comment: Give some more details to solve your problem...
Answer: If you put these images in a RelativeLayout, one has @+id/first, another @+id/second,
then in the second image specify: android:alignBottom="@id/first"
Comment: absolutely what i am looking for. Thanks. had never use alignBOttom.and android:baseLine do the same work :)
Answer: Wrap them in a linearlayout with equal weighting.


What language do Belgian football players use to communicate between themselves?

Question: Belgium is a country with three official languages (Dutch, French and German), all of which are used in practice by significant portions of the population, largely divided by geography. Of course, football players come from all different regions. How do they communicate on national teams? Is there a dominant language, or does each just use his most fluent language while all others are assumed to be able to understand, more or less? In what language does the coach instruct the team?
On a side note, I've read somewhere that players (and some supporters) of Anderlecht use English to communicate and support the team. I hadn't imagined English to be such a popular choice in a country where it's not an official language. Does this claim make sense?
Comment: One could ask the same for Swiss players.
Comment: yesterday the swiss coach Ottmar Hitzfeld talkt to them in Swiss-German. A kind of german dialect, but hard to understand for germans.
Comment: Note that during the debates of the Belgian federal parliament (and incidentally also of the Swiss "national council"), MP simply speak in their own language, with no translation. They are expected to have at least a passive knowledge of the other language. German speakers in Belgium and Italian speakers in Switzerland very often know the two other languages.
Answer: German isn't really a significant language in Belgium. All players will speak either French or Dutch. English is increasingly becoming an unifying language in the country as the Dutch of Wallonians is virtually non existent and despite some knowledge of French being widespread in Flanders it tends to be weaker than their English ability. I somehow doubt Anderlecht fans make much use of English on the terraces as they would be predominantly French speaking, although some chants may be in English for the benefit of the visiting supporters who are mainly Flemish as the vast majority of Belgian league teams hail from the Dutch speaking Flemmish region.
Answer: According to The Sun:

Kevin de Bruyne is a Flemish-speaker from Ghent whilst Axel Witsel
  speaks only French (he was born in Liège). [...] Romelu Lukaku can
  speak six – Flemish, English, French, Portuguese, Spanish and Swahili.
  But some of the French-speaking players are monolingual.
English is reportedly used as the common language in the dressing
  room, so the Belgian FA cannot be accused of favouring either French
  or Flemish over the other and creating language barriers.

Their current coach speaks to the team in English, but this is something that can change over time, if Roberto Martinez leaves the team.

Martinez is a Spanish coach who talks in none of the three official
  languages of Belgium: French, Flemish and German. He uses English when
  speaking to the players, where it acts as a middle ground.

Regarding the second question: given that French is de-facto the main language of Brussels (where Anderlecht is based), you would expect the locals (homegrown players, fans) to communicate mainly in this language. But if you include international players into the equation and also the increasing popularity of English in Brussels, it wouldn't be a surprise if players spoke it as well. In either case it's definitely not Flemish (a variant of Dutch) which interestingly was the historical language of Brussels.


The most effective way of computing distance to sphere in CUDA?

Question: I'm raymarching Signed Distance Fields in CUDA and the scene I'm rendering contains thousands of spheres (spheres have their location stored in device buffer, so my SDF function iterates through all of the spheres for each pixel).
Currently, I'm computing distance to sphere surface as:
sqrtf( dot( pos - sphere_center, pos - sphere_center ) ) - sphere_radius
With the sqrt() function, the rendering took about 250ms for my scene. However, when I removed the call to sqrt() and left just dot( pos - sphere_center, pos - sphere_center ) - sphere_radius, the rendering time dropped to 17ms (and rendering black image).
The sqrt() function seems to be the bottleneck so I want to ask if there is a way I can improve my rendering time (either by using different formula that does not use square root or different rendering approach)?
I'm already using -use-fast-math.
Edit: I've tried formula suggested by Nico Schertler, but it didn't work in my renderer. Link to M(n)WE on Shadertoy.
Comment: If you only need the zero levelset, you can use the field `dot( pos - sphere_center, pos - sphere_center ) - sphere_radius * sphere_radius`.
Comment: And just in case: If all you want is to intersect spheres, then there is no need to use distance fields. The intersection of a sphere and a ray can simply be computed directly…
Comment: Maybe you can "propagate" the use of the squared distance to the rest of your computation. At the very least you could do: `min(squared_distance_to_closest_sphere, distance_to_the_closest_object_in_the_rest_of_the_scene^2)` - right?
Comment: `--use-fast-math` has [no effect](https://docs.nvidia.com/cuda/cuda-c-programming-guide/index.html#intrinsic-functions) on `sqrt()` AFAIK.  If you are using `sqrt()` (i.e. not `sqrtf()`)  you may get some benefit if you can switch to e.g. [`__fsqrt_rn()`](https://docs.nvidia.com/cuda/cuda-math-api/group__CUDA__MATH__INTRINSIC__SINGLE.html#group__CUDA__MATH__INTRINSIC__SINGLE_1gf021e85b5e9de141a0fc2ff6fbe85875)
Comment: @wlcezar `currPt += rd * currDst;` is obviously not going to work if `currDst` is not an actual distance…but even when it is, this probably doesn't do what you want…unless your ray hits the center of the sphere exactly, the distance you move along the ray here is not a distance measured along the ray…
Comment: @NicoSchertler I have tried that formula before, but it didn't work with my current rendering approach. Here is [link to Shadertoy](https://www.shadertoy.com/view/tlf3zB) with both formulas (set `USE_SQRT` to `0` for sqrt-less formula).
Comment: @MichaelKenzel thank you, unfortunately, (I think) I need to use ray marching, because the scene I'm rendering contains also other SDF functions. My final SDF function looks like this: `min(distance_to_the_closest_sphere, distance_to_the_closest_object_in_the_rest_of_the_scene)`.
Comment: @wclezar that's fine, in this case, however, you will generally not be able to just directly skip all the way to the point where you hit an object and will have to properly step through the distance field anyways…
Comment: Thank you for your answers. I implemented the approach suggested by @einpoklum and it did bring significant improvement!
Answer: (Making my comment into an answer since it seems to have worked for OP)
You're feeling the pain of having to compute sqrt(). I sympathize... It would be great if you could just, umm, not do that. Well, what's stopping you? After all, the square-distance to a sphere is a monotone function from $R^+$ to $R^+$ - hell, it's actually a convex bijection! The problem is that you have non-squared distances coming from elsewhere, and you compute:
min(sqrt(square_distance_to_the_closest_sphere),
    distance_to_the_closest_object_in_the_rest_of_the_scene)

So let's just do things the other way around: Instead of taking the square-root of the squared distance to the sphere, let's square the other distance:
min(square_distance_to_the_closest_sphere,
    distance_to_the_closest_object_in_the_rest_of_the_scene^2)

This makes the same choice as the un-squared min() computation, due to the monotonicity of the squaring function. From here, try to propagate the use of the squared distance further in your program, avoiding taking a root as far as possible, perhaps even all the way.


Rails file field doesn't change the name when using multiple

Question: When using multiple for my file field, it displays a name with an array [] appending at the end, but I'm trying to get rid of it. I'm not getting the correct name as I'm supposed to. I'm supposed to remove the [] from the name by hard coding it, the name still gives me business_photos[bizurl][].
<%= form_for BusinessPhoto.new, :html => {:class => "biz_image"} do |f| %>
    <%= f.file_field :bizurl, multiple: true, name: "business_photos[bizurl]" %>
    <%= f.hidden_field :business_id, :value => @biz.id %>
 <%= f.submit %>
<% end %>

Is there something I'm missing?
Answer: With file_field it will automatically add the [] array in the name.
If you want to remove it you can use file_field_tag instead of f.file_field
f.file_field :foo, multiple: true, name: 'foo' # results in "name='foo[]'" (f is a form-helper)
file_field_tag :foo, multiple: true, name: 'foo' # results in "name='foo'"

Similar discussion here
Answer: You are not passing html option
:multipart => true

with form_for
Comment: i've had that before, but i still have `[]` at the end of the name
Comment: yeah I have restarted the server
Comment: From the [3.2 API](http://api.rubyonrails.org/v3.2.8/) seems that the multipart is already set from the file_field method `self.multipart = true`