For a projection matrix, is the left nullspace equal to the nullspace?

Question: Projecting onto a subspace, the vectors that project to the null vector (i.e. the nullspace vectors) are those with no component in the column space -- they are orthogonal to the column space. The vectors that are orthogonal to the column space are the left nullspace.
Question: For a projection matrix $A$, does the above argument prove that $N(A) = N(A^T)$?
It seems like the dimensions make sense for that to be true, because a projection matrix must be square (since $P^T=P$ and also since $P^2 = P$) and $$\dim N(A^T) = m - \dim C(A) = n-r = n - \dim C(A^T) = \dim N(A) .$$
(I'm new to this material, so simple language is appreciated.) Thanks!
Answer: If $P$ is an orthogonal projection, then it follows that $P = P^T$ and hence $N(P) = N(P^T)$. However, if $P$ is not orthogonal, then it may not be true that $N(P) = N(P^T)$. For example, consider the (non-orthogonal $\iff$ non-symmetric) projection matrix
$$
P = \left[
\begin{array}{cc}
0 & 1\\
0 & 1\\
\end{array}
\right]
$$
It is clear that $N(P)=\{(a,0)\in\mathbb{R}^2\,|\, a\in\mathbb{R}\}$ and $N(P^T) = \{(a,-a)\in\mathbb{R}^2\,|\, a\in\mathbb{R}\}$. The only point they have in common is the zero vector.


Was Sviatoslav Richter using the pedal in his recordings for Well-Tempered Clavier?

Question: Was Sviatoslav Richter using the pedal in his recordings for Well-Tempered Clavier ?

I'm not able to listen if he is using it or not.
(Since I like his way of playing, I would like to do the same : use the sustain pedal if he does, and not use it if he does not.)
Comment: I guess, this would be more appropriate for Music Fans section.
Answer: It's obvious (to me) that the first C major prelude is absolutely drowned in pedal, and there is plenty at the start of the fugue as well.
Totally unauthentic, but whatever turns you on!
But if you cant "hear" what effects he is producing with the pedal, simply "using it because he does" might not achieve what you want!
Comment: I like the prelude arpeggios with pedal - and I bet Bach would have marked it if he had one. ;)
Comment: It can't be "authentic" anyway if it's being played on the piano, so the pursuit of authenticity doesn't strike me as a goal for people playing Bach on the piano — even Glenn Gould. As for what the OP wants, he has much to learn about that, and he could do a lot worse than emulating Richter as well as he might.
Answer: If you want to compare one which has very little pedal, have a listen to some of Glenn Gould's recordings. For example this one:

The same fugue starts at 15:10 on the Richter recording you've provided. You will see that the difference in pedal usage is pronounced.
Comment: @MathieuKrisztian I think what can be said of Gould is that he uses less pedal than many pianists (Richter, for example), but certainly not no pedal at all. He is also known for playing passages staccato that nobody else would ([here's](https://www.youtube.com/watch?v=_3MVZfLReo0) a famous example, which you can also compare to Richter's version), but that doesn't mean that he never plays legato, either.
Comment: thank you. I'm surprised though : Glen Gould uses pedal while I *thought* that he was *never using pedal*, and that he was playing staccato, which is not what we hear. He plays legato here.
Comment: For a couple of eye-openers on the kind of pianist that Gould was, have a listen to [this](https://www.youtube.com/watch?v=5JwKDzPlYQs) and [this](https://www.youtube.com/watch?v=eXoL60ipygo).


Database Tables For Images And Videos

Question: I'm trying to build Database design for news website.
The problem that I faced is:
should I build tables for images and videos in the database??
Answer: No, you should not. Databases are not geared towards good handing of large files. Consider using file system for that.
There are tons of similar discussions around so I just drop links to them here:

Storing a file in a database as opposed to the file system?
Storing Images in DB - Yea or Nay?
https://softwareengineering.stackexchange.com/questions/150669/is-it-a-bad-practice-to-store-large-files-10-mb-in-a-database
Comment: can you clarify that please??
Comment: @Ibrahim Added some links to help you understand all pros and cons

Database Tables For Images And Videos


Javascript muito lento no safari mobile

Question: Na minha aplicação tem um siples javascript para incrementar um campo, o problema que no safari fica ultra lerdo quase não funciona, enquanto no chrome funciona perfeitamente.Existe algo a se fazer para rodar normal no safari?
js:
$("#aumentaDesconto").click(function () {
var input = $("#txtDesconto")[0];
var desconto = parseInt(input.value, 10) + 1;
input.value = desconto;

});

Comment: Poste também a função `calcularValor`.
Comment: Utilize `console.count('teste')` dentro da função e veja no seu console quantas vezes a função foi chamada. Talvez você deixou este código dentro de um loop e o evento foi vinculado várias vezes.
Comment: Na verdade vou remover ela , pois elan ao tem nada ave com meu problema.
Comment: Está lento pra incrementar os valores no campo.
Comment: Acho difícil a culpa estar nesse código, mas de qualquer maneira tente `var desconto = +input.value + 1;`
Comment: acho que a culpa é do safari mesmo, vi varios relatos de lentesas com safari e javascript, porem preciso do mesmo rodando no safari.Vou testar seu codigo
Answer: A única coisa que vejo poder optimizar aqui é remover o jQuery e fazer isso com JavaScript puro. Ficaria assim:
document.getElementById("aumentaDesconto").addEventListener('click', function () {
    var input = document.getElementById("txtDesconto");
    var desconto = parseInt(input.value, 10) + 1;
    input.value = desconto;
});

Se nõ resolver o problema sugiro que coloques um jsFiddle que reproduza o problema para podermos analizar.
Comment: Fiz dessa forma e o incremento nao funcionou.
Comment: @WarLock tinha deixado um `#` a mais, corrigi agora. Coloca esse script no final do body e testa.
Answer: Da maneira como você fez, o código executa uma busca no seu HTML pelo elemento de id txtDesconto toda vez que #aumentaDesconto é clicado.
Uma maneira de otimizar é fazer o cache dos elementos utilizados repetidamente, pois pesquisar na DOMTree é bastante custoso para o browser.
Tente assim:
var input_desconto = document.getElementById("txtDesconto"),
    aumenta_desconto = document.getElementById("aumentaDesconto");

aumentaDesconto.addEventListener("click", function () {
    input.value = parseInt(input_desconto.value, 10) + 1;
}, false);

Fiz um JSFiddle.
Comment: Tem certeza que é esse script que está deixando lento?
Já tentou tirar ele e ver como a página se comporta sem o script?
Comment: Continua lento, testei no ipad e iphone, safari realmente nao rola...

Javascript muito lento no safari mobile


Como incluir uma variável PHP dentro de um texto salvo no MySQl

Question: estou tentando inserir variáveis PHP dentro de um texto que é salvo no meu MySql, de forma que sejam lidos automaticamente na minha aplicação.
Primeiramente, vou explicar qual é minha realidade:
Página de impressão:
<?php
//PRIMEIRO, FAÇA A BUSCA POR ALGUNS VALORES DO BD.
//EXEMPLO: $variavel1, $variavel2, etc...
?>

//TEXTO PADRÃO EM HTML (para impressão):
// PERCEBAM QUE INCLUO AS VARIAVEIS PHP DENTRO DO TEXTO
Número do contrato: <?php echo $variavel1;?>

Nome: <?php echo $variavel2;?>

Endereço: <?php echo $variavel3;?>
//AQUI VAI O RESTANTE DO TEXTO DO CONTRATO ....

Ao invés de manter esse texto estático, de forma que eu só altero o valor das variaveis, gostaria de registrá-lo tambem no bd, de forma que fique mais facil para eu altera-lo. Ficando da seguinte forma:
//TEXTO SALVO NO BD:
Número do contrato: {contrato}
Nome: {nome}
etc...

DAI, quando eu for executar a aplicação, ele já carregue os dados automaticamente.
Desta maneira, eu conseguiria tanto alterar o texto, como também as variaveis de lugar. É possível?
Answer: Isso é um template.
Basta apenas substituir as "tags" pelas variáveis.
Exemplo:
$texto_db = 'Número do contrato: {contrato}
Nome: {nome}
etc...';

echo str_replace(
    array(
        '{contrato}',
        '{nome}'),
    array(
        $variavel1,
        $variavel2),
    $texto_db
);

Comment: Oi Daniel, Entendi! No caso, essa é a forma mais indicada? Não existe alguma outra forma de interpretar automaticamente as variaveis sem precisar fazer a substituição?
Comment: E se eu não tiver o numero exato de variaveis, como posso fazer dessa forma?
Comment: A automação é trabalho do programador. rsrs Essa substituição do exemplo acima é uma forma "automática".
Quanto a quantidade de variáveis, não está descrito na pergunta. Mas não existe mágica. Você deve criar uma pré automação, montar algum padrão que facilite a rotina. O exemplo acima é meramente didático. Não quer dizer que é o melhor e tampouco a única forma de resolver.


Question regarding Sheldon Axler's proof that every operator on a complex vector space has an eigenvalue

Question: For reference, Axler's proof was copied in full in this question.  In the beginning of that proof, Axler chooses the nonzero vector $v$ without loss of generality.  This made me doubt his proof because it is obvious that not all nonzero vectors are necessarily eigenvectors.  So I looked for something that would help me to distinguish $v$ from other arbitrary vectors, and I realized that for it to be true that $(v,Tv,\dots,T^nv)$ is linearly dependent, each $T^i$ for $0<i\leq n$ must be nonzero.  Thus I am left thinking that Axler's proof must show that such a $v$ can definitely be chosen.  Was this step left out of the proof because the existence of such a $v$ trivial in some manner that I am not noticing?  Or is my reasoning about the proof incorrect?
Comment: If $T^i = 0$, then the vectors $T^i v,\, T^{i+1}v,\,\dotsc,\, T^n v$ are all $0$, then the system is surely linearly dependent too.
Comment: If those are all zero, then the set of $T^jv$ for $0\leq j<i$ might be linearly independent, right? Then adding in those zero vectors shouldn't make it linearly dependent.
Comment: **Every** set of vectors containing a zero is linearly dependent. You then have the nontrivial relation $\vec{0} = 0\cdot v_1 + \dotsc + 0\cdot v_j + 1\cdot \vec{0} + 0\cdot v_{j+2} + \dotsc + 0\cdot v_k$.
Answer: Well, the proof doesn't claim that $v$ is an eigenvector, so there's no problem if it isn't.
The vectors $(v,Tv,\dots,T^nv)$ are linearly dependent regardless of the values of $v$ and $T$. It doesn't matter whether $v$ is nonzero. It doesn't matter whether $T^i$ is nonzero. It doesn't even matter that $T$ is a linear operator. Any set of $n+1$ vectors is linearly dependent.
Comment: But, according to the author's proof, does that mean every Vector $v$ in $V$ is then an Eigen Vector?
Comment: @MathMan I don't think so, but you're welcome to ask this as a separate question!
Answer: I believe the point of confusion is the assumption
$$0=c(T-\lambda_1 I)\cdots (T- \lambda_m I)v$$
means $(T-\lambda_k I)v = 0$ for some $v$. Given this assumption, it would indeed seem to be the case that $v$ must be an eigenvector for the eigenvalue $\lambda_k$.
However, recall the way multiplication of operators is defined here: The multiplication of the operators $T * T = T^2$ means $(TT)v = T(Tv)$, not $(TT)v = (Tv)(Tv)$, as we can't multiply two vectors in a vector space, only a vector with a scalar. Function multiplication is defined as function composition.
That being said, the main equation is saying we plug $v$ into the operator $T-\lambda_m I$, then take the output and plug it into $T-\lambda_{m-1}I$, etc. until we finally plug the output into $T - \lambda_1 I$ and get $0$. Since we start with a nonzero input and get a zero output, there is some $\lambda_k$ such that $T - \lambda_k I$ takes in a nonzero input and produces a zero output, hence $T - \lambda_k I$ is not invertible and $\lambda_k$ is an eigenvalue.
We cannot definitively conclude anything about the starting vector $v$, since it may "disappear" after the first plugin into $T- \lambda_m I$. For example, say $(T-\lambda_m I)v$ is equal to an eigenvector for the eigenvalue $\lambda_{m-1}$, then when we plug in this eigenvector into the next operator $T - \lambda_{m-1} I$, we get $0$. Note that we can't conclude $v$ is an eigenvector.
Comment: I just want to say that this is a fantastic answer that helped me immensely. Thanks!


Finding linear and angular speeds

Question: (b) A wheel of radius 5 in. is rotating 45°/sec. What is the linear speed v, the angular speed in RPM and the angular speed in rad/sec?
So for this one I thought the linear speed (v)= 5(pi/2) because it is asking for rad/sec so 45 degrees in pi/2. But it is wrong..
(c) You are standing on the equator of the earth (radius 3960 miles). What is your linear (mph) and angular speed (rad/hr)?
So I dont know how to even get the answer. I know the equation v (linear speed) = w(omega) *radius is important, but I dont know how to apply it.
Answer: $45^\circ/sec=\frac{\pi}{4} rad/sec$
So, angular speed $\omega=\frac{\pi}{4}$ rad/sec=$15\pi$ rad/min = $7.5$ RPM (since $2\pi =$ one revolution)
linear speed = $\omega * r = \frac{\pi}{4}(5)$ in/sec
you should be able to do part (c) now.

Finding linear and angular speeds


Plot for unbiasedness

Question: I was reading a paper and the authors describe a plot which they used to determine whether their estimator was unbiased. This plot is described as follows (verbatim):

To assess if the probabilities of taxonomic placement were unbiased, we ordered the classification probabilities from lowest to highest, and computed a cumulative sum of both these probabilities as well as the indicator variables describing whether the outcome predicted with highest probability was a correct one. We then plotted these two cumulative sums against each other. If the classification probabilities are unbiased, such a plot should follow the identity line.

Is there a specific name for this type of plot? Is there a reference which describes the theory justifying this plot?
Source:
Somervuo, P., et al. "Quantifying uncertainty of taxonomic placement in DNA barcoding and metabarcoding." Methods in Ecology and Evolution (2017): 398-407.
Answer: This sounds like a qq-plot to me.  It's most typically used to compare the distributions of two samples (e.g., groups), or to compare a sample to a theoretical distribution (e.g., the normal).  (It may help you to read my answer to: PP-plots vs. QQ-plots.)  I gather they have ordered categorical distributions, and they are plotting the ECDFs (empirical cumulative distribution function) against each other.  If I'm not misunderstanding, what they did seems pretty reasonable to me, although using an agreement chart might be better.

Plot for unbiasedness


Reverse a list of list in F#

Question: I want to reverse a function called revLists that takes a list of lists and reverses all the sub-lists.
Any suggestion will help.
This is my idea:
let revLists[[]] = List.map (fun [[]] -> List.rev);;
revLists[[1;2;3],[4;5]];;

Answer: let lists = [[1;2;3];[4;5]]
let reverseLists list = list |> List.map List.rev

> reverseLists lists;;
val it : int list list = [[3; 2; 1]; [5; 4]]

Comment: yes but stackoverflow doesn't let me, it says that I have asked 6 questions already in the past month and have not been well received by the community @Foole
Comment: thanks, what the |> for, return statement like ->? @Foole
Comment: @MarkDwayne That is the forward pipe operator.  See: http://www.kevinberridge.com/2012/12/neat-f-pipe-forward.html
Comment: thanks again if I want to interleave 2 lists, is there a way that I can accomplish that without using list.zip?                                                                   > interleave ([1;2;3],[4;5;6]);; should produce [1;4;2;5;3;6] @Foole
Comment: I have this but it is giving errors:                                                                           let interleave a b = List.filter List.head a List.head b a b;;                                   These are preparation f# questions for tests, thanks. @Foole
Comment: @MarkDwayne You should post this as a new question
Comment: @MarkDwayne It is really not good. But you can get help in the [F# chat room on SO](http://chat.stackoverflow.com/rooms/51909/f) and I strongly recommend joining to the [F# Slack](http://fsharp.org/guides/slack/)

Reverse a list of list in F#


WebSocket data cannot be converted to array from the buffer

Question: I simply send an array from client to server. When I try to log this array from the client-side it gives me random values in the array.
Client-Side Code

let ws = new WebSocket("ws://localhost:4000");
ws.send([1,2,3]);

Server-Side Code

wss.on("connection", (ws) => {
  ws.on("message", m => {
    //I searched a little and learnt a way to convert buffer to array with a simple ES6 feature but it doesn't work properly
    console.log([...m]);
  });
});

The output is: [ 49, 44, 50, 44, 51 ]
Please post how can I fix it, and explain the reason for it so I and other people can understand the logic behind it.
Answer: try parsing the buffer into a javascript object using JSON.parse(m)is not required.
Please note that if the message is not a JSON string, this will throw an error.
Answer: I still don't know why it happens but know I got a workaround for this problem. I'm simply converting the array to a string on the client-side and reconverting it to an array on the server side.
Client-Side

ws.send([1,2,3].toString());

Server Side

arr = []

wss.on("connection", (ws) => {
    ws.on("message", m => {
        arr = m.toString().split(",");
        arr = arr.map(x => {
            return parseInt(x);
        });
        console.log(arr);
    });
});


Second leg home advantage

Question: In football during two-legged ties there exists a phenomenon called "second leg home advantage". Many managers, players and commentators believe that if the second match of a tie is played on one team's field then they have slightly better chances to win the tie.
UEFA also believes in this phenomenon, because e.g in the round of 16 of the Champions League the teams winning their group stages are playing their second game against group runners-up at home, so that group winners have more chances to win the tie.
So, the question is, does the second leg home advantage phenomenon exist and is it statistically justified?
Answer: This question has been addressed in the paper by Lionel Page and Katie Page (2007) 'The second leg home advantage: Evidence from European football cup competitions', Journal of Sports Sciences, 25: 14, 1547 — 1556.
The researchers statistically analyzed 12,364 individual matches from the following competitions:

UEFA Champions League (1955 - 2006)
UEFA Cup (previously InterCities Fairs Cup, now Europa League, 1955 - 2006)
Cup Winners Cup (1955 - 1971)

In order to reduce the effects of the UEFA seeding system allocating the "better" teams as the second leg home team, the UEFA club coefficients were taken into account in calculations of the probability of the second leg home team winning the tie. The results were as follows:
<code>-----------------------------------------------------------------
| Tie-breaker | Prob. of SLHT* winning the tie | Number of ties |
-----------------------------------------------------------------
|    None     |             53.77%             |      5750      |
-----------------------------------------------------------------
| Extra time  |             66.42%             |      186       |
-----------------------------------------------------------------
|  Penalties  |             57.33%             |      148       |
-----------------------------------------------------------------
|   Overall   |             54.33%             |      6084      |
-----------------------------------------------------------------

*SLHT - Second leg home team
</code>
The probabilities above show us that SLHTs have slightly better chances for winning the tie, but the following chart illustrates how these probabilities (considering only the ties without tie-breakers) decreased over time since the beginning of the aforementioned competitions.
Source
What this paper shows us is that there is a very small second leg home advantage in the ties decided without tie-breakers and a significant advantage in the ties where tie-breakers were used.

There was also another research by Manuel J.A. Eugster, Jan Gertheiss & Sebastian Kaiser (2010) LMU Munich 'Having the Second Leg At Home – Advantage in the UEFA Champions League Knockout Phase?', where they analyzed only 304 individual matches from the UEFA Champions League (1994 - 2010) also using UEFA club coefficients for removing seeding system disturbance and they concluded that:

There is no statistical evidence for the
common belief that the chance of winning is higher if a team is
playing away in the first leg and having the second leg at home.

Moreover, they have proposed:

to change UEFA regulations in the sense that in the round of 16 group
winners do not automatically play at home in the second leg, but may
choose depending on their individual preferences.

But, why people do believe in this phenomenon despite poor statistical evidences?
Well, perhaps, because when the tied teams are equal they choose "defend away, win at home" strategy, and mainly because of the away goals rule. Probably, the general reasoning, as Patrick Kluivert stated, is that:

Sometimes people make mistakes and it is better to make your mistakes
in the first leg away from home because there is still time to put
things right in the second match.
Answer: One potential advantage is that they know that if they can get one or more away goals and keep the score level or only down by one they can advance either with a scoreless draw and park the bus or by only scoring one goal and then parking the bus. Another advantage would be that if the tie went to extra time the 3o minutes of extra time would be played at their ground, and therefore they would have an extra 30 minutes at home.
Answer: I crunched the numbers on Word Cup intercontinental playoffs. The team that plays the 2nd leg at home has won 61% of the time as per bitedge.com.
I think it's because in the 2nd leg you know exactly what result you need and you have a greater chance of determining the result at home than you would away.
Comment: 16 (7 vs 9) samples with such a high entropy are never enough for almost any statistical study. It was a nice thing to know, but I am afraid it doesn't qualify as an answer for the original question.

Second leg home advantage


Adicionar valor do produto

Question: Eu tenho um painel simples de venda de alguns produtos :

e eu gostaria que quando eu escolhesse qualquer um dos produtos ali do combobox, o valor do produto mudasse para o valor do produto que eu escolhi sera que tem algum modo de fazer isso em javascript ou de outro modo? , minha tabela :

Meu código :
 <!DOCTYPE html>

    <title></title>

<link rel="stylesheet" type="text/css" href="css/bootstrap.css">
<link rel="stylesheet" type="text/css" href="css/estilo.css">
<link  type="text/javascript" href="jquery.js">
<link type="text/javascript" href="post.js">
<link  type="text/javascript" href="jquery-form.js">

<form action="" method="post" enctype="multipart/form-data">
    <fieldset>
        <?php
        include ('banco.php');
        ini_set('default_charset','UTF-8');

        if($_GET){
            $id = $_GET['id_venda'];
        }

        if(isset($_POST['send'])){

            $produtos = $_POST['produtos'];
            $id_venda = $_POST['id_venda'];
            $quantidade = $_POST['quantidade'];
            $valor = $_POST['valor'];
            $valortotal = $_POST['valortotal'];

            mysql_query("INSERT INTO pedido(id, produtos, id_venda, quantidade, valor, valortotal )
            values(
                NULL,

                '{$produtos}',
                '{$id_venda}',
                '{$quantidade}',
                '{$valor}',
                '{$valortotal}'
                              );
            ");

            header("location:cabecalho.php?&id={$id} ");

        }

        ?>
        <legend style="color: #ffffff" class="btn btn-inverse">Vendas </legend>
    <?php
        ini_set('default_charset','UTF-8');
        mysql_connect('127.0.0.1','root','');
        mysql_select_db('mecanica');
        $query='Select * from produtos';
    ?>

    Produto :
     <select name="produtos"   style="width: 400px">
       <?php
       //execução da query
        $resultado=mysql_query($query);
         while($linha=mysql_fetch_array($resultado))
            {

                echo '<option  value="' . $linha['id_produto'] . '">' . $linha['produtos'] . '</option>';
            }
            echo '</select>';
        ?>
        </select>

        Quantidade :
        <input style="width: 85px" type="number"  name="quantidade" value="1">

    <?php
        ini_set('default_charset','UTF-8');
        mysql_connect('127.0.0.1','root','');
        mysql_select_db('mecanica');
        $query='Select * from produtos';
    ?>
        Valor :
        <select name="produtos"   style="width: 100px">
        <?php
        //execução da query
        $resultado=mysql_query($query);
        while($linha=mysql_fetch_array($resultado))
        {

            echo '<option  value="' . $linha['id_produto'] . '">' . $linha['valor'] . '</option>';
        }
        echo '</select>';
        ?>
    </select>

            Valor Total:
            <input style="width: 85px" type="text"  name="valortotal" readonly="true"  >

    <?php
        ini_set('default_charset','UTF-8');
        mysql_connect('127.0.0.1','root','');
        mysql_select_db('mecanica');
        $query='Select * from pedido';
        ?>

        ID VENDA :
        <select name="id_venda" style="width: 75px">
    <?php
           $resultado=mysql_query($query);
            while($linha=mysql_fetch_array($resultado))
            {

            }
            echo '<option >' . $_GET['id_venda'] . '</option>';
            echo '</select>';
    ?>
        </select>

        <input type="submit" class="btn btn-inverse" value="Enviar" name="send">
        Cancelar
    </fieldset>
</form>

Comment: Recomendo ler essa pergunta: [Por que não devemos usar funções do tipo mysql_*?](http://pt.stackoverflow.com/questions/579/por-que-n%C3%A3o-devemos-usar-fun%C3%A7%C3%B5es-do-tipo-mysql). Se você atualizar seu código, provavelmente terá mais colaboração do pessoal do SOpt. Outra recomendação que te dou, é procure separar a a conexão com o banco da sua HTML.
Comment: Não está claro como será inserido o novo valor.
Comment: Eu gostaria de que quando eu escolhesse um dos produtos la na lista o campo do valor atualize para o valor correto do produto.
Comment: Só uma pergunta, você ta familiarizado com Jquery?
Comment: Ja fiz algumas coisinhas com jquery mas so bem leigo
Answer: Uma forma simples de resolver isso é através do evento change, passando o valor do formulário para o outro campo:
Com jQuery:
    /* "campo_valor" é a id do input
       e "combo" é a classe do elemento select
    */
  $(function() {
    $('select.combo').on('change',function(){
        $( "select.combo option:selected" ).each(function() {
           $('#campo_valor').val($(this).val());
        });
    });
  });

Com Javascript puro:
function jumpValue(obj) {
     document.formulario.valor.value = obj.options[obj.selectedIndex].value;
}

Nestos dois exemplos acima, irão funcionar no exemplo de HTML abaixo.
Para o jQuery, basta remover o método jumpValue(this) do onchange da HTML e incluir a biblioteca do jQuery:
<form name="formulario">
   Opção:
    <select class="combo" name="selecao" onchange="jumpValue(this)">
      <option value="valor 1">valor 1</option>
      <option value="valor 2">valor 2</option>
    </select>
    Valor:
       <input type="text" id="campo_valor" name="valor">
</form>

Answer: Conseguir resolve usando o seguinte script :

teste.php :
<?php
include('banco.php');

$id = $_POST['idVar'];
$sqlVar = mysql_query("SELECT * FROM produtos WHERE id_produto='$id'");
$val = mysql_fetch_object($sqlVar);
$dados = $val -> valor;
echo $dados;

?>

e no select :
onchange="prodValor(this.value)"

Obg a todos pela ajuda ;)

Adicionar valor do produto


FindSimilar items in a complex dataset

Question: I'm a Machine Learning newbie, but I want to learn more about this interesting topic using a practical example, on which I would appreciate any theoretical and practical help:
I have a database of "recipes" (~100,000). Each recipe is represented by an object of the following format:
<code>{
  "id": "XXX-000-123",
  "origin": "asia",
  "spicyness": 2,
  "mainIngredient": "rice",
  "ingredients":
  [
    {
      "name": "chicken",
      "amount": 300,
      "unit": "g"
    },
    {
      "name": "garlic",
      "amount": 10,
      "unit": "g"
    },
    {
      "name": "coconut-milk",
      "amount": 0.3,
      "unit": "l"
    }
  ]
}
</code>
The number of ingredients can range from 1 ... 20
Now, I want to create an algorithm which takes an object like this as an input and returns a list of similar recipes from my database.
My questions now are:
Is this scenario suitable for a ML approach?
Could you point me to any existing algorithms to have a closer look at?
Any suggestions for a practical implementation of the given scenario?
Answer:
Is this scenario suitable for a ML approach?

Your problem seems to be closer to Information Retrieval than machine learning.

Could you point me to any existing algorithms to have a closer look at? Any suggestions for a practical implementation of the given scenario?

Search engines, the data structure you are looking for is called inverted index. There are many standard libraries for Information Retrieval, ranging from lower-level stuff like Python's Whoosh to full-blown search engine frameworks like Elasticsearch or Solr.
Note that most Information Retrieval system implementations are based on Bag of Words model, so they mostly cover exact matches, and do not take semantics into account (for example they wouldn't know that 'yolks' and 'eggs' are similar ingredients). If you'd like to model semantics, then you'd need to do some sort of semantic search, which is much harder problem than standard IR (if you want to know more, read some reviews on neural networks in IR).

FindSimilar items in a complex dataset


Using getTag and setTag to hold ListItem Values

Question: I am learning about getTag and setTag. I need explanation about these methods and want to know how they work.
I have made a simple CustomListView having two buttons and one textview.
Buttons are add and subtract which increment or decrements the value of counter but the problem is that only the last item value is changing. Please give me a solution as well as a good explanation
Thanks .
@Override
    public View getView(int position, View convertView, ViewGroup parent) {

        if (convertView == null) {
            convertView = inflater.inflate(R.layout.list_items, null);
            add = (Button) convertView.findViewById(R.id.add);
            sub = (Button) convertView.findViewById(R.id.sub);
            textView = (TextView) convertView.findViewById(R.id.numberTV);
            convertView.setTag(new ViewHolder(add, sub, textView , count));
        }
        holder = (ViewHolder) convertView.getTag();
        textView = holder.textView;
        count = holder.counter;
        add = holder.add;
        sub = holder.sub;
        add.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                count +=1;
                textView.setText(String.valueOf(count));
            }
        });
        sub.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                count -=1;
                textView.setText(String.valueOf(count));
            }
        });
        return convertView;
    }
}

class ViewHolder {

    Button add, sub;
    TextView textView;
int counter = 0;
    public ViewHolder(Button add, Button sub, TextView textView , int counter) {
        this.add = add;
        this.sub = sub;
        this.counter = counter;
        this.textView = textView;
    }
}

Answer: In your custom listview adapter what you are trying to implement is recycling of the single item (list_items) showed in the Listview. and because of which you require to use the getTag and setTag methods to that View.
So why do you require these method in the first place...

You are trying to recycle the list_items and view's inside it, to do that you are making the ViewHolder which will hold the inner references of views inside the list_items.
You don't want to call inflater and referencing on Views every-time getView is called so you save the ViewHolder's instance to the View, which will be used again without re-inflating the list_items and references inside it.
By setTag() you can attach as Object to the View
By getTag() you can get back the Object attached to the View

So this way you are recycling the same initialization of your list_items every time getView() is called
Seems like a lot of work, Use RecyclerView.
your solution for the code... you may check the code on gitHub
public class ListViewTestFiveActivity extends AppCompatActivity{

    private ListView listView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_list_view_test_five);

        initializeUI();
    }

    private void initializeUI() {
        listView = (ListView)findViewById(R.id.ListViewTestFiveActivity_listView);
        ArrayList<Item> items = new ArrayList<>();

        for (int i = 0; i < 15; i++) {
            Item item = new Item();
            item.setCount(i);
            items.add(item);
        }

        MyAdapter adapter = new MyAdapter(getApplicationContext(), R.layout.single_item_listview_five, items);
        listView.setAdapter(adapter);
    }

    private class MyAdapter extends ArrayAdapter{

        private ArrayList<Item> items;
        private Context a_context;
        private LayoutInflater a_layoutInflater;

        public MyAdapter(Context context, int resource, ArrayList<Item> items) {
            super(context, resource, items);
            this.a_context = context;
            this.items = items;
            a_layoutInflater = LayoutInflater.from(this.a_context);
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            View row = convertView;
            ViewHolder holder = null;
            if (row == null) {
                row = a_layoutInflater.inflate(R.layout.single_item_listview_five, parent, false);
                holder = new ViewHolder();
                holder.plus = (Button) row.findViewById(R.id.ListViewTestFiveActivity_plus_button);
                holder.textView = (TextView) row.findViewById(R.id.ListViewTestFiveActivity_count_textView4);
                holder.minus = (Button) row.findViewById(R.id.ListViewTestFiveActivity_minus_button);
                row.setTag(holder);
            } else {
                holder = (ViewHolder) row.getTag();
            }

            final Item item = items.get(position);
            holder.textView.setText("" + item.getCount());
            holder.plus.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    int increase_count =item.getCount();
                    item.setCount(++increase_count);
                    notifyDataSetChanged();
                }
            });
            holder.minus.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    int decrease_count =item.getCount();
                    item.setCount(--decrease_count );
                    notifyDataSetChanged();
                }
            });
            return row;
        }

        private class ViewHolder{
            Button plus;
            TextView textView;
            TextView minus;
        }
    }

    private class Item {
        int count;

        public int getCount() {
            return count;
        }

        public void setCount(int count) {
            this.count = count;
        }
    }
}

Output


application with zebra jar failed to build on non zebra device with INSTALL_FAILED_NO_MATCHING_ABIS

Question: I have developed an application that runs on a zebra TC70.
The main reason for this is that this device has a built-in 2D barcode scanner.
Now I want to also publish the same app in the app store without the zebra requirement. I have built in a check that checks if the device is a zebra device or not (as described here by Zebra)
Now when I build this app on a doogee s60, this works without a problem.
The app uses the camera instead of the barcode scanner.
When I want to install in on my Sony Xperia XZ Premiumn, I get the following error in android studio

Now I am not really familiar with "ABIS" in android.
I tried some googeling and this gave me hints to split APKs per CPU model but I don't get that working.
The end goal is that I can get this app working on "every" android device without having to copy all my code into a second project without the zebra jar.
Android manifest

Min SDK: 16
Target SDK: 19
Zebra device I have run Android 4.4 or android 5.1
uses-permission android:name="com.symbol.emdk.permission.EMDK"

build.grade (app)

provided fileTree(include: ['com.symbol.emdk.jar'], dir: 'libs') // this needs to be provided as else the app won't build

End status:

TC70: app is working with the built-in scanner
Doogee S60: app is working with the camera
Sony Xperia XZ Premium: app fails to build with error.
Comment: I'm not positive, but I believe the 'ABIS' refers to the binary interface.  When you run native code on a processor/platform it has to adhere to the binary interface spec.  Do a search/verification on what I'm asserting here - it might be as simple as adding an additional library (maybe in the form of a static library, etc.) but you'll need to reach out to the Xperia community no doubt.
Comment: https://stackoverflow.com/questions/28100291/how-to-target-different-android-architectures
Answer: I finally found the answer.
Apparently it was just one specific library.
I replaced:
compile 'org.apache.directory.studio:org.apache.commons.io:2.4'

by:
compile group: 'commons-io', name: 'commons-io', version: '2.5'

and this fixed my issue. It was not related to the zebra library.
Also: implementation group: 'commons-io', name: 'commons-io', version: '2.5' //Works.
Thanks to "sweisgerber.dev" in this post INSTALL_FAILED_NO_MATCHING_ABIS error on Android 8 as it fixed the issue


configuring axis in core plot

Question: Here is the screenshot of graph...
In this graph the minimum value of y-axis is 0(at origin) and the maximum value is 700.
I want to set the mininmum value to 500 and maximum value to 700.

how it can be achieved??
Any help would be appreciated.
Answer: Try using this if you are using core plot
<code> CPXYPlotSpace *plotSpace = (CPXYPlotSpace *)graph.defaultPlotSpace;
 plotSpace.yRange = [CPPlotRange plotRangeWithLocation: 500 length:200   ];
</code>
Answer: There are 2 steps to be done,
<code>1. Setting the orthogonalCoordinateDecimal, this is the point where your graph starts

   CPTXYAxis *y = axisSet.yAxis;
   y.orthogonalCoordinateDecimal = CPTDecimalFromFloat(500.0);

2. Setting the plotRange, this is to determine where should the graph start and its range

   CPTXYPlotSpace *plotSpace = (CPTXYPlotSpace *)graph.defaultPlotSpace;
   plotSpace.yRange = [CPTPlotRange plotRangeWithLocation:500 length:200];
</code>
Comment: in this example, it should be x.orthogonalCoordinateDecimal you are changing, not y.
Comment: i am trying to set the origin of y-axis to 500,but through your method distance between the two ticks gets broader and by orthogonalCoordinateDecimal we can change the position of y-axis intersecting x-axis.
Comment: what is your x.orthogonalCoordinateDecimal ?
Comment: You need to set the  y.majorIntervalLength also
Comment: it is 0 for x.orthogonalCoordinateDecimal
Comment: this helped out a whole lot! and noRema's comment on changing x to y did the trick!

configuring axis in core plot


About $n! > (\frac{n}{e})^n$ in "Introduction to Algorithms 3rd Edition" by CLRS.

Question: I am reading "Introduction to Algorithms 3rd Edition" by CLRS.
In Apendix C, the authors use the following inequality:
$n! > (\frac{n}{e})^n$.
My proof of this fact is the following:

base case:
$1! = 1 > \frac{1}{e} = (\frac{1}{e})^1$.
induction step:
  Assume that $k! > (\frac{k}{e})^k$.
  Then, $(k+1)! = (k+1) k! \geq (k+1)(\frac{k}{e})^k$.
  By the way, $((1+\frac{1}{k})^k)_{k \in \{1,2, \cdots\}}$ is a monotonic increasing sequence which converges to $e$.
  So, $e > (1+\frac{1}{k})^k$.
  So, $1 > \frac{(1+\frac{1}{k})^k}{e}$.
  So, $k^k > \frac{(k+1)^k}{e}$.
  So, $\frac{(k+1)k^k}{e^k} > \frac{(k+1)^{k+1}}{e^{k+1}}$.
  So, $(k+1)! \geq (k+1)(\frac{k}{e})^k > \frac{(k+1)^{k+1}}{e^{k+1}}$.

On the other hand, obviously, $n^n \geq n!$.
So, $(\frac{n}{1})^n \geq n! > (\frac{n}{e})^n$.
$1 \in\{c | c > 0, n! \in O((\frac{n}{c})^n)\}$.
$e \notin\{c | c > 0, n! \in O((\frac{n}{c})^n)\}$.
My question is here:
What is the value $\sup \{c | c > 0, n! \in O((\frac{n}{c})^n)\}$?
Answer: From Stirling's approximation we have $n!\sim\sqrt{2\pi n}\left(\frac{n}e\right)^n$, so consider
$$\lim_{n\to\infty}\frac{n!}{\left(\frac{n}c\right)^n}=\lim_{n\to\infty}\frac{\sqrt{2\pi n}\left(\frac{n}e\right)^n}{\left(\frac{n}c\right)^n}=\lim_{n\to\infty}\sqrt{2\pi n}\left(\frac{c}e\right)^n\;;$$
this is clearly infinite if $c\ge e$ and $0$ if $0\le c<e$. Thus, $$\sup\left\{c>0:n!\in O\left(\left(\frac{n}c\right)^n\right)\right\}=e\;$$
Comment: Brian M. Scott, Thank you very much for your answer.
Comment: @tchappyha: You're very welcome.


Construction of a sequence of Random Variable with certain distribution

Question: So in my lecture notes I often encounter the statement: " There exist a prob. space on which are defined a sequence of independent RV's $(Y_n)_n$ with distrbution xy". Since this statement is used that often I am beginning to wonder if there is a specific standard technique to achieve this. I know this is true for normally distibuted RVs using the Rademacher functions. Is this also true for the Poisson distribution? Or even for any distribution?
Answer: A general result is the Kolmogorov extension theorem. Essentially, you just need to specify finite-dimensional distributions in a way that doesn't contradict itself (these are the consistency conditions). The extension theorem then tells you that there exists a probability space and a random variable on this space that has the corresponding joint distribution.
In the special case of a countable amount of independent random variables, there is a simpler argumentation. The corresponding construction is that of the product measure.
Comment: Oh yes haven't thought about Kolmogorov!
Can you go into a bit more detail concerning the product measure? How would I use it to construct these?
Comment: Suppose you have a countable set of probability spaces $(\mathbb{R}, \mathcal{B}(\mathbb{R}), P_i)$ and the corresponding product space $(\mathbb{R}^\mathbb{N}, \mathcal{B}(\mathbb{R}^\mathbb{N}), P)$. Let $X_i$ be the map, that maps the $i$-th coordinate from the product measure to the real line (i.e. $X_2: (x_1, x_2, x_3, \ldots) \mapsto x_2$ etc.). Then $X_i$ is a countable collection of independent random variables, where $X_i$ has distribution $P_i$.


Por que costumam dizer que o uso de variáveis globais é uma má prática?

Question: Vou direto ao assunto. Em tutoriais internet a fora, sempre você acha alguém criticando alguma, considerando aquilo como uma "má prática".
Por exemplo, uma delas é a utilização da palavra-chave global.
Até onde pode alcançar meu humilde entendimento, linguagens como Python e PHP (se tiver mais podem citar), aceitam isso.
Por exemplo:
counter = 0;

 def faz_alguma_coisa():

    global counter
    counter = counter + 1

faz_alguma_coisa()
faz_alguma_coisa()

print(counter) # 2

Também é possível fazer isso em PHP.
$variable = 1;

function imitando_python()
{
      global $variable;

      $variable += 1;
}

imitando_python();

var_dump($variable); // 2

Por esse código eu consigo perceber que pode ter um problema com o escopo da variável.
Mas falar que algo é má prática simplesmente porque uma coisa ruim não é muito da minha praia.
Então, gostaria de saber:

Por que usar global (variáveis globais) seria uma má prática?
Existe algum caso onde o uso de global seria essencial, ou há outras práticas melhores?
Comment: Duplicada!!!!!!!
http://pt.stackoverflow.com/questions/925/por-que-usar-vari%C3%A1veis-globais-n%C3%A3o-%C3%A9-uma-boa-pr%C3%A1tica
Comment: Tudo tem uma forma de ser para cada tipo de paradigma utilizado , acredito que há vantagens e desvantagens para cada tipo de linguagem. Utilizar linguagens mais fortemente tipadas por exemplo garante que não haja tantos erros.
Answer: Como isso abrange varias linguagens vou responder com um exemplo simples em JS:
i = null;
function contador1(){
    for(i = 0; i < 60; i++){
        if((i%5) == 0){
            contador2();
        }
    }
}

function contador2(){
    for(i = 0; i < 60; i++){
        console.log(i);
    }
}

Note que este loop não vai funcionar devidamente, pois i é global e o contador2 vai sobrescrever a mesma variável do contador1.
Seria melhor ter uma variável local ou encapsular para assim não ter conflitos.


Set permissions on ApplicationPoolIdentity for adding performance counters?

Question: Hi,
I have a WCF(TCP/IIS7) application that needs to add performance counters on startup, this is a bit of my code for that :
category = PerformanceCounterCategory.Create("Orbit5Service", "MyApp Application Service Counters", PerformanceCounterCategoryType.SingleInstance, col);

The problem is that this will throw an "Requested registry access is not allowed." excetpion. I really need to add this performance counters on startup so how do I grant the ApplicationPoolIdentity the rights to do that?
Answer: You need to add iis apppool\PoolName to group "Performance Monitor Users"
Select the Computer Location:

And type iis apppool\PoolName

Or with command line:
net localgroup "Performance Monitor Users" "iis apppool\PoolName" /add

Answer: I hade to change the account that runes the AppPool to a account that do have admin rights.
Answer: Add AppPool to a group "Performance Log Users".
Alternatively add AppPool to Access Control List of the registry key HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Perflib, set that the AppPool has Full Control ACL. See https://support.microsoft.com/en-us/kb/555129


How to ignore specific echo when returning data to AJAX request

Question: I want to get information from database using ajax call, and then get this information back to the ajax function with the data as JSON.
(I do this to change content in a specified time interval).
So in the PHP file I use "echo" with "json_encode" to return the SQL query data.
But there is also an echo from the dbconfig.php file, which is the file used to connect to the database. (It has  echo "Connected Successfully"; in case the connection was successful)
Comment: Or don't echo at all in the `dbconfig.php`?
Comment: why can't you just only echo when the connection fails? Also since you are using `json`, you can easily send a failed `json` response when the connection fails
Comment: So you're suggesting not to echo at all when connection is successful?(only in case of failed connection)
Actually I'm a beginner and I probably copy the connection code from certain websites so I was sure it's not a bad thing to echo, but seems it does cause problems.

But is my general idea for sending data back OK?
i.e: AJAX call to PHP file > Getting data using SQL query > json_encode back to the AJAX function?

Thanks
Comment: If the response is expecting JSON, only return valid JSON.  If you have error messages, those could be put in a JSON response as well, in addition to setting the proper response code.
Answer: The simplest method would obviously be to edit dbconfig.php to remove the echo statement. It isn't really useful; it's just included in tutorials/examples so you can see that something's happening.
If (for whatever reason) you're restricted from changing that file, you can include it in an output buffer to prevent that status message from being output with your JSON.
ob_start();
include 'dbconfig.php';
$connectionStatus = ob_get_clean();

// do your other stuff

Comment: Thank you,
And may I ask something related to my original question:
Is the general idea of dynamically changing content correct?
as in my code: First make an AJAX call to a PHP script which gets data. From that PHP file echo back the data, and in the AJAX call upon success, you trigger a function that changes the content? Or you would do something else?
For example I want to change a div content to show different news headlines every 1 minute, and the headlines are stored in a "news" table in the database
Comment: That sounds like a pretty standard approach. Although you might want to load a set of headlines instead of just one and cycle through them for a bit before loading another set, to reduce the number of requests. As far as your general idea, though, it sounds fine.
Comment: Actually I tried with the single request with many interval and the web really slowed down. Your idea is obviously the correct! So I really only need to load once and loop through a regular JS / Jquery function instead :)! genius you are


Determinar o maior numero de uma coluna e exibir o nome em uma tabela do banco mysql?

Question: Tenho uma tabela funcionario que utiliza varias redes de uma empresa. Preciso determinar qual a rede que o funcionario passou mais tempo logado dentro e 90 dias apartir de hoje.
+------+----------+------------+
| id   | matricula| rede       |
+------+----------+------------+
|    1 |   333    |        MAN |
|    2 |   333    |        MAN |
|    3 |   111    |       Test |
|    4 |   333    |        MAN |
|    5 |   111    |       Test |
|    6 |   333    |       Test |
|    7 |   333    |       Test |
+------+----------+------------+

Explicando melhor: Tenho de mostrar apos o select
333 MAN
111 Test

O programador tem de criar um select para determinar qual a rede que mais usou e mostra na saída.
Código
select
    matricula, count(rede) as rede_bb
from
    ids_sti_tab_login
where
    data_inc  BETWEEN DATE_SUB(NOW(), INTERVAL 90 DAY) AND NOW()
GROUP BY matricula

Imagem

Tenho de mostrar o nome da REDE no select !!
Comment: https://dev.mysql.com/doc/refman/8.0/en/group-by-modifiers.html
Comment: Grato pelo ajudar. Falta apenas mostrarr o nome ao fim de select ! De que forma posso exibir o nome da maior rede utilizada ? @Motta ?
Answer: A minha solução:
select
    distinct(matricula), rede_bb, count(*) as quantidade
from
    ids_sti_tab_login
where
    data_inc  BETWEEN DATE_SUB(NOW(), INTERVAL 90 DAY) AND NOW()
group by
    matricula, rede_bb order by quantidade desc;

Imagem:


how can i change new password/confirm password by using services module in drupal

Question: I am using services module to consume users account details.
Enabled user in admin->services->resources.
URL: https://drupal.com/service/user/23
method : post
request body:
{
"current_pass":"xyz"
"email":"email@example.com"
}
I have updated these two values are successfully,
but how can I change new password and confirm password values.
How to take these values in request body and I have tried like this(new_pass) but failed to update.
Please help me.
Answer: https://drupal.com/servics/user/9
where 9 is User ID
Method : PUT
Pass 'X-CSRF-Token' paramerter with user token value in header.
Example Call :
{"uid":"9","current_pass":"guessusername1","pass":"guessusername1xxx","pass1":"guessusername1xxx"}
Comment: it shows ["Access denied for user anonymous"] error
Comment: for change your password you need already been logged in. You need to get X-CSRF-Token and then you need to call this change password.
Comment: i have already logged in,and taken X-CSRF token and entered in header page and entered current_pass and pass,pass1 and click on PUT ,same error got.{ACCESS DENIED}
Comment: you need to post not put
Comment: if click POST 404 error ,could not find controller
Comment: if i click on PUT,password changed successfully,but getting 500 internal server error,base table or view not found.
Comment: sorry need to PUT not POST. I change recently and got 200 ok
Comment: if i click on PUT 500 error got,but password changed successfully.
Comment: Check your server logs @User, a 500 error will leave a proper error message so you can work out what's going wrong
Comment: yes, there may be different error not for user password change service. I think file permission related.
Comment: i checked in logs,but there is no information
Comment: @VimalGoradiya how can i take body filed value in request format,body is a text area,i have tried "body":"this is a body",but not saved these filed value.
Comment: For body you need to pass like "body":{"und":[{"value":"buy miui with 50% off"}]}


sqlalchemy bind table to multiple engines

Question: I have two different mysql databases with the same schema.
In short I want to use sqlalchemy to read from one database and insert the data into the other one.
Here is my code so far
   Base = declarative_base()
   class Test(Base):
       __tablename__ = 'test'
       ID = Column(Integer,primary_key=True)
       Name = Column(String,nullable=True)
       Updated = Column(Integer)

   sourceEngine  = create_engine(sourceDBString)
   destEngine = create_engine(destDBString)
   Base.metadata.bind = sourceEngine

   SourceSession = sessionmaker()
   SourceSession.bind = sourceEngine
   DestSession = sessionmaker(destEngine)

   source_session = SourceSession()
   destSession = DestSession()
   notupdated = source_session.query(Test).filter_by(Updated=0)

   for row in notupdated:
      row.Updated=1
   destSession.add_all(notupdated)
   destSession.commit()
   source_session.commit()
   destSession.close()
   source_session.close()

The error I'm getting is:
sqlalchemy.exc.InvalidRequestError: Object '<Test at 0x7f7e1a83ce50>' is already attached to session '1' (this is '2')

It seems to be that I can only bind the object Test to one engine at a time, is there any  way I can set both engines to use it?
Answer: You have to call make_transient to transfer an object from one session to another.  You may also want to clear the obj.id column by setting it to None.
This SO question should help you further.
How to use make_transient() to duplicate an SQLAlchemy mapped object?


How can I correct for non-indepence without individual tracking?

Question: I have some data taken at multiple time points from a set of individuals, but without tracking the individuals.
For example, at each of six time points, the heights of all individuals are recorded -- but there is no information on which height came from which individual. (This is similar to the R builtin data-set Loblolly if you ignore the Seed column which tracks individuals.)
I am trying to run a linear regression to analyze growth, and I know that the lack of independence is problematic for over-confidence in estimates of group differences and for adding excessive noise to the model. However, I am not sure how to go about correcting for those impacts.
In the simplest case, there would be just one group in which I am trying to model growth by predicting height by age. In more complicated cases, I will have two or more groups and will want to predict height by the interaction of age and group. The groups generally start as randomized and relatively homogenous, so the main expected difference is in growth rate. (Occasionally, I may need to handle differences in starting groups, but I think that is beyond the scope of this question.)
Yes: the correct answer is that I should track individuals and include them in the model. I am working on that. However, the production environment I am working in does not make that easy, and I don't have a Delorean to go back and get them from past experiments. So, I am forced to  find at least a bit of guidance on correction methods, even if they are just back-of-the-envelope/rule-of-thumb guiding principles to let me know how much salt I should take with the results.
Here is the output from the R Loblolly dataset for those working in other systems that want a starting point (may just be too much time on StackOverflow, but I know it sometimes helps).
 height age Seed
   4.51   3  301
  10.89   5  301
  28.72  10  301
  41.74  15  301
  52.70  20  301
  60.92  25  301
   4.55   3  303
  10.92   5  303
  29.07  10  303
  42.83  15  303
  53.88  20  303
  63.39  25  303
   4.79   3  305
  11.37   5  305
  30.21  10  305
  44.40  15  305
  55.82  20  305
  64.10  25  305
   3.91   3  307
   9.48   5  307
  25.66  10  307
  39.07  15  307
  50.78  20  307
  59.07  25  307
   4.81   3  309
  11.20   5  309
  28.66  10  309
  41.66  15  309
  53.31  20  309
  63.05  25  309
   3.88   3  311
   9.40   5  311
  25.99  10  311
  39.55  15  311
  51.46  20  311
  59.64  25  311
   4.32   3  315
  10.43   5  315
  27.16  10  315
  40.85  15  315
  51.33  20  315
  60.07  25  315
   4.57   3  319
  10.57   5  319
  27.90  10  319
  41.13  15  319
  52.43  20  319
  60.69  25  319
   3.77   3  321
   9.03   5  321
  25.45  10  321
  38.98  15  321
  49.76  20  321
  60.28  25  321
   4.33   3  323
  10.79   5  323
  28.97  10  323
  42.44  15  323
  53.17  20  323
  61.62  25  323
   4.38   3  325
  10.48   5  325
  27.93  10  325
  40.20  15  325
  50.06  20  325
  58.49  25  325
   4.12   3  327
   9.92   5  327
  26.54  10  327
  37.82  15  327
  48.43  20  327
  56.81  25  327
   3.93   3  329
   9.34   5  329
  26.08  10  329
  37.79  15  329
  48.31  20  329
  56.43  25  329
   3.46   3  331
   9.05   5  331
  25.85  10  331
  39.15  15  331
  49.12  20  331
  59.49  25  331

Comment: What variables are in the regression?
Comment: Edited to add model description. Looking to predict height by age (with interaction with group sometimes)
Answer: This is not really an answer, but this is an interesting question.
I had a similar dataset where I did have individual tracking and I was not sure how to adjust the model (ultimately, I ended up sampling one from each individual to eliminate the dependencies, but I wondered whether there was a better way to do it).
With a ggplot2 plot of the Loblolly dataset such that each line corresponds to one seed:

You can see that the coefficient on age for each individual should be similar. Therefore, at least with this dataset, even if you didn't have tracking, you would be able to make a statement about a confidence interval for the coefficient on age. Of course, you only know this for this dataset because you could plot according to individual. Without individual tracking you cannot know, but perhaps domain expertise could inform you here.


What is meant by "Message sorting optimization records" in dovecot index?

Question: Dovecot documentation here "https://doc.dovecot.org/developer_manual/design/indexes/index_file_format/#main-index" says that "Message sorting optimization records" are stored in the in the main index file. I am confused in what exactly is their content.
I read somewhere that they contain highest and lowest UIDs for a sorting criteria. But that didn't makes sense as shouldn't they be same for all criteria.
Comment: If we finally stopped reinventing the RDBMS wheel, none of those custom databases would make sense..
Answer: Dovecot is a popular email server and its index files are responsible for managing and accessing email data. However, Message sorting optimization records don't appear to be a standard used term  with Dovecot.


Basic contour integral of $\frac{\sin z}{z - i}$

Question: I'm trying to evaluate a basic contour integral, but am getting an incorrect factor of 2 in my answer. Evaluating $$\int_{-\infty}^{\infty} \frac{\sin z}{z - i} = \Im \left( \int_{-\infty}^{\infty} \frac{e^{i z}}{z - i} \right) \, ,$$
I express this as a closed semi-circular contour of radius $R$ in the upper-half plane and take $\lim R \to \infty$. By Jordan's lemma, the integral over the arc contour vanishes and we can evaluate the integral by the residue theorem
$$\int_{-\infty}^{\infty} \frac{\sin z}{z - i} = \Im \left( 2 \pi i \, \left. \mathrm{Res}\left(
\frac{e^{i z}}{z - i} \right) \right|_{z = i} \right) = \frac{2 \pi}{e} \, ,$$
while the correct answer is $\pi / e$. I've stared at this for a bit and still cannot see what I've done wrong. Can anyone quickly point out how the factor of 2 cancels?
Comment: Your topmost identity might not hold true. Even though $\mathfrak I(e^{iz}) = \sin z$ for real $z$, this won't be correct in general if you divide the expression by a non-real number (like $z-i$ in this case). You might be able to adapt your proof by replacing $\sin z = \frac1{2i}(e^{iz}-e^{-iz})$, not using $\mathfrak I$ altogether.
Comment: @DominikS Ah, right. Cheers!
Comment: Your answer seems to be right.
Answer: Note that we have
$$\begin{align}
\int_{-\infty}^\infty \frac{\sin(x)}{x-i}\,dx&=\int_{-\infty}^\infty \frac{(x+i)\sin(x)}{x^2+1}\,dx\\\\
&=\int_{-\infty}^\infty \frac{x\sin(x)}{x^2+1}\,dx\\\\
&=-i\int_{-\infty}^\infty \frac{xe^{ix}}{x^2+1}\,dx
\end{align}$$
Now, we can close the contour in the upper-half plane and write
$$\begin{align}
\int_{-\infty}^\infty \frac{\sin(x)}{x-i}\,dx&=2\pi i \text{Res}\left(-i\frac{xe^{ix}}{x^2+1}, z=i\right)\\\\
&=\frac{\pi}{e}
\end{align}$$
as expected!


snmpd does not update date due to filesystem access error in new ubuntu versions

Question: My Cacti stopped graphing network data for servers that I monitor using snmp.
I am able to manually query the corresponding counter using snmpget
$ snmpget -v 2c -c XXX XXX .22.214.171.124.22.214.171.124.188.8.131.52
iso.18.104.22.168.184.108.40.206.1.6.4 = Counter64: 13662736603625

However the Counter does not increase until I restart snmpd on the server.
In the syslog of the server I noticed theese lines:
Jun 17 16:25:33 ns375911 snmpd[18307]: Cannot statfs /sys/kernel/security#012: Permission denied
Jun 17 16:25:33 ns375911 snmpd[18307]: message repeated 17 times: [ Cannot statfs /sys/kernel/security#012: Permission denied]

The problem appears to affect only servers that I installed after a certain date (somewhere around may 2015)
I have Ubuntu 14.04.2 LTS.
Can anybody explain what is going on here and how can I fix it? I think the error causes snmp to abort and prevent it from updating the network interface statistics. Can I configure snmp to ignore this sys folder? Or give it permissions?
Answer: turned out the server was installed with a gsecurity enabled kernel andthe respective group was not enabled in grsec kernel config
i could have done that but i opted for the easy option of just installing the default server kernel via apt repositories
on ubuntu that would be apt-get install linux-image-server
dont forget to check the order of kernels in /etc/grub.d/
in my case that was cd /etc/grub.d && mv 06_OVHkernel 25_OVHkernel
now update-grub && reboot


Selenium: Trying to enter text in the active element without id but failing

Question: Trying to enter text in the active element but failing..
Can anyone help? Code is as follows. element is commented on.
Using python and selenium and web driver.
using time to give breaks between code to wait for loading
keyboard shortcuts are used to enter the elements as names for gmail are not available.
from selenium import webdriver
import time
from selenium.webdriver.common.keys import Keys

u = input("Enter username: ")

p = input("Enter password: ")

a = input("Enter email address(multiple separated by comma: ")

s = input("Enter subject: ")

t = input("Enter text: ")

browser = webdriver.Firefox()
browser.get('https://accounts.google.com/ServiceLogin/identifier?service=mail&passive=true&rm=false&continue=https%3A%2F%2Fmail.google.com%2Fmail%2F&ss=1&scc=1&ltmpl=default&ltmplcache=2&emr=1&osid=1&flowName=GlifWebSignIn&flowEntry=AddSession')

userid = browser.find_element_by_name("identifier")
userid.send_keys(u)
userid.send_keys(u'\ue007')

time.sleep(2)

passw = browser.find_element_by_name("password")
passw.send_keys(p)
passw.send_keys(u'\ue007')

time.sleep(10)

browser.get('https://mail.google.com/mail/u/0/#inbox?compose=new')

time.sleep(5)

to = browser.find_element_by_name("to")
to.send_keys(a)
fr = browser.find_element_by_name("subjectbox")
fr.send_keys(s)
fr.send_keys(Keys.TAB)

x = browser.switch_to.active_element
time.sleep(1)
x.send_keys(t) #THIS IS NOT WORKING

Comment: print(x.get_attribute("outerHTML")) // This Line prints the Outer Html. Validate the outer html with your expected elements. If it is referring to some other element. You need to change the element identification strategy
Answer: Using browser.switch_to.active_element turns x into a dict whose 'value' key contains the Selenium web element you want to send keys to. I have no idea why that happens on Firefox, on Chrome your script works fine.
Anyway, use this to solve your problem:
x['value'].send_keys(t)
Comment: Oh.. Thank you. I shall try this out.


Topological sorting algorithm on a directed graph

Question: Consider a directed graph $D = (V, A)$ with $n$ vertices and $m$ arcs.
I came up with this $O(m + n)$ algorithm (a modification of the Breadth first search algorithm) that finds a topological sort of the vertices or decides that there is a directed cycle in G.
Let s be a vertex such that there is no arc $(v,s)\in A$ that goes into it. We assume $G$ is connected, otherwise there would be elements that aren't comparable $\implies$ no total order
The vector $D$ will contain the distances from $s$ to each vertex.
<code>INPUT: a directed graph
OUTPUT: state that there is a cycle or give an ordering of V

D[s]:=0 the distance from s to itself is zero
D[v]:=infinity for all v != s
L:={}
Q:={s}
While Q is non empty
    u:=Head(Q)
        For v in the set of vertices such that u->v is in A
            If D[v]=infinity
                D[v]:=D[u]+1
            Else If D[v]!=D[u]+1
                output "there is a directed cycle)
                STOP
            add v to the end of Q
            add v to the end of L
        Delete the first element of Q
For s' such that D[s']=infinity (the vertices without a path s->...->s')
    do the while loop from above
    add L' (the ordering of the children of v) to the beginning of L (this is because we can
              start at any vertex that has no parent and the order of
              those sub-sequences doen't matter in the final ordering)
output L
</code>
I am now wondering if this algorithm works well. Any comment would be appreciated, thanks.
Answer: First, even if there is no total order, it is still possible to have a topological ordering. The difference being that this is no longer unique. Secondly, your algorithm is almost correct. Consider a graph with three vertices $1,2,3$ with $1 \to 2, 1 \to 3, 2 \to 3$. So you would have vertex $3$ as $s$. You won't actually add $3$ to $L$, and you may add vertex $1$ before vertex $2$. What you want to do is to add vertices to the front of $L$ as you delete them from your queue.
Last point is that, I assume repeat the while loop is done by choosing another such vertex with no outdegree. (Else this step is wrong as is) You might want to add a bit more detail as how to do this efficiently. As it is possible that you take too much time in this step. Note that as you repeat, you should initialize the variables accordingly as well as your loop invariant of what your $D$ stores is now invalid. I suggest you to use a boolean array keeping track of visited instead.
Comment: This works. But consider a path $a \to b \to ... \to c$. Your algorithm may take quadratic time.
Comment: As I was reading your answer I came up with something way more simple: a recursive algorithm that puts all roots with no parents at the end of L. Then let G' be G without all those root vertices. Now add all roots of G' at the end of L. etc

But first make sure there is no cycle by doing the BFS modified algorithm (without all the stuff about finding an order)
Comment: And the part with "Else If D[v]!=D[u]+1 output "there is a directed cycle" makes sense?
Comment: Oh noes. I didn't read it carefully. Consider the same counter example I provided in my answer, on that input, your algorithm says there is a directed cycle, despite not being any. This is as $D[1] = D[2] = D[3]+1$. So when it looks at vertex $2$, it would realise that it will fail.
Answer: What has already been done though is to (a) partition the vertices of a digraph $G$ into its strong connected components, and then (b) once this has been done, give a topological sort of the equivalence classes of $G$.
But (a) has been done already in linear time, google Kosaraju strongly connected components--beautiful linear-time algorithm that is a classic and is in any worthwhile graph algorithms book. And once given (a) doing (b) is easy. Collapse each strongly connected component of $G$ into a single vertex (if it isn't one already) and call the resulting graph $G'$. Then $G'$ is necessarily directed acyclic. Then at each stage,
While $G'$ is nonempty:
--$i \leftarrow i+1$
--remove from $G'$ the vertices w indegree 0 from $G'$. Give these removed vertices an index of $i$.
--$G' \leftarrow G' \setminus$  {removed vertices}
Each vertex in $G'$ corresponds to a strongly connected component of $G$. Each vertex $v$ in $G$ falls in the topological sort in the same place the strongly connected component $v$ is in falls into the topological sort of $G'$
Comment: But how does this take linear time? You need to go through every vertex and see if it has indegree 0 at every iteration
Comment: The algorithm of Kosaraju that I am referring to e.g., (a)? Yes. As far as (b) with good implementation, I am pretty sure yes.
Comment: The (b) part that you wrote, I don't see how it can be linear
Comment: Well, each time you remove a vertex $v$ w indegree 0, you can subtract 1 from the indegree of each vertex $y$ s.t there is an arc $(v,y)$ from $v$ to $y$. So new vertices of indegree 0 are discovered and removed on the spot--taking them at that moment before other previously discovered indegree-0 vertices will still result in a valid topological sort.
Comment: If Depth-First-Search can be implemented in linear time--and it can, then so should the above
Comment: How is it similar to DFS? The while loop iterates in O(n+m) and the operations done in the while are not all constant are they? For instance "remove from G′ the vertices w indegree 0" implies that we find all vertices with indegree zero. Can we do that in constant time?


Método Replace no VBA substitui texto indevidamente em todas as planilhas da pasta de trabalho

Question: Há um problema com o método "Replace" do objeto "Range". Quando anteriormente executado o comando "Localizar" (e substituir ou não) na interface de usuário, com a opção "Pasta de trabalho" selecionada, o método "Replace" ignora a delimitação do intervalo de células com o qual o método foi chamado e SUBSTITUI TODAS AS OCORRÊNCIAS do texto procurado EM TODAS AS PLANILHAS da pasta de trabalho. O problema é que até onde pesquisei não há parâmetro para alterar essa opção de "Pasta de trabalho" para "Planilha" no VBA (nem no método "Find" nem no método "Replace"). É até mesmo impossível saber o que está selecionado para esse parâmetro.
Como, no meu caso, não posso fazer a substituição do texto que desejo em outras planilhas, além de uma específica, fica inviabilizada a utilização do método "Search". Há a solução de usar o método "Find" e, após testar se a célula é ainda pertencente à planilha desejada, alterar o valor da célula encontrada com um comando, e depois usar o método "FindNext", e assim por diante. Mas a planilha pode ter milhares de linhas e muitas ocorrências do texto pesquisado e essa solução impacta muito a performance.
Se alguém se deparou com esse problema e tem alguma ideia fico grato.
Summary: There is a problem with the method "Replace" in the object "Range". When previously executed the command "Find" (and replace or not) in the user-interface, with the option "Workbook"  ("Pasta de trabalho", in portuguese) selected, the method "Replace" ignores the delimitation of the range over wich the method was called and REPLACES ALL THE OCCURENCIES of the searched text IN ALL WORKSHEETS...
Answer: Estamos falando de um bug do Excel na versão 365 atualizada (não verifiquei se já ocorria em outras versões). Ele foi reportado à Microsoft. Até que seja corrigido há as seguintes soluções de contorno possíveis:
1) FUNÇÃO REPLACE
Usar os métodos 'Find' e 'FindNext' combinados com a FUNÇÃO 'Replace' (não o método do objeto intervalo), mediante verificação da propriedade 'Worksheet' de cada célula encontrada, como descrito na pergunta.
A pesquisa deve ser iniciada na primeira célula da planilha desejada, de modo que ao ser encontrada célula fora da planilha a iteração deve ser interrompida. Não adotei essa solução devido ao custo, porque no meu caso se esperam centenas de milhares ou mais substituições.
2) PROMPT DE CONFIRMAÇÃO
Exibir um prompt para confirmação pelo usuário do prosseguimento da execução, alertando para a necessidade de não estar selecionado 'pasta de trabalho' na caixa de diálogo da ferramenta 'Localizar e substituir' do Excel, ou serão feitas alterações em toda a pasta de trabalho que irão inutizá-la. Foi o que adotei como solução imediata.
3) PROTEGER E DESPROTEGER DEMAIS PLANILHAS
Proteger todas as outras planilhas, em que a substituição seja indesejada, antes de se aplicar o método 'Replace', e tornar a desproteger as planilhas. Se necessário, deve ser salva a lista de planilhas que já estejam protegidas, para que não fiquem desprotegidas indevidamente depois da execução do script.
Haverá ainda um problema: se a aplicação fizer uso de planilhas protegidas com células desbloqueadas. Será trabalhoso, se forem muitos intervalos, bloqueá-los, antes do 'Replace', para depois desbloqueá-los.
Não foi o meu caso, então foi essa a solução que adotei por fim.


How to approach the functional equation $\frac{f(x+T)}{f(x)} = g(x)$?

Question: I am trying (for fun!) to study the ongoing COVID-19 pandemic and have the following question. we know that an exponential function satisfies the following functional equation:
\begin{equation}
\frac{f(x+T)}{f(x)} = e^T = \text{constant}
\end{equation}
for some period $T$. For instance the function $f(x)=2^x$ satisfies
\begin{equation}
\frac{f(x+1)}{f(x)} = 2
\end{equation}
Now, since here in Italy the growth rate of the infected is falling, the function describing the total amount of covid-19 cases since the start of the outbreak might satisfy the following equation:
\begin{equation}
\frac{f(x+T)}{f(x)} = g(x)\qquad \text{with $g$ decreasing to 1}
\end{equation}
My question is this: how to solve this, is the solution existing, is it unique? Any hint on how I could approach this?
Comment: The solution is not unique. Already the exponential solution was not unique: If $f$ is a solution then so is $c\cdot f$ for any constant. Apart from that, $f$ can behave arbitrarily on an initial interval $[0,T)$, say
Comment: You need to read more on epidemiology models. This is a good try but to say bluntly, too naive.
Comment: @timur Ok I am not really interested in having a good model for the epidemic (I know about SIR models etc) but I thought that this mathematical problem was interesting
Comment: agree with timur's comment: spreading is a [multiplicative diffusion process](https://en.wikipedia.org/wiki/Diffusion) quite similar to nuclear fission
Answer: Let $f(x)$ be given for $x\in[0,T)$, and let $g(x)$ be given for $x\in[0,b]$, for some $T>0$ and $b\geq T$. Then the equation
$$
f(x+T)=g(x)f(x) ,
$$
has a unique solution for $x\in[0,b]$.
In other words, the solution $f$ is unique as a function defined on $[0,T+b]$.


How to add a top-level link to the Admin menu via the links.menu and routing yaml's

Question: Let's say I want to add an additional link to the admin toolbar after Reports such as Groups does.
In my_module.routing.yml I have:
my_module.admin:
  path: '/admin/my_module'
  defaults:
    _controller: '\Drupal\system\Controller\SystemController::systemAdminMenuBlockPage'
    _title: 'My Module Stuff'
  requirements:
    _permission: 'access administration pages'

In my_module.links.menu.yml I have:
my_module.admin:
  title: My Link
  route_name: 'my_module.admin'
  parent: 'system.admin'
  description: 'Stuff my link does'
  weight: 8

I took these from the corresponding Groups module. When I clear cache, nothing new shows up in the admin toolbar or the admin menu UI settings.
Answer: This does actually work. I created a brand new module and copied your code into those files and it worked - I got the My Link menu appearing in the admin toolbar. I can only think that you don't have the correct permissions for the user you were testing with or that you didn't do a full cache clear (drush cr).
Comment: It was something similar. You're correct that the code is right so it had to be config related. In my case I changed the route permission to the role but forgot to change the key itself to role.
Comment: This does not provide an answer to the question. Once you have sufficient [reputation](https://drupal.stackexchange.com/help/whats-reputation) you will be able to [comment on any post](https://drupal.stackexchange.com/help/privileges/comment); instead, [provide answers that don't require clarification from the asker](https://meta.stackexchange.com/questions/214173/why-do-i-need-50-reputation-to-comment-what-can-i-do-instead). - [From Review](/review/late-answers/136568)
Comment: @cliefen It does. I pointed out that the code works but that the permissions for the route needed checking (which turned out to be the issue). If someone else has the same problem my response would have given them the knowledge that this code works and that the permissions needed checking.


Jquery mobile error with localStorage

Question: I developed a jquery mobile web-app and it works great on pc and on some mobile devices.
Now I tested it on a blackberry z10 and on an ipad mini and the app doesn´t work on this devices.
I build a example app (code below) where I found out, that the reason is the access on the localStorage.
If I delete the line with the set or an line with a get access to the localStorage it works fine.
Error: I can´t change the Page with the localStorage access.
Without the line...
localStorage.setItem("test", "testal");

...it works.
CODE:
<!DOCTYPE html>

    <title>Titel</title>
    <meta name="apple-mobile-web-app-capable" content="yes" />

    <link rel="stylesheet" href="http://code.jquery.com/mobile/1.2.0/jquery.mobile-1.2.0.min.css" />

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

Header

Menü

Example

Header 2

Page 2

Answer: maybe there is a version issue. here is an overview for that:
http://caniuse.com/#index
also on ipad you could try to turning off private browsing...
Comment: It can´t be a version issue because localStorage is compatible with Blackberry 10.

Jquery mobile error with localStorage


Marking a section of measures as optional

Question: Is there an "official" way of marking a section of measures as optional?
I'm not talking about an ossia, but defining a whole consecutive set of measures as "include according to preference".
I'm transcribing a piece with quite a large intro, which consists of three sections, each adding either a layer or a twist to the theme. In practice, any combination of those (as long as you keep the order) can be used, and any combination can actually be found in renditions of the piece.
Is there way to properly annotate this in sheet music, other than textual instructions to the player?
Answer: My choice is KISS (keep it simple, stupid):  just put in "Optional cut to .." either a measure number or a segno marking.   No need to get fancy.
Comment: Yeah, that's the current implementation :)
It's mostly curiosity **if** there is proper way to annotate this (other than text), that lead to the question. Never had the need to do it before.
Answer: I'm only aware of the (also textual) ad libitum marking which is mostly combined with a sonewhat smaller note appearance, to signal the scope. The following unconditional part is then again marked with something like solo, play or similar.
The typical use is, however, to permit a soloist to join some tutti passages as well.
Comment: It's for solo guitar, so a highly specialized case of a tutti scenario ;)
Ad libitum does indeed not quite cover it, but it might be handy, since it's generally recognized as an option for "customization" (with still the accompanying notes, of course).


How do i convert .txt file to .csv file in shell script

Question: I am trying to copy the contents of test.txt (FILE_MASTER) to test.csv in shell script, what command should I use?
cp $FILE_MASTER test.csv

The contents of text.txt are as below (comma separated)
3058819,AA TIRES,,,2934 AJ

Comment: `cp file.txt file.csv`
Comment: It is not clear what your question is. If you only want to copy a file you already wrote the command in your question. Copying a file does not depend on its contents. In the title you wrote "convert .txt to .csv". If you want to **convert** the contents instead of copying it unchanged, please describe how exactly the data should be converted.
Answer: The file contents already are .csv, (i.e. Comma Seperated Values), so all that needs be done is to cp or mv the file to whatever name seems fitting:
cp "${FILE_MASTER}" test.csv


JSF error while passing method call in ui:param

Question: I have the following code:
some_file.xhtml containing:
<ui:decorate template="template/a_template.xhtml">
    ...
    <ui:param name="doSmthg" value="#{aBean.someAction()}"/>
    ...
</ui:decorate>

And in the template file a_template.xhtml:

The issue here is that, aBean.someAction() is called normally but I've an error "Identity 'doSmthg' was null and was unable to invoke".
I don't have the error if I use directly actionListener="#{aBean.someAction()}" in the template though.
Does anyone have an idea ? Thx
Answer: Try this:
Passthe name of the method as parameter:
 <ui:param name="doSmthgName" value="someAction"/>

and use it:


Modernizr - uncompressed JavaScript and CSS files warning in SEO

Question: I'm using Drupal 9.5.9 version.
I have enabled Aggregation for css/js files under "admin/config/development/performance".
But, in page view source, I can see, core modernizr js file is not compressed.

Due to this one uncompressed js file, am getting more errors/warnings in SEO tool.
Can you guide me how to compress/aggregate this file, please?
Comment: If you use Drupal 9.5 or Drupal 10, the bug reported in https://www.drupal.org/project/drupal/issues/1040534 has been already fixed. You do not need to apply that patch; trying to apply it would probably return an error. Notice also that, looking at the page source, you will not be able to understand which files have been compressed because the URL are rewritten on server side. The rules in the .htaccess do this: Check if the browser accepts `gzip` as encoding; check there is a .gz file for the requested file; if both those conditions are met, rewrite the URL to the URL of the .gzip file.
Comment: What warnings are those, and in what SEO tool? That filename is modernizr.min.js, suggesting that it it minified. In a Drupal installation, that file is minified. If this question is actually about compression (like gzip), that's another matter. But there is nothing in this question explaining that.
Comment: To add to what @cilefen said, aggregated files are not necessarily compressed. JavaScript and CSS files are served compressed if the browser supports them compressed.
Comment: In the [.htaccess](https://git.drupalcode.org/project/drupal/-/blob/11.x/.htaccess) file used by Drupal core, there are two comments: `Serve gzip compressed CSS files if they exist and the client accepts gzip` and `Serve gzip compressed JS files if they exist and the client accepts gzip`.
Comment: Thanks @cilefen , SEO tool: SEMRUSH and even the file is minified, SEMRUSH is reporting that this particular one file is not compressed, while other minified js files has been compressed.
Comment: And, Thanks @apaderno, I have seen this .htaccess file for js/css compressed gzip and even tried patch from here: https://www.drupal.org/project/drupal/issues/1040534, but still issue is same. after trying all possibilities , I came here for help.
Answer: Local JavaScript and CSS files are aggregated and then compressed when:

Their definition sets preprocess to true (or 1)
There is more than a file in that group

Remote JavaScript and CSS files are never aggregated and compressed.
In the case of the core/modernizr library (line 1124 of the core.libraries.yml file), the library uses two files (assets/vendor/modernizr/modernizr.min.js and misc/modernizr-additional-tests.js), but preprocess is set to 0 for both of them.
modernizr:
  # Block the page from being loaded until Modernizr is initialized.
  header: true
  remote: https://github.com/Modernizr/Modernizr
  license:
    name: MIT
    url: https://modernizr.com/license/
    gpl-compatible: true
  version: "3.11.7"
  js:
    assets/vendor/modernizr/modernizr.min.js: { preprocess: 0, weight: -21, minified: true }
    misc/modernizr-additional-tests.js: { preprocess: 0, weight: -20 }

Implementing hook_js_alter(), it is possible to change preprocess to TRUE for those files. That would let Drupal aggregate and compress those files too, but it could cause the JavaScript code not to work correctly. There must be a reason for Drupal core to set preprocess to 0 for those files.
Comment: Thank you so much @apaderno. I will try for altering. Because, in SEMRUSH, our website performance goes down from 62 to below 30 due to this issue. Will try altering and if new issue comes, will check on that as well. Thanks again.


Manifold with infinitely many based loops but only two unbased loops (up to homotopy).

Question: It is known that homotopy classes of free loops in a topological space are in bijection with conjugacy classes of the the spaces fundamental group, that every group is the fundamental group of some space, and that there exists an infinite (finitely generated!) group with exactly two conjugacy classes. This has the interesting consequence that there is some space with infinitely many distinct based loops but only two unbased loops (up to homotopy).
I'm wondering if there is any manifold that has this property. It is known that every compact manifold has finitely presented fundamental group (and that every finitely presented group is a fundamental group of a manifold), so showing there is a infinite finitely presented group with two conjugacy classes would suffice, although I believe this is unknown. But if we allow noncompact manifolds, perhaps things get easier.
Comment: Every countable group is the fundamental group of a manifold. There is even finitely generated infinite group with two conjugacy classes. For finitely presented groups, I think, it is an open problem.
Answer:
For every countable group $G$ there exists a (smooth) connected manifold $M$ with $\pi_1(M)\cong G$, see this MathOverflow discussion.
There exist a countable infinite group with exactly two conjugacy classes: This is a classical result due to Higman, Neuman and Neuman ("Embedding Theorems for Groups", 1949). See this MSE post.

Hence, there exists a connected manifold with infinite fundamental group but only two free homotopy classes of loops.
The existence of a compact manifold with this property is equivalent to the existence of an infinite finitely presented group with exactly two conjugacy classes. The latter, I believe, is an open problem. A construction of finitely generated groups with this property is highly nontrivial and is due to D.Osin:
D. Osin, Small Cancellations over Relatively Hyperbolic Groups and Embedding Theorems, Ann Math. 172, no. 1 (2010), 1-39.


How to show a View field depending on roles?

Question: I have a view, and I added 2 fields: "title" and "edit link".
Now I just want to show the "edit link" link if the visitor is a registered user, and has the "administrators" role.
How can I accomplish it?
Answer: Check the permissions for the role of "administrators" (D7: admin/people/permissions, D6: admin/user/permissions).  If the user has permission to edit the node, the edit link will be visible, if not, the edit link will not be shown. Views takes into account a user's (role's) permissions.
D7 Example:  Say you are creating a list of Stories. If the administrators role has the permission "Story: Edit any content", the user will be able to see the "Edit" link for that node in the listing, while if the role only has the permission "Story: Edit own content" the "Edit" link will only be shown if the current user created the Story.


Test for trend and seasonality in time series

Question: This is my data:
x <- c(88, 88, 88, 85, 85, 85, 85, 85, 86, 90, 83, 83, 84, 88, 88, 88, 89,
       89, 89, 89, 87, 89, 82, 82, 85, 85, 87, 87, 87, 87, 87, 87, 92, 92,
       84, 84)

My purpose here is to check whether x has trend or seasonality. What I have done for now is:
stlm <- stl(ts(x,frequency = 12), s.window = "periodic")
plot(stlm)

After I obtain and view the graph, I want to measure whether trend and seasonality are statistically significantly or not. I would like to get something like a $p$-value in regression analysis.
How can I do that?
Answer: Are you sure you want to formally test for the presence of a trend or a seasonal pattern? What are you going to do with the test result?
To get a fair result you would need to formulate a hypothesis before you see the data. For example, $H_0 \colon \text{there is a linear trend}$. Then you would build a model for the data including a linear trend and test whether the corresponding coefficient is zero or not.
However, if you (1) do not have a hypothesis to begin with and (2) take a look at the data to identify the possible shape of the trend and/or the seasonal component and then (3) specify a model allowing for this particular shape, then you will quite likely reject the null of absence of the shape. Think about it: you extract a pattern from the data and then question its presence; of course, you will likely conclude the pattern is present. Therefore, when testing you cannot apply the critical values of the regular null distribution as if the pattern was specified before viewing the data.

For example, if you (1) you do not know what type of time trend to expect and (2) take a look at the data and see a linear time trend, then (3) specify a model allowing for a linear time trend and then (4) test for its absence, then you will quite likely reject the null hypothesis. This will happen by the design of the testing procedure, rendering it quite unsuitable for inference.

If trend/seasonality is a just a nuisance and your focus will be on some other aspects of the model, you could include trend/seasonality without formal testing. Even if those patterns do not truly belong in the model, presence of irrelevant regressors is normally considered less problematic than absence of relevant ones (although exceptions exist).
Update
Your data series is only three years long, which makes seasonality modelling quite problematic and prone to overfitting. Extra care will be needed there (but that is a separate topic, so I will not expand on it).
You may visualize seasonality using function seasonplot from "forecast" package in R. The function takes a time series object (ts) as an input and plots the development of the series stacked over full seasonal periods. (In the figure, I assumed your series starts in January, but you could change that.)
Comment: @Richad, the x is here my dependent value for multiple regression before building regression model I wanted to check if there is any pattern like trend or seasonality after viewed the graph above ı have some doubt about seasonality because every november the x is decreasing between 6 and 8 points thats way ı want to test power of seasonality and fix it like using dummy variable. Do u have any suggestion about my problem?Thanks in advance
Comment: @tiko33, you could include seasonal variables (e.g. dummies) in your model, but it does not seem you would really need to test for presence of seasonality.
Comment: thanks for your interest `ts=ts(uba_down[,2],freq=12)
apply(stlm$time.series, 2, var) / var(ts)` after tried this I obtain   `seasonal      trend  remainder
0.66415287 0.07936102 0.21969780` do u think it's the prove presence of seasonality and now how can I build up my model with decompositon of seasonality or dummy variables or both. I m  confused about that
Comment: Building a model is a separate question and should be asked as such. I could only hint that three years is a very short period and thus extra care should be taken to prevent overfitting. Using STL decomposition could probably work alright if you sensibly tune the model parameters (I cannot help with it as I have not used STL much; better refer to the existing literature). After the STL decomposition, you could subtract the fitted seasonal component from your data and further model the modified series (run a regression with the variables of interest or the like).
Answer: Well, you can run your model with a time trend and check if it's significant. If you suspect that the trend is not linear --for instance, quadratic--, you can add a polynomial time trend and check its significance again. I do not know if it is the best strategy, but it may help.


Existence of a square root of an non-uniformizer over an extension of $\mathbb{Q}_5$

Question: Let $L/\mathbb{Q}_5$ be an extension with ramification index $6$. Assume that there is an element $\alpha \in L$ with valuation $1/3$.

Question Is there a square root of $\alpha$ in L (i.e. an element $\beta \in L$ with $\beta^2 = \alpha$)?

My own effort:

If there is such an element $\beta$, it would have valuation $1/6$, i.e. it would be a uniformizer.

I cannot apply Hensel's Lemma to $f = x^2 - \alpha \in L[x]$ since its reduction is not separable.

Could you please help me to advance with my question? Thank you!
Answer: Not necessarily.  In fact, if every element of valuation $1/3$ has a square root, then by taking ratios of these it follows that every element of valuation 0 has a square root as well.  This is never true when $L/\mathbb Q_5$ is finite.  (For example, in $\mathbb Q_5(5^{1/6})$, the element $5^{1/3}$ has a square root but $2 \cdot 5^{1/3}$ does not, since the ratio 2 isn't a square in $\mathcal O_L/\mathfrak m_L = \mathbb F_5$.)
What is true that if there exists $\beta$ such that $\beta^2 - \alpha$ has valuation greater than $1/3$ (i.e. "$\alpha$ has a square root up to first-order approximation"), then $\alpha$ has a square root.  You can prove this by the strategy in reuns's answer.
Answer: Choose some uniformizer $\pi_L$, it is of valuation $1/6$, then apply Hensel lemma to $\alpha/\pi_L^2\in O_L^\times$