Can we solve $\frac{\cos x \sin x+\cos y \sin y}{\cos x+\sin y}$ further?

Question: I was solving a mechanics question in physics, where I came across the following expression which I am not able to evaluate.
How to evaluate this:
$$\frac{\cos x \sin x+\cos y \sin y}{\cos x+\sin y}$$
Help would be genuinely appreciated. Thanks.

I know it is not a very well-framed question, but I have no approach. Sorry.
Comment: Write \sin and \cos insted of just cos and sin and then you do not need to put those extra spaces there. I corrected it for you this time.
Comment: What do you mean by *I am not able to evaluate*? If $x,y$ are given, you're perfectly able to evaluate that quantity. What are you willing to do with it?
Comment: Why do you want to evaluate this further? What are you trying to achieve? It's very vague otherwise, like shooting arrows in the air.
Comment: @Phymathechem And why do you want to do so? What's your ultimate goal?
Comment: Is there a specific trigonometric identity for the question, like we have $$\sin(a+b) = \sin a \cos b + \cos a \sin b $$ Basically I want to reduce the equation into something that looks more concise.
Answer: Your expression is equivalent to
$$\frac{\sin 2x+\sin 2y}{2(\cos x+\sin y)}.$$
There's little more that you can say.
Comment: It should be $\sin y$ in the denominator instead of $\sin x$.
Comment: Can you edit and add the steps and identities you used please
Comment: @mag Yep. In any case the formula is ugly :-)
Answer: $$\cfrac{\cos x \sin x+\cos y \sin y}{\cos x+\sin y}=\cfrac{\frac 12[\sin (2x)+ \sin (2y)]}{\cos x+\sin y}=\dfrac{1}{2(\cos x+\sin y)}\left[2\sin\frac{2x+2y}{2}\cos\frac{2x-2y}{2}\right]=\dfrac{\sin (x+y)\cos (x-y)}{\cos x+\sin y}$$
Formulae: $$\sin\: x\cdot \cos\:y=\frac{1}{2}[\sin(x+y)+\sin(x-y)]\\\sin\: x+\sin\: y=2\sin\frac{x+y}{2}\cos\frac{x-y}{2}$$


Getting "Unable to complete authentication for user due to looping logins" while making an api call through postman to azure

Question: I am trying to fetch ticket using azure api, but it's showing "Unable to complete authentication for user due to looping logins" while making an api call, i have passed proper Authorization header and provided correct personal access token in base64 encoded.(see fig)
I am using GET https://dev.azure.com/{organization}/{project}/_apis/wit/workitems/{id}?api-version=1.0 for making an api call.
link: https://learn.microsoft.com/en-us/rest/api/azure/devops/wit/work-items/get-work-item?view=azure-devops-rest-6.0
am i missing something? Looking for suggestion.
Answer: On Postman, to execute RESI API using PAT (Personal Access Token) as the authentication, you should set on Authorization tab, instead of directly on the Headers tab.
Answer: The personal access token may not have enough scope. Try changing the scope of token
Comment: As it's currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer).


Repeated elements in regexes of literals with alternation in Perl 6

Question:
What is the best way to treat repetitions in regexes like abc | cde | abc | cde | cde | abc or <regex1> | <regex2> | <regex3> | <regex4> | <regex5> | <regex6>, where many of regexN will be the same literals?
To explain what I mean, I'll give an example from German. Here is a sample grammar that can parse several Present tense verbal forms.
grammar Verb {
    token TOP {
        <base>
        <ending>
    }
    token base {
        geh   |
        spiel |
        mach
    }
    token ending {
        e     |  # 1sg
        st    |  # 2sg
        t     |  # 3sg
        en    |  # 1pl
        t     |  # 2pl
        en       # 3pl
    }
}

my @verbs = <gehe spielst machen>;
for @verbs -> $verb {
  my $match = Verb.parse($verb);
  say $match;
}

Endings for 1pl and 3pl (en) are the same, but for the sake of clarity it's more convenient to put them both into the token (in my real-life data inflexional paradigms are much more complex, and it's easy to get lost). The token ending works as expected, but I understand that if I put en only once, the program would work a bit faster (I've made tests with regexes consisting of many such repeated elements, and yes, the performance suffers greatly). With my data, there are lots of such repetitions, so I wonder what is the best way to treat them?
Of course, I could put the endings in an array outside the grammar, make this array .unique and then just pass the values:
my @endings = < ... >;
@endings .= unique;
...
token ending { @endings }

But taking data out of the grammar will make it less clear. Also, in some cases it might be necessary to make each ending a separate token (token ending {<ending_1sg> | <ending_2sg> ... <ending_3pl>}, which would be impossible if they are defined outside the grammar.
Answer: If I understand you, for the sake of clarity, you want to repeat regex terms with a comment that describes which notes it's a separate concept? Just comment the line out.
By the way, since empty regexes are ignored in this case, it's okay to begin the line with your branch operator, instead of putting it at the end. It makes things easier, especially when you need to add and remove lines. So I suggest something like this:
grammar Verb {
    # ...
    token ending {
        | e       # 1sg
        | st      # 2sg
        | t       # 3sg
        | en      # 1pl
        #| t       # 2pl
        #| en      # 3pl
    }
}

Because what you're writing is exclusively for the human, not for the parser. Now, if you wanted to use the different regexes to go into different parse matches so you could access the ending as either $<_3sg> or $<_2p1> (named regexes so both would succeed), you can't comment it out, and you're gonna have to force the computer to do the extra work. And obviously you'll need to use :exhaustive or :overlap. Instead, I would suggest you make a named regex that represents both 3sg and 2p1, and define it like I did above: write them both but comment one out.
Comment: ① having dozens of different endings, it's very difficult to remember, which of them are unique and which are duplicate, and manually commenting/uncommenting many lines is inevitably prone to errors. ② If my conditions change slightly (say, I want to add or remove several endings, or to modify some of them), I'll have to check all of them, commenting/uncommenting the relevant lines. That's why I was thinking about something like `.unique`. It seems, the only solution is to give the computer extra work, which is not very exciting, since my textual corpora and number of `base`s are very large.
Comment: @EugeneBarsky It seems like you want a way to generate a grammar, or to generate parts of a grammar. That way you could write the generator in the way you understand best, and make changes in the generating code. Be warned, this is HARD! I read a blog post on this, but it's just a summary. The full implementation is harder. (But the author linked to an example module they wrote which you can download and look at.): https://perl6advent.wordpress.com/2015/12/08/day-8-grammars-generating-grammars/
Comment: Another practical solution came to my mind. The problem can be split into two parts. ① Time-consuming filtering of the corpus. Here the endings can be passed from `@array.unique`, which can be even 'precompiled' to work faster. ② Parsing of the filtered forms, where we can leave all the duplicate endings in the `grammar`/`regex`, since the speed is not crucial here.
Comment: Thanks for your answer, especially for showing the possibility to put `|` before the 1st alternative!
I considered both solutions (commenting lines with duplicates or merging duplicates into one `token`). Both of them have certain drawbacks for me (continued in the next comment).
Comment: That's very interesting indeed! But alas, it certainly exceeds my present skills :) So (having this in mind for future) I'll stick to the 3 alternatives you've shown me (depending on the actual task): ① leaving some extra work for the computer, ② commenting the unwanted lines and ③ combining several identical endings into one `token`.


como preencher automaticamente um input?

Question: Como mostra o codigo com vários textfield, quero deixar visível apenas dataEntrada, dataSaida e KM e a partir destas 3 preencher as outras que vão estar invisíveis, o valor a ser pago será exibido em um alert quando se clica em simular. Está funcionando a conta, mas eu preciso ficar clicando nos campos textfield para conseguir preencher, para que o cálculo saia em branco.

function funcao1()
{

var form3 = document.getElementById('simulador');
var valorreal = document.getElementById('valorreal');

form3.addEventListener('submit', function(e) {
    // alerta o valor do campo
    alert("O valor total a ser pago será de: "  + "R$" + valorreal.value);

    // impede o envio do form
    e.preventDefault();
});

}
 function calcula_valor(){
  document.form3.valortotal.value = document.form3.KM.value * document.form3.valorKM.value;
     //document.form3.valortotal.value = ((document.form3.dataSaida.value - document.form3.dataEntrada.value) * document.form3.diaria.value) + (document.form3.KM.value * document.form3.ValorKM.value);
  }

 function difDias(){
    var dataSaida = new Date(document.getElementById("dataSaida").value);
    var dataEntrada = new Date(document.getElementById("dataEntrada").value);
    return parseInt((dataSaida - dataEntrada) / (24 * 3600 * 1000));
}

function chamar(){

     document.getElementById("ndias").value = isNaN(difDias()) ? "" : difDias();

}

 function calcula_aluguel(){
  document.form3.valoraluguel.value = document.form3.ndias.value * document.form3.diaria.value;

  }

  function calculo_total(){
  document.form3.valorreal.value = (document.form3.valoraluguel.value*1) + (document.form3.valortotal.value*1);

  }

Simulador

                     <form class="bloco3" name="form3" action="" method="post">
                            <input type="date" id="dataEntrada" name="dataEntrada" placeholder="dataEntrada" onchange="chamar()">
                            <input type="date" id="dataSaida" name="dataSaida" placeholder="dataSaida" onchange="chamar()">
                            <input type="text" id="ndias" name="ndias" value=""  placeholder="nº dias">
                            <input type="hidden" id="diaria" name="diaria" value="50" required=""  placeholder="Diaria">
                            <input type="text" id="valoraluguel" name="valoraluguel"  value="" onclick="calcula_aluguel()"  onkeyup="calcula_aluguel()" placeholder="valor da diaria">
                            <input type="hidden" id="valorKM" name="valorKM" value="2" placeholder="valorKM">
                            <input type="text" id="KM" name="KM" value="" onclick="calcula_valor()"  onkeyup="calcula_valor()" placeholder="digite o KM percorrido">
                            <input type="text" id="valortotal" name="valortotal"  value=""  placeholder="valor total do KM percorrido">
                            <input type="text" id="valorreal" name="valorreal"  value="" onclick="calculo_total()"  onkeyup="calculo_total()" placeholder="valor total a ser pago">

                            <input type="submit" onclick="return funcao1()" onkeyup="funcao1()" value="Simular" />
                    </form>

Comment: @LeoCaracciolo virou disputa isso daqui hahahaha
Comment: @LeoCaracciolo oloco, aguardo a perfeição então hahahaha. Obrigado por toda ajuda que me deram e estão me dando
Comment: @LeoCaracciolo tudo certo tmb, agora tenho duas opções de codigo para usar hahahaha
Comment: @dvd , que concorrencia! vou correr atras e melhorar esse código!!
Comment: Rapaz, a gente vai estudando o código, vai entendendo cada vez mais e daí vamos melhorando ele.
Comment: Gosto do que é perfeito!!
Comment: mas acho que já atingi o objetivo, teste minha resposta e me diga se algo não está correto.
Answer:
Pelo que entendi, apenas dataEntrada, dataSaida e KM são os inputs que dever ser setados pelo usuário, portanto o código pode e deve ser melhorado.

Melhorias no código:

Na função funcao1() se o valor total é nulo dispara um alerta, caso contrário dispara outro alerta informando o valor total.
As funções calcula_aluguel() e calculo_total() foram removidas. Esses cálculos são feitos em outras funções já existentes.
Não são necessários tantos eventos em tantos inputs, bastam os dos input type="date"
Alguns inputs receberam o atributo readonly já que não dever ser setados pelo usuário.
Acredito que da forma como fiz a legibilidade ficou melhor.

var simulador = document.getElementById('simulador'),
valortotal = document.getElementById("valortotal"),
KM = document.getElementById("KM"),
valorKM = document.getElementById("valorKM"),
valoraluguel = document.getElementById("valoraluguel"),
ndias = document.getElementById("ndias"),
diaria = document.getElementById("diaria"),
valorreal = document.getElementById("valorreal"),
dataSaida = document.getElementById("dataSaida"),
dataEntrada = document.getElementById("dataEntrada");

function funcao1(){
   simulador.addEventListener('submit', function(e) {
      // alerta o valor do campo
      if(valortotal.value==""){
          alert("É tudo 0800! dvd paga a conta : )");
      }else{
          alert("O valor total a ser pago será de: "  + "R$" + valorreal.value);
      }

      // impede o envio do form
      e.preventDefault();
   });
}

function calcula_valor(){
  valortotal.value = KM.value * valorKM.value;
   if(valortotal.value){
      valorreal.value = (valoraluguel.value*1) + (valortotal.value*1);
   }
}

function difDias(){
   if ((dataEntrada.value)&&(dataSaida.value)){
      return parseInt((new Date(dataSaida.value) - new Date(dataEntrada.value)) / (24 * 3600 * 1000));
   }
}

function chamar(){
   var dias = ndias.value = isNaN(difDias()) ? "" : difDias();
   if(dias!=""){
      valoraluguel.value = ndias.value * diaria.value;
      calcula_valor();
   }else{
      valortotal.value = "";
      valorreal.value = "";
      valoraluguel.value = "";
   }
}

//colinha do código do dvd, afinal está sem aviso de direitos autorais rs.
KM.oninput = function(){
   var valor = this.value;
   if(isNaN(valor)){
      this.value = "";
      valortotal.value = "";
      valorreal.value = "";
   }else{
      calcula_valor();
   }
}

Simulador

            <form class="bloco3" name="form3" action="" method="post">
                   <input type="date" id="dataEntrada" name="dataEntrada" placeholder="dataEntrada" onchange="chamar()">
                   <input type="date" id="dataSaida" name="dataSaida" placeholder="dataSaida" onchange="chamar()">
                   <input type="text" id="ndias" name="ndias" value=""  placeholder="nº dias" readonly>
                   <input type="hidden" id="diaria" name="diaria" value="50" required="" placeholder="Diaria">
                   <input type="text" id="valoraluguel" name="valoraluguel"  value=""  placeholder="valor da diaria" readonly>
                   <input type="hidden" id="valorKM" name="valorKM" value="2" placeholder="valorKM">
                   <input type="text" id="KM" name="KM" value="" placeholder="digite o KM percorrido">
                   <input type="text" id="valortotal" name="valortotal"  value=""  placeholder="valor total do KM percorrido" readonly>
                   <input type="text" id="valorreal" name="valorreal"  value=""  onkeyup="calculo_total()" placeholder="valor total a ser pago" readonly>

                   <input type="submit" onclick="return funcao1()" onkeyup="funcao1()" value="Simular" />
           </form>

Comment: Muito Obrigado, ficou muito melhor.
Comment: Meio tabajara essa função pra aceitar somente números.
Comment: Com regex ou isNaN é muito mais fácil fazer isso do que verificar que tecla foi pressionada. E se o cara copiar e colar uma letra no campo?
Comment: @dvd diga como fazer!
Comment: @dvd percebi isso tmb, mas se trocar o type pra number o problema é resolvido
Comment: @MarcoAurélio Type number eu acho mt ruim. Mas se quer usar, use.
Comment: @dvd achei a solução, ele tinha colocado o onkeypress="return SomenteNumero(event);" no input nº dias e deixou o  <input type="text" id="KM" name="KM" value=""  onkeyup="calculo_total()" placeholder="digite o KM percorrido"  sem
Comment: @MarcoAurélio Atualizei a minha resposta com uma solução bem mais simples.
Comment: @LeoCaracciolo atualizei a minha resposta. Tente colar ou adicionar qualquer coisa que não seja um número no campo lá. rss
Comment: @dvd mitou kkkkkkkk
Answer: Uma forma simples é adicionando dois ifs nas funções onde são calculados os valores chamando as outras funções que dependem dos elementos que você quer ocultar (veja comentários  // ADICIONADO no código).
E adicione um novo evento para o campo KM para evitar que seja digitado caracteres não numéricos:
document.getElementById("KM").oninput = function(){
   var valor = this.value;
   if(isNaN(valor)){
      this.value = "";
      document.getElementById("valortotal").value = "";
      document.getElementById("valorreal").value = "";
   }else{
      calcula_valor();
   }
}

function funcao1(){

   var form3 = document.getElementById('simulador');
   var valorreal = document.getElementById('valorreal');

   form3.addEventListener('submit', function(e) {
      // alerta o valor do campo
      alert("O valor total a ser pago será de: "  + "R$" + valorreal.value);

      // impede o envio do form
      e.preventDefault();
   });
}

function calcula_valor(){
   document.form3.valortotal.value = document.form3.KM.value * document.form3.valorKM.value;
   if(document.form3.valortotal.value){ // ADICIONADO
      calculo_total();
   }
   //document.form3.valortotal.value = ((document.form3.dataSaida.value - document.form3.dataEntrada.value) * document.form3.diaria.value) + (document.form3.KM.value * document.form3.ValorKM.value);
}

function difDias(){
   var dataSaida = new Date(document.getElementById("dataSaida").value);
   var dataEntrada = new Date(document.getElementById("dataEntrada").value);
   return parseInt((dataSaida - dataEntrada) / (24 * 3600 * 1000));
}

function chamar(){
   document.getElementById("ndias").value = isNaN(difDias()) ? "" : difDias();
   if(!isNaN(document.getElementById("ndias").value)){ // ADICIONADO
      calcula_aluguel();
   }
}

function calcula_aluguel(){
   document.form3.valoraluguel.value = document.form3.ndias.value * document.form3.diaria.value;
}

function calculo_total(){
   document.form3.valorreal.value = (document.form3.valoraluguel.value*1) + (document.form3.valortotal.value*1);
}

// ADICIONADO EVENTO ABAIXO
document.getElementById("KM").oninput = function(){
   var valor = this.value;
   if(isNaN(valor)){
      this.value = "";
      document.getElementById("valortotal").value = "";
      document.getElementById("valorreal").value = "";
   }else{
      calcula_valor();
   }
}

Simulador

            <form class="bloco3" name="form3" action="" method="post">
                   <input type="date" id="dataEntrada" name="dataEntrada" placeholder="dataEntrada" onchange="chamar()">
                   <input type="date" id="dataSaida" name="dataSaida" placeholder="dataSaida" onchange="chamar()">
                   <input type="text" id="ndias" name="ndias" value=""  placeholder="nº dias">
                   <input type="hidden" id="diaria" name="diaria" value="50" required=""  placeholder="Diaria">
                   <input type="text" id="valoraluguel" name="valoraluguel"  value="" onclick="calcula_aluguel()"  onkeyup="calcula_aluguel()" placeholder="valor da diaria">
                   <input type="hidden" id="valorKM" name="valorKM" value="2" placeholder="valorKM">
                   <input type="text" id="KM" name="KM" value="" placeholder="digite o KM percorrido">
                   <input type="text" id="valortotal" name="valortotal"  value=""  placeholder="valor total do KM percorrido">
                   <input type="text" id="valorreal" name="valorreal"  value="" onclick="calculo_total()"  onkeyup="calculo_total()" placeholder="valor total a ser pago">

                   <input type="submit" onclick="return funcao1()" onkeyup="funcao1()" value="Simular" />
           </form>

Então você pode remover dos elementos que ficarão hidden os eventos
  como onclick etc.
Comment: Muito obrigado cara, era uma coisa tão simples assim hahahaha, vlw mesmo.
Comment: Veja se algo não funciona na minha resposta! Se achar vai ganhar uma garrafa `dvd` rs
Comment: @LeoCaracciolo parece que funciona normal.
Comment: já nas melhores casas de bebidas do Brasil https://i.stack.imgur.com/axVOb.png
Comment: @LeoCaracciolo que falta de sacanagem! criou uma bebida com meu nome?!


exponential sum on complex numbers with a prime number

Question: how you describe this sum? i don't have any idea. i tried to solve it by trigonometric way but I couldn't.
$$\sum_{h = 1}^p {{e^{\frac{{2\pi ih}}{p}}}}  = -1$$
$p$ is a prime number
Comment: [Geometrical series](https://en.wikipedia.org/wiki/Geometric_series): $\sum_{h=1}^p x^h$ with $x = e^{\frac{2\pi i}{p}}$
Comment: Except the equation the OP wrote is incorrect; it comes out to 0.
Comment: Oh, they probably meant the sum only from $h=1$ to $p-1$, not all the way to $p$.
Comment: @AlexMeiburg you know the answer?
Comment: DonAntonio's answer explains the computation. But $0 = \sum_{h=1}^p f(h) = f(p) + \sum_{h=1}^{p-1} \implies \sum_{h=1}^{p-1} = -f(p) = -e^{2\pi i} = -1$.
Comment: @AlexMeiburg thank you
Answer: $$\sum_{h=1}^p\left(e^{2\pi i/p}\right)^h=e^{2\pi i/p}\frac{1-e^{2\pi ip/p}}{1-e^{2\pi i/p}}=0$$
so either you've a mistake or else the upper limit is different.


Order by id MYSQL

Question: I have here my code
$query=mysqli_query($dbcon,"select count(user_name) from `viewlist` where user_name='$_name'");

What I want to do is that it only shows columns with the username $_name but arrange it on the table descending through id (which is auto increment). I have tried ordered by id DESC but didn't work.
Comment: This question doesn't make sense. If you're using the `COUNT` aggregator, without a `GROUP BY`, you're only going to get one result. Why would you need to order one result?
Comment: Possible duplicate of [Best practice question for MySQL: order by id or date?](https://stackoverflow.com/questions/2166752/best-practice-question-for-mysql-order-by-id-or-date)
Comment: Forget about the php for now. Instead, see https://meta.stackoverflow.com/questions/333952/why-should-i-provide-an-mcve-for-what-seems-to-me-to-be-a-very-simple-sql-query
Answer: maybe..
$query=mysqli_query($dbcon,"select tb.* from (select count(user_name) as total from `viewlist` group by user_name) as tb order by tb.total desc");

Order by id MYSQL


jquery $.getJSON error

Question: Using a Float Charts jquery tool the data var value is like that
var d2 = [[0,0],[1,0],[2,0],[3,0],[4,"1"],[5,0],[6,0],[7,0],[8,0],[9,0],[10,0],[11,0]]

When i change it to be got from a Request using that $.getJSON
 var d2 = var d2 = $.getJSON( "UpdateCharts", function() { ......

The Response return as
[[0,0],[1,0],[2,0],[3,0],[4,"1"],[5,0],[6,0],[7,0],[8,0],[9,0],[10,0],[11,0]]

But i got an error that d2 value is 0 and not like first value
Uncaught TypeError: Cannot read property '0' of undefined

Comment: jQuery's [`getJSON()`](http://api.jquery.com/jQuery.getJSON/) is asynchronous. It doesn't `return` the response, but rather calls a `success` callback, that you'll have to provide, passing the response as an argument. Related: [How to return the response from an AJAX call?](http://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-ajax-call)
Answer: Try this (THIS WORKS):
var d2;
$.getJSON( "path/to/json/file", function(data) {
   // parse data to the d2
   // d2 = data; // <-- use this if you want same array/object structure like json file contents has
   console.log(d2); // <-- this will output correct d2 contents
}

Instead of this (EXAMPLE HOW NOT TO DO):
var d2 = $.getJSON( "path/to/json/file", function(data) {
   // parse data to the d2
}
console.log(d2); // <-- this will show error/wrong contents, because it is shown before json data was parsed

Error appears, because getJSON is async function. You just define actions which will be done, when something will happen. With getJSON you define actions will be done, when data would be loaded from external storage. You can output data exactly in the function specified in parameter, but not after.
Example:
1. // this part is executing first, order: 1
2. var xxx = $.getJSON( "xxx", function(xxx) { // you just specified what to do when data will be parsed there
3.    // this part will be called after all contents will be loaded, order: 3
4. }
5. // this part is executing right after 1st lane, order: 2

Comment: @JonathanLonowski, yes if he need same structure as json file has
Comment: @MostafaKasem what exactly you tried? Show jsfiddle please
Comment: Fixed using $.ajax instead of $.getJSON , Your replay is right (Y) can not use $.getJSON like that .

jquery $.getJSON error


Pesquisar imagens em todo os subdirectorios

Question: Preciso procurar por imagens em todos os subdiretórios e apresentá-las numa picturebox, porém o código que tenho atualmente só me permite procurar numa única pasta e sem filtrar por tipos de ficheiros como por exemplo *jpg, *png, etc...
Segue abaixo meu código:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;

namespace _myfotospf
{
    public partial class FormFotos1 : Form
    {
        public FormFotos1()
        {
            InitializeComponent();
        }

        private void FormFotos_Load(object sender, EventArgs e)
        {
            string[] files = Directory.GetFiles(@"C:\Users\...\Imagens");
            DataTable table = new DataTable();
            table.Columns.Add("Nome do ficheiro (duplo clique para ver a miniatura)");
            for (int i = 0; i < files.Length; i++)
            {
                FileInfo file = new FileInfo(files[i]);
                table.Rows.Add(file.Name);
            }
            dataGridView1.DataSource = table;
        }

        private void dataGridView1_DoubleClick(object sender, EventArgs e)
        {
            FormFotos2 myForm = new FormFotos2();
            string imageName = dataGridView1.CurrentRow.Cells[0].Value.ToString();
            Image img;
            img = Image.FromFile(@"C:\Users\...\Imagens\" + imageName);
            myForm.pictureBox1.Image = img;
            myForm.ShowDialog();
        }

        private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {

        }
    }
}
Answer: Você pode retornar um IEnumerable com os diretórios dos seus arquivos. Esse método que estou te passando irá buscar no diretório raiz e nos subdiretórios a partir do caminho informado.
Primeiro parâmetro é o diretório raiz que deseja iniciar a busca por seus arquivos.
Segundo parâmetro é o padrão de busca de arquivos, nesse caso estamos dizendo para buscar todos os arquivos de todas as extensões.
Terceiro parâmetro estamos dizendo que iremos procurar em todos os subdiretórios a partir do nosso caminho raiz.
A cláusula Where do Linq é para filtrarmos os arquivos que possuam as extensões que desejamos encontrar, no seu caso deseja jpg ou png. Caso queira inserir mais uma extensão, basta adicionar mais uma condição OR com a extensão desejada.
IEnumerable<string> arquivos = Directory.EnumerateFiles(@"C:\Imagens", "*.*", SearchOption.AllDirectories).Where(w => w.ToLower().EndsWith(".jpg") || w.ToLower().EndsWith(".png"));

Answer: Penso que esta solução é bastante abrangente:
// se pretender ter várias pastas
List<string> diretorios = new List<string>()
{
    @"C:\Pasta1",
    @"C:\Pasta2",
    @"C:\Pasta3"
};

// se pretender pesquisar várias extensões
// é necessário ter um ponto antes da extensão
List<string> extensoes = new List<string>()
{
    ".jpg",
    ".bmp",
    ".png",
    ".tiff",
    ".gif"
};

private void FormFotos_Load(object sender, EventArgs e)
{
    DataTable table = new DataTable();

    table.Columns.Add("Nome do ficheiro (duplo clique para ver a miniatura)");

    foreach (string diretorio in diretorios)
    {
        var ficheiros = Directory.EnumerateFiles(diretorio, "*", SearchOption.AllDirectories).
            Where(r => extensoes.Contains(Path.GetExtension(r.ToLower())));

        foreach (var ficheiro in ficheiros)
            table.Rows.Add(Path.GetFileName(ficheiro));
    }

    dataGridView1.DataSource = table;
}

Comment: João Martins, Obrigado. Agora não surgem os resultados no datagridview
Comment: Certo, faltava um ponto "." antes de cada extensão quando declaramos a lista `extensoes`. Editei o código e assim já deve funcionar!
Comment: Era isso mesmo. Eu nem reparei nesse pormenor. O problema é que os resultados surgem na datagridview mas quando faço duplo clique na tabela para visualizar as imagens, elas não surgem.             FormFotos2 myForm = new FormFotos2();
            string imageName = dataGridView1.CurrentRow.Cells[0].Value.ToString();
            Image img;
            img = Image.FromFile(@"C:\...\...\...\...\" + imageName);
            myForm.pictureBox1.Image = img;
            myForm.ShowDialog();
Comment: Valide se o caminho para a imagem fica correto quando faz o `Image.FromFile`.
Comment: Quando as imagens estão na raiz do diretório, surgem, mas quando estão dentro de outras subpastas, dá erro: System.IO.FileNotFoundException
  HResult=0x80070002
  Message=C:\...\...\...\...\20170301_102446.jpg
Comment: Na variável `diretorios` só precisa colocar um diretório, senão ele vai fazer 3 vezes a mesma coisa desnecessariamente. Quanto ao problema do caminho, coloque o caminho absoluto ao invés do caminho relativo.
Comment: O caminho já é absoluto. Eu é que eliminei os nomes das pastas.
Comment: Então há algum erro no próprio caminho. O erro é bastante explícito `System.IO.FileNotFoundException`.
Comment: As imagens só não surgem se estiverem dentro de subpastas. Não sei como resolver isto.
Comment: Se colocar o caminho manualmente nesta linha `Image.FromFile(@"C:\Users\...\Imagens\" + imageName);`, continua sem funcionar?
Comment: João Martins, obrigado uma vez mais pela ajuda. Não funciona. A picturebox só devolve a imagem se ela estiver na pasta raíz que eu aponto no caminho. Se a imagem estiver dentro de subpastas, já não surge. Estou a dar voltas á cabeça e não encontro o motivo.
Comment: Será permissões de acesso? Já tentou aceder ao Visual Studio como Administrador?
Comment: Não é permissões. Já tinha testado. O problema é que o caminho para o ficheiro não fica correto se a imagem estiver dentro de outra pasta. Tipo: se a imagem x estiver na pasta A, ela surge na picturebox, mas se a imagem y estiver dentro da pasta B que por sua vez está dentro da pasta A, já dá erro. A picturebox não está a ir buscar o caminho correto.
Comment: Quando diz que o caminho para o ficheiro não fica correto quando estiver dentro de outra pasta, o que quer dizer ao certo? Como é que fica o caminho? Pode dar um exemplo real?
Comment: Imaginemos que tenho estes ficheiros:
C:\Users\User1\Desktop\Imagens\img001.jpg
C:\Users\User1\Desktop\Imagens\2018\img002.jpg
O caminho que está definido é:
img = Image.FromFile(@"C:\Users\User1\Desktop\Imagens\" + imageName);
O ficheiro img001.jpg surge na picturebox quando faço duplo clique na datagridview, mas a imagem img002.jpg já não surge (dá erro), isto porque o duplo clique na datagridview devolve sempre um caminho para a pasta raíz, tipo:
C:\Users\User1\Desktop\Imagens\img002.jpg


ffprobe get bit depth from audio file

Question: For one of my script I need to read out the bit depth of a wav file.
ffprobe -v error -show_entries format=bits_per_sample -of default=noprint_wrappers=1 test.wav

there is no output at all -  I use this in the same way for the duration (format=duration) and it works fine.
Answer: Found the solution - the stream needs to be defined:
ffprobe -v error -select_streams a:0 -show_entries stream=bits_per_raw_sample -of default=noprint_wrappers=1:nokey=1

Comment: `ffprobe -v error -select_streams a:0 -show_entries stream=bits_per_sample -of default=noprint_wrappers=1:nokey=1` seems more consistent
Comment: `ffprobe -v error -select_streams a:0 -show_entries stream` will display all of the possible streams

ffprobe get bit depth from audio file


R: Convert contingency table to long data.frame

Question: Consider you are given a summarized crosstable like this:
kdat <- data.frame(positive = c(8, 4), negative = c(3, 6),
                   row.names = c("positive", "negative"))
kdat
#>          positive negative
#> positive        8        3
#> negative        4        6

Now you want to compute Cohen's Kappa, a statistic to determine the agreement between two raters. Given data in this format, you can use psych::cohen.kappa:
psych::cohen.kappa(kdat)$kappa
#> Warning in any(abs(bounds)): coercing argument of type 'double' to logical
#> [1] 0.3287671

Which irks me, because I prefer my data to be long and thin, which would let me use irr::kappa2. A similar function that I prefer for arbitrary reasons. So I assembled this function to reformat my data:
longify_xtab <- function(x) {
  nm <- names(x)
  # Convert to table
  x_tab <- as.table(as.matrix(x))
  # Just in case there are now rownames, required for conversion
  rownames(x_tab) <- nm
  # Use appropriate method to get a df
  x_df <- as.data.frame(x_tab)

  # Restructure df in a painful and unsightly way
  data.frame(lapply(x_df[seq_len(ncol(x_df) - 1)], function(col) {
    rep(col, x_df$Freq)
  }))
}

The function returns this format:
longify_xtab(kdat)
#>        Var1     Var2
#> 1  positive positive
#> 2  positive positive
#> 3  positive positive
#> 4  positive positive
#> 5  positive positive
#> 6  positive positive
#> 7  positive positive
#> 8  positive positive
#> 9  negative positive
#> 10 negative positive
#> 11 negative positive
#> 12 negative positive
#> 13 positive negative
#> 14 positive negative
#> 15 positive negative
#> 16 negative negative
#> 17 negative negative
#> 18 negative negative
#> 19 negative negative
#> 20 negative negative
#> 21 negative negative

...which let's you compute Kappa via irr::kappa2:
irr::kappa2(longify_xtab(kdat))$value
#> [1] 0.3287671

My question is:
Is there a better way to do this (in base R or with a package)? It strikes me as a relatively simple issue, but by trying to solve it I realized that it's oddly tricky, at least in my head.
Answer: kdat <- data.frame(positive = c(8, 4),
                   negative = c(3, 6),
                   row.names = c("positive", "negative"))

library(tidyverse)

kdat %>%
  rownames_to_column() %>%            # set row names as a variable
  gather(rowname2,value,-rowname) %>% # reshape
  rowwise() %>%                       # for every row
  mutate(value = list(1:value)) %>%   # create a series of numbers based on the value
  unnest(value) %>%                   # unnest the counter
  select(-value)                      # remove the counts

# # A tibble: 21 x 2
#    rowname  rowname2
#      <chr>    <chr>
# 1 positive positive
# 2 positive positive
# 3 positive positive
# 4 positive positive
# 5 positive positive
# 6 positive positive
# 7 positive positive
# 8 positive positive
# 9 negative positive
# 10 negative positive
# # ... with 11 more rows

Comment: Thanks, it's a good tidyverse alternative but I think due to the general nature of the question I'll accept the base R answer. Nice piping though!
Answer: Here is some public domain code from: http://www.cookbook-r.com/Manipulating_data/Converting_between_data_frames_and_contingency_tables/ which I have used to do exactly what you have asked.

# Convert from data frame of counts to data frame of cases.
# `countcol` is the name of the column containing the counts
countsToCases <- function(x, countcol = "Freq") {
    # Get the row indices to pull from x
    idx <- rep.int(seq_len(nrow(x)), x[[countcol]])

    # Drop count column
    x[[countcol]] <- NULL

    # Get the rows from x
    x[idx, ]
}

Comment: so for op example: `d = as.data.frame(as.table(as.matrix(kdat))) ;
countsToCases(d)`
Comment: Now I feel silly because at one point when I started with R I read through the entire Cookbook and I _know_ I once scrolled past this function. Thanks for the answer, I'll accept this one as a solution because it uses base R and is already published public domain code.


How to parse String "06\24\1989" into Date 06/24/1989 format using SimpleDateFormat

Question: How to parse String "06\24\1989" (if user entered like this) in to Date format (MM/DD/YYYY) using SimpleDateFormat.
Comment: by writing some code.. did youu write any ?
Comment: Simplest way: `"09\24\1989".replace("\\", "/");`
Comment: FYI, the troublesome old date-time classes such as [`java.util.Date`](https://docs.oracle.com/javase/9/docs/api/java/util/Date.html), [`java.util.Calendar`](https://docs.oracle.com/javase/9/docs/api/java/util/Calendar.html), and `java.text.SimpleDateFormat` are now [legacy](https://en.wikipedia.org/wiki/Legacy_system), supplanted by the [*java.time*](https://docs.oracle.com/javase/9/docs/api/java/time/package-summary.html) classes built into Java 8 & Java 9. See [*Tutorial* by Oracle](https://docs.oracle.com/javase/tutorial/datetime/TOC.html).
Answer: Just use a SimpleDateFormat to parse the String into a Date and another one to transform it back to a String in the format you want. Remember to use double backslashes in string literals (\ is an escape character)
SimpleDateFormat sdfParse = new SimpleDateFormat("MM\\dd\\yyyy");
SimpleDateFormat sdfFormat = new SimpleDateFormat("MM/dd/yyyy");
try{
    Date date = sdfParse.parse("09\\24\\1989");
    System.out.println(sdfFormat.format(date)); // Prints 09/24/1989
}
catch (ParseException e){
    System.out.println("Invalid date");
}

Of course you could just replace all backslashes to forward slashes, and try to parse it with a new SimpleDateFormat("MM/dd/yyyy"); if you want to validate it is a valid date.
String input = "09\\24\\1989".replace("\\", "/");
SimpleDateFormat sdfParse = new SimpleDateFormat("MM\\dd\\yyyy");
try{
    sdfFormat.parse(input))
}
catch (ParseException e){
    System.out.println("Invalid date");
}

Comment: Indeed! Fixed answer. Anyway the intent of the answer wasn't to provide ready-to-c&p code, particulary given the OP hasn't shown any research effort at all.
Comment: for replaceAll you need 4 slashes, not 2. `replaceAll("\\\\", "/");`
Answer:
try {
    String dateString = "09\\24\\1989";
    SimpleDateFormat format = new SimpleDateFormat("MM\\DD\\YYYY");
    Date myDate = format.parse(dateString);
} catch (ParseException e) {
    //what you want
}


Repeated measures but not longitudinal: A case of multivariate LMM or repeated measures LMM?

Question: I am trying to get my head around the question of what kind of model is most appropriate for the following data:
Every participant rated 14 written statements in terms of various aspects (e.g. credibility, writing style, and logic). All aspects were rated on a Likert scale from 1-7. The statements were presented randomly.
The dataset looks as follows in the long form (example with 4 statements instead of 14):

I would like to explore what predicts the perceived credibility.
Predictors: writing_style, logic
Outcome/y: credibility
I am thinking of my data as having the individual at L2 and the statements (repeated measures/observations) at L1.
First, I was thinking that this is an instance of an LMM with repeated measures (as I repeatedly measure the same thing but it is measured for different items, i.e. statements, rather than for different points in time). However, most examples I encountered in literature or found online are longitudinal studies which does not apply to my data.
Question: I began to wonder whether my data needs to be understood as multivariate or whether it can still be analysed as LMM with repeated measures but perhaps something needs to be analysed differently as the sequence is not of interest?
Answer:
I am thinking of my data as having the individual at L2 and the statements (repeated measures/observations) at L1.

I don't see how statements are nested within individuals because each statement occurs within every individual.
Observations are repeated/nested/clustered within individuals, so observations on the same individual will be more alike one another than observations on another individual and hence not independent, and that's why we use a random intercept for ID. But observations are also nested within statements, that is, each observation "belongs" to a particular statement (as well as to an individual), and this creates further dependence among the observations for that statement, because observations on the same statement will be more similar to one another than those on another statement and hence the random intercept for statement. Statements are not nested within individuals because each statement does not "belong" to any one individual. So this is a 2-level model with crossed random effects (cross-classified)
To make this clearer, contrast your setup with a 3-level model, where repeated observations (L1) are made on pupils (L2) in schools (L3). Observations are nested within pupils and pupils are nested with schools. Each observation "belongs" to one pupil, and each pupil "belongs" to one school
You could model this as a (generalized) linear mixed model. Due to the nature of your outcome variable (7 point likert item) you should ideally fit a model that allows an ordinal outcome as well as crossed random effects, such as MCMCglmm or clmm in the ordinal package. With clmm this would look something like:
clmm(credibility ~ writing_style + logic + (1|ID) + (1|statement), data=mydata)

Comment: Yes, you have repeated measures with observations (L1) nested within individuals (L2), but observations (L1) are also nested (separately) within statements (also L2), hence the cross-classified structure. I will expand on this by updating the answer in a moment.
Comment: No, the treatment group would would be a fixed effect in the 2-level model. It wouldn't make sense to use it as a clustering variable because, a) there are only 2 levels and it's distribution would not follow anything resembling a normal distribution, and b) you may be interested in the "experimental effect" itself, rather than just controlling for it.
Comment: Many thanks for your response. Maybe this is a case of me not using the correct terms. I suppose I meant that the observations are repeated within individuals and each observation can be linked to one of the 14 statements. So I thought that the observations are L1. What I do not fully understand is in what sense is this different from repeated measures where the observations (different time points) are at L1 and individuals are at L2? Would it be wrong to apply this idea to my data or is crossed random effects just a different approach to the same thing?
Comment: Many thanks for your helpful elaboration on this. Just to check I get this right: If I were to have an experimental and a control group and the members of each of the two groups judge 14 statements (which are different for the EG and the CG), then subject and statement would be crossed within groups and the group variable would be one level higher?


FIFA World Cup 2014 final ranking rules

Question: I have tried to find the final ranking rules for the FIFA World Cup 2014.
What are the rules to rank teams after the tournament finished?
Comment: Are you asking for the ranking after the world cup, or the final standing inside the cup?
Answer: read this http://en.wikipedia.org/wiki/FIFA_World_Rankings
It explains the system FIFA uses to asses points. There are many different multipliers, but if you read the section titled Match status you'll see that the the points of World Cup matches are multiplied by 4, where Continental cup matches are multiplied by 3, cup qualifiers match points are multiplied by 2 and friendly matched have multiplier 1.
Comment: I don't think the question is about the world rankings, but rather how the thirty-two teams who compete in the World Cup Finals are ranked at the end of the tournament.
Answer: There are two parts to the final World Cup standings; first, how the teams are grouped together, and second, how they're ranked within their groups.
Grouping
Teams knocked out in the same phase of the tournament are grouped together and ranked against each other. In practice, this could mean that a team eliminated at an earlier stage will be ranked lower than a team that advanced to a later stage, despite having more points. (For example, see the 2006 final standings, where Spain (9 points, 9th place) ended with more points than Ukraine (7 points, 8th place).) Thus there are four groups of teams:

teams 17-32 (eliminated in the group stage)
teams 9-16 (eliminated in the round of 16)
teams 5-8 (eliminated in the quarterfinals)
teams 1-4 (reached the semi-finals)

Ranking
The tiebreakers (for teams 17-32, 9-16, and 5-8) are the same as are used to determine which teams advanced from the group stage:

Total points earned
Goal differential
Goals scored
Number of points obtained in matches between tied teams
Goal difference in matches between tied teams
Number of goals scored in matches between tied teams

Teams still tied after the sixth tiebreaker would be listed as sharing the given rank. See the 2006 final standings, where Iran and the United States are listed as tied for 25th.
Teams 1-4 are ranked based on the results of the final and third-place game.

FIFA World Cup 2014 final ranking rules


Fox Pro Database File Locked by Shadow Copy?

Question: I'm using Process Explorer to determine what process has a lock on a particular Fox Pro Database file in windows.
It's telling me that System has a lock on it.  When I go to kill the "System" process (which if you ask me doesn't sound like a very good idea), it asks me if I'm sure I want to kill the System process.  I haven't answered yes yet.

It's a company server, and I'm thinking that maybe my only option is to tell everybody to get off of it and reboot.
Do I have any other options?
Answer: You have many other options, but like trying to kill the System process, most of them are bad ideas too.  (And it's unlikely that kicking every user off is going to help either, by the way.)
First of all, it's a database file.  So there's a file lock on it because something, like the database engine, is reading from or writing to that file.  Incidentally, this is what happens 100% of the time that a database is online or available.  The database file is locked.  It should be; it needs to be.  You really shouldn't be doing file-level operations on a database file unless you really know what you're doing anyway, which, pardon me for observing, doesn't seem like a description that fits you.
If you must do file level operations on a database, the proper solution is to use the database management console and/or SQL/ODBC queries to take the database offline  and/or "detach" it. You can do this while the database is online only if you have clustering, mirroring or some other HA functionality turned on. (If you have to ask, you don't.  Or should pray very hard that you don't.)  Once the database is not in use any more, you can play around with the file to your heart's content, though again, you shouldn't unless you really know what you're doing.
Should that not be possible, which happens from time to time, the next best thing is to terminate the database engine, which will be running as a service.  It should be possible to do so from the command line with net stop or through the GUI MMC snap-in services.msc, or as a last resort, through task manager by ending the process.  This should release the lock and allow you to do whatever it is with the file you're contemplating doing, which, again, is probably a bad idea.  If the service can't be stopped and the process can't be killed, you're looking at a system reboot, as the service is hung waiting on a kernel resource, and won't release the file lock.
Now, before you rush off and try to kill the process, maybe another question is in order about how to achieve what you're ultimately trying to achieve.  Would seem to be the wiser approach, at least to me.
Comment: Well I don't know about any services that run the database, but I'm not completely ruling it out either...It's fox pro that runs inside a proprietary application so I don't have access to it with vfp.  However I can get in there via ODBC using SquirreL SQL, and there are a few access databases that link to it using linked tables.

Eventually we just rebooted the server to get rid of that process, and the lock didn't come back, so that really makes me think that there isn't a service.
Comment: @leeand00  Enh, proprietary garbage running on Access databases... only sure fire fix to that is to nuke from orbit.  Having said that, next time you can probably unlock the database file by killing the app.  Though, being that it's an Access database and support by MS for exactly no purpose whatsoever, there's no way to say for sure.
Comment: Well the access databases are pretty small and used for purposes of querying the big access database and the big fox pro database.  It's a legacy system to be sure... :)


Erro de consulta em banco de dados - número inválido

Question: Boa tarde. Estou com problema em uma consulta em banco de dados. Ao realizá-la, retorna esse erro:
ORA-01722: número inválido
01722. 00000 -  "invalid number"
*Cause:    The specified number was invalid.
*Action:   Specify a valid number.

Meu código:
SELECT T2.ID_EMPRESA, T2.ID_EQUIPAMENTO, T1.ID_OBRA, T1.ID_ATIVIDADE, SUM(T1.KM_FINAL - T1.KM_INICIAL) AS DIFERENCA_KMS
FROM CE_REGISTRO_LEVES T1
INNER JOIN CE_BOLETIM T2 ON T2.ID = T1.ID_BOLETIM AND T2.DATA BETWEEN TO_DATE('01/06/2018', 'DD/MM/YYYY') AND TO_DATE('30/06/2018', 'DD/MM/YYYY')
WHERE CASE WHEN T1.ID_OBRA = '82' AND T1.ID_ATIVIDADE = '12' THEN 0 ELSE 1 END = 1
GROUP BY T2.ID_EMPRESA, T2.ID_EQUIPAMENTO, T1.ID_OBRA, T1.ID_ATIVIDADE
ORDER BY T2.ID_EQUIPAMENTO

Alguém consegue me auxiliar? Obrigado.
Comment: Você tem certeza que KM_FINAL e KM_INICIAL sao campos numéricos? Eu creio que seja ai o problema.
Comment: Seria mais fácil responder sua pergunta de forma mais certeira se você informar como são modeladas as tabelas `CE_REGISTRO_LEVES` e `CE_BOLETIM`.
Answer: Fazer JOIN com BETWEEN não é boa ideia. É melhor mover o BETWEEN para o WHERE. O seu CASE também parece ser algo mais complicado do que deveria ser, podendo ser simplificado. Sugiro fazer isso:
SELECT
    T2.ID_EMPRESA,
    T2.ID_EQUIPAMENTO,
    T1.ID_OBRA,
    T1.ID_ATIVIDADE,
    SUM(T1.KM_FINAL - T1.KM_INICIAL) AS DIFERENCA_KMS
FROM
    CE_REGISTRO_LEVES T1
INNER JOIN CE_BOLETIM T2 ON T2.ID = T1.ID_BOLETIM
WHERE T2.DATA BETWEEN TO_DATE('01/06/2018', 'DD/MM/YYYY')
    AND TO_DATE('30/06/2018', 'DD/MM/YYYY')
AND (T1.ID_OBRA <> '82' OR T1.ID_ATIVIDADE <> '12')
GROUP BY T2.ID_EMPRESA, T2.ID_EQUIPAMENTO, T1.ID_OBRA, T1.ID_ATIVIDADE
ORDER BY T2.ID_EQUIPAMENTO


the Poisson result and Exponential interpretation for spare part requirement analysis

Question: I am confused with with the Poisson result and Exponential interpretation for spare part requirement analysis. I try to calculate the required number of spare parts for a disposable remove-replace item.
From a real life case; if:

warranty period for a part is $t=400 hr$
constant failure rate for the part is $\lambda=0,003534$ 1/hour so mean time to failure $MTTF=1/\lambda=283{\rm hours}$

then if I use Poisson distribution to calculate what is the required number of spares NOT to be in shortage for 400 hours for this part with at least a probability of 95%, solution is 4 pieces of spares. (the reason is:
1st x value which satisfies below inequality is 4.
$$
{P(x=0)\lor P(x=1)\lor P(x=2)\lor P(x=3)\lor P(x=4) }>0,95
$$
)
However logicly $MTTF$ says that average time between failure events will be 283 hours so even the part fails at 1st hour then I will need 1 piece of spare.
So in this point I'm very confused since 1 and 4 are very different and has very serious consequences. (cost, customer satisfaction etc.)
I also had the graph for Reliability for this part. (${\rm Reliability}=e^{-\lambda(t)}$ )
Observing the graph also didn't help me!
Can you please explain "where and why my logic fails"? I think I've some trouble with understanding the true nature of exponential distribution and meaning of failure rate or MTTF.
Answer: Notice that with a poisson distribution for the number of failures, the expected number of failures in 400 hours is 1.4.  It's important to realize the distinction between the following two phrases "what you expect to happen" and how that differs from "what will happen most of the time".
If you simulated this 400 hour period many times, the average number of failures across the simulations would be 1.4.  It would probably be helpful to think of expected value in this way.  Notice that the expected number of failures coincides with your faulty logic regarding the MTTF.  However, the proportion of simulations with failures less than or equal to 4 would be .985.  In assessing how to use this information, it seems more sensible to base your decision on what will happen most of the time as opposed to what happens on average.
Comment: really appreciated your answer. easy to understand because of your ability to teach I think, thank you.
Comment: You're welcome. I'm glad I was able to help.


What is the simplest way of giving Tone.js arrays of notes and durations in seconds to play back?

Question: I would like to give Tone.js a list of notes and corresponding durations for each note and have it play back the sequence. As far as I can see, there is no easy way to do this.
In the following, the corresponding time values are not the ones I entered (i.e 0.25, 0.5, 0.25), as evidenced by the console.log:
var part = new Tone.Part(function(time, note){
    console.log(time);
    console.log(note);
    synth.triggerAttackRelease(note, time);
}, [[0.25, "C2"], [0.5, "C3"], [0.25, "G2"]]);

part.start(0).loop = false;
Tone.Transport.start();

How can I give Tone.js notes and corresponding ms for playback?
Comment: Tone needs to know the note (frequency), duration (how long to play the note), and time (when to play the note) for each note. See the docs for [`synth.triggerAttackRelease`](https://tonejs.github.io/docs/14.7.77/Synth#triggerAttackRelease)
Answer: I'm not familiar with Tone.js, so there's probably a better way of doing this. The official example for the array shorthand that you're using doesn't seem to work, so it might be a library issue.
As for what you're trying to achieve, I fiddled with it out of curiosity and here's what I've come to:
function timeFromDurations(value, i, arr) {
  const prevTime = arr[i - 1]?.time;
  value.time = prevTime + arr[i - 1]?.duration || 0;
  return value;
}

const notesAndDurations = [
  { note: 'C3', duration: .25 },
  { note: 'C4', duration: .5 },
  { note: 'G2', duration: 1 },
].map(timeFromDurations);
console.log(notesAndDurations);

const synth = new Tone.Synth().toDestination();
// use an array of objects as long as the object has a "time" attribute
const part = new Tone.Part((time, value) => {
  // the value is an object which contains both the note and the velocity
  synth.triggerAttackRelease(value.note, value.duration, time);
}, notesAndDurations).start(0);
Tone.Transport.start();

The idea is that you need to set start time of each note based on previous note start time + duration. That removes the need to set the start time(not optional) manually.
Edit
For your second case where the durations and the notes come in separate arrays you can use the following reduce function:
const notes = ['C3', 'C4', 'G2'];
const durations = [0.25, 0.5, 1];

const noteDurationTime = notes.reduce((acc, note, i) => {
  const prevTime = acc[i - 1]?.time;
  const time = prevTime + acc[i - 1]?.duration || 0;
  const duration = durations[i];

  acc.push({ note, duration, time });
  return acc;
}, []);

The idea is the same, you're building an array of objects that have all the needed properties(note, duration, time), but this time from different sources(notes array and durations array).
You want to make sure that both these arrays are the same length.
Comment: `timeFromDurations` is a mapping function, I've edited the example. I've also added an example for your second question.
Comment: Thanks. Where does the timeFromDurations function actually get called?
Comment: If I wanted the input to be two separate arrays for the notes and durations e.g var notes = ['C3', 'C4', 'G2'] ; var durations = [.25, .5. 1]; do you think I would still need to convert to the notesAndDurations array structure?


Finding $\int x\arctan(x)\,dx$ through inverse substitution

Question: I have to find $\int x\arctan(x)\,dx$ through inverse substitution.
My attempt:
Let $x = \tan\theta$, and $dx = \sec^2\theta \,d\theta$. So, we have that
$\int x\arctan(x)\,dx = \int \tan(\theta)\arctan(\tan(\theta))sec^2\theta d\theta = \int \tan(\theta)\theta \sec^2(\theta) = \int \theta \tan(\theta)(\tan^2(\theta) + 1)d\theta$.
That's about as far as I could get. I tried substituting or integrating by parts after I got to the last step, but nothing really worked.
EDIT: The problem states that we must integrate by inverse substitution.
Thanks.
Comment: Surely parts works.  Just try the less intuitive direction...integrate $x$ and differentiate $\arctan x$.  That gives you something like $\int \frac {x^2}{1+x^2} dx$.  No problem.
Comment: But I have to use inverse substitution as its a requirement of the problem. I tried doing it by parts after I got to my last step, and nothing really worked as far as I can see.
Comment: Well, my way has an inverse substitution at some point!  I mean, you just write $\frac {x^2}{1+x^2}=1-\frac {1}{1+x^2}$ and I need an inverse substitution to do the last bit!  (ok, I really don't but artificial problems call for artificial solutions).
Comment: I haven't used theta substitution ,so I hope that won't be a problem for your question.
Answer: Take $u= tan^{-1}(x)$. Then$ u'=1/(1+x^2)$.Let $v' =x ,v=x^2/2$.
Here we use the inverse substitution
Therefore on integrating we get:-
Solving using integration by parts.
$x^2 \frac {tan^{-1}(x)}{2} -\frac{1}{2} \int \frac{ x^2 dx}{(1+x^2)}$
Skipping the remaining steps,if you want I can add them too
Answer :-
$\frac{x^2 tan^{-1}(x)}{2} - \frac {x}{2} + \frac {tan^{-1}(x)}{2} +C$
Answer: If you must integrate by inverse substitution, just as you did using $x=\tan (t)$, $dx=\sec ^2(t)\,dt$ you effectively end with
$$\int x \tan ^{-1}(x)\,dx=\int t \tan (t) \sec ^2(t)\,dt$$ Now, one integration by parts
$$u=t \implies u'=dt$$
$$v'=\tan (t) \sec ^2(t)\,dt\implies v=\frac{1}{2}\sec ^2(t)$$ leading to
$$\frac{t}{2}\sec ^2(t)-\frac{1}{2}\int\sec ^2(t)\,dt=\frac{t}{2}\sec ^2(t)-\frac{1}{2}\tan(t)$$


Extra Space Between UITableViewSections in iOS 15

Question: UITableView with multiple sections without section footers is shown with an extra space between sections. Xcode's view debugger shows that it's not a view, but just an empty space.
In my case the behavior is unwanted.
Playing with adding a 1.0/0.0 height footer doesn't help. Neither does changing the table view's style.
Here's a sample code:
import UIKit

final class ViewController: UITableViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        tableView.separatorColor = .yellow
    }

    override func numberOfSections(in tableView: UITableView) -> Int {
        return 3
    }

    override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let header = UIView()
        header.backgroundColor = .green

        return header
    }

    override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 20.0
    }

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 3
    }

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = UITableViewCell()
        cell.backgroundColor = .blue

        return cell
    }

    override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 30.0
    }

    override func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        let footer = UIView()
        footer.backgroundColor = .red

        return footer
    }

    override func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return 20.0
    }

}

Here's output in iOS 14 and iOS 15:

Comment: Duplicated question... See here to fix your problem: https://stackoverflow.com/a/69350529/6883935
Comment: @EduardoSanti No, it's not. In the question you pointed out, a person asks about margins around their table view. I ask about blank space between sections. The accepted answer contains solution of my problem, but the author of that question said that it's not a solution for their problem.
Comment: I'm sorry, I read wrong. Are you using the heightForHeaderInSection delegate method?
Comment: I tried both using `heightForHeaderInSection` and not, and tried using 0.0 and 1.0 height – it didn't affect the space. As I've mentioned, Xcode's view debugger showed that there's no header (or any other view) between sections, just an empty space. And this space only appeared in iOS 15.
Comment: Could you share images please?
Comment: @EduardoSanti Sure! I updated the question with a sample code and the corresponding output in iOS 14 and iOS 15.
Answer: In iOS 15 the property sectionHeaderTopPadding was added. It affects that exact space. The property's default value is automaticDimension. Setting it to 0.0 fixes the problem.
Since the property is only available in iOS 15, you may want to wrap it with an availability block:
if #available(iOS 15.0, *) {
  tableView.sectionHeaderTopPadding = 0.0
}

Here's the original code snippet from the question including necessary changes:
import UIKit

final class ViewController: UITableViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        tableView.separatorColor = .yellow
        if #available(iOS 15.0, *) {
            tableView.sectionHeaderTopPadding = 0.0
        }
    }

    // The rest is without changes.

}

Here's the output in iOS 15 after the change:


Why do we use Gamma($\epsilon, \epsilon$) as non-informative prior for precision and Normal prior for betas in Linear Regression

Question: Suppose my regression model is
$$Y_i = \beta_0 + \beta_1X_{i1} + \epsilon_i $$
In most books I am seeing that the prior used for precision $\tau = 1/\sigma^2 $ is $Gamma(\epsilon, \epsilon)$. However I am unable to understand how is that found given that the beta's are unknown too? Similarly I am not getting how is Normal prior used for the beta's.
Comment: Betas could be negative. Precisions must be positive.
Comment: but why exactly these distributions?
Answer: A simple linear regression model is
$$ Y_i = \beta_0 + \beta_1 X_{i1} + \epsilon_i, \epsilon_i \stackrel{ind}{\sim} N(0,\sigma^2). $$
A frequently used prior is
$$ p(\beta_0,\beta_1,\sigma^2) \propto 1/\sigma^2 $$
Notice that this is a joint prior for $\beta_0$, $\beta_1$ and $\sigma^2$. Marginally the priors for $\beta_0$ and $\beta_1$ are uniform over the real line and the marginal prior for $\sigma^2$ is the limit as $\epsilon \to 0$ of an inverse gamma distribution with shape and scale both $\epsilon$ (or equivalently a gamma distribution on the precision $\tau=1/\sigma^2$ with the shape and rate both $\epsilon$).
You question appears to be why do we use this prior and I can think of two reasons: 1) it corresponds to the prior derived by some methods of deriving default priors (I believe a particular reference prior approach and the maximal data information approach) and 2) the resulting posterior exactly matches a non-Bayesian solution, i.e. inference through the sampling distributions of the MLE.
Comment: Thank you for correcting my linear model mistake.  If the betas have uniform over the line then is the use of Normal distribution as prior just to make sure it is proper? For e.g. using a normal dist with large variance. Secondly I was looking for this proof of marginal prior for sigma^2 from the jeffry's joint prior(although it seems that is sigma^(-3)), do you have any resources to cite so that I could see the proof and try to understand it?
Comment: I am considering Jeffrey's prior for precision, which is proportional to 1/tau. I tried to take limiting distribution of gamma distribution. So for as alpha=beta and alpha->0, the part where I get stuck is lim(alpha->0) 1/gamma(alpha). The remaining part is 1/x. But it seems gamma function tends to positive infinity as alpha tends to 0+. Any suggestions to proceed further?
Comment: However even it tends to infinity as alpha approaches 0+, it is still a constant. So I can anyway say that distribution is proportional to 1/x. And prove what you had written in the answer. Is this approach correct?


Convert a fraction to infinite repeating decimal?

Question: We all know how to convert an infinite repeating decimal to fraction. It is simple.
But now I have these fractions 10/23, 3/29, etc. I know these fractions can be written in infinite repeating decimal, but the repeating digits are too long ( over 10 digits), so it cannot show fully on the calculator screen.
So is there any algorithm to find the repeating decimal digits by calculator ?
thanks very much.
Comment: You could do long division by hand until the pattern emerges. Since these are rational numbers, you know that they must either repeat or terminate. In the case where the denominator is prime, then it must repeat, so you can just get enough digits until you have the solution you seek.
Comment: Why "by calculator"?
Comment: But it take a long time to do devision by hand. I want to know is there any way to do this by calculator ?
Comment: Before calculators you could get the Fields medal for dividing 1 by 7.
Comment: I think the duplicate is the other way around, this question was asked first and answered first. (You can hardly be duplicated more than these two questions: almost the exact same wording, from the same account.)
Answer: An important fact, coming from Euler's theorem, is that the repeat period of $a/b$ divides into $\phi(b)$.  You can use a calculator similarly to doing it by hand, but getting more digits at once.  If I type $10/23$ into my calculator, it gives $0.434782609$ in the display.  There may be some guard digits held inside the calculator and not displayed.  Clear it, type in $0.43478260 \times 23$ (note I deleted the last digit to avoid rounding problems) and get $9.9999998$, which is exact.  The remainder is $2E-7$, so divide that by $23$, getting $0.086956522$, so now you have $0.4347826086956522$  As it hasn't repeated yet, the repeat is $22$ digits.  Delete the last digit, find the remainder, divide again, and you are there.


What is the equivalent of the null-safe equality operator <=> in SQLite?

Question: I need to determine what is the equivalent for SQLite of the <=> operator in MySQL.
Any idea?
Answer:
The IS and IS NOT operators work like = and != except when one or both
  of the operands are NULL. In this case, if both operands are NULL,
  then the IS operator evaluates to 1 (true) and the IS NOT operator
  evaluates to 0 (false)

http://www.sqlite.org/lang_expr.html#isisnot
Answer: I have just found the "IS" operator, but not sure if it has exactly the same behaviour?
Answer: From
2022-06-25 (3.39.0):

Add new binary comparison operators IS NOT DISTINCT FROM and IS DISTINCT FROM that are equivalent to IS and IS NOT, respective, for compatibility with PostgreSQL and SQL standards.

IS NOT DISTINCT FROM:
The IS NOT DISTINCT FROM operator is an alternative spelling for the IS operator. Likewise, the IS DISTINCT FROM operator means the same thing as IS NOT. Standard SQL does not support the compact IS and IS NOT notation. Those compact forms are an SQLite extension. You have to use the prolix and much less readable IS NOT DISTINCT FROM and IS DISTINCT FROM operators on other SQL database engines.

Sample:
CREATE TABLE test(col1 INT, col2 INT);

INSERT INTO test(col1, col2)
VALUES (0, 0), (0, 1), (0, NULL), (1, 0), (1, 1), (NULL, 0), (NULL, NULL);

Query:
SELECT *, col1 IS NOT DISTINCT FROM col2 AS "<=>"
FROM  test;

Output:

db<>fiddle demo - SQLite
db<>fiddle demo - PostgreSQL


Is there any Talend component to create ANSI X12 edi file?

Question: Is there any Talend component to create ANSI X12 edi file? I need to process the following EDI Transaction sets:
<code>*846 - Inventory Inquiry/Advice
*856 - Ship Notice/Manifest
*888 - Item Maintenance
*940 - Warehouse Shipping Order
*943 - Warehouse Stock Transfer Shipment Advice
*944 - Warehouse Stock Transfer Receipt Advice
*945 - Warehouse Shipping Advice
*947 - Warehouse Inventory Adjustment Advice
*204 - Motor Carrier Load Tender
*210 - Motor Carrier Freight Details and Invoice
*212 - Motor Carrier Delivery Trailer Manifest
</code>
The EDI's has to be sent back and forth using the AS2 standard.
Since I am new to EDI and don't even know much about how to send EDI using AS2 format.
Thanks in advance.
Updated on Sep 3, 2012.
I have found X12 parser, which is seems to be working. I was able to parse 856 EDI Transaction set. I didn't try with other formats yet.
Following is the link :
http://x12-parser.googlecode.com/svn/trunk/
If someone has any valuable comments or suggestion on X12 parser please post it here.
Thanks
Comment: Or is there any alternative to process the above mentioned EDI transaction sets using **java code** will also be helpful.
Answer: Have a look at the Oakland Data Transformer. It handles all sorts of formats including X12 and is well integrated with the Talend ESB (Apache Camel). A number of Talend customers have used this.
Answer: You may want to look at Altova's MapForce.  A graphical mapper (good), but then the transform is Java code.
For AS2, I recommend Cleo Lexicom or Liaison ECS.  Both are well-established, cost effective commercial packages.
Answer: maybe you can integrate bots (http://bots.sourceforge.net) in Talend for these edi translations.
for AS2:
- http://sourceforge.net/projects/openas2/
- http://as2.mendelson-e-c.com/
Answer: We're using Altova MapForce and Mendelson AS2 Opensource for our EDI needs.
MapForce makes mapping a breeze and the Mendelson AS2 server is straight forward to setup and use.
A bonus for MapForce is it allows you to export your mapping to royalty free Java, C#, C++, XQuery, and XSLT 1.0/2.0 code so it is an easy drop in product.
I'm not a huge fan of the generated code ( empty catch statements etc ) but it works and the code is available for you to edit.


Symfony2 authentication

Question: I am currently developing a website using the framework Symfony2. I am nearly at the end of its development, and just the "security" part is missing (authentication and authorization). What I would like is to use Symfony2 core bundle to authorize the user but I want to use my Drupal database to get the authentication of the user.
I have previously used the module Services 3 with a REST server to get the user information and to authorize him/she to go on my website (which was flat php coded). Now, I want to make something robust and secure, so here my question, do you know a method for getting the authentication from the Drupal website and then authorize the user via Symfony core bundle?
Here are my 2 thoughts about it:
-> Fetch the user data ($username & $password) using the REST server and a query made in my custom UserProvider (Symfony Doc) and then leave Symfony makes the authentication using the Drupal's password encoder. But here the problem is that when you fetch the user data using the REST server, you get everything but the password.
-> Get access to the Drupal database using Doctrine as usual in my application and fetch the user & pass from it. Then use the Drupal's password encoder to check this result.
To conclude, I am really far to be an expert on this kind of stuff, so I would really appreciate your help.
Answer: You can use a custom User Provider in Symonfy and then use the Service Module from Drupal to login via a REST interface

Symfony2 authentication


How to use $x + \frac{1}{x} = 7$ to compute $x^2 + \frac{1}{x^2}$.

Question: I am not sure how to approach this question:

You know that $x + \frac{1}{x} = 7$. Compute $x^2 + \frac{1}{x^2}$.

I have tried adding $x + \frac{1}{x}$ to get $\frac{x^2 +1}{x}$ but can't see if this was useful or not.
I need help in getting started.
Comment: You can multiple by x, solve the equation and compute the formula
Comment: Better to just square both sides of the equation.
Answer: Notice $\left(x + \frac{1}{x}\right)^2 = x^2 + \frac{1}{x^2} + 2$.
Answer: Observe that
$$x^2+\frac{1}{x^2}=\left(x+\frac{1}{x}\right
)^2-2.$$
Hope this helps. :)
Comment: Simple, effective and to the point. While calculating $x$ from the equation is not hard, this is much, much faster.
Comment: Thanks for your appreciation. :)
Answer: Thank you to Yiyuan Lee and awllower who really answered the question.
I am only adding this for completeness, and to remind myself of the solution.
We are given $x + \frac{1}{x} =7$ and want to use this to find $x^2 + \frac{1}{x^2}$.
Using the fact $$\left(x +\frac{1}{x}\right)^2 = x^2 +\frac{1}{x^2} +2$$
and rewriting this as:
$$\left(x +\frac{1}{x}\right)^2 -2 = x^2 +\frac{1}{x^2}$$
We can substitute $x + \frac{1}{x} =7$ to get:
$$(7)^2 -2 = x^2 +\frac{1}{x^2}$$
So $$x^2 +\frac{1}{x^2} = 47$$
The same method can be used to calculate $x^3 + \frac{1}{x^3}$:
$$\left(x +\frac{1}{x}\right)^3 = x^3 +\frac{1}{x^3} +3x +\frac{3}{x}$$
Noticing that $3x +\frac{3}{x}$ = $3(x+ \frac{1}{x})$, which means $3x +\frac{3}{x} = 3.(7) = 21$
Then it is possible to write:
$$\left(x +\frac{1}{x}\right)^3 -21 = x^3 + \frac{1}{x^3}$$
$$(7)^3 -21 = x^3 + \frac{1}{x^3}$$
$$x^3 + \frac{1}{x^3} = 343 -21$$
$$x^3 + \frac{1}{x^3} = 322$$
Comment: Use $(x^2+\frac{1}{x^2})(x^3+\frac{1}{x^3})=x^5+\frac{1}{x^5}+(x+\frac{1}{x})$ to find $x^5+\frac{1}{x^5}$ and generalize it to other powers.
Comment: Or, you could generalize it with a recursive general formula, perhaps through induction. I would find such a formula more useful.
Comment: @mikoyan Since it seems you are interested, I have a challenge for you: If given that $x+\frac{1}{x}= \sqrt{3}$, then find, $$x^{204}+\frac{1}{x^{204}}$$
Comment: In fact, the same approach can be used to find $x^n + \frac{1}{x^n}$ for $4,5,6...$.
Comment: I was thinking of ways to extend the approach to show it for the nth case. Thank you again for your help and interest.


How to isolate two distinct effects of a unique independent variable in multiple regression analysis?

Question: Salut!
First of all thank you if you're reading this post and I wish you all the best for 2020!

Edit 1: All variables are continuous variables (no dummy or categorical)
Edit 2: An illustration of the problem has been added at the end of the post

Problem
My question can be illustrated with a simple regression as follow :
\begin{equation}
Y_t = \beta_a*A_t + \varepsilon_t \;\;\;\;\;\;\; (1)
\end{equation}
Assume that the effect of variable $A_t$ on $Y_t$ have two (and only two) specific channels, meaning that $A_t$ have two distinct effects (let's call them $e_1$ and $e_2$ for the sake of simplicity) on $Y_t$.
In equation (1), we can only conclude about the overall effect of $A$ on $Y$; where $\beta_a$ would represent both the sum of the effects $e_1 + e_2$, right?

Now assume we can characterize one of the channel using another variable, say $B_{t}$. This variable $B_t$ allows us to control for the effect $e_1$, but also capture other effects. Including it in Equation (1), we obtain :
\begin{equation}
Y_t = \beta_a*A_t + \beta_b*B_t + \varepsilon_t \;\;\;\;\;\;\; (2)
\end{equation}
When we estimate both Equation $(1)$ and $(2)$, we find two different $\hat{\beta_a}$. But, can we draw any conclusion from there about $e_1$ and $e_2$?
My intuition is that:

In Equation $(1)$: $\hat{\beta_a}$ accounts for $e_1 + e_2$
In Equation $(2)$: $\hat{\beta_a}$ accounts only for $e_2$ since we control for $e_1$ with the variable $B_t$

Is my intuition correct? If yes, is there a way I can estimate/measure $e_1$ from there ($\beta_b \neq e_1$)?

Potential solution:
Would integrating an interaction term of $A$ and $B$ be a way to capture $e_1$ (as follow)?
\begin{equation}
Y_t = \beta_a*A_t + \beta_b*B_t + \beta_{ab}*A_tB_t + \varepsilon_t \;\;\;\;\;\;\; (3)
\end{equation}
In which:

$\hat{\beta_a}$ : would account for $e_2$
$\hat{\beta_b}$ : would account for the general effect of $B_t$
$\hat{\beta_{ab}}$ : would account for $e_1$ (which would change based on the level of $B_t$)

Any help would be much appreciated. I hope the problem is clear enough, don't hesitate to ask if you need further information/specification. Thank you :)
Comment: When you say that the variable has two specific channels, do you mean that it's a factor (or categorical) variable with two levels? And those levels are e1 and e2?
Comment: Hi Nick, thank you for your answer. Actually A, B and Y are all continuous. By the two channels I mean that when A changes, it has two direct impacts on Y. As an exemple you could think of Y as the average price in a market, and A as the quantity of cheap goods produced in this market. If A increases, the average price on the market will drop because more cheap products might be sold (effect 1), but also because the market share of middle-range and expensive products might be reduced (effect 2). I don't know if the exemple is really good, but that's the idea.
Answer: Multiple regression model always capture effect et ceteris paribus for each variable, meaning when every other variables are held constant. I think this property is enough to justify my first intuition, that is:

In Equation $(1)$: $\hat{\beta_a}$ accounts for $e_1 + e_2$
In Equation $(2)$: $\hat{\beta_a}$ accounts only for $e_2$; $\hat{\beta_b}$ accounts for the general effect of $B_t$

$e_1$ is not captured anymore in equation $(2)$, but rather goes is in the error term $\varepsilon_t$, am I right ?
Thus, adding an interaction term, see equation $(3)$, would rather leads :

$\hat{\beta_a}$: accounts for $e_2$
$\hat{\beta_b}$: accounts for the general effect of $B_t$
$\hat{\beta_{ab}}$: accounts for the interaction between $e_2$ and $B_t$

I can argue without the measure of $e_1$, but I'm still very curious if there is a way to measure it?
Since we know the value of ($e_1$ + $e_2$) and the value of $e_2$ only, I guess there is some sort of method, maybe I've learned it before but can't remember. Any help would be welcome please.
Comment: Consider incorporating  this elaboration directly into your post. It doesn't seem to answer the question.


Integration by parts twice yields $0=0$?

Question: I had this question:
$$\int 3x\sec^2(4x) dx$$
After doing integration by parts for the first time, setting $u=3x$ and $dv=\sec^2(4x)dx$ and doing derivative and integral, I got
$$\int 3x\sec^2(4x) dx = \frac{3}{4}x\tan(4x)-\frac{3}{4}\int \tan(4x) dx$$
At this point, I realize I can solve for the $\tan(4x)$ using $u$-substitution, but I continue doing integration by parts.
For
$$\int \tan(4x) dx$$
I substitute $u=\tan(4x)$ and $dv=1dx$ getting
$$\int \tan(4x) dx = \tan(4x)\cdot x - \int x\cdot 4\sec^2(4x)dx$$
Substituting everything back in, I get
$$\int 3x\sec^2(4x) dx = \frac{3}{4}x\tan(4x) - \frac{3}{4}\left(\tan(4x)\cdot x -\int x\cdot 4\sec^2(4x)dx\right)$$
Distributing the $3/4$ and simplifying, I get $0=0$ — that's not the answer. I don't believe I broke any rules using integration by parts, yet the answer is invalid. Why doesn't this work?
Thanks.
Comment: I'd just like to point out that, in fact, zero does equal zero.
Comment: But Art, I hope you realise that law-of-fives was making a serious point.  You have **not** got an invalid answer.  You have **not** made any algebraic mistakes (I assume - didn't actually check), and the answer you have got is a correct equation.  It happens to be useless because it doesn't tell you the value of the integral you want, but that's a different thing...
Comment: Your second integration by parts is not wrong, but it's taking you backwards: first you had $dv = \sec^24x dx$ to get $v = \frac14 \tan 4x$, and then you set $u = \tan 4x$ to get $du = 4 \sec^24x dx$. This is like multiplying by 2 then dividing by 2.
Comment: :/...............
Comment: I didn't read your post in detail, but I would bet on a sign error
Comment: Did it 5 times. Possible, but doubt it.
Answer: You proved that your integral is equal to itself. This is a true statement! It's not a useful thing to do, but the integration by parts formula doesn't come with a guarantee that it will produce something useful.
In general, if we apply integration by parts twice, we could always get back to where we started:
$$
\int u \, dv = uv - \int v \, du = uv - \left(uv - \int u \,dv\right)=\int u \, dv
$$
This is essentially what you just did. The $u$ in your second integration by parts is equal to the $v$ in your first one, and vice versa.
Comment: Makes sense. So, I would have to do u-sub for tan(4x)?
Comment: That seems like a good way to proceed, yes.


Enter object with dsm

Question: i am actualy trying to read a field value in my panelized node.
I want to recieve the data in the red marked field, as u can see in my screenshot.

I tried to following:
<?php print_r($display->context['panelizer']['data']['field_centerpage_layout'][0]['value']); ?>

But I recieve this Error:
Fatal error: Cannot use object of type ctools_context as array in C:\seu\xampp\htdocs\iptp\sites\all\themes\mytheme\plugins\layouts\he_two_70_30\he-two-70-30.tpl.php on line 29
I would be thankful for any kind of help :-)
Answer: As you can see from your Krumo output (plus the very descriptive error message), data is an object, not an array. I'd imagine $display->context['panelizer'] is also an object but it's hard to say as you haven't mentioned in your question how that's populated. You should use either
$display->context['panelizer']['data']->field_centerpage_layout[0]['value']

or
$display->context['panelizer']->data->field_centerpage_layout[0]['value']

Probably the second one.

Enter object with dsm


Error when complie chaincode

Question: I followed the tutorial Simple Asset Chaincode of Hyperledger Fabric Docs, but

when I execute the code  go get -u --tags nopkcs11
github.com/hyperledger/fabric/core/chaincode/shim, I got the
following error message:

package github.com/hyperledger/fabric/core/chaincode/shim: cannot download, http ://gerrit.hyperledger.org/r/fabric uses insecure
  protocol

How can I solve it? (I have successfully implemented the network
using Docker Quickstart Terminal tool on Windows 7)
If I ignore the command in question 1, I still can successful build the chaincode when I execute go build --tags nopkcs11. Does it mean that the command in question 1 is ignorable?
Comment: The command works for me on windows and on linux.
What is your golang version?
Comment: My golang version is go1.9 windows/amd64.
Answer:
If I ignore the command in question 1, I still can successful build
  the chaincode when I execute go build --tags nopkcs11. Does it mean
  that the command in question 1 is ignorable?

No, it just means you probably have this package in your GOPATH already, or that your chaincode does't require to include the shim package in the binary.
Comment: Thank you~~~  Do you know how can I solve the problem in question 1?
Comment: are you behind a proxy or something?
Comment: Maybe, I deployed the test environment in the company. Is it a problem?:(
Comment: Suggest you use wireshark or something similar to track what happens - maybe you're redirected or something.

Error when complie chaincode


Changing Y position of player (code runs like the player has two position simultaneously)

Question: I am making a game that runs up infinite stairs.
First, I coded prototype code that can run infinite hallway by manipulating the player's Z position and it works.
Then, I change that code to manipulate the player's Y position.
This is HallWayController script
    void FixedUpdate()
    {
        this.handleInfiniteHallway();
    }

    private void handleInfiniteHallway()
    {
        if (this.isPlayerOutOfBounds())
        {
            float posYmod = HALLWAY_HEIGHT;
            if (this.player.position.y > MAX_Y_BOUND)
            {
                posYmod *= -1;
            }
            this.player.position = new Vector3(this.player.position.x, this.player.position.y + posYmod, this.player.position.z);
            Debug.Log("Player Y position: " + this.player.position.y);
        }

    }

    private bool isPlayerOutOfBounds()
    {
        return this.player.position.y > MAX_Y_BOUND || this.player.position.y < MIN_Y_BOUND;
    }

With this code, the game malfunctions just like the player have two Y position simultaneously.
What I found:

If I use FixedUpdate(), the player's position doesn't change on game play view, but debug.Log says player Y Position has changed. And if player ever reached Y_Bound, code inside if(this.isPlayterOutOfBounds())  infinitely executes.
If I use Update() instead of FixedUpdate(), the player's position does change in game play view and debug.Log, but sometimes the player flashes back and forth between the original position and repositioned position. And if player ever reached Y_Bound code inside if(this.isPlayterOutOfBounds())  infinitely executes.

This is Player Controller script that linked to the player game object
using UnityEngine;

[RequireComponent(typeof(CharacterController))]
public class PlayerController : MonoBehaviour
{
    [SerializeField] private float playerSpeed = 10.0f;
    [SerializeField] private float jumpHeight = 1.0f;
    [SerializeField] private float gravityValue = -9.81f;

    private bool isFlashLightOn = true;
    public GameObject lightSource;

    private CharacterController controller;
    private Vector3 playerVelocity;
    private bool groundedPlayer;
    private InputManager inputManager;
    private Transform cameraTransform;

    private void Start()
    {
        controller = gameObject.GetComponent<CharacterController>();
        inputManager = InputManager.Instance;
        cameraTransform = Camera.main.transform;

        lightSource.gameObject.SetActive(true);
        isFlashLightOn = true;
    }

    void FixedUpdate()
    {
        groundedPlayer = controller.isGrounded;
        if (groundedPlayer && playerVelocity.y < 0)
        {
            playerVelocity.y = 0f;
        }

        Vector2 movement = inputManager.GetPlayerMovement();
        Vector3 move = new Vector3(movement.x, 0, movement.y);
        move = cameraTransform.forward * move.z + cameraTransform.right * move.x;
        move.y = 0f;
        controller.Move(move * Time.deltaTime * playerSpeed);

        // Changes the height position of the player..
        if (inputManager.PlayerJumped() && groundedPlayer)
        {
            playerVelocity.y += Mathf.Sqrt(jumpHeight * -3.0f * gravityValue);
        }

        playerVelocity.y += gravityValue * Time.deltaTime;
        controller.Move(playerVelocity * Time.deltaTime);
    }

    void Update()
    {
        if (inputManager.PlayerFlashLightOn())
        {
            isFlashLightOn = !isFlashLightOn;
            lightSource.gameObject.SetActive(isFlashLightOn);
        }
    }
}

Comment: What is your `this.player` referring to? `GameObject`or `transform`attached to the GameObject?
Comment: I believe it is transform attached to the GameObject. `public Transform player;`
Comment: Yes it probably is. GameObject doesn't have property position, so it would thrown an error.
Answer: Hmm, I think I quess what is the problem here. See comments I added
// You may call this twice on each frame, depending on your frame rate
void FixedUpdate()
    {
        this.handleInfiniteHallway();
    }

    private void handleInfiniteHallway()
    {
        if (this.isPlayerOutOfBounds())
        {
            // Problem is probably here. When your object hits another limit, you move it all HALLWAY_HEIGHT, so it hits another limit
            // If you move just half of the height, your character returns to the middle.
            // Original float posYmod = HALLWAY_HEIGHT;
            float posYmod = HALLWAY_HEIGHT / 2;
            if (this.player.position.y > MAX_Y_BOUND)
            {
                posYmod *= -1;
            }
            this.player.position = new Vector3(this.player.position.x, this.player.position.y + posYmod, this.player.position.z);
            Debug.Log("Player Y position: " + this.player.position.y);
        }

    }

    private bool isPlayerOutOfBounds()
    {
        return this.player.position.y > MAX_Y_BOUND || this.player.position.y < MIN_Y_BOUND;
    }

If you call FixedUpdate method, it is run twice a frame so position is moved back and forth during one frame. Update method would be called each frame player is jumping between borders.
Comment: Ok, so that means that something your control scripts moves the player back to the original position.
Comment: I tried your code but it has the same problem. It keeps flashing back and forth between the original position and the new position. I found that even if my position seems to change to a new position, it is affected collision mesh of the original position. So It looks like the character walks through invisible stairs in the sky.
Comment: you log your player y-position. Does that change in log?
Comment: And none of your code does anything with collisions.
Comment: I think it is not a bound value problem. `MAX_Y_BOUND = 58f`, `MIN_Y_BOUND = 0f`, `HALLWAY_HEIGHT = 49f`. Player flashes between Y value `58.5024` and `9.5024`.
Comment: Log says my position has changed to 9.5024.
Comment: And you don't have any other codes linked to your player prefab which could cause that?
Comment: `Character Controller` and `Player Controller` script. I got that script from this youtube video https://youtu.be/5n_hmqHdijM. I'll add that code to my post.
Comment: Just for test. If you remove your Character Control and Player Control from your player and then set your player starting position to y=59 (over the limit) and run your game, does player flash in two position or just move to new position?
Comment: If I remove `Character Control` and `Player Control` and set the player starting position to y=59, it moves to position y=10. it doesn't flashes, just move to the new position.
Comment: I Changed `FixedUpdate()` to `Update()` in `PlayerController` script and `Update()` to `FixedUpdate()` in `HallWayController` script and now it all works. Thanks for your help!


Possible relationship between non-divisors of odd perfect numbers and coefficients of corresponding cyclotomic polynomials?

Question: A positive integer $n$ is called perfect if $\sigma(n)=2n$, where
$$\sigma(n)=\sum_{d \mid n}{d}$$
is the sum of divisors of $n$.
If $n$ is odd and $\sigma(n)=2n$, then $n$ is called an odd perfect number.  Euler proved that an odd perfect number, if one exists, must have the form $n=p^k m^2$ where $p$ is the special/Euler prime satisfying $p \equiv k \equiv 1 \pmod 4$ and $\gcd(p,m)=1$.
It is not known if any odd integers $< 100$ divide an odd perfect number.
It is known, however, that:
An odd perfect number cannot be divisible by 105
An odd perfect number cannot be divisible by 825
An odd perfect number cannot be divisible by 5313
We also have the following MSE question:
Can an odd perfect number be divisible by 165?
where the accepted answer is that: "An odd perfect number, if one exists, could in principle be divisible by 165."
Note that
$$105 = 3\cdot 5\cdot 7$$
$$825 = 3\cdot {5}^2 \cdot 11$$
$$5313 = 3\cdot 7\cdot 11\cdot 23$$
and that
$$165 = 3\cdot 5\cdot 11.$$
Now, I am intrigued by a possible relationship of these non-divisors of odd perfect numbers to coefficients of cyclotomic polynomials.  Indeed, from the Wikipedia page on Cyclotomic polynomial, we have the following penultimate observation:
The case of the 105th cyclotomic polynomial is interesting because 105 is the lowest integer that is the product of three distinct odd prime numbers (3*5*7) and this polynomial is the first one that has a coefficient other than 1, 0, or −1:
WolframAlpha computation of the 105th cyclotomic polynomial
A similar case holds for the 825th and 5313th cyclotomic polynomials:
WolframAlpha computation of the 825th cyclotomic polynomial
WolframAlpha computation of the 5313th cyclotomic polynomial
Lastly, we have the following expression for the 165th cyclotomic polynomial:
$$x^{80} + x^{79} + x^{78} - x^{75} - x^{74} - x^{73} - x^{69} - x^{68} - x^{67}$$
$$+ x^{65} + 2x^{64} + 2x^{63} + x^{62} - x^{60} - x^{59} - x^{58} - x^{54}$$
$$- x^{53} - x^{52} + x^{50} + 2x^{49} + 2x^{48} + 2x^{47} + x^{46} - x^{44}$$
$$- x^{43} - x^{42} - x^{41} - x^{40} - x^{39} - x^{38} - x^{37} - x^{36}$$
$$+ x^{34} + 2x^{33} + 2x^{32} + 2x^{31} + x^{30} - x^{28} - x^{27} - x^{26}$$
$$- x^{22} - x^{21} - x^{20} + x^{18} + 2x^{17} + 2x^{16} + x^{15} - x^{13}$$
$$- x^{12} - x^{11} - x^7 - x^6 - x^5 + x^2 + x + 1$$
WolframAlpha computation of the 165th cyclotomic polynomial
I therefore dare to conjecture that:

CONJECTURE 1 An odd perfect number $n = p^k m^2$ is not divisible by $165$.
CONJECTURE 2 An odd perfect number $n = p^k m^2$ is not divisible by an odd number $l$ if the $l$-th cyclotomic polynomial has a coefficient other than $1, 0$, or $-1$.

Alas, I have no proof.  So here is my question:

Can anybody here (yes, somebody with more computing power) come up with a counterexample?
Answer: $$\frac{\sigma(5.3^2.11^2)}{5.3^2.11^2}< 2$$
thus there is no barrier for an odd perfect number divisible by $3,5,11$.
On the other hand $$\frac{\sigma(5.3^2.7^2)}{5.3^2.7^2}> 2$$
Comment: Thank you for your answer, @reuns. (Upvoted as well!)  Would you care to comment more on why "there is no barrier for an odd perfect number divisible by $165$"?  I am sure you are aware of the [factor chain method](https://math.stackexchange.com/questions/414232) of producing consequent factors from an assumed (initial) set of factors for an odd perfect number.


Android get mobile phones screensize inside View

Question: I am trying to draw x and y axis line, but I can't get the user's phone size. How is this done inside a view? I have tried this:
DisplayMetrics dm = new DisplayMetrics();
int width = dm.widthPixels;
int height = dm.heightPixels;

The entire Android class code is the following:
http://pastebin.com/J02irHd8
Answer: In an Activity or Context run the following code:
getResources().getDisplayMetrics().widthPixels

If you are in a View then try
getContext().getResources().getDisplayMetrics().widthPixels


Trying to get property of non-object in LARAVEL(PHP)

Question: I am using the laravel framework and I am with the following problem:

ErrorException in 26f94b8c1c08197a35c59fdc230bbd6f line 5: Trying to get property of non-object (View: C:\Users\xxx\Desktop\PHP\laravel\resources\views\exemplo.blade.php)

WelcomeController.php:
<?php

namespace CodeCommerce\Http\Controllers;

use CodeCommerce\Category; // Importando o Model Category

use Illuminate\Http\Request;

use CodeCommerce\Http\Requests;
use CodeCommerce\Http\Controllers\Controller;

class WelcomeController extends Controller
{
    private $categories;

    public function __construct(Category $categories)
    {
        $this->categories = $categories;
    }

    public function exemplo()
    {
        $categories = $this->categories;

        return view('exemplo', compact('categories'));
    }
}

Exemplo.blade.php:

Exemplo

    @foreach($categories as $category)

{{ $category->name }}

    @endforeach

Model --- Category.php:
<?php

namespace CodeCommerce;

use Illuminate\Database\Eloquent\Model;

class Category extends Model
{
    //
}

Answer: I have the answer, just called the method all ();
public function exemplo()
{
    $categories = $this->categories->all();

    return view('exemplo', compact('categories'));
}


Selecting parts of div text via the code

Question: Is it possible to select specific text inside a div using the code. I have a div of text, and I need to iterate through each word selecting it individually, then deslecting and onto the next word.
I'm not talking about simulating a select by changing the background css of the words requiring highlighting, but actually selecting it so the outcome is the same as if the user used the mouse to select it.
I know it's possible inside a text area input, but is it possible on a Div?
------------------------UPDATE------------------------------------------
Ok this is where I'm at with it after having another look at it today.  I can select all the text in a span, but not specifically a range of words within that span.  The closest I have come ( code shown below...  ) is selecting the range manually, then removing the selection, then reapplying it.

A selection of words but only from here to here to be selected

The stored selection range object has a startOffset and endOffset property.  My question is how do I set this alongside the initial selection via the code ( not via a mouse select ) ?
Comment: What are you attempting to do? Provide a little bit more info about what you want the outcome to be.
Comment: It's definitely possible because HTML editors us DIVs in combination with 'contenteditable' to achieve things that relate to what you're trying to do (assumption here).
Comment: What browsers do you care about? The Selections API allows this but it's not supported by IE (Edge will have it)
Comment: Yes I looked into contenteditable in the hope it would allow the div to function like a text area but it didn't unfortunately.
Comment: Would need to be just chrome compatible
Comment: Apparently document.execCommand('copy') is supported by most current browsers. Scroll down to the answer with 70 upvotes for this question: http://stackoverflow.com/questions/400212/how-do-i-copy-to-the-clipboard-in-javascript
Comment: https://developers.google.com/web/updates/2015/04/cut-and-copy-commands?hl=en
Comment: Thanks for that but it doesn't shed any light on how to select specific words in a div.
Comment: Sorry, select a specific block of words I mean.
Answer: Please read this article, it's difficult to summarise, so better read it:
http://www.quirksmode.org/dom/range_intro.html
This answer here can be useful too:
Can you set and/or change the user's text selection in JavaScript?
Comment: As much as I like PPK, that Quirksmode article appears to be very old; I'm not sure of how much use it still is today.
Comment: Well, I think at least he'll get some ideas on how this works and what should he look further
Comment: Unfortunately the quirksmode didn't provide an answer.  The method it suggested to set a range of text didn't work.
Answer: Turns out it's fairly straightforward...

adsf asdf asdf asdf