Como fazer para ter no máximo um líder selecionado em todos os selects?

Question: Como faço para quando eu selecionar a opção Líder, o javascript não permitir que seja selecionado uma outra função (multiselect)?
O cenário é o seguinte: Cada select representa as funções de cada usuário.
O usuário que for selecionado como Líder, não pode ter mais nenhuma outra função; apenas a de Líder.
Se a opção for diferente de Líder, então o javascript permite selecionar mais de uma função.
Aqui está a minha tentativa:

$("select").on("change", function() {
    var self = $(this);
    var values = self.val();

    $("select").not(self).each(function() {
        var _values = $(this).val();
  if (_values == "1") {
    $(this).selectpicker('deselectAll')
   for (var v = _values.length; v--;) {
    if (values.indexOf(_values[v]) >= 0) {
     _values.splice(v, 1);
    }
   }

   $(this).val(_values);
  }
    });

 $(".selectpicker").selectpicker("refresh");
});

<link href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.6.3/css/bootstrap-select.css" rel="stylesheet" />
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.2/css/bootstrap.css" rel="stylesheet" />

<select class="selectpicker" multiple>
      <option value="1">Líder</option>
      <option value="10">Para Conhecimentor</option>
      <option value="11">Participante</option>
    </select>

<select class="selectpicker" multiple>
      <option value="1">Líder</option>
      <option value="10">Para Conhecimentor</option>
      <option value="11">Participante</option>
    </select>

<select class="selectpicker" multiple>
      <option value="1">Líder</option>
      <option value="10">Para Conhecimentor</option>
      <option value="11">Participante</option>
    </select>

<select class="selectpicker" multiple>
      <option value="1">Líder</option>
      <option value="10">Para Conhecimentor</option>
      <option value="11">Participante</option>
    </select>
Answer: Acredito que seja isso que você quer:

$("select").on("change", function() {
    var self = $(this);

    if($.inArray('1', self.val()) != -1) {
      self.find('[value!="1"]').prop('selected', false).prop('disabled', true);
    } else {
      self.find('[value!="1"]').prop('disabled', false);
    }

    // Bloquear as opções líderes caso alguma seja selecionada
    var selectedValues = $.map($('select option:selected'), function(el) {
      return el.value;
    });

    if($.inArray('1', selectedValues) != -1) {
      $('option[value="1"]:not(:selected)').prop('disabled', true);
    } else {
      $('option[value="1"]').prop('disabled', false);
    }

 $(".selectpicker").selectpicker("refresh");
});

<link href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.6.3/css/bootstrap-select.css" rel="stylesheet" />
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.2/css/bootstrap.css" rel="stylesheet" />

<select class="selectpicker" multiple>
      <option value="1">Líder</option>
      <option value="10">Para Conhecimentor</option>
      <option value="11">Participante</option>
    </select>

<select class="selectpicker" multiple>
      <option value="1">Líder</option>
      <option value="10">Para Conhecimentor</option>
      <option value="11">Participante</option>
    </select>

<select class="selectpicker" multiple>
      <option value="1">Líder</option>
      <option value="10">Para Conhecimentor</option>
      <option value="11">Participante</option>
    </select>

<select class="selectpicker" multiple>
      <option value="1">Líder</option>
      <option value="10">Para Conhecimentor</option>
      <option value="11">Participante</option>
    </select>

Explicação:
O select será monitorado pelo evento change, então toda vez que tiver uma alteração no valor ele executará a função.
Na função eu obtenho os valores do select modificado, e verifico se algum desses valores é igual a 1, se sim eu procuro por todas as options desse select que são diferentes de 1 e tiro a propriedade selected e adiciono a disabled, se o valor 1 não tiver sido selecionado, eu habilito todas as options novamente.
Comment: Muito obrigado @JuniorNunes. O resultado era esse mesmo! Valeu!
Comment: Muito obrigado pela ajuda. Mas teria como quando um select(pai) fosse selecionado como "Líder" e em outro select(filha) quando eu clicasse em "Líder" também, o javascript 'deselecionar' o  Líder do select(pai)? Você poderia me ajudar?
Comment: No caso só existiria no máximo um líder selecionado em todos os selects?
Comment: Exatamente isso
Comment: Acho que isso caberia melhor em uma nova pergunta, já que a pergunta inicial não detalha muito bem isso, edite a pergunta inicial ou crie uma nova para eu te ajudar.
Comment: Beleza, vou editar a pergunta
Comment: Pergunta editada
Comment: Editei a resposta, vê se isso te ajuda!


Substituir uso de dataframe com pandas .apply

Question: Eu possuo uma função que itera uma planilha, que faz alguns controles. Procurei sobre e vi sobre o .apply, mas não consegui implentar. Gostaria de saber se conseguiria nesse caso, substituir o uso que faço e por questão de performance, alterar para o .apply.
No caso, possuo um dicionário que ele consulta para minhas condições tratadas. E a função que itera fazendo um laço pra que isso ocorra. A função depende do cargo que eu passo no dicionário e que vem da planilha para saber se exibe um campo de foto ou não.
    for i, row in df.iterrows():
        if row['cargo'] in cargos_to_display_photo:
            df.loc[i, 'display_foto'] = True
        else:
            df.loc[i, 'display_foto'] = False
    return df

a função que "prepara" o data frame é:
def prepare_dataframe(df_google):
    df_google = set_display_photo(df_google)
    return df_google

o dicionário:
cargos_to_display_photo = [
    'Trainee | Assessoria de Investimentos',
    'Sócio Fundador',
    'Superintendente',
    'Assessor de Investimentos',
    'Sócia | Assessor de Investimentos',
    'Líder Corporate',
    'Trainee | Corporate',
]

a coluna que consulto:
columns_dict = {
    'SEXO' : 'sexo',
    'CÓDIGO' : 'codigo',
    'Nome Completo' : 'nome',
    'Cidade' : 'unidade',
    'Cargo' : 'cargo',
}

As colunas que não efetuo consulta ou que não foram citadas no trecho eu descarto pelo próprio código, dando um drop nelas com as tratativas necessárias pra que não precise iterar.
das formas que pesquisei, não consegui implentar nenhuma. Não consegui fazer com que o apply populasse a planilha. Seria possível fazer isso com essas funções?
Comment: A formatação do código da sua pergunta ficou ruim, abaixo do primeiro return df você deve colocar os ``` mais pro lado esquerdo.
Outra questão, você consegue disponibilizar a planilha para testes?
Comment: ajustei, o link da mesma: https://docs.google.com/spreadsheets/d/1VFETvsNvA-NCFPlplCtZ1qPw3HeaCV7Te2x8kopf7ZE/edit?usp=sharing
Comment: @lmonferrari eu tirei alguns campos da planilha porque possui alguns dados confidenciais. Mas acredito que dê pra você testar.
Comment: Claro, sem problemas!
Answer:
Procurei sobre e vi sobre o .apply, mas não consegui implementar. Gostaria de saber se conseguiria nesse caso, substituir o uso que faço e por questão de performance, alterar para o .apply.

Importando o arquivo:
<code>import pandas as pd

df = pd.read_excel('./Cadastro Colaboradores BT.xlsx')
</code>
Lista com os cargos:
<code>cargos_to_display_photo = [ 'Trainee | Assessoria de Investimentos',
                           'Sócio Fundador', 'Superintendente',
                           'Assessor de Investimentos',
                           'Sócia | Assessor de Investimentos',
                           'Líder Corporate', 'Trainee | Corporate', ]
</code>
Código com o apply:
<code>df['display_foto'] = df['Cargo'].apply(lambda x: x in cargos_to_display_photo)
</code>
Crio uma coluna chamada display_foto, aplico o apply na coluna Cargo do dataframe e faço uma função anonima que verifica se o conteúdo da coluna linha a linha.

Tempo de execução com o laço for:
69.4 ms ± 1.52 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)

Tempo de execução com apply:
305 µs ± 30.8 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
Comment: não consegui entender ainda. O que muda na função do display_photo?
Comment: No código que postei a função `set_display_foto` é substituída por uma função anonima `lambda`, essa função verifica dentro da sua lista de `cargos_to_display_fotos` se na coluna `cargos` existe  algum valor compatível, caso encontre o valor verdadeiro, ele retorna True, caso não encontre retorna False.  No comando `df['display_foto'] =` está sendo criado uma nova coluna chamada `display_foto` exatamente como sua função fazia.
Comment: mas essa coluna é criada na planilha? Porque eu não posso alterar ela. Não é de meu controle, eu uso ela somente pra leitura dos dados e iteração.
Comment: Não Wanderson, ela é criada no seu data frame, da mesma forma que sua função faz. Essa coluna vai aparecer somente se você criar um novo arquivo excel ou mandar salvar na planilha atual.
Comment: o df['display_foto'] = df['Cargo'].apply(lambda x: x in cargos_to_display_photo) eu chamo no prepare dataframe, no caso?
Comment: Caso você queira chamar dentro da prepare_dataframe você poderia fazer assim:
 `def prepare_dataframe(df_google):
    df_google['display_foto'] = df_google['Cargo'].apply(lambda x: x in cargos_to_display_photo)`
Comment: Caso você queira retornar um NOVO dataframe: `def prepare_dataframe(df_google):
    df_prepared = df_google
    df_prepared['display_foto'] = df_google['Cargo'].apply(lambda x: x in cargos_to_display_photo)
    return df_prepared`
Comment: legal! só não consegui testar.. Antes usava:
```
 for i, row in df_google.iterrows():
   ...:     print(row['nome'], row['cargo'], row['display_foto'])
```
no shell e ele retornava a planilha. Como você testou?
Comment: da uma olhada: https://ibb.co/Jm4Dw50
removi os nomes da imagem mas ai está como eu faço
Answer: Uma forma de fazer isso seria usando a função .isin() do pandas. Ela retorna uma lista booleana quando encontra algum valor dentro do array cargos_to_display_photo
df['display_foto'] = df['Cargo'].isin(cargos_to_display_photo)
df.head()
    SEXO    CÓDIGO  Nome completo   Cidade      Cargo       display_foto
0   m       NaN     Samuel...       Ribeir...   Sócio ...   False
1   m       NaN     Leonar...       Uberlâ...   Assess...   True
2   m       NaN     Andre ...       Franca      Sócio ...   False
3   f       NaN     Rejane...       Uberlâ...   Assess...   False
4   m       NaN     Wevers...       Rio de...   Traine...   True

Uma boa prática para se obter desempenho(velocidade) nas execuções em pandas é evitar usar loops de repetição, assim como a função apply (que também é um tipo de iteração).
Segue o tempo de execução da minha proposta:

220 µs ± 5.93 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)


How to add action inheriting a workflow in openerp?

Question: I need to add an action in the account_voucher workflow
<code>    <record id="act_done" model="workflow.activity">
        <field name="wkf_id" ref="wkf"/>
        <field name="name">done</field>
        <field name="action">proforma_voucher()</field>
        <field name="kind">function</field>
        <field name="flow_stop">True</field>
    </record>
</code>
The action is "reference_action()", but i dont know how to do it. I tried whit this
<code>    <record id="act_reference_done" model="workflow.activity">
        <field name="wkf_id" ref="account_voucher.act_done"/>
        <field name="action">reference_action()</field>
    </record>
</code>
Thing is that i have to put the column "name" or i violate a not-null constraint, but if i do that i just add another activity with the same name and i dont over-ride the other one.
Any tip on how to correct inherit and edit a workflow?
Thanks!
Answer: You are doing wrong to override/inherit workflow activity.
To override workflow activity, you have to use same xml id with module name where it is created.
Try this:
<code><record id="module_name.act_done" model="workflow.activity">
    <field name="wkf_id" ref="module_name.wkf"/>
    <field name="name">done</field>
    <field name="action">proforma_voucher()
    reference_action()
    </field>
    <field name="kind">function</field>
    <field name="flow_stop">True</field>
</record>
</code>


Localhost vs 127.0.0.1 using tomcat

Question: I'm using tomcat7 in Ubuntu 14.04.
My problem is simple: when i run http://localhost:8080 it works. But when i run http://127.0.0.1:8080/ it doesn't work. I got Etat HTTP 404 - /.
What is the problem ? and how can i resolve it please ?
Answer: Probably you did a typo  there 127.0.0.7 should be 127.0.0.1. If still doesnt work try to update /etc/hosts file and add localhost to 127.0.0.1 mapping.
EDIT
Seems like you did type in question and edited. Also take a look here
Comment: if you run cat /etc/hosts command you should see something like localhost 127.0.0.1,  which means each time i open this ip forward to this host. https://ubuntu-tutorials.com/2006/12/05/user-feedback-etchosts-explained-ubuntu-510-6061-610/

Localhost vs 127.0.0.1 using tomcat


How to change where jQuery input is displayed

Question: The problem is: http://trulydesigns.com/horoscope/
When you press submit after entering the form, I would the value displayed in the input box below in a separate div.
For example: http://whatismysign.net/
function sunsign() {
document.form1.date.selectedIndex;
document.form1.month.selectedIndex;
document.form1.sign.value;

if (document.form1.month.selectedIndex == 1 && document.form1.date.selectedIndex <=19) {document.form1.sign.value = "Capricorn";}
if (document.form1.month.selectedIndex == 1 && document.form1.date.selectedIndex >=20) {document.form1.sign.value = "Aquarius";}
if (document.form1.month.selectedIndex == 2 && document.form1.date.selectedIndex <=18) {document.form1.sign.value = "Aquarius";}
if (document.form1.month.selectedIndex == 2 && document.form1.date.selectedIndex >=19) {document.form1.sign.value = "Pisces";}
if (document.form1.month.selectedIndex == 3 && document.form1.date.selectedIndex <=20) {document.form1.sign.value = "Pisces";}
if (document.form1.month.selectedIndex == 3 && document.form1.date.selectedIndex >=21) {document.form1.sign.value = "Aries";}
if (document.form1.month.selectedIndex == 4 && document.form1.date.selectedIndex <=20) {document.form1.sign.value = "Aries";}
if (document.form1.month.selectedIndex == 4 && document.form1.date.selectedIndex >=21) {document.form1.sign.value = "Taurus";}
if (document.form1.month.selectedIndex == 5 && document.form1.date.selectedIndex <=20) {document.form1.sign.value = "Taurus";}
if (document.form1.month.selectedIndex == 5 && document.form1.date.selectedIndex >=21) {document.form1.sign.value = "Gemini";}
if (document.form1.month.selectedIndex == 6 && document.form1.date.selectedIndex <=20) {document.form1.sign.value = "Gemini";}
if (document.form1.month.selectedIndex == 6 && document.form1.date.selectedIndex >=21) {document.form1.sign.value = "Cancer";}
if (document.form1.month.selectedIndex == 7 && document.form1.date.selectedIndex <=21) {document.form1.sign.value = "Cancer";}
if (document.form1.month.selectedIndex == 7 && document.form1.date.selectedIndex >=22) {document.form1.sign.value = "Leo";}
if (document.form1.month.selectedIndex == 8 && document.form1.date.selectedIndex <=21) {document.form1.sign.value = "Leo";}
if (document.form1.month.selectedIndex == 8 && document.form1.date.selectedIndex >=22) {document.form1.sign.value = "Virgo";}
if (document.form1.month.selectedIndex == 9 && document.form1.date.selectedIndex <=21) {document.form1.sign.value = "Virgo";}
if (document.form1.month.selectedIndex == 9 && document.form1.date.selectedIndex >=22) {document.form1.sign.value = "Libra";}
if (document.form1.month.selectedIndex == 10 && document.form1.date.selectedIndex <=21) {document.form1.sign.value = "Libra";}
if (document.form1.month.selectedIndex == 10 && document.form1.date.selectedIndex >=22) {document.form1.sign.value = "Scorpio";}
if (document.form1.month.selectedIndex == 11 && document.form1.date.selectedIndex <=21) {document.form1.sign.value = "Scorpio";}
if (document.form1.month.selectedIndex == 11 && document.form1.date.selectedIndex >=22) {document.form1.sign.value = "Sagittarius";}
if (document.form1.month.selectedIndex == 12 && document.form1.date.selectedIndex <=20) {document.form1.sign.value = "Sagittarius";}
if (document.form1.month.selectedIndex == 12 && document.form1.date.selectedIndex >=21) {document.form1.sign.value = "Capricorn";}

if (document.form1.month.selectedIndex == "x" || document.form1.date.selectedIndex == "y") return;

}
<form style="padding-top:150px" name="form1">

                 Month

                 Date

                  :

                 Sunsign

                <select name="month">
                    <option value="x" selected>Month</option>
                    <option value="1">January</option>
                    <option value="2">February</option>
                    <option value="3">March</option>
                    <option value="4">April</option>
                    <option value="5">May</option>
                    <option value="6">June</option>
                    <option value="7">July</option>
                    <option value="8">August</option>
                    <option value="9">September</option>
                    <option value="10">October</option>
                    <option value="11">November</option>
                    <option value="12">December</option>
                </select>

                <select name="date" onChange="validate()">
                    <option value="y" selected>Day</option>
                    <option value="1">1</option>
                    <option value="2">2</option>
                    <option value="3">3</option>
                    <option value="4">4</option>
                    <option value="5">5</option>
                    <option value="6">6</option>
                    <option value="7">7</option>
                    <option value="8">8</option>
                    <option value="9">9</option>
                    <option value="10">10</option>
                    <option value="11">11</option>
                    <option value="12">12</option>
                    <option value="13">13</option>
                    <option value="14">14</option>
                    <option value="15">15</option>
                    <option value="16">16</option>
                    <option value="17">17</option>
                    <option value="18">18</option>
                    <option value="19">19</option>
                    <option value="20">20</option>
                    <option value="21">21</option>
                    <option value="22">22</option>
                    <option value="23">23</option>
                    <option value="24">24</option>
                    <option value="25">25</option>
                    <option value="26">26</option>
                    <option value="27">27</option>
                    <option value="28">28</option>
                    <option value="29">29</option>
                    <option value="30">30</option>
                    <option value="31">31</option>
                </select>

                <input name="sign" size="12" value="??" /> <input type="button" value="submit" onClick="sunsign()">

</form>

Comment: @depperm fixed, wasn't sure how to.
Answer: I have this error :
GET http://trulydesigns.com/horoscope/assets/js/horoscope.js 404 (Not Found)

Ok now add to your html a div (where you want the result to be displayed) :

And modify your js and replace
document.form1.sign.value

by
document.getElementById('result').innerHTML

So you replace the line that put the result inside the input, and instead put it in a div.


Do smooth functions have fractional derivatives of all orders?

Question: Suppose $\nu > 0$ and $n$ is such that $\lceil\nu\rceil = n$. The Riemann-Liouville definition of the fractional derivative would be
$$f^{(\nu)}(x) = \frac{1}{\Gamma(1-\nu)}\frac{d^{n}}{dx^{n}}\int_0^x(x-t)^{n-\nu-1}f(t)\,dt.$$
Based on the Riemann-Liouville definition of the fractional derivative, it would seem to me that any smooth function has a fractional derivative of all orders but I am still somewhat skeptical of this. Is there an easy way to argue this? The differentiation under the integral sign seems a bit formidable.
Answer: Not exactly unless you re-define smooth:
Smooth functions are considered to be those function with continuous derivatives of all orders
I am not sure if the function necessarily must have its (integral) derivative exist at all points (correct me if i'm wrong)
but that can mean a function such as the classic
$$  \begin{pmatrix} \frac{2x^{\frac{1}{2}}}{\sqrt{\pi}} x \ge 0 \\ -\frac{2(-x)^{\frac{1}{2}}}{\sqrt{\pi}} x < 0\end{pmatrix}    $$
is smooth.
Since any integer derivative will also result in a function too (which will have singularities at the point 0 but these functions are still continuous!)
Interestingly if one takes a $\frac{3}{2}$ derivative of this function you will obtain the function 0 which will continue to be the function if you keep taking any sort of fractional derivative.
The lesson, a function can be smooth for all integral derivatives but not be smooth for all rational derivatives.
On the other hand smooth's original definition was "function with derivative of all orders" and I just assumed they meant integral since that was what was available at the time when the definition was made.
Now it could very well be that there was a specific reason for that ambiguity in the definition and that with this invention of the frational derivative it could mean smooth should also be smooth for fractional (And real) derivatives. It's not apparently clear if that was the intentionn
Comment: Interesting. My question is a little less well-posed than I thought since "existence" was pretty vague in my post. Existence would naturally mean that $f^{(\nu)}(x)$ exists for all $\nu > 0$ and $x\in\Bbb R$. Clearly smooth as most people know it is not sufficient. Taking $f(x) = x$ and $\nu = \frac{3}{2}$, we would get a function proportional to $x^{-1/2}$ and this is singular at $0$. This then makes me wonder how common it is for a fractional derivative of all orders to suggest. If even monomials fail, it might be that the only function that has derivative all orders is the zero function.
Comment: Maybe existence could be relaxed to being just in the almost everywhere sense which naively seems to work (at least for polynomials), but I wouldn't know how to appropriately incorporate measure-theoretic arguments into this. The appearance of the integral might be masking the almost everywhere behavior but this is something I'd have to think about for a while.


Storing a shapefile into postgresql using PHP

Question: I'm trying to develop a PHP script that lets users upload shapefiles to import to a postGIS database.
First of all, for the conversion part, AFAIK we can use shp2pgsql to convert the shapefile to a postgresql table; I was wondering if there is another way of doing the conversion, as I would prefer not to use the exec() command.
I would also appretiate any idea on storing the data in a way that does not require dozens of uniquenamed tables.
Comment: What is the cause for needing "dozens of unique named coloumns"? I don't see anything in base file structure that would require this in the data output. Also, why do you want to avoid exec/shellcmd/etc? Running an external compiled application to convert the data will be far more efficient than attempting to process the data with something like PHP, and there is nothing particularly wrong with doing so.
Comment: Can you be more specific about what a "shape" is? If it is a polygon having lines between a number of (x, y) nodes, then a table having `(x, y, ord)` columns will do the trick. The `ord` is to keep the coordinates in the right order, of course.
Comment: @halfer 'shapefile's are datasheets, containing a column with geometrical data.
Comment: @JacobS Sorry, my bad. I meant "tables"!
Answer: There seems to be no other way than using the postgresql's binary to convert the shapefile. Although it is not really a bad choice, I would rather not use exec() if there is a  PHP native function, or apache module to do it!
However, it sounds like exec is the only sane option available. So I'm going to use it.
No hard feelings! :)
About the last part, it's a different question and should be asked separately. Although, I'm afraid there is no other way of doing it.
UPDATE example added
$queries = shell_exec("shp2pgsql -s ".SRID." -c $shpfilpath $tblname")
                    or respond(false, "Error parsing the shapfile.");
pg_query($queries) or respond(false, "Query failed!");

SRID is a constant containing the "SRID"!
$shpfilpath is a path to the desired ShapeFile
$tblname is the desired name for the table
Comment: How exactly did you use it? Can you provide an example? Thanks
Answer: See this blog post about loading shapefiles using the PHP shapefile reader plugin from here.  http://www.phpclasses.org/package/1741-PHP-Read-vectorial-data-from-geographic-shape-files.html.  The blog post focuses on using PHP on the backend to load data for a Flash app, but you should be able to ignore the flash part and use the PHP portion for your needs.
Once you have the data loaded from the shapefile, you could convert the geometry to a WKT string and use ST_GeomFromText or other PostGIS functions to store in the database.
Regarding the unique columns for a shapefile, I've found that to be the most straightforward way to store ad-hoc shapefile attributes and then retrieve that data.  However, you could use a "tuple" system, and convert the attributes to strings, then store them in arbitrarily named columns (col1, col2, col3, etc.) if you don't care about attribute names or types.
If you cared about names and types, you could go one step further and store them as a shapefile "schema" in another table.
Answer:
Write your shp2pgsql and define its parameters using text editor ie
sublime notepad etc.
Copy, paste and change shapefile name for each
layer.
Save as a batch file .bat.
Pull up command window.
Pull up directory with where yu .bat file is saved.
Hit enter and itll run the code for all your shapefiles and they will be uploaded to the
database you defined in writing your code.
Use qgis, go to postgis window and hit connect.

You are good to go your shapefiles are now ready to go and can be added as layers to your map. Make sure the spatial reference matches what they were prior to running it. Does that make sense? I hope that helped its the quickest way.
Comment: Unfortunately not. As I mentioned, it's an script that enables the users of the website to upload their own shapefiles. Welcome to SOF though :)
Answer: Adding this answer just for the benefit of anyone who is looking for the same as the OP and does not want to rely on eval() nor external tools.
As of August 2019, you could use PHP Shapefile, a free and open source PHP library  I have been developing and maintaining for a few years that can read and write any ESRI Shapefile and convert it natively from/to WKT and GeoJSON, without any third party dependency.
Using my library, which provides WKT to use with PostGIS ST_GeomFromText() function and an array containing all the data to perform a simple INSERT, makes this task trivial, fast and secure, without the need of evil eval().


Clone a xorg session remotelly

Question: Does somebody knows how to clone/connect to a running xorg server to see in soft real time what is the monitor/display showing (The display is a couple of miles away but I can reach it throw TCP/IP)?
I have a small script to get a screenshot but is a bit limited.
#!/bin/bash
REMOTE_USER=root
IP=$1
IMAGE_FILE=/tmp/host_${IP}_`date +"%Y%m%d-%H:%M:%S"`.png
ssh root@$IP 'xwd -d :0 -root | gzip' | gunzip | convert - $IMAGE_FILE

I thought that it would be nice to see what the display is showing in soft real time, if possible of course. :)
Thanks in advance,
Humber
Answer: If you want to install x11vnc on the remote machine you can use it like this:
ssh remote_ip_address sudo x11vnc -auth /home/some_user/.Xauthority -display :0
Remember to have X11 Forwarding enabled in sshd.config. And you need a VNC client.
If you don't want to use VNC you can use any other program like Xnest:
Xnest -geometry 1024x768 :1& DISPLAY=:1 ssh -X  gnome-session
Will need some modification for you particular case, but for someone who is using xwd it shouldn't be a problem.
Comment: what?  x11vnc does not need to run as root.
Answer: I have this in bin/startvnc in my machines:
x11vnc -display :0 -localhost -nopw -clear_mods

If the box has other users on it remove the -nopw if you are paranoid about security.
I login with something like this:
ssh -C -L 5904:localhost:5900 box

and then run startvnc
then on my local machine run
xvncviewer 0:1

It's not as automated as a single command, but I'm always logged into a screen session anyway, so if I want to use vnc I just open a new screen window and run startvnc,
Comment: Thanks Justin.
"$ x11vnc -display :0 -nopw -clear_mods" at remote host after installing x11vnc and "$ vncviewer -compresslevel 9 -depth 24 -nocursorshape -quality 5 xxx.xxx.xxx.xxx" did the trick.
I didn't use ssh because both hosts are running over a VPN where only trusted hosts have valid certificates (I hope :D)
Answer: Maybe this is overkill for your particular case. But I'll post it anyway in case it's useful for other people coming to this question in the future.
Another way to attach to an X session is by setting up FreeNX on the machine that you wish to control remotely. Then on your local machine you must run the NX client, requesting a shadow session.
When the NX client connects to the remote machine, you'll be shown a list of available sessions. If you choose "X0 (Local)", you'll be able to see and control the remote display.
For more details you can take a look at Getting Started with NX (see section 4.5, "Desktop sharing and session shadowing")
Answer: Actually with some distribution like Opensuse 11.2, if you're going to use x11vnc then you're probably going to need to use an .Xauthority  file created for the login manager (gdm, kdm), instead of a file created for the user itself (something like /home/user/.Xauthority or so),  and you could find it in Opensuse, looking at:
/var/lib/xdm/authdir/authfiles/something-name-psedorandomly-generated

probably you should clean up this directory before trying to use the .Xauthority file (it will be a lot of previously created auth files for former X sessions), shutting down X and then restarting it, after that, you'll find a new file, the actual authorization to the new X session recently started.

If you are using other distro, you should probably look at /var/lib/gdm, /var/lib/kdm, and similar directories.

Clone a xorg session remotelly


Clarification- Complements of a normal Hall Subgroup are Conjugate

Question: While reading through "Permutation Groups" by Donald S. Passman, I came across a proof explaining why for a finite group $G$ with a normal Hall subgroup $H$, if we let $G/H$ be solvable, any two complements of $H$ are solvable. I understand up till defining a group $V=E \cap HU$ such that $V\mathrel{\unlhd}H$ and $V\cong U$.
I don't understand why we define $V$ in such a way. The proof is written below.
Let $G/H$ be solvable and let $B$ and $E$ be complements for $H$.  We show that $B$ and $E$ are conjugate by induction on $|G|$. Let $U$ be a minimal normal subgroup of $B$. Since $B \cong G/H$ is solvable, U is a $p$-group for some prime $p$.  Set $V=E \cap HU$ such that $V\mathrel{\unlhd}E$ and $V\cong U$. Clearly, $U$ and $V$ are Sylow $p$-subgroups of $HU$ and hence there exists $g \in HU$ with $V^g=U$. Thus $U\mathrel{\unlhd}B$ and $U\mathrel{\unlhd}E^g$, and both $B$ and $E^g$ are complements for $H \cap N$ in $N$, where $N=\mathfrak{N}(U)$. Since, $B/U$ and $E^g/U$ are complements for $(H \cap N)U/U$ in $N/U$ and $|N/U|<|G|$, induction implies that $B/U$ and $E^g/U$ are conjugate in $N/U$. Hence, $B$ and $E^g$ are conjugate in $G$ and the result follows. $\square$
Comment: Thank you @Shaun, I have now transcribed the proof in TeX instead.
Comment: Please don't rely on pictures of text. See [here](https://math.meta.stackexchange.com/a/34123/104041).
Comment: It should be $V \unlhd E$, not $V \unlhd H$. It is not clear to me what we are asking. We define $V$ that way, because that''s the way the proof works. If you don't understand the proof, then you need to say exactly which step you don't understand.
Comment: @DerekHolt, my confusion is stemming from not understanding the motivation behind $V$. While the following steps all make sense it seems like $V$ was "pulled out of thin air" and I would not be able to come up with this on my own.
Answer: The idea is that, since $G/H$ is soluble, one can work up a series for $G/H$ whose terms are elementary abelian $p$-groups for various primes $p$. So the outline is:

Choose $B$ and $E$ complements to $H$ in $G$. Show that, by replacing $E$ with a conjugate, $B\cap E$ can be made non-trivial (and in fact $B\cap E$ contains a non-trivial subgroup normal in both $B$ and $E$).

Since $G/H$ is soluble, the only thing we really have are minimal normal subgroups, so let $U\leq B$ be such. Now, take the image of $U$ in $G/H$, which is $HU/H$. We have that $G/H$ is isomorphic to $E$ as well, so choose $V\leq H$ such that the image of $V$ in $G/H$ is the same as the image of $U$. This is $V=E\cap HU$. Then we can conjugate $E$ by some element $g\in G$ so that $V^g=U$. Replace $E$ by $E^g$ and $E\cap B\geq U$.


Laravel 5.4 optimizing redirect 301

Question: I am creating some permanent redirects in laravel 5.4 and I want to know if this is the best way to do it and how to optimize this code. I saw in this answer Optimize Redirect 301 for a multilingual site an example in .htaccess but how to do the same in routes? and what is better, do it in routes or in .htaccess?
I've put this in routes:
Route::get('es/nosotros/quienes/quienes.php', function(){ return Redirect::to('quienes', 301); });
Route::get('en/nosotros/quienes/quienes.php', function(){ return Redirect::to('quienes', 301); });
Route::get('pt/nosotros/quienes/quienes.php', function(){ return Redirect::to('quienes', 301); });

Another question is that I have to redirect about 5,000 urls. As a final result, I'm going to get a file with the 5,000 old urls and the 5,000 new urls. Do I also include it in the routes file? In the .htaccess? Thanks.
Answer: Why not using a placeholder?
Route::get('{lang}/nosotros/quienes/quienes.php', function ($language) {
    return Redirect::to('quienes', 301)->with('language', $language);
});

The difference between routes and .htaccess is speed: the second one will not pass information to the application and the redirect answer will be received directly from the webserver (Apache). Server will thanks you!
Comment: Thanks Simone! I'm going to see how to optimize with the .htaccess the 5,000 urls ...

Laravel 5.4 optimizing redirect 301


What is the probability of excatly two out of three events happening?

Question: I'm started working on probabilities and now I'm facing two problems.
So I have 3 independent events, p1 = 0,90, p2 = 0,65, p3 = 0,90;
I calculated probability when all events occur: P(p1 ∩ p2 ∩ p3) = P(p1) * P(p2) * P(p3) = 0,9 * 0,65 * 0,9 = 0,5265;
Then I calculated probability when at least one event occurs: P(p1) + P(p2) + P(p3) - P(p1 ∩ p2) - P(p1 ∩ p3) - P(p2 ∩ p3) + P(p1 ∩ p2 ∩ p3) = 0,9 + 0,65 + 0,9 – 0,585 – 0,81 – 0,585 + 0,5265 = 0,9965;
Also I have calculated probability when none of the events occur - 0,0035
Now I need to calculate:

Probability when exactly two out of three events occur.
At least one event NOT happening.

Waiting for yours suggestions!
Comment: Welcome to MSE. For some basic information about writing mathematics at this site see, *e.g.*, [basic help on mathjax notation](/help/notation), [mathjax tutorial and quick reference](//math.meta.stackexchange.com/q/5020), [main meta site math tutorial](//meta.stackexchange.com/a/70559) and [equation editing how-to](//math.meta.stackexchange.com/q/1773).
Answer: Probability of first and second event occuring but third one not occuring is is $p_1p_2(1-p_3)$, that of second and third  events occuring but not the first one  is $p_2p_3(1-p_1)$  and that of first and third  events occuring but not the second one is  is $p_2p_3(1-p_2)$. Add these to get the probability of exactly two events occuring.
Probability of at least one event happening is just $1-(1-p_1)(1-p_2)(1-p_3)$.
Comment: @KarolisKazlauskas Telling you this since you're a new user: Please "accept" the answer if it indeed answers your question.
Comment: Thank you! But whats about when at least one event NOT happening?
Comment: @KarolisKazlauskas The probability that at least one event does not occur is $1$ minus the probability that all three events occur.
Comment: Thanks you for your helpful and fast answer! Have a nice day!
Comment: Have a look at probability trees. They are often useful to reveal all the possibilities for events in situations like yours and orient the computation of asked probabilities.


Is Wishart distance always positive?

Question: From what is told on page 268 of the Polarimetric Radar Imaging: From Basics To Applications:

I have written the following code for wishart distance calculation in Matlab:
<code>function distance = WishartDistance(Cm,Z)
    distance = log(det(Cm))+trace(Cm\Z);
end
</code>
But for matrices $C_m$ and $Z$ in the following:

I get the negative answer:
$$-8.2715$$
I want to see if the formula should be written as
$$d_3(Z,\omega_m)=|\ln|C_m|+\text{Tr}(C_m^{-1}Z)|$$
Or is an absolute value omitted in the book incorrectly?
Comment: Basically, I think the book's equation is correct, and it is OK that d_3 is negative, and the only problem is that calling it a "distance" rather than a "score" or something similar is a little confusing.
Comment: p. 2 of https://www.cv.tu-berlin.de/fileadmin/fg140/Clustering_by_deterministic.pdf : "In [1] a distance measure ... was developed based on the Wishart distribution.  Unfortunately this distance measure is not a metric, because it is neither homogeneous, nor symmetric and does not fullfill the triangle inequality."
Nonetheless this distance measure is often used and showed its effectiveness in practice. Because of this and its direct relation to the density function it will be also used in this work.
Comment: Just to be clear, the end quote in my comment should have been at the end of the comment. The claim "showed its effectiveness in practice" was made by the authors of the article I linked, not by me. I agree it's not a distance metric, despite its name. I have nothing to offer regarding its effectiveness.
Comment: I don't know this field at all, but I think that d is the log of a distance measure that's always positive. Look at the paragraph above Eq. 8.11 - they start with a measure based on the Wishart PDF (which is always positive), then they take the log to get the "distance" function. This isn't a distance in the sense of a distance metric, but I guess they just want to know whether distances increase or decrease to classify - so the log transform is fine.
Comment: so @MarkL.Stone it says that in spite of not being a real metric but it is effective and so the classification results should be good. But in my case, I get really incorrect classification results and I really don't understand why?
Comment: I would say that without seeing (8.12) we can only guess what is going on. So let me guess. This arises by taking log of (soething related to) a Wishart distribution. There are a bunch of other factors in a Wishart that the authors assume constant in the specific setup. This constants are dropped for simplicty, which may result in negative numbers. If you really want a thorough answer you should summarize the setup and not just copy paste an image from a book. After doing that, you might realize you know the answer yourself.
Answer: Can any sensible distance measure be negative? No.
Consider this. Can you have a distance that is closer than zero? If you do then what is the meaning of it?
The beginning of the page 268 from your book describes how they got the distance measure: it's based on the natural log of the probability density. The density is based on Wishart distribution. When a matrix Z is close to matrix C, the probability density is high, and this probability density is low when C is not similar to Z.
So, for low probabilities, the log will be negative, making your measure become negative too. Hence, this measure is not a good distance. Apparently, it's still good enough for the classifier that is used in this domain.
A good distance measure will have several properties including non-negativity and triangle inequality.
Comment: This does not really answer the question. If you have a different question, you can ask it by clicking [Ask Question](https://stats.stackexchange.com/questions/ask). You can also [add a bounty](https://stats.stackexchange.com/help/privileges/set-bounties) to draw more attention to this question. - [From Review](/review/low-quality-posts/161885)
Comment: I know it can't be but consider two matrices $A=\begin{bmatrix}0.75 & 0 & 0\\0 & 0.5 0\\0 & 0 & 0.25\end{bmatrix}$ and $B=\begin{bmatrix}0.5 & 0 & 0\\0 & 0.25 0\\0 & 0 & 0.125\end{bmatrix}$ both of them are positive definite. then surely we will have $|A|=0.09375$ and $\ln|A|=-2.3671$ and $A^{-1}B=\begin{bmatrix}0.66 & 0 & 0\\0 & 0.5 0\\0 & 0 & 0.5\end{bmatrix}$ and $\text{Tr}(A^{-1}B)=1.66$ and we will have $\ln|A|+\text{Tr}(A^{-1}B)=-2.3671+1.66=-0.7071\lt 0$. I mean it seems that either the formula in the book is incorrect or I am doing something wrong
Comment: @sepideh, the formula is correct **only** because it's the one used in this domain. They call thing thing a distance measure. I bet it's because it's not a sensible distance. It doesn't have any features of the distance, such as subadditivity. It's something that can be used in this classifier
Comment: @Ferdi this answers OP's question. I'm not sure yoy what you mean.
Comment: Perhaps edit your new example into the question?
Comment: In PolSAR the C is garunteed to be positive semi-definite and hermitian. With that constrain, this can be used as a distance measure.

Is Wishart distance always positive?


How to separate UI language from node's language?

Question: I have a site that uses 3 languages, namely English, Polish and Russian. And we have content editors with 3 native languages. Now, most of the times Russian guy will want Russian UI and will be editing Russian nodes. But sometimes he will need to correct nodes written in Polish. He will not want his UI to turn to Polish when doing that, of course.
Is there a way to allow users to select their default admin language? Desired effect for nodes is:

http://example.com/node/435 displayed in layout based on node's language (let's say, Polish)
http://example.com/en/node/435 redirected to proper language (here http://example.com/pl/node/435) - that's pretty much easy and was answered in many places.
http://example.com/node/435/edit should be opened in UI based on user's preference set in a profile field, for example, or redirected to proper language edit path like http://example.com/pl/node/435/edit
http://example.com/en/node/435/edit should be redirected to http://example.com/node/435/edit or http://example.com/pl/node/435/edit (consistent with previous point).

If possible, I want this globally, for all admin pages, not only node edits, but of course node edits will be most common = most important to me.
Comment: Have you checked the Admin Language module ? It seems to answer part of your question and specs and does have a 7.X release... It doesn't, however, allow different admin languages per user.
Comment: @mariomc actually that answers the part that wasn't easy to find and made me ask this question. Post it as an answer please, so I can check it accepted. Now I wonder how did I fail to find it?
Answer: I forgot this in my initial comment but you can actually solve this by installing Entity Translation!
It separates entity and interface translation. With both you can specify different language negotiation schemes. In admin/config/regional/language/configure simply set the user's language setting as the highest priority in the interface language negotiation queue.
By having URL as the first criteria and user preference in the content language negotiation queue you can attain this functionality you documented.


If pedaled, must I keep holding a key down?

Question: In the following passage from Chopin's second piano sonata, mvt.I, m.78,
If I insist holding down the half notes, the fingering is awkward, if still possible.
But since the pedal is clearly intended, and I do use it, why can I not release the whole notes just after playing them?
The dampers will not silence them due to presence of the pedal.
Such instances are abundant within this piece, and this is certainly not the first time I face the dilemma.
If I hold these key (gb4, db5, ab4, c5 in my case) down all the way as indicated, I feel I am more faithful to the original intention of the composer.
But if I release them, I play better and more comfortably.
And after all, what is the significance of holding these sustained notes (the half notes mentioned above)?
Answer: The half notes should sound their duration and form a line of their own.  The question is how to achieve this.  If you use the dampener pedal, all no longer struck notes will get finished in the same manner.
Now the shorter figures in the bass have their own character and are somewhat independent with their overlap and individual capacity of being cut off by unpedaling.  The other treble notes form melody lines where each sustained note is followed by an adjacent note, so the basic "attention" moves on.
That makes the question important just how you are going to end the sustain.  Letting the last note of the melody and bass lines stand out when unpedaling does not make sense, so the unpedaling action should be rather brief.
That means that your long notes are probably fine being held just with the pedal.  However, you want to let them keep some basic weight over the accumulating sustained notes, so it would be good if you manage to strike them more distinctly/louder than the simultaneously starting "shorter" notes that are actually sustained just as long.
So just to get a bit of a feeling for the long notes: if you have the skills required for holding the long notes while playing onward without needing to practice a lot, it may make some sense to try at first not pedalling at all and playing as written, just to get a hang of the voice leading you want to have more or less in the end.
It might also be possible to strike the long notes slightly before the shorter ones (so basically the reverse of the written order) to have them stand out with a slightly different point of articulation while not then interrupting the faster line.  You need to try it out to see whether this works in your desired speed and interpretation.
Basically when you record the result, it should sound like what was written: consider the score a hearing rather than a playing instruction.
Answer: I would advise not to hold the keys down.
You said "I feel I am more faithful to the original intention of the composer", but what was really his intention, physically holding down the notes, or making the notes sound during their duration? It's surely the second choice.
"And after all, what is the significance of holding these sustained notes?"
Those notes are certainly very significant. They create a different harmony, try playing without them and listen at how it sounds.
Answer: A note duration is not an instruction to physically hold the keys down for a length of time. It's an instruction to make the note sound for that long. There's no reason to keep holding the keys down, since you're pedaling.
Answer: There's no point in hanging on to those notes. That's what the pedal's for. If it's already held, then those notes will join the ones you've already held the pedal down after playing (but not let go till the pedal is deployed).
You could use the middle pedal, but there is no point.
Answer: In my opinion you should hold the keys down (at least for a while). But there are different points which influence the answer.

The written note duration is the maximum duration a note shall sound. In general a note is always a little shorter then it is written. Exceptions are, when the notes are under a legato bow.
It further seems that only one voice continuous in the next bar. Therefore, maybe the two notes do not need to have the same duration.
In Brahms edition, the half note ab4 is even missing.
This may already solve your problem.
Sometimes it is easier to connect long notes musically, if they are pressed down all of their time.
If Chopin wanted to have short notes, then he probably would have written a quarter note.
If Chopin wanted to have a short note, which is sustained by the pedal then he would have written a short note with exact pedal markings.
You could think about not to play the melody legato here. Legato is not necessary to connect notes under a legato bow.
The d int the Ab-chord does not sound good if it is sustained for the whole bar. At least I would hold the keys from the second two half notes down until the d does not sound anymore. And only then use the pedal.
Comment: In music there is never a single truth. That's why, I refrained from beeing more detailed. It is important, that you consider all of the points I wrote down (and probably 100 more). If you do so, and at the end you decide: "I don't hold the keys down, but rather use the pedal", then it will be totally right, and your interpretation will sound right.
But if you only spend one or two thoughts about the pedaling problem, and at the end you decide: "I don't hold the keys down, but rather use the pedal", then it will sound wrong.

To help you more, I totally agree with user41282.
Comment: I am not completely sure about what your stance is. You say one may release half notes, but some of your reasons seem to suggest otherwise.
Comment: Welcome to Music.SE and thanks for sharing your expertise! This a high-level answer which seems very helpful. It would help me (& Aminopterin) better understand your response if you could provide a single overarching recommendation about whether or not to hold each half note. When I read your current response, I see that some reasons conflict--certain reasons suggest to hold the half note, while others reasons suggest to release the half note. Could you additionally explain which of the reasons should receive the highest priority, & which of the reasons should receive the least consideration?


What are nullary connectives in propositional logic?

Question: Some sources include the symbols $\top$ and $\bot$ as elements of the alphabet for the formal language of propositional logic and call them nullary connectives, meaning they are logical connectives that take zero arguments. Though I've seen them being called logical constants as well.
I don't understand how I am supposed to think about them, how does a logical connective work that doesn't connect any statements?
Is $\top$ just always true and $\bot$ always false no matter what? If so, where's the distinction between those symbols (part of the formal language) and the (metalinguistic) concept of tautology/contradiction?
Why should one choose to include it in the language or not?
What especially trips me up is that wikipedia lists sets like $\{\rightarrow,\bot\}$ or $\{\nrightarrow,\top\}$ as functionally complete.
Sorry if the question is incoherent.
Comment: Well, they work exactly like the propostional symbols, except that for any interpration $\phi$, $\phi (\bot)=0$, and $\phi (\top)=1$.
Comment: Also there is no big deal about $\{\rightarrow,\bot\}$(for instance) being functionally complete, you can get $\neg a$ as $a\to\bot$ and $a\land b$ as $(a\to (b\to\bot )) \to \bot$ since $\land,\neg$ is functionally complete you may conclude.
Comment: Yes a constant truth-function
Answer: First of all, $\top$ and $\bot$ are special constants whose valuations are always set to true and false respectively. In other words, we always have $\models \top$ and $\models \neg \bot$.
It is, however, convenient to consider them as connectives ($0$-ary connectives, hence) when one is dealing with sets of connectives. One never writes the braces, but you can imagine eg $\top$ as an operator $\top ()$.
As to why $X :=\{\rightarrow,\bot\}$ and $Y := \{\nrightarrow,\top\}$ are functionally complete sets of connectives, it is enough to show that you can express the operators $\wedge$ and $\neg$. I leave you as an exercise to show that:

$\neg A \equiv A \rightarrow \bot$
$A \wedge B \equiv \big( A \rightarrow (B \rightarrow \bot) \big) \rightarrow \bot$ (with 1. that makes $X$ functionally complete)

(edited)

$\neg A \equiv \top \nrightarrow A$
$A \land B \equiv A \nrightarrow (\top \nrightarrow B)$ (with 3. that makes $Y$ functionally complete)
Comment: I did the exercise and tried to show functional completeness of those sets treating $\top$ and $\bot$ as propositional "variables" just like $A$ and $B$ except they're either just true or just false in the truth tables. However I got different results than you for 3. and 4. : $\neg A \equiv \top \nrightarrow A$ and $A \land B \equiv A \nrightarrow (\top \nrightarrow B)$ Is this correct?
Comment: @LinusDieLinse There isn't a unique solution indeed and yes you are correct, well done. Oh and by the way I made a mistake on point 3. and 4! I'll correct my answer using your suggestion. :-)
Comment: thank you! :) I understand $\top$ and $\bot$ as *constants*, but could you elaborate on how and why it is convenient to consider them as nullary *connectives*, and what a nullary connective is?
Comment: @LinusDieLinse It is convenient because you can speak of a "set of connectives instead of a "set with connectives and eventually some constants". That is really all there is to it.
Comment: @LinusDieLinse "What is a nullary connective?" Formally it is the unique function $\emptyset \mapsto \{a\}$ for some $a$.
Comment: @LinusDieLinse One reason to think of these as connectives is that a lot of the basic theorems about propositional logic are proved by induction on the structure of formulas, and so it's nice to avoid having a special case about constants in the definition of a formula.


Interpreting simple slopes in OLS regression with multiple interactions

Question: I dug through previous simple slope/effect questions and couldn't find what I was looking for, but happy to be pointed to it if it exists.
On p. 17 of Jaccard and Turrisi (2003), they offer the following basic example of a regression equation with a single interaction term:
$Y= a + β_1X+β_2Z+β_3XZ+ε$
They explain how to interpret the coefficients for X and Z thus (p. 24):

The coefficient for X estimates the effect of X on Y when Z is at a specific value, namely, when Z = 0. The coefficient for Z estimates the effect of Z on Y when X is at a specific value, namely, when X = 0.

These are simple slopes (or "simple effects" as J & T call them). This makes sense to me. However, I don't understand how to interpret the non-interaction coefficients in the following case, which adds W and XW as new predictors:
$Y= a + β_1X+β_2Z+β_3W+β_4XZ+β_5XW+ε$
When only one interaction term is present, it is straightforward to interpret $β_1$ and $β_2$. But in a model where X is present in two (or more) interaction terms, how is $β_1$ to be interpreted? Is it now the effect of X on Y when both Z and W = 0, or something else? I'm also guessing the interpretation of $β_2$ remains unchanged as Z only appears in one interaction.
Thanks in advance.
Reference
Jaccard, J., & Turrisi, R. (2003). Interaction effects in multiple regression (No. 72). Sage.
Answer: Algebraic Expression
We can just as easily reshape the linear equation you have below (I changed $a$ to $\beta_0$ for consistency in notation):
$$
y = \beta_0 + \beta_1{X} + \beta_2{Z} + \beta_3{W} + \beta_4{XZ} + \beta_5{XW} + \epsilon
$$
Into this congruent equation, re-expressed with $X$ as the conditional effect (see Aiken & West, 1991, p.13):
$$
y = (\beta_1 + \beta_4Z + \beta_5{W})X +  \beta_0 + \beta_2Z + \beta_3W + \epsilon
$$
You can then see that the intercept and individual main effects of $\beta_2Z$ and $\beta_3W$ are unchanged (and algebraically, neither is $\beta_1X$). The only parts that are not additive here are the products formed from $\beta_4XZ$ and $\beta_5XW$. We are only estimating the products of $X$ with $W$ and $Z$ explicitly for interactions. So to be explicit, the $XW$ here is an interaction, albeit a simple two-way interaction between $X$ and $W$. I assume here that three-way interactions have not been modeled in this equation, else it would be included as another coefficient.
The interpretation for this model is still the same. You set all the $\beta$ coefficients to zero, thereafter a change in one coefficient is conditional on all the rest being equal to zero. To find out what the effect of $X$ is on the outcome, we can just plug this into our earlier re-expressed equation like so, leaving only our $\beta_0$ and $\beta_1$ alone:
$$
y = (\beta_1 + 0 + 0)X +  \beta_0 + 0 + 0 + \epsilon
$$
Which simplifies to:
$$
y = \beta_0 + \beta_1{X} + \epsilon
$$
Simulated Example
Using your example above, we can simulate this directly in R, setting all of the mean and standard deviations to their defaults with $n = 1000$.
#### Simulate Data ####
set.seed(123)
n <- 1000
x <- rnorm(n)
y <- rnorm(n)
z <- rnorm(n)
w <- rnorm(n)

Then we can fit the data into a regression which explicitly models the main effects of $X$,$W$,and $Z$, along with the interactions with $X$.
#### Fit Data ####
fit <- lm(
  y ~ x + z + w + x:z + x:w
)
summary(fit)

The results can be shown below:
Call:
lm(formula = y ~ x + z + w + x:z + x:w)

Residuals:
    Min      1Q  Median      3Q     Max
-2.7916 -0.6280 -0.0261  0.6446  3.4334

Coefficients:
            Estimate Std. Error t value Pr(>|t|)
(Intercept) -0.01657    0.03105  -0.534   0.5937
x            0.02560    0.03073   0.833   0.4050
z            0.05043    0.03112   1.620   0.1055
w           -0.01367    0.03104  -0.440   0.6598
x:z         -0.05401    0.03003  -1.798   0.0724 .
x:w         -0.05447    0.03035  -1.795   0.0730 .
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Residual standard error: 0.9761 on 994 degrees of freedom
Multiple R-squared:  0.009623,  Adjusted R-squared:  0.004641
F-statistic: 1.932 on 5 and 994 DF,  p-value: 0.08655

Using the example I gave earlier, we can simply set $W$ and $Z$ to zero and $X$ to an arbitrary value of $2$. By creating new data, we simply fill this into our linear equation and use predict to see what it should come out as:
#### Create New Data ####
new.data <- data.frame(
  z = 0,
  w = 0,
  x = 2
)

#### Predict New Data ####
pred <- predict(fit,
        newdata = new.data)

The estimated value of the prediction is $0.03462692$. If we calculate our coefficients the same way we spoke about earlier, we should get the same result as the pred object (I have commented which of our $\beta$ coefficients go where in hash comments next to the R code, as by default R codes the coefficients by their sequential order):
#### Check if Predicted Outcome Matches Coefficients ####
pred == (
  fit$coefficients[1] # beta 0
  + (fit$coefficients[2] * 2) # beta 1
  + (fit$coefficients[3] * 0) # beta 2
  + (fit$coefficients[4] * 0) # beta 3
  + (fit$coefficients[5] * 0) # beta 4
  + (fit$coefficients[6] * 0) # beta 5
  )

By doing so, our prediction comes true:
   1
TRUE

Citation
Aiken, L. S., & West, S. G. (1991). Multiple regression: Testing and interpreting interactions. Sage Publications.
Comment: Yes you were correct.
Comment: Thanks for the detailed explanation! So I guess my initial interpretation was right?


Realizando update em vários registros para o mesmo ID

Question: Considere o seguinte cenário para o controle de informações sobre as licenças em um banco de dados
Produtos
1 - Solução x
2 - Solução y
3 - Solução z

Suponha que o Cliente tenha as 3 soluções
Tabela Licenças
| ID | CLIENTE_ID | PRODUTO_ID | DATA_VALIDADE_INICIAL | DATA_VALIDADE_FINAL |
| 1  | 11222      |     1      |    2015-01-01         |   2016-01-01        |
| 2  | 11222      |     2      |    2015-01-01         |   2016-01-01        |
| 3  | 11222      |     3      |    2015-01-01         |   2016-01-01        |

Meu objetivo e realizar atualização do prazo de licença de todos os produtos para um cliente especifico.
Inicialmente utilizei a seguinte instrução para realizar update de todas as licenças do cliente , veja :
UPDATE licenca
SET
data_validade_inicial= '2016-01-01 00:00:00',
data_validade_final= '2020-01-01 00:00:00'
WHERE cliente_id = 11222

Gostaria de aprimorar esta funcionalidade por exemplo caso o cliente deseje atualizar somente duas licenças em uma unica ação como posso implementar isso ?
Comment: Por "atualizar somente 2" devemos entender o produto 2 ?
Comment: atualizei a pergunta me desculpe
Answer: Parceiro, você precisará de um checkbox ao lado de cada registro na sua listagem, para marcar os registros que deseja alterar.
A sua instrução SQL ficará assim:
UPDATE licenca
SET data_validade_inicial= '2016-01-01 00:00:00',
    data_validade_final= '2020-01-01 00:00:00'
WHERE cliente_id = 11222 AND produto_id IN (1,3)

Nesse exemplo, será atualizado a validade dos produtos com id = 1 e id =3 do cliente = 11222.
Espero ter ajudado!
Comment: kk esses ferias me deixaram enferrujado pra caramba =x Muito obrigado !
Comment: @stringnome vlw
Answer: UPDATE licenca
SET data_validade_inicial= '2016-01-01 00:00:00',
    data_validade_final= '2020-01-01 00:00:00'
WHERE cliente_id = 11222
    AND produto_id in (1,3)

ou se quiser pelo nome do produto:
UPDATE lic
SET lic.data_validade_inicial= '2016-01-01 00:00:00',
    lic.data_validade_final= '2020-01-01 00:00:00'
FROM licenca lic
    INNER JOIN produto pr on lic.produto_id = pr.id
WHERE lic.cliente_id = 11222
    AND pr.nome in ('Solução x', 'Solução z')

Comment: Muito obrigado pela atenção @nuno


Importing nested XML using Feeds XPath Parser

Question: I have some XML formatted as such:
<item>
    <title>Name</title>
    <id>12</id>
    <upgrade>
        <id>13</id>
        <level>2</level>
    </upgrade>
    <upgrade>
        <id>14</id>
        <level>3</level>
    </upgrade>
</item>

Ultimately from this example I want 3 nodes:

Title: "Name (1)" GUID: 12
Title: "Name (2)" GUID: 13
Title: "Name (3)" GUID: 14

I'm quite happy to do 2 runs of the file if necessary. I have one importer at the moment which sets up the "Name (1)" items. This works perfectly.
I have a second importer set up which I can successfully create the secondary "upgrade" nodes but only if I use \item\upgrade as the context, at which point I lose the title element so the nodes come through as " (2)", " (3)" etc.
If I use \item as the context like the initial importer, I can't seem to loop through the upgrade XML nodes.
Answer: Answered on drupal.org
Import will need to be done using the context \\item\upgrade.
Then to target the title from the parent node, use ..\title.


What is the correct formulation of two consecutive yaw, pitch, roll, translation transformations?

Question: I want to project a 3D point using the rotation-translation matrix R:
$$R=\begin{pmatrix} \begin{matrix} { r }_{ 11 } & { r }_{ 12 } & { r }_{ 13 } & x \\ { r }_{ 21 } & { r }_{ 22 } & { r }_{ 23 } & y \\ { r }_{ 31 } & { r }_{ 32 } & { r }_{ 33 } & z \\ 0 & 0 & 0 & 1 \end{matrix} \end{pmatrix}$$
I need to do two transformations, both consisting of a composition of rotations (in this order: yaw, pitch roll) and a translation.
First transformation:

Rotate yaw, pitch, roll
Translate x, y, z

Second transformation with respect to the system that is obtained after the first transformation:

Rotate gamma, beta, alpha (yaw, pitch, roll with other values)
Translate a, b, c

Is this the correct way to do it?
$$\begin{pmatrix} { P }_{ x } \\ { P }_{ y } \\ { P }_{ z } \\ 1 \end{pmatrix}= \begin{pmatrix} \begin{matrix} { r }_{ 11 } & { r }_{ 12 } & { r }_{ 13 } & x \\ { r }_{ 21 } & { r }_{ 22 } & { r }_{ 23 } & y \\ { r }_{ 31 } & { r }_{ 32 } & { r }_{ 33 } & z \\ 0 & 0 & 0 & 1 \end{matrix} \end{pmatrix}\cdot\begin{pmatrix} \begin{matrix} { h }_{ 11 } & { h }_{ 12 } & { h }_{ 13 } & a \\ { h }_{ 21 } & { h }_{ 22 } & { h }_{ 23 } & b \\ { h }_{ 31 } & { h }_{ 32 } & { h }_{ 33 } & c \\ 0 & 0 & 0 & 1 \end{matrix} \end{pmatrix}\cdot\begin{pmatrix} { p }_{ x } \\ { p }_{ y } \\ { p }_{ z } \\ 1 \end{pmatrix}$$
where the $r_{ij}$ are the first three combined rotations, and the $h_{ij}$ are the second three combined rotations.
Answer: You can reason as follows: multiplying on the left some vector by a transformation matrix has the effect of rotating and translating the coordinate frame to which the point is "attached". If you multiply the result by another matrix on the left, you rotated and translate both the transformed frame and the attached point. The global effect is indeed the chaining of the two transformations, performed in the order $H$ then $R$.


how to add count column with join?

Question: i have run this query to join between two table and that was ok
SELECT
TaskName AS TaskStatusTitle,
COUNT(TblTask.UserID),
CreateDate,
UserID,
TblProfiles.FullName AS [User Full Name]
FROM Task.TblTask
RIGHT JOIN Users.TblProfiles
ON Task.TblTask.UserID=Users.TblProfiles.UserrId
GROUP BY UserID`

but then i added count to this query but i gave this error!
what should i do??
Column 'Task.TblTask.TaskName' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.
Comment: Are you using MySQLor MS SQL Server? Don't tag products not involved.
Comment: That GROUP BY is invalid. The general GROUP BY rule says: If a GROUP BY clause is specified, each column reference in the SELECT list must either identify a grouping column or be the argument of a set function!
Comment: Why RIGHT JOIN?!? Switch to LEFT JOIN instead, since most people find "main table left join optiona data" much easier to understand than "option data right join main table".
Comment: Can you please update this question to contain both the old query that ran correctly, and also the new query that doesn't work.
Answer: You need to add all the columns into the group by clause when using an aggregate function. Like this
SELECT
TaskName AS TaskStatusTitle,
COUNT(TblTask.UserID),
CreateDate,
UserID,
TblProfiles.FullName AS [User Full Name]
FROM Task.TblTask
RIGHT JOIN Users.TblProfiles
ON Task.TblTask.UserID=Users.TblProfiles.UserrId
GROUP BY
UserID,TaskName ,CreateDate,    TblProfiles.FullName

Answer: You will need every column, which you are selecting in group by clause.
SELECT
TaskName AS TaskStatusTitle,
COUNT(TblTask.UserID),
CreateDate,
UserID,
TblProfiles.FullName AS [User Full Name]
FROM Task.TblTask
RIGHT JOIN Users.TblProfiles
ON Task.TblTask.UserID=Users.TblProfiles.UserrId
GROUP BY UserID,TaskName,CreateDate,TblProfiles.FullName

Comment: Duplicate answer!!
Answer: When you are working on aggregate functions with group by clause, make sure that you have included all the columns into group by clause also.
Try this:
SELECT
TaskName AS TaskStatusTitle,
COUNT(TblTask.UserID),
CreateDate,
TblTask.UserID,
TblProfiles.FullName AS [User Full Name]
FROM Task.TblTask
RIGHT JOIN Users.TblProfiles
ON Task.TblTask.UserID=Users.TblProfiles.UserrId
GROUP BY TaskName,CreateDate,TblTask.UserID,TblProfiles.FullName;

Answer: SELECT DISTINCT
TaskName AS TaskStatusTitle,
COUNT(TblTask.UserID)OVER(PARTITION BY UserID) AS CNT ,
CreateDate,
UserID,
TblProfiles.FullName AS [User Full Name]
FROM Task.TblTask
RIGHT JOIN Users.TblProfiles
ON Task.TblTask.UserID=Users.TblProfiles.UserrId

how to add count column with join?


Spivak Calculus Ch. 19 #15

Question:
(a) Find $\int \sin^4 x\, dx$ in two different ways: first using the
  reduction formula and then using the formula for $\sin^2x$.
(b) Combine your answers to obtain an impressive trigonometric
  identity.

So, while working on part (a), the power reduction was straight forward enough:
$$\int \sin^4 x\, dx=\int \left(\frac{1-\cos(2x)}{2}\right)^2\, dx=\frac{1}{4}\int \frac{3}{2}-2\cos(2x)+\frac{1}{2}\cos(4x)\, dx$$
$$=\frac{1}{32}\sin(4x)-\frac{1}{4}\sin(2x)+\frac{3}{8}x+C.$$
However, I am unsure of what "formula for $\sin^2 x$" the author is referring to here. I initially thought he meant $\sin^2x=1-\cos^2x$, so I wrote
$$\sin^4 x=\sin^2x(1-\cos^2x)=\sin^2x-\frac{1}{4}\sin^2(2x),$$
and then power reduced those two integrals, but obtained the exact same result. The manipulation
$$\sin^4 x=(1-\cos^2x)^2=1-2\cos^2x+\cos^4x,$$
also ended up giving me the same answer after integration.
I'm assuming that I should arrive at some seemingly different solution for this integral, and then use the fact that the difference of the two expressions must be constant to derive the "impressive trigonometric identity," but I can't seem to find a method of integration that doesn't give an identical result. Any help is much appreciated.
Comment: Use the **reduction** formula again I guess.
Comment: But that doesn't give me the other expression I need for the identity?
Comment: By reduction formaula I mean this one: http://math.stackexchange.com/questions/383478/how-can-i-develop-a-reduction-formula-for-int-sinn-d-x-in-1-step-jumps
Comment: You could use integration by parts.
Comment: Ahhh, I confused power reduction with the trick of reducing the power in the integrand with integration by parts. Thanks!
Answer: I think that the formula for $\sin^2x$ is the one you used the first time and by "reduction formula", the author means that you should integrate by parts:
$$\int\sin^n\mathrm dx = -\cos x\sin^{n-1} x + (n-1)\int\cos^2x\sin^{n-2}x\mathrm dx$$
I think the above is mostly right although I'm not sure it's absolutely correct

Spivak Calculus Ch. 19 #15


when to use include (inc) files in module development

Question: I think I understand the structural differences of a .inc file (compared to a .module), but could someone describe the design differences?  I see drupal example modules calling an .inc file with hook_menu, or I see call .inc file for function defintions.

Under what circumstances does one put code in a .inc file?  Any general design guidlines that some adhere to?
Is there any advantage other than clarity as to why one would use an (or multiple) .inc file? performance? versioning?

thanks!
Comment: personally, if i have a mod that supports multiple urls or whatever, i use a `.inc` per url. just organization i guess instead of dumping random functions into one large `.module` file. but as @Clive's post references, its really just personal opinion or what you are used to. no right or wrong here.
Comment: You can't get a better explanation than the accepted answer to [this question](http://stackoverflow.com/questions/7129842/what-is-inc-and-why-to-use-it) in my opinion :)
Comment: indeed, I have used modulename.preprocess.inc, modulename.node.inc, modulename.menu.inc etc to break up large modules into reasonable chunks of related functions, but the only real reason from any performance standpoint to use them outside of development organization is probably if your module has some rather large functions that are rarely called that you don't want your php engine to parse each time it's loaded.  you could then bring them in when needed, much like how things are done with menu callback includes.
Comment: For what it's worth I group my hook implementations and helper functions and categorize their doc blocks using an appropriate naming convention (in CAPITALS). So as I scroll through my module's code I can see separation between the different groups of functionality. I looked in the commenting standards to see if a system already existed, but I could see one.
Answer: As general rule, I would put in the module file the code that is required more often (e.g. helper functions used from more than one function), and in .inc files the code that is not used so often, or that is used for specific pages.
Since Drupal 6, the code automatically loads the files containing the page callbacks, or the form builders used for the menu items. For that reason, page callbacks for administrative pages are normally put on .admin.inc files, while page callback for normal pages are put on .pages.inc files.
Since Drupal 7, files containing classes are automatically loaded when a class is instantiated. Drupal 7 allows modules to define in which files their hooks are defined (through hook_hook_info()). For example, system_hook_info() defines the .tokens.inc files as files where hook_token_info(), hook_token_info_alter(), hook_tokens(), and hook_tokens_alter() implementations can be found; in this way, those files are automatically loaded when one of those hooks are required.
This allows to further split the code in files that are loaded when necessary, and code that is always loaded from Drupal.


YUI events don't seem to work recursively

Question: I ran across a piece of legacy YUI3 plugin code that was trying to inject itself into an event-based flow. Basically, the code would subscribe to an event X and, in the handler, do something like the following:
if (!this._hasDoneStuff) {
    doStuff();
    event.preventDefault();
    fire("theEvent", newEvent);
}

The preventDefault() call didn't seem to be working; the event continued as normal. I managed to replicate this with a small example:
        var eidCounter = 0;
        this.publish("myEvent", {
            defaultFn: function (myEvent) {
                console.log("default function hit by event " + myEvent.eid);
            },
            context: this
        });
        this.on("myEvent", function (myEvent) {
            console.log("saw & prevented " + myEvent.eid);
            myEvent.preventDefault();
            if (myEvent.eid < 3) {
                this.fire("myEvent", { eid: eidCounter++ });
            } else {
                console.log("stopped " + mikeEvent.eid);
            }
        }, this);
        this.fire("myEvent", { eid: eidCounter++ });

I would expect this to NEVER run the default function, because preventDefault() is always called. However, the actual output is:

saw & prevented 0
saw & prevented 1
saw & prevented 2
saw & prevented 3
stopped 3
default function hit by event 2
default function hit by event 1
default function hit by event 0

Thus, the preventDefault() only seems to work on the last event in the stack. This seems like a bug, but am I actually violating some part of the event API? Is there a workaround?
Answer: Unfortunately, YUI has always worked this way. Despite the fact that it seems odd to fire the subscribed event from the subscription, it does seem like a bug. You can file it here: https://github.com/yui/yui3/issues


Is a sequential limit of homeomorphisms a homeomorphism?

Question: Suppose that we have a diagram in the category Top of the following form
$$
\cdots X_2 \to X_1 \to X_0=X
$$
where the arrows are homeomorphisms. Is it true that that the natural morphism $lim_i  X_i \to X$ is a homeomorphism?
It certainly seems like it should be to me, but my intuition sometimes isn't great in these things.
The reason why I am worrying about this is that I wish to show that the infinite barycentric subdivision of a CW complex is homeomorphic to the original complex. Thanks a million in advance for your help!
Answer: Yes.
Simply show that $X$ satisfies the universal property of being the  limit.
Answer: Yes. The inverse limit $X' = \lim\{X_i, p_i : X_{i+1} \to X_i\}$ comes along with a family of maps $p'_i : X' \to X_i$ such that the universal property of the inverse limit is satisfied (see e.g. https://en.wikipedia.org/wiki/Inverse_limit).
In your case take $X' = X = X_0$ and $p'_i = p_{i-1}^{-1} \circ \ldots \circ p_0^{-1}$ and verify that the universal property is satisfied.
In your question you also ask for the "infinite barycentric subdivision of a CW-complex". I have never heard about the barycentric subdivision of a CW-complex. Usually this only applies to simplicial complexes. But even in that case I have no idea what an "infinite barycentric subdivision" should be. You can form the $n$-th barycentric subdivision for each $n$, but you cannot get something like an $\infty$-th barycentric subdivision. All simplices of such a space would have mesh $0$, i.e. would be points.
Comment: Surely you can take the sequential limit of ... -->sd^n(X)-> ...sd(X) -> X?
Comment: Yes, you can do that. But as a topological space the result is $X$ itself and it does not have the structure of a "simplicial complex with infinitely small simplices".
Comment: I wanted to carry out this construction in the category of simplicial sets. I was worried that the realization of sd^oo(X) would be the completion of the realization of X and thus have the wrong homotopy type, but I think that your response shows that this is not the case.


What's the purpose of a sound post?

Question: Almost all bowed string instruments have a sound post. It is said that this adds stability to the instrument and also "transmits vibrations to the bottom".
Interestingly though, guitars do not have such a thing – neither flat-top acoustic guitars nor the more violin-resembling archtop ones. So apparently a sound post isn't really necessary for a stable, well-sounding string instruments.
Yet it seems vital for violin / viola / cello / double bass. Why is this?
Answer: The crucial difference in this regard, between guitars and bowed strings, is in which direction the strings vibrate. A bow causes vibration in the plane you're moving (it moves the string by friction: the string sticks on the rosin and is "dragged along" some way; perpendicular vibrations are strongly damped by the bow-hair). Because you can't vary the bowing angle a lot, this roughly means the vibration is along the top.
A plucked string has no such restriction, it can in principle vibrate in any direction – at first in the direction you've plucked, which tends to be both down and sidewards; but afterwards the plane of vibration can move, there might even be circular oscillation. However, the transversal components often decay a bit faster, because the string can "slip" quite well on the metal frets and thus loose energy in friction, whereas vertical movement is completely prevented (unless you don't press down strong enough).

The vertical movement in the guitar is, in a way, much easier to exploit: simply put in a few supporting bars, then the entire top will vibrate coherently  with the string and emit a lot of volume. With transversal movement this wouldn't work nearly as well: the top would merely "slide around", but this doesn't excite a lot of air movement, which is one of the reasons it sounds rather poor when you try to play guitar with a bow.
String instruments take for this reason another approach. First to note, the much higher bridge. This acts as a lever. The instrument's interior is also built quite differently: we can to first approximation describe the sound post as a rigid fulcrum, whereas the bass bar supports the top but in particular also picks up the bridge's vibrations and distributes them over the top, much like the bars in a guitar.

So that's the purpose of a sound post: it makes sure the body vibrates in a way that's actually useful, despite the string vibrations being in a somewhat badly suited direction.

If we look at it a bit more closely, the sound post is in fact not quite such a rigid support. It sure does transmit some energy to the bottom. But this is more of a side effect; the bottom does by design not spread sound as well as the top. Also, note that the bottom will vibrate with opposite phase (whenever the top goes down, the bottom goes up). That's really important for a full sound – it allows the instrument to "pump" the air, like a balloon inflating and deflating. If bottom and top were completely in phase, it would be just like a single sheet vibrating, which can only send out a little dipole radiation – not very efficient, in particular at low frequencies; the instrument would sound very thin.
What a sound post does not do (though some people will tell you so) is "transmit the high notes to the instrument bottom, while the low notes are amplified by the top". You can actually turn around the strings† and it doesn't sound dramatically different, because the bridges fulcrum-action works more or less the same from both directions.

†In fact, some left-handed players use right-handed instruments with inverted strings (if they don't, like most do, just play like a right-handed person). There are a few problems with this, but the sound post isn't actually the biggest (the asymmetric finger board is rather more obstructive). In fact, a classical guitar will suffer more, sound-wise, from turning around the strings than a violin does, because in a guitar it is the vertical motion that's directly used on each side of the bridge.
Comment: I'm a little confused by the last part.  If the sound post is transmitting the vibrations, then the bottom will be in phase with the top (well, it will be off by the time it takes to propagate through the post, but close enough).  In the absence of a sound post I could see the air movement causing the phases to be opposite ... but not both.  Maybe something to do with the post being off-center, but intuitively I am not sure how the interior volume could change with that setup.
Comment: @MatthewRead: the bottom will be in phase with a small spot on top: where the energy is passed from the "treble" leg of the bridge to the sound post. A much larger part of the top is however in phase with the other leg, because a) it's not fixed by the sound post and b) the bass bar readily distributes the vibration over a large area, more quickly than the thin wood alone on the other side.
Comment: I've heard that having a sound post is also essential for tuning the wolf tones.
Comment: @luserdroog: well... yeah. But this is a bit like saying "the engine is essential for tuning the weight distribution of a car": it does have a great influence on the weight distribution, but obviously that's not the reason we put engines in cars.
Comment: [Jim Woodhouse](http://www2.eng.cam.ac.uk/~jw12/) sometimes gives talks at science festivals etc. to open up his group's research work on bowed instruments to a general audience. One of the things he does is to dislodge the sound post while a violinist plays. As you can guess from [leftroundabout's wonderful answer](http://music.stackexchange.com/a/23614/2125) the effect is dramatic - the sound drops off immediately.
Comment: This answer is full of speculative hypotheses without any evidence that they've been tested experimentally.  The assertion about the instrument body "pumping" air is particularly dubious, especially in light of the fact that a vibrating plate will have some nodes moving up while others move down, implying that the volume enclosed by an instrument body remains constant.  Without reference to actual measurements, this answer is no better than an answer saying "the sound post transmits high notes to the bottom."
Comment: @phoog and that's why a vibrating plate is really bad at transmitting low frequency sound, specifically anything with a wavelength (in air) larger than the plate / instrument body won't make it out of the near field. But clearly all the string instruments are designed to produce tones lower than that wavelength (violin 36 cm ~ 915 Hz, G3 = 196 Hz). Ok, you can get away with omitting the fundamental at the low end, but at least the lower overtones must be present lest you get only a horrible squeaky rasp. So the instrument _must_ pump air to be usable in the lower register. ...
Comment: ...Now, for the higher registers yes, there the vibration modes get much more complicated and the sound post doesn't serve such a clear role anymore. In that regime the response is very hard to control by design details and more dependent on material properties. But it's definitely just wrong to say the sound post transmits the high notes to the bottom, they will be transmitted both by the top and bottom just as the low notes are, though not as orderly and with clear opposite phase.
Answer: The sound of a  bowed instrument (violin family) is not the sound of the vibrating string but the vibrating wood it activates through the bridge. The high notes come from the wood between the treble foot of the bridge and the top of the sound post. That is why you get no sound if the sound post is directly under the foot the bridge. It also is why the sound the high notes mellows as the sound post is moved away from the foot of the bridge. The bass bar helps the bass foot of the bridge to activate the entire top of the instrument to produce bass notes. The f-holes create between them a central area of the top activated by both feet to produce midrange pitches. Tweeter, Woofer, Midrange. With a guitar you hear the sound of the vibrating string amplified by the sound box. That is why bowing a guitar does not produce a sound like violin family instruments.
Comment: Not true.  If the soundpost is placed directly under the foot of the bridge, you will still get a sound, albeit a rather cramped one.  Try it yourself.

What's the purpose of a sound post?


combine multiindex dataframe with Int64Index dataframe

Question: i have one dataframe with multiindex
result =
MultiIndex([(1, 'HK_MN001'),
            (2, 'HK_MN001'),
            (3, 'HK_MN002'),
            (4, 'HK_MN003'),
            (5, 'HK_MN004'),
            (6, 'HK_MN005'),
            (7, 'HK_MN005'),
            (8, 'HK_MN005')],
           names=['ID1', 'ID2'])

Another dataframe with index:
photo_df:
Int64Index([1, 2, 3, 4, 5, 6, 7, 8], dtype='int64', name='ID1')

I want to concatenate both the dataframes but it gives me error:
Code:
result = pd.concat([result,photo_df], axis = 1,sort=False)

error:
"Can only union MultiIndex with MultiIndex or Index of tuples, "

NotImplementedError: Can only union MultiIndex with MultiIndex or Index of tuples, try mi.to_flat_index().union(other) instead.

Result Dataframe is:

photo_df dataframe is:
   PhotoID                          raw_photo
0        1  HK_MN001_DSC_2160_161014Ushio.JPG
1        2  HK_MN001_DSC_2308_161014Ushio.JPG
2        3  HK_MN002_DSC_2327_161014Ushio.JPG
3        4  HK_MN003_DSC_1474_181015Ushio.jpg
4        5  HK_MN004_DSC_1491_181015Ushio.jpg
5        6  HK_MN005_DSC_1506_181015Ushio.JPG
6        7  HK_MN005_DSC_1527_181015Ushio.JPG
7        8  HK_MN005_DSC_1528_181015Ushio.jpg

Required Output dataframe:(If possible drop the index = Id1)
Answer: I think you need in both DataFrames create MultiIndex:
photo_df = photo_df.set_index('PhotoID', drop=False)
photo_df.columns = pd.MultiIndex.from_product([photo_df.columns, ['']])
print (photo_df)
        PhotoID                          raw_photo

PhotoID
1             1  HK_MN001_DSC_2160_161014Ushio.JPG
2             2  HK_MN001_DSC_2308_161014Ushio.JPG
3             3  HK_MN002_DSC_2327_161014Ushio.JPG
4             4  HK_MN003_DSC_1474_181015Ushio.jpg
5             5  HK_MN004_DSC_1491_181015Ushio.jpg
6             6  HK_MN005_DSC_1506_181015Ushio.JPG
7             7  HK_MN005_DSC_1527_181015Ushio.JPG
8             8  HK_MN005_DSC_1528_181015Ushio.jpg

#second level ID2 is column
result = pd.concat([result.reset_index(level=1),photo_df], axis = 1,sort=False)

Comment: @KrupaliMistry - hmmm, is possible see how looks `result` and `photo_df` sample data?
Comment: can I convert from multi index dataframe to single index dataframe? Like the index should be ID2
Comment: @KrupaliMistry - Do you think last paragraph solution?


Using RemoteFX without Remote Desktop Services

Question: I manage a Windows Server 2008 R2 SP1 server and I would like to enable RemoteFX for my Windows 7 SP1 client.
As I'm a single user on my server, I don't want to setup optional Remote Desktop Services role. I just use Remote Desktop Connection from Computer's properties.
Is it possible to enable RemoteFX this way? Thanks.
Answer: You can just setup the VM to use the RemoteFX adapter, but you still have to install the RemoteFX components from the remote desktop services role (and of course use W7 Ent/Ult as the VM OS)
However you can then simply RDP direct to the VM's IP.
This brings the licensing issue out - in that because RemoteFX is part of the Remote Desktop Services you still require RDL's to use a RemoteFX enabled VM.


Find XP client DNS settings in the registry?

Question: I'm troubleshooting an issue and I need to find where client XP machines store their DNS information. I have a server with 3 NICs. 1 one of them has DNS information and two of them are in a private network not using DNS.
It appears to be NameServer entry under System\CurrentControlSet\Services\TCPip\parameters\Interfaces\guid. Anywhere else that info would be found?
Answer: that's the place.
Answer: That's the place, unless the DNS have been set by group policy.  In that case, it will be at HKEY_LOCAL_MACHINE\SOFTWARE\Policies\Microsoft\Windows NT\DNSclient or similar.  In fact, ipconfig will only show the addresses set at System\CurrentControlSet\Services\TCPip\parameters\Interfaces\guid., but any group policy DNS addresses will override them.
Answer: If the problem continues check that default domain policy does not have dns servers setting enabled. its under Computer conf. > policies > admin templates > network > DNS Client


why the curve for smoothing term different?

Question:
According to what i had read,that  An edf of 2 is equivalent to a quadratic curve, but my plot does not look like quadratic curve. i want to know the reason. This the link for that i refer to https://noamross.github.io/gams-in-r-course/chapter2

I wanted to add another question, what make plot curve in fb.ratio different from SOM even when both had edf=2?
It is because of the distribution for observation data point in fb.ratio more disperse while SOM observation more collected in group?
Comment: Please don't edit questions to *add* new questions. It's better to have a single question per thread, and substantial edits to the question will invalidate existing answers. Instead. please ask a new self-contained question. (Do feel free to link here from the new question, and from this one to the new one, to provide context.)
Answer: Your plot looks quite quadratic to me.
It's all a question of scaling the vertical axis. Here are two plots of $y=x^2$. In the left one, the $y$ axis is scaled so the curve fills the vertical space, in the right one the $y$ axis is scaled (and the $x$ axis is truncated) to give something similar to your data - but both plots show the same parabola:

R code:
<code>xx <- seq(-1,1,.0001)
yy <- xx^2
opar <- par(mfrow=c(1,2))
plot(xx,yy,type="l",xlab="",ylab="",las=1)
plot(xx,yy,type="l",xlab="",ylab="",las=1,xlim=c(-.5,1), ylim=c(-5,7))
</code>


Python3 Multiprocessing os.fork operates on the same resource?

Question: import os
a=[]
pid=os.fork()
if(pid!=0):
    a.append(1)
    print("Original: ", end='')
    print(a,id(a))
else:
    a.append(2)
    print("Child: ", end='')
    print(a,id(a))

# Result:
# Original: [1] 139725666412296
# Child: [2] 139725666412296

1. Why the parent and the child process share the same resource id?
2. If they share the same id, after I appended 2 to the list, why child process didn't print out 2?
3.
I then printed out (in a new Jupyter notebook code block) what lst contains now after executing the above code block. It prints: [1]. If the parent process executes first and child process executes last, why lst isn't [1,2]?
Comment: ID distinctness guarantees only apply within a single process. Equal IDs in separate processes mean nothing.
Answer: [Partial answer: I address your questions 1 and 2 but not 3.]
fork can be thought of as producing a process that starts with a copy of the parent process memory but then the two can be separately modified so the contents can diverge after the initial copy.  In fact for efficiency it is implemented as copy-on-write, so that any copying only takes place if and when memory pages are actually modified, but this fact should not affect the concept of it being a copy.
This means that, to answer your questions 1 and 2, the ID of the object is the same because it was created before the fork, but the assignments done after the fork will not be visible in the other process.  In any case, you have no control here over the timings of the execution in the parent and child process (but even if the timing varied, the results of each would not be affected, only possibly the order in which they were collated).


Should I implement GC.SupressFinalize on IDisposable AND Finalize?

Question: The code review checklist in my new client place has the following -

Class implementing Dispose and Finalize should have a call to GC.SupressFinalize in Dispose implementation

Why?
Should it not read as Class implementing IDisposable interface should have a call to GC.SupressFinalize in the Dispose implementation?
Or Am I missing something silly?
Answer: You're missing the fact that not every disposable class needs a finalizer - in fact, very few do, particularly due to .NET 2.0's SafeHandle type. If there's no finalizer, why would you need to call SuppressFinalize?
Answer: It's accurate.  If the Dispose(bool) method did its job then there is no longer any point to let the finalizer do it again.  Calling GC.SuppressFinalize() is an optimization, you stop .NET from bothering to call a finalizer that does nothing.
I noticed that you wrote Class with a capital C.  That's a hint that you are writing your code in VB.NET.  Watch out, the IDE does the wrong thing in 99.99% of all cases.  As soon as you press Enter after typing "Implements IDisposable", it inserts the wrong code:
    Private disposedValue As Boolean = False        ' To detect redundant calls

    ' IDisposable
    Protected Overridable Sub Dispose(ByVal disposing As Boolean)
        If Not Me.disposedValue Then
            If disposing Then
                ' TODO: free other state (managed objects).
            End If

            ' TODO: free your own state (unmanaged objects).
            ' TODO: set large fields to null.
        End If
        Me.disposedValue = True
    End Sub

#Region " IDisposable Support "
    ' This code added by Visual Basic to correctly implement the disposable pattern.
    Public Sub Dispose() Implements IDisposable.Dispose
        ' Do not change this code.  Put cleanup code in Dispose(ByVal disposing As Boolean) above.
        Dispose(True)
        GC.SuppressFinalize(Me)
    End Sub
#End Region

Yuck.  That's the boilerplate implementation of a finalizer, well documented in the MSDN Library btw.  It's wrong.  It is extremely rare to actually need a finalizer, the .NET classes already take care of it themselves.  If you really do use an operating system handle then you should use one of the SafeHandle derived classes.  Or write your own wrapper.
Edit it back to this:
Public Sub Dispose() Implements IDisposable.Dispose
    someField.Dispose()
    '' maybe some more
    ''...
End Sub