Conversão de Datas para o banco de dados Mysql

Question: Olá!
Bem, Estou utilizando o xhtml e primefaces.
Na minha pagina xhtml, tenho um campo para data e uso o conversor para salvar no banco de dados, eu tenho um problema com o dia.
Se quero salvar 30/04/1989
No banco de dados salva 1989/04/29
Meu campo é do tipo Date.
public class Funcionario {
    private Long id;
    private String nomeUsuario;
    private String senha;
    private String nome;
    private String cpf;
    private Date data;
    private Cargo funcao = new Cargo();
    private Restricao restricao = new Restricao();

    //getters e setters omitidos
}

Qualquer data, sempre é gravada com um dia a menos.
Na minha pagina xhtml estou utilizando um converter do jsf.

       <f:converter converterId="javax.faces.DateTime" />

No entando, fiz uns teste em de inserção Utilizando uma classe com jUnit e eu note que:
   @Test
public void salvar(){

    CargoDAO cargo = new CargoDAO();
    RestricaoDAO restricao = new RestricaoDAO();

    //Cargos e retricoes
    List<Cargo> lista = cargo.listar();
    List<Restricao> lista2 = restricao.listar();

    //CRIA UM USUARIO
    Funcionario usuario = new Funcionario();
    usuario.setNomeUsuario("jhimmyliborio");
    usuario.setSenha("s2mm1s");
    usuario.setNome("TESTE DE INCLUSAO 1");
    usuario.setCpf("88888888888");

    // DEFININDO DATA
    Date data = new Date("1989/04/30");
    usuario.setData(data);

    //DEFINE FUNCAO E RESTRICAO
    usuario.setFuncao(lista.get(1));
    usuario.setRestricao(lista2.get(1));

    // SALVAR
    FuncionarioDAO udao = new FuncionarioDAO();
    udao.salvar(usuario);
}

Se uso o Date para definir a data, tudo ocorre bem.

Se uso o Calendar para definir a data, acabo tendo probelmas com o mês. ele é incrementado +1;
30/04/1989 - >> 1989/05/30
    @Test
public void salvar(){

    CargoDAO cargo = new CargoDAO();
    RestricaoDAO restricao = new RestricaoDAO();

    //Cargos e retricoes
    List<Cargo> lista = cargo.listar();
    List<Restricao> lista2 = restricao.listar();

    //CRIA UM USUARIO
    Funcionario usuario = new Funcionario();
    usuario.setNomeUsuario("liborioJhimmy");
    usuario.setSenha("s2mm1s");
    usuario.setNome("TESTE DE INCLUSAO 2");
    usuario.setCpf("99999999999");

    // DEFININDO DATA
    Calendar c = Calendar.getInstance();
    c.set(1989, 04, 30);
    Date data = c.getTime();
    usuario.setData(data);

    //DEFINE FUNCAO E RESTRICAO
    usuario.setFuncao(lista.get(1));
    usuario.setRestricao(lista2.get(1));

    // SALVAR
    FuncionarioDAO udao = new FuncionarioDAO();
    udao.salvar(usuario);
}

Essa aqui é meu DAO.
   public void salvar(Funcionario user) {
    StringBuilder sql = new StringBuilder();
    sql.append(" INSERT INTO funcionario ");
    sql.append("(nome_usuario, senha, nome, cpf, nascimento, cargo_id) ");
    sql.append("VALUES (lower(?),lower(?),lower(?),lower(?), ?,lower(?)) ");

    try (Connection conexao = new Conexao().getConexao()) {
        PreparedStatement pstm = conexao.prepareStatement(sql.toString());
        pstm.setString(1, user.getNomeUsuario());
        pstm.setString(2, user.getSenha());
        pstm.setString(3, user.getNome());
        pstm.setString(4, user.getCpf());
        pstm.setDate(5, new Date(user.getData().getTime()));
        pstm.setLong(6, user.getFuncao().getId());

        pstm.executeUpdate();
        //Mensagens.msgSucesso("Novo usuário salvo", user.getNomeUsuario());
        pstm.close();
    } catch (SQLException e) {
        e.printStackTrace();
        Mensagens.msgErro("Erro", e.getMessage().toString());
    }

Eu não sei como o converter do jsf se comporta, Já criei minha prorpia classe que converte a entrada da pagina do usuário para o banco. Porém da um erro de conversão. Não foi possível converter uma String para Date.
    public static void dataBanco(Funcionario funcionario){
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
    String banco = sdf.format(funcionario.getData());
    Date data;
    try {
        data = sdf.parse(banco);
        funcionario.setData(data);
    } catch (ParseException e) {
        e.printStackTrace();
    }
}

Alguém pode me ajudar?
Comment: Poderia definir melhor a sua pergunta? Pois vejo várias dúvidas.
Answer: Você relata dois problemas: um com a data usando componentes primefaces (que é inocente, neste caso particular, pois este comportamento é do JSF em si) e um usando a classe Calendar.
Problema com data no JSF
O JSF trata de converter o horário informado para GMT. O fuso horário de Brasília é GMT-3. Ou seja, o JSF está diminuindo 3 horas da data informada, 30/04/1989 (meia-noite), resultando no dia anterior.
Você pode informar o time zone desejado (GMT-3) para o conversor de datas. No seu código, ficaria assim:

    <f:convertDateTime pattern="dd/MM/yyyy" timeZone="GMT-3"/>

Ou pode configurar seu aplicativo para que o JSF sempre utilize o GMT local do sistema (arquivo web.xml):
<context-param>
    <param-name>
            javax.faces.DATETIMECONVERTER_DEFAULT_TIMEZONE_IS_SYSTEM_TIMEZONE
    </param-name>
    <param-value>true</param-value>
</context-param>

Problema com data considerando múltiplos fuso horários no JSF
A primeira solução que apresentei acima se aplica caso o seu sistema seja usado apenas no Brail, e a segunda solução se aplica bem caso o seu sistema seja usado em um país apenas (independentemente de qual).
Se o seu sistema precisa ser compartilhado por usuários em diferentes fuso horários, e dependendo da necessidade, você pode ter que fazer um tratamento mais complexo de data e hora, como por exemplo deixando o JSF converter a data para GMT e salvar também o GMT do usuário. Mas a solução ideal vai depender dos seus requisitos.
Problema com data usando a classe Calendar
O método set de um objeto Calendar espera que o mês esteja indexado em zero (pois é...). De modo que este código:
Calendar c = Calendar.getInstance();
c.set(1989, 04, 30);
Date data = c.getTime();
System.out.println(data.toString());

Produz a seguinte saída:
Tue May 30 10:27:33 BRT 1989
Ou seja, 30 de maio e não 30 de abril como você espera.
Você teria que setar 3 para abril. Ou usar as constantes da classe Calendar:
c.set(1989, Calendar.APRIL, 30);
Comment: Entao eu teria que pegar a String digitada pelo usuário lá no xhtml. Converter para data e manipular com o Calendar e diminuir o mês,  é isso?
Comment: @user3096136 Atualizei minha resposta para tratar também o problema com a data no JSF; que parece ser o problema principal enquanto o problema com o Calendar parece ser apenas uma investigação.
Comment: Muito bem explicado Caffé, Obrigado pela ajuda!


How many valuations of these literals satisfy this expression?

Question: considering all the possible valuations of literals A, B, C, D, E, F, G and H (256 valuations in total), how would you go about finding how many of these valuations satisfy this expression:
$$ (A\rightarrow B) \wedge (B\rightarrow C) \wedge (D\rightarrow E) \wedge (F\rightarrow G) \wedge (G\rightarrow H)$$
I know I could draw the truth table with all the possible valuations, but what's a more efficient method? The solution that I calculated through software simulation should be 48.
Answer: Note that you can divide the expression in three parts:
$$
\underbrace{(A\rightarrow B) \wedge (B\rightarrow C)}_{P} \wedge \underbrace{(D\rightarrow E)}_{Q} \wedge \underbrace{(F\rightarrow G) \wedge (G\rightarrow H)}_{R}
$$
The value of $P$ depends only on $A,B,C$, the value of $Q$ depends only on $D,E$, and the value of $R$ depends only on $F,G,H$. So if $N_P$ is the number of choices of $A,B,C$ for which $P$ is true, $N_Q$ is the number of choices of $D,E$ for which $Q$ is true, and $N_R$ is the number of choices of $F,G,H$ for which $R$ is true, the total number is
$$
N_P N_Q N_R.
$$
Comment: Thank you for that! What happens if I cannot divide the expression into independent parts?
Answer: Observe that the three groups $\{A,B,C\}$, $\{D,E\}$, and $\{F,G,H\}$ are essentially independent; we can analyze them separately.
In a group like $\{A, B, C\}$, not all truth values are possible, if $A$ is true then so are $B$ and $C$; if $B$ is true then so is $C$.  If we consider $A$ to be 'earlier' then $B$, and $B$ to be 'earlier' than $C$, then it suffices to know the earliest true value in the set of three; this completely determines the other values.  For example, if $B$ is the earliest true value than $A$ is false (since it is earlier than $B$) and $C$ is true (since $B\to C$).  So there there only four values this group can have: any of $A$, $B$, or $C$ can be the earliest true value, or else none is true; this is four possibilities.
$\{F,G,H\}$ similarly has four possible values.
$\{D,E\}$ similarly has three values: none is true; $E$ is the earliest true value, or $D$ is the earliest true value.
$4\cdot 4\cdot 3 = 48$.
Answer: Take subsets and then combinations.
From A,B,C we can make a subset, that has I think 4 solutions.
For F,G,H, the same.
And for D,E only 3 solution.
But all combinations can occur, so 4x4x3
Answer: Welcome to Edinburgh
This part concerns the 256 possible truth valuations of the following eight propositional letters A, B, C, D, E, F, G, H. For each of the following ex- pressions, say how many of the 256 valuations satisfy the expression, and briefly explain your reasoning. For example, the expression D is satisfied by half of the valuations, that is 128 of the 256, since for each valuation that makes D true there is a matching valuation that makes D false.


What does one dot under a note mean?

Question: I'm not sure what this notation (dots under notes)means exactly. I am practicing both pieces for an audition to enter orchestra. Help would be greatly appreciated. Also, if you would like to let me know anything else about this piece, as I am quite a beginner, please do let me know. Thank you. The piece is Symphony No. 15 in G Major and Appalachian Festival.
Comment: 1) Welcome! Please take a moment to read through [the topics covered here](https://music.stackexchange.com/help/on-topic). 2) Did you mean to attach an image? It's most likely staccato, but it would be nice to see to know for sure. 3) What instrument do you play? You can add a tag to the question to help connect with people who specialize in that instrument, or to make the "how do I do it" answer more targeted. 4) "Symphony No 15 in G Major" by whom? Lots of people have written symphonies, often more than 15....
Comment: It means _staccato_, detached https://en.wikipedia.org/wiki/Staccato Play a snappy short note that dies out quickly. You know the tune Popcorn? Imagine you're playing Popcorn. Short sounds. https://www.youtube.com/watch?v=NjxNnqTcHhg
Comment: ... and 5) The goal here is to focus each post on a single question. "Anything else about the piece" is too broad for a single question, though "what's the best way to practice this" would be a great question. There's also a chat room here where you can discuss more broadly. ...
Comment: ... 6) Search this site; there are a lot of questions and answers about practice and auditions, like [this one about handling nerves](https://music.stackexchange.com/questions/10151/how-to-deal-with-the-fear-of-auditions) or [this one about practicing](https://music.stackexchange.com/questions/29315/how-can-i-get-through-some-difficult-runs-in-a-piece-otherwise-at-my-level), or [this one](https://music.stackexchange.com/questions/12160/practice-amount-and-habits-for-time-constrained-individuals).
Answer: The dot under a note generally speaking means cut the note off short - often to around half its value. It doesn't mean the next note will be played any sooner, just that the note in question is truncated. This could even have been written as a shorter note, with a corresponding rest after, but it's simpler to merely write a staccato dot instead. The length is affected by approximately half, but is usually left to the discretion of the player.

What does one dot under a note mean?


Como utilizar a string criada string.xml via código

Question: Como utilizar a string criada strings.xml via código
exemplo tem como chamar <string name="hello_world">Hello world!</string> em algum momento no código (Activity).
Answer: Recomendo uma leitura deste tópico:
http://developer.android.com/guide/topics/resources/string-resource.html
Mas para referenciar a uma String localizada nos resources/values, é deste modo:
String string = getString(R.string.hello);

Answer: String mensagem = getResources().getString(R.string.hello_world);

http://developer.android.com/guide/topics/resources/string-resource.html


why is $Y(\omega_1)=\int_{\Omega_2}K(\omega_1,d\omega_2)X_{\omega_1}(\omega_2)$ a $\mathcal{B}_1$-measurable function?

Question: In the picture below, why is $$Y(\omega_1)=\int_{\Omega_2}K(\omega_1,d\omega_2)X_{\omega_1}(\omega_2)$$  $\mathcal{B}_1$-measurable?

I understand that $X_{\cdot}(\omega_2)$ is $\mathcal{B}_1$-measurable, being a section of measurable function $X$, and $K(\cdot, A_2)$ is also $\mathcal{B}_1$-measurable. But why is $Y$ ?
Any help would be appreciated.
Answer: You may use a version of the functional monotone class theorem found in Durrett (Theorem 6.1.3 on page 235) to show that (1) is $\mathcal{B}_1$-measurable for all nonnegative measurable functions on $\Omega_1\times\Omega_2$. Let $\mathcal{H}$ be a collection of functions $f$ on $\Omega_1\times\Omega_2$ for which
$$
\omega_1\mapsto \int_{\Omega_2} K(\omega_1,d\omega_2)f(\omega_1,\omega_2)\tag{1}
$$
is measurable. Then for $f,g\in\mathcal{H}$ and $c\in \mathbb{R}$, $(f+g),cf\in \mathcal{H}$. Also $\mathcal{H}$ is closed under increasing pointwise limits and contains all indicators of sets of the form $A\times B$ with $A\in \mathcal{B}_1$ and $B\in\mathcal{B}_2$ because
$$
\int_{\Omega_2}K(\omega_1,d\omega_2)1_{A\times B}(\omega_1,\omega_2)=1_A(\omega_1)\int_B K(\omega_1,d\omega_2).
$$
Thus, $\mathcal{H}$ contains all bounded measurable functions. Finally, measurability holds for all nonnegative measurable functions by considering the limit of $\int_{\Omega_2}K(\omega_1,d\omega_2)(n\wedge f(\omega_1,\omega_2))$.


Como criar um executável C# com o .NET Core?

Question: Estou desenvolvendo um material de introdução à programação usando o .NET Core. Eu li a documentação quanto à criação e execução de projetos para a web, mas não achei nada que aborde como criar um projeto de um aplicativo de console e gerar dele um .EXE.
Imaginei que com o namespace ConsoleApplication o código geraria um executável, mas na verdade ele cria um .DLL que pode ser executado com dotnet programa.dll.
O que devo fazer para que o projeto crie um executável?
Answer: Encontrei.
Primeiramente o projeto deve ser criado com dotnet new -t console
Como o framework padrão é o netcoreapp1.0, quando dotnet buildfor invocado, ele irá compilar Program.cs como uma dll. Par que ele compile um executável:
No arquivo project.json, deve-se navegar até a opção "frameworks", abrir uma nova linha e incluir "net461":{}, (com a vírgula). Remova a opção "type": "platform", e acrescente
"runtimes": {
    "win7-x64":{}
  }
Após a declaração de imports. Regenere o projeto com dotnet restore. Depois disso, dotnet build compilará Project.cs como um executável.
Answer: Quando fazes criar novo projeto tens que escolher a opção "Console Application" no tipo de projeto.
Comment: Removi a tag visual-studio, não guarda relação com o assunto. Mas também não adicionei vscode, pois a pergunta não trata das IDEs, e sim de como criar a aplicação executável e console, se entendi bem (creio que uma boa resposta não deva apresentar solução que funcione somente em uma IDE).
Comment: Obrigado por sua resposta, mas não entendo. Uso o prompt de comando para invocar `dotnet new` na pasta onde habitará o projeto; como escolho Console Application como tipo de projeto?
Comment: Usas o Visual Studio para escrever código?
Comment: Não; para este projeto de material introdutório, a ser usado em laboratórios de informática com poucos recursos, vou usar o Visual Studio Code como editor. Queria usar uma tag `vscode`, mas ainda não tenho reputação suficiente neste StackOverflow para isto.
Comment: Completamente ridiculo. Esta situação tem tudo a ver com o tipo de IDE que tens obviamente. Se trabalhares com o Visual Studio é de uma maneira, com o VS Code é outra, é ridiculo uma resposta certa a esta pergunta e que não indique que com o Visual Studio Community (Gratis) é só clikar new console application e no outro não. E responde à pergunta, ele é que não foi explicito. Mas abandono a pergunta já que se calhar a única que responde à questão sem depender do IDE é "Fazendo")


Why do we require that the collection of elements in a group form a set?

Question: According to Wikipedia, the collection of elements in a group forms a set.  Is this true, and if it is true is there ever a case where we use something that doesn't work if they instead formed a proper class?
Comment: Conway would have called such a thing a Group rather than a group.
Comment: It is my understanding that the [Surreal Numbers](https://en.wikipedia.org/wiki/Surreal_number) are a proper class yet still satisfies the properties (*apart from being a set*) of being a field (*and therefore also the properties of being a group*).
Comment: It makes it much harder to talk about subgroups and the like. And some versions of set theory don't have "classes," including the most commonly used version, ZFC.
Comment: Pretty similar question: https://math.stackexchange.com/q/83426/87023
Answer:
Yes, a group is defined as a set with an operation on that set.
I believe that the reason groups must operate on sets rather than on some exotic collection is simply convenience. Mathematicians are used to working with sets, and we have lots of familiar notation and technology (e.g. subsets, relations, and functions) that are defined only on sets.


Intersection Observer (Scroll Animation) not working

Question: I bumped into this problem while watching the Intersection Observer tutorial. Mine is a div instead of an image so I did not have to specify an attribute like the one in the video and I believe I almost did everything right as I get 10 console logs because I have 10 divs with a class "box", which were used as a variable in JS file. I used opacity and transformation for the animation as indicated in CSS. I appreciate what I am doing wrong that I cannot see the scroll animation happening.

const targets = document.querySelectorAll('.box');

const lazyLoad = target => {
  const io = new IntersectionObserver((entries,observer) => {
    entries.forEach(entry => {
      console.log('hello World');
      if(entry.isIntersecting) {
        const div = entry.target;

        div.classList.add('fade');

        observer.disconnect();
      }
    });
  });

  io.observe(target);
};

targets.forEach(lazyLoad);
:root {
    --primary-color:#425b84;
    --secondary-color:#5b7bb4;
    --max-width:1100px;
}

* {
    margin:0;
    padding:0;
    box-sizing:border-box;
}

body {
    font:normal 1rem/1.5 'Arial', sans-serif;
    background:var(--primary-color);
    color:#fff;
    overflow-x:hidden;
    padding-bottom:50px;
}

#main-header {
    background:var(--secondary-color);
    padding:4rem 0;
}

.container {
    max-width:var(--max-width);
    margin:0 auto;
    text-align:center;
}

h1 {
    font-size:2.3rem;
}

#timeline ul {
    background:var(--primary-color);
    padding:50px 0;
}

/* Create Line */
#timeline ul li {
    list-style:none;
    position: relative;
    width:6px;
    margin:0 auto;
    padding-top:50px;
    background:#fff;
}

/* Boxes */
#timeline ul li div {
    position: relative;
    bottom:0;
    width:400px;
    padding:1rem;
    background:var(--secondary-color);
    transition:all 0.5s ease-in-out;
    opacity:0;
}

.fade {
    opacity:1;
    transition:all 0.5s ease-in-out;
    transform:translateX(0);
}

/* Right Side */
#timeline ul li:nth-child(odd) div {
    left:40px;
    transform:translateX(1100px);
}

/* Left Side */
#timeline ul li:nth-child(even) div {
    left:-434px;
    transform:translateX(-1100px);
}

/* Dots */
#timeline ul li:after {
    content:'';
    position: absolute;
    left:50%;
    bottom:0;
    width:25px;
    height:25px;
    background:var(--secondary-color);
    transform:translateX(-50%);
    border-radius:50%;
    transition:background 0.5s ease-in-out;
}

/* Arrows Base */
#timeline div:before {
    content:'';
    position: absolute;
    bottom:5px;
    width:0;
    height:0;
    border-style:solid;
}

/* Right Side Arrows */
#timeline ul li:nth-child(odd) div:before {
    left:-15px;
    border-width:8px 16px 8px 0;
    border-color:transparent var(--secondary-color) transparent transparent;
}

/* Left Side Arrows */
#timeline ul li:nth-child(even) div:before {
    right:-15px;
    border-width:8px 0 8px 16px;
    border-color:transparent transparent transparent  var(--secondary-color);
}

@media(max-width:900px){
    #timeline ul li div {
        width:250px;
    }

    #timeline ul li:nth-child(even) div {
        left:-284px;
    }
}

@media(max-width:600px) {
    #timeline ul li {
        margin-left:20px;
    }

    #timeline ul li div {
        width:calc(100vw - 90px);
    }

    #timeline ul li:nth-child(even) div {
        left:40px;
    }

    /* Right Side Arrows */
#timeline ul li:nth-child(even) div:before {
    left:-15px;
    border-width:8px 16px 8px 0;
    border-color:transparent var(--secondary-color) transparent transparent;
}
}
<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">

    <link rel="stylesheet" href="./css/aos.css">
    <link rel="stylesheet" href="./css/style.css">
    <title>Knowledge Timeline</title>

 Knowledge Resume

 Jun Jung

 2007: HTML & CSS

Lorem ipsum dolor sit amet consectetur adipisicing elit. Cumque animi at, dolorum tempora labore exercitationem sapiente voluptate possimus necessitatibus quos cum, voluptatibus maiores voluptates quam illum consequatur nemo est dolores.

 2009: JavaScript & jQuery

Lorem ipsum dolor sit amet consectetur adipisicing elit. Cumque animi at, dolorum tempora labore exercitationem sapiente voluptate possimus necessitatibus quos cum, voluptatibus maiores voluptates quam illum consequatur nemo est dolores.

 2010: PHP & Wordpress

Lorem ipsum dolor sit amet consectetur adipisicing elit. Cumque animi at, dolorum tempora labore exercitationem sapiente voluptate possimus necessitatibus quos cum, voluptatibus maiores voluptates quam illum consequatur nemo est dolores.

 2011: Ruby on Rails

Lorem ipsum dolor sit amet consectetur adipisicing elit. Cumque animi at, dolorum tempora labore exercitationem sapiente voluptate possimus necessitatibus quos cum, voluptatibus maiores voluptates quam illum consequatur nemo est dolores.

 2012: Python

Lorem ipsum dolor sit amet consectetur adipisicing elit. Cumque animi at, dolorum tempora labore exercitationem sapiente voluptate possimus necessitatibus quos cum, voluptatibus maiores voluptates quam illum consequatur nemo est dolores.

 2013: Node.js & React

Lorem ipsum dolor sit amet consectetur adipisicing elit. Cumque animi at, dolorum tempora labore exercitationem sapiente voluptate possimus necessitatibus quos cum, voluptatibus maiores voluptates quam illum consequatur nemo est dolores.

 2014: Angular & React Native

Lorem ipsum dolor sit amet consectetur adipisicing elit. Cumque animi at, dolorum tempora labore exercitationem sapiente voluptate possimus necessitatibus quos cum, voluptatibus maiores voluptates quam illum consequatur nemo est dolores.

 2015: Vue.js

Lorem ipsum dolor sit amet consectetur adipisicing elit. Cumque animi at, dolorum tempora labore exercitationem sapiente voluptate possimus necessitatibus quos cum, voluptatibus maiores voluptates quam illum consequatur nemo est dolores.

 2016:GraphQL & Apollo

Lorem ipsum dolor sit amet consectetur adipisicing elit. Cumque animi at, dolorum tempora labore exercitationem sapiente voluptate possimus necessitatibus quos cum, voluptatibus maiores voluptates quam illum consequatur nemo est dolores.

 2017: Machine Learning

Lorem ipsum dolor sit amet consectetur adipisicing elit. Cumque animi at, dolorum tempora labore exercitationem sapiente voluptate possimus necessitatibus quos cum, voluptatibus maiores voluptates quam illum consequatur nemo est dolores.

Answer: Your intersection observer is currently targeting the .box elements which trigger the initial 10 console logs because they exist on the DOM but wont trigger on scroll because they're not on the screen (out of viewport).
Also, as mentioned in the other answer, you should use a common observer for all your instances.
However, if you want to use a separate observer for each instance, you can target the .box element's parent i.e. the
 element and when the
 element is scrolled into view, you can just add the class to it's child element which is the .box element you were targeting earlier using the ParentNode.children property like this:
const targets = document.querySelectorAll('#timeline li');

const lazyLoad = target => {
  const io = new IntersectionObserver((entries,observer) => {
    entries.forEach(entry => {
      console.log('hello World');
      if(entry.isIntersecting) {
        const div = entry.target.children[0];

        div.classList.add('fade');

        observer.disconnect();
      }
    });
  });

  io.observe(target);
};

targets.forEach(lazyLoad);

Also, your css #timeline ul li:nth-child(odd) div style properties is overriding your new .fade properties because it targetting is more precise. You will need the new .fade properties to target the .box element as precise as you did with the initial styles like this:
#timeline ul li:nth-child(odd) div.fade {
    opacity:1;
    transition:all 0.5s ease-in-out;
    transform:translateX(0) !important;
}
#timeline ul li:nth-child(even) div.fade {
    opacity:1;
    transition:all 0.5s ease-in-out;
    transform:translateX(0) !important;
}

Or you can combined the above css like this:
#timeline ul li:nth-child(odd) div.fade, #timeline ul li:nth-child(even) div.fade {
    opacity:1;
    transition:all 0.5s ease-in-out;
    transform:translateX(0) !important;
}

Check and run the following Code Snippet or open this JSFiddle link for a practical example of the above:

const targets = document.querySelectorAll('#timeline li');

const lazyLoad = target => {
  const io = new IntersectionObserver((entries,observer) => {
    entries.forEach(entry => {
      console.log('hello World');
      if(entry.isIntersecting) {
        const div = entry.target.children[0];

        div.classList.add('fade');

        observer.disconnect();
      }
    });
  });

  io.observe(target);
};

targets.forEach(lazyLoad);
:root {
    --primary-color:#425b84;
    --secondary-color:#5b7bb4;
    --max-width:1100px;
}

* {
    margin:0;
    padding:0;
    box-sizing:border-box;
}

body {
    font:normal 1rem/1.5 'Arial', sans-serif;
    background:var(--primary-color);
    color:#fff;
    overflow-x:hidden;
    padding-bottom:50px;
}

#main-header {
    background:var(--secondary-color);
    padding:4rem 0;
}

.container {
    max-width:var(--max-width);
    margin:0 auto;
    text-align:center;
}

h1 {
    font-size:2.3rem;
}

#timeline ul {
    background:var(--primary-color);
    padding:50px 0;
}

/* Create Line */
#timeline ul li {
    list-style:none;
    position: relative;
    width:6px;
    margin:0 auto;
    padding-top:50px;
    background:#fff;
}

/* Boxes */
#timeline ul li div {
    position: relative;
    bottom:0;
    width:400px;
    padding:1rem;
    background:var(--secondary-color);
    transition:all 0.5s ease-in-out;
    opacity:0;
}

#timeline ul li:nth-child(odd) div.fade, #timeline ul li:nth-child(even) div.fade {
    opacity:1;
    transition:all 0.5s ease-in-out;
    transform:translateX(0) !important;
}

/* Right Side */
#timeline ul li:nth-child(odd) div {
    left:40px;
    transform:translateX(1100px);
}

/* Left Side */
#timeline ul li:nth-child(even) div {
    left:-434px;
    transform:translateX(-1100px);
}

/* Dots */
#timeline ul li:after {
    content:'';
    position: absolute;
    left:50%;
    bottom:0;
    width:25px;
    height:25px;
    background:var(--secondary-color);
    transform:translateX(-50%);
    border-radius:50%;
    transition:background 0.5s ease-in-out;
}

/* Arrows Base */
#timeline div:before {
    content:'';
    position: absolute;
    bottom:5px;
    width:0;
    height:0;
    border-style:solid;
}

/* Right Side Arrows */
#timeline ul li:nth-child(odd) div:before {
    left:-15px;
    border-width:8px 16px 8px 0;
    border-color:transparent var(--secondary-color) transparent transparent;
}

/* Left Side Arrows */
#timeline ul li:nth-child(even) div:before {

 Knowledge Resume

 Jun Jung

 2007: HTML & CSS

Lorem ipsum dolor sit amet consectetur adipisicing elit. Cumque animi at, dolorum tempora labore exercitationem sapiente voluptate possimus necessitatibus quos cum, voluptatibus maiores voluptates quam illum consequatur nemo est dolores.

 2009: JavaScript & jQuery

Lorem ipsum dolor sit amet consectetur adipisicing elit. Cumque animi at, dolorum tempora labore exercitationem sapiente voluptate possimus necessitatibus quos cum, voluptatibus maiores voluptates quam illum consequatur nemo est dolores.

 2010: PHP & Wordpress

Lorem ipsum dolor sit amet consectetur adipisicing elit. Cumque animi at, dolorum tempora labore exercitationem sapiente voluptate possimus necessitatibus quos cum, voluptatibus maiores voluptates quam illum consequatur nemo est dolores.

 2011: Ruby on Rails

Lorem ipsum dolor sit amet consectetur adipisicing elit. Cumque animi at, dolorum tempora labore exercitationem sapiente voluptate possimus necessitatibus quos cum, voluptatibus maiores voluptates quam illum consequatur nemo est dolores.

 2012: Python

Lorem ipsum dolor sit amet consectetur adipisicing elit. Cumque animi at, dolorum tempora labore exercitationem sapiente voluptate possimus necessitatibus quos cum, voluptatibus maiores voluptates quam illum consequatur nemo est dolores.

 2013: Node.js & React

Lorem ipsum dolor sit amet consectetur adipisicing elit. Cumque animi at, dolorum tempora labore exercitationem sapiente voluptate possimus necessitatibus quos cum, voluptatibus maiores voluptates quam illum consequatur nemo est dolores.

 2014: Angular & React Native

Lorem ipsum dolor sit amet consectetur adipisicing elit. Cumque animi at, dolorum tempora labore exercitationem sapiente voluptate possimus necessitatibus quos cum, voluptatibus maiores voluptates quam illum consequatur nemo est dolores.

 2015: Vue.js

Lorem ipsum dolor sit amet consectetur adipisicing elit. Cumque animi at, dolorum tempora labore exercitationem sapiente voluptate possimus necessitatibus quos cum, voluptatibus maiores voluptates quam illum consequatur nemo est dolores.

 2016:GraphQL & Apollo

Lorem ipsum dolor sit amet consectetur adipisicing elit. Cumque animi at, dolorum tempora labore exercitationem sapiente voluptate possimus necessitatibus quos cum, voluptatibus maiores voluptates quam illum consequatur nemo est dolores.

 2017: Machine Learning

Lorem ipsum dolor sit amet consectetur adipisicing elit. Cumque animi at, dolorum tempora labore exercitationem sapiente voluptate possimus necessitatibus quos cum, voluptatibus maiores voluptates quam illum consequatur nemo est dolores.

Comment: Thank you for the answer and clarifying my question.
Comment: Happy i could help Yong. Cheers.
Answer: Transforming out of view
In the example you gave the .box elements would not be intersecting because they are out of the viewport. This is due to the transform property on these elements which places them outside of the view. Removing the transform properties would fix it. You can tackle this by adding another div inside the .box element which is transformed outside of the view. This way the parent (.box) is observed and in the view and the child of .box is transform outside and can be animated back whenever .box is intersecting.
Fade
The .fade class is not working because of the specificity on the the .box divs. #timeline ul li div is far more specific than .fade and thus .fade will always be overwritten by the id selector of #timeline ul li div. To tackle this either make your selectors less specific by using .box { ... } and .box.fade { ... } or add the .fade to the specific selector like so: #timeline ul li div.fade.
A single instance
Also, avoid creating an instance of an IntersectionObserver for each element. A single observer can observe multiple elements. Multiple instances should only be created if the callback argument varies.
In your case, all .box elements have to be handled the same.

const targets = document.querySelectorAll('.box');

const onObserve = (entries, observer) => {
  entries.forEach(entry => {
    if (entry.isIntersecting) {
      const div = entry.target;
      div.classList.add('fade');
      observer.unobserve(div);
    }
  });
}

const io = new IntersectionObserver(onObserve);

const observeTargets = targets => targets.forEach(target => {
  io.observe(target);
});

observeTargets(targets);
:root {
  --primary-color: #425b84;
  --secondary-color: #5b7bb4;
  --max-width: 1100px;
}

* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

body {
  font: normal 1rem/1.5 'Arial', sans-serif;
  background: var(--primary-color);
  color: #fff;
  overflow-x: hidden;
  padding-bottom: 50px;
}

#main-header {
  background: var(--secondary-color);
  padding: 4rem 0;
}

.container {
  max-width: var(--max-width);
  margin: 0 auto;
  text-align: center;
}

h1 {
  font-size: 2.3rem;
}

#timeline ul {
  background: var(--primary-color);
  padding: 50px 0;
}

/* Create Line */

#timeline ul li {
  list-style: none;
  position: relative;
  width: 6px;
  margin: 0 auto;
  padding-top: 50px;
  background: #fff;
}

/* Boxes */

#timeline ul li div {
  position: relative;
  bottom: 0;
  width: 400px;
  padding: 1rem;
  background: var(--secondary-color);
  transition: all 0.5s ease-in-out;
  opacity: 0;
}

#timeline ul li div.fade {
  opacity: 1;
  transition: all 0.5s ease-in-out;
  transform: translateX(0);
}

/* Right Side */

#timeline ul li:nth-child(odd) div {
  left: 40px;
  /* transform: translateX(1100px); */
}

/* Left Side */

#timeline ul li:nth-child(even) div {
  left: -434px;
  /* transform: translateX(-1100px); */
}

/* Dots */

#timeline ul li:after {
  content: '';
  position: absolute;
  left: 50%;
  bottom: 0;
  width: 25px;
  height: 25px;
  background: var(--secondary-color);
  transform: translateX(-50%);
  border-radius: 50%;
  transition: background 0.5s ease-in-out;
}

/* Arrows Base */

#timeline div:before {
  content: '';
  position: absolute;
  bottom: 5px;
  width: 0;
  height: 0;
  border-style: solid;
}

/* Right Side Arrows */

#timeline ul li:nth-child(odd) div:before {
  left: -15px;
  border-width: 8px 16px 8px 0;
  border-color: transparent var(--secondary-color) transparent transparent;
}

/* Left Side Arrows */

#timeline ul li:nth-child(even) div:before {
  right: -15px;
  border-width: 8px 0 8px 16px;
  border-color: transparent transparent transparent var(--secondary-color);
}

@media(max-width:900px) {
  #timeline ul li div {
    width: 250px;
  }
  #timeline ul li:nth-child(even) div {
    left: -284px;
  }
}

@media(max-width:600px) {
  #timeline ul li {
    margin-left: 20px;
  }
  #timeline ul li div {
    width: calc(100vw - 90px);
  }
  #timeline ul li:nth-child(even) div {
    left: 40px;
  }
  /* Right Side Arrows */
  #timeline ul li:nth-child(even) div:before {
    left: -15px;
    border-width: 8px 16px 8px 0;
    border-color: transparent var(--secondary-color) transparent transparent;
  }
}
<!DOCTYPE html>

  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">

  <link rel="stylesheet" href="./css/aos.css">
  <link rel="stylesheet" href="./css/style.css">
  <title>Knowledge Timeline</title>

 Knowledge Resume

 Jun Jung

 2007: HTML & CSS

Lorem ipsum dolor sit amet consectetur adipisicing elit. Cumque animi at, dolorum tempora labore exercitationem sapiente voluptate possimus necessitatibus quos cum, voluptatibus maiores voluptates quam illum consequatur nemo est dolores.

 2009: JavaScript & jQuery

Lorem ipsum dolor sit amet consectetur adipisicing elit. Cumque animi at, dolorum tempora labore exercitationem sapiente voluptate possimus necessitatibus quos cum, voluptatibus maiores voluptates quam illum consequatur nemo est dolores.

 2010: PHP & Wordpress

Lorem ipsum dolor sit amet consectetur adipisicing elit. Cumque animi at, dolorum tempora labore exercitationem sapiente voluptate possimus necessitatibus quos cum, voluptatibus maiores voluptates quam illum consequatur nemo est dolores.

 2011: Ruby on Rails

Lorem ipsum dolor sit amet consectetur adipisicing elit. Cumque animi at, dolorum tempora labore exercitationem sapiente voluptate possimus necessitatibus quos cum, voluptatibus maiores voluptates quam illum consequatur nemo est dolores.

 2012: Python

Lorem ipsum dolor sit amet consectetur adipisicing elit. Cumque animi at, dolorum tempora labore exercitationem sapiente voluptate possimus necessitatibus quos cum, voluptatibus maiores voluptates quam illum consequatur nemo est dolores.

 2013: Node.js & React

Lorem ipsum dolor sit amet consectetur adipisicing elit. Cumque animi at, dolorum tempora labore exercitationem sapiente voluptate possimus necessitatibus quos cum, voluptatibus maiores voluptates quam illum consequatur nemo est dolores.

 2014: Angular & React Native

Lorem ipsum dolor sit amet consectetur adipisicing elit. Cumque animi at, dolorum tempora labore exercitationem sapiente voluptate possimus necessitatibus quos cum, voluptatibus maiores voluptates quam illum consequatur nemo est dolores.

 2015: Vue.js

Lorem ipsum dolor sit amet consectetur adipisicing elit. Cumque animi at, dolorum tempora labore exercitationem sapiente voluptate possimus necessitatibus quos cum, voluptatibus maiores voluptates quam illum consequatur nemo est dolores.

 2016:GraphQL & Apollo

Lorem ipsum dolor sit amet consectetur adipisicing elit. Cumque animi at, dolorum tempora labore exercitationem sapiente voluptate possimus necessitatibus quos cum, voluptatibus maiores voluptates quam illum consequatur nemo est dolores.

 2017: Machine Learning

Lorem ipsum dolor sit amet consectetur adipisicing elit. Cumque animi at, dolorum tempora labore exercitationem sapiente voluptate possimus necessitatibus quos cum, voluptatibus maiores voluptates quam illum consequatur nemo est dolores.

Comment: Thank you so much! I wish I can accept your answer as well as you wrote the detailed description but I have to give it to Andrew since he implemented "Transform" property.


Solving a quadratic matrix equation with transpose matrix

Question: Let $X$ be an unknown matrix and $A$ a known matrix, and suppose the problem is well posed in terms of dimensions.
Is there any way to solve the matrix equation $X^TX=A$, analytically or using numerical methods?
Comment: Have you looked at https://math.stackexchange.com/questions/158219/is-a-matrix-multiplied-with-its-transpose-something-special ? It gives some (fairly obvious) properties of $X^TX$.
Comment: Is $A$ real or complex? Do $X$ and $A$ have the same dimensions, i.e. $n\times n$, or do you want a low-rank approximation with a smaller $X$?
Comment: $A$ is real, and they have the same dimensions.
Comment: Thanks for the link! I'll read it carefully
Answer: The matrix $A$ is symmetric. Thus there exists a unitary matrix $U$ such that $UAU^T=D=diag(d_{i})$ is diagonal with real non-negative entries (source: https://en.wikipedia.org/wiki/Symmetric_matrix#Complex_symmetric_matrices).
Thus,
$$ A = X^TX = (U^\dagger \sqrt{D})(\sqrt{D}U^*). $$
Inspection tells you that
$$ X = \sqrt{D}U^*. $$
Note that this is not unique. For any orthogonal matrix $R$, $\tilde X=RX$ is also a solution.


Website encountered unexpected error - how to avoid?

Question: I'm having that typical problem of Website encountered unexpected error popping up sometimes and then after repairing watchdog MySQL table it all works find again.
My question is if there is a module that would do this automatically? Or any script that I could run from cron or from drupal?
I installed db maintenance module and thought it does that, but apparently no.
Thank you!
Answer: Does MySQL crash after that error? Either way your watchdog table is being corrupted. Are you running out of disk space? Make sure you are using InnoDB tables; MyISAM is prone to corruption.
You can check your table type by running this from a MySQL command prompt and looking for the Engine= parameter.
mysql> show create table watchdog;

You can also disable dblog and enable syslog instead. Syslog writes to your system logs and is much more scalable for higher traffic sites. See if that solves your problem.


Complex logarithm $\log(zw)\neq\log(z)+\log(w)$

Question: Can anyone help me out with explaining why
$\log(zw)\neq\log(z)+\log(w)$?
Answer: The reason why $\log(ab) \ne \log(a)+\log(b)$ is because log is a multi-valued function. Just like $\sqrt x = \pm x^{1/2}$, ${\rm Log}(x) = log(x) +2\pi k i$ for any integer k. I.e. ${\rm Log}(x)$ is not one distinct value. To show why this gives us problems, consider one example;
$$0=\log(1)=\log(-1*-1)\ne \log(-1)+\log(-1)=\pi i +\pi i = 2\pi i$$
$$\log(-1*-1) \ne \log(-1)+\log(-1)$$
Answer: Put $z=-1$ and $w=i{{{{{}}}}}.$
Comment: I'm not sure this answer addresses the OP...
Comment: @DonAntonio I am an [anti-psychologist](http://en.wikipedia.org/wiki/Anti-psychologism). To me this is an explanation.
Comment: Hmmm...and I'm a skeptic...:) How does this even hint towards the "why" in the OP?
Comment: @DonAntonio ^_^ To an anti-psychologist the 'why' you refer to is merely psychological state of mind. A proof, no matter how little explanatory it might look, is as a good as an explanatory one, and I mean this not in mathematical acceptance, but in epistemological acceptance.
Comment: @DonAntonio: IMO, this very clearly hints towards the "why" the OP asked -- any dissatisfaction is because a person didn't want an answer to the "why" the OP asked, but an answer to a different, unasked question.
Comment: I can't see how it is towards the why, @Hurkyl. About the dissatisfaction: I can't understand why you meant ("a person"?)
Comment: @DonAntonio I think Hurkyl means that upon computing both sides of the equality, one realises that they differ by $2\pi i$ and that hints towards something, though that wasn't my intent at all.
Comment: @Git Gud: Then what was your intent?
Comment: @mike4ty4 My intent was that a counter example explains the 'why'. See my first comment in this answer.
Answer: They will always be equal modulo $2\pi i$. The problem is that $\rm exp$ is $2\pi i$ periodic so you have to pick which logarithm you take, and you can't make a continuous choice on all of $\mathbb C^*$.


Is it possible to find which user created an account?

Question: I currently have a Drupal 7 site set up to allow users with the Doctor role to create users with the Patient role, via admin/people/create.
Does Drupal store data about which user created a specific account? If the answer is yes, how can I display this information in a view?
Answer: You have to create a custom module for this.

First you have to add a user field here admin/config/people/accounts/fields. Add a field that will check whether the user has been created by user with role "doctor". A boolean field would suffice. Mark the field as non-mandatory
Create a custom module. This module will provide an interface that only the users with role "doctor" can access. In the interface provide a button, clicking that button will create user with role "patient", also flag the field you created above.
Now in views create a page or block that will display the users, in the filter criteria of the view check whether the boolean field is flagged for that user.
Answer: On admin/reports/dblog, if you filter the log messages by type, and select "user" as log type, you see who created a user.

The "Message" column will contain a message starting with "New User"
The "User" column will contain a link to the user account of who created the user, or it will not contain a link when the user has not been created from a logged-in user

The same is true for who deleted a user account, as visible in the first screenshot.


How to remove results returned from Views UI

Question: I am getting results as expected using Views UI. But I don't want to display a particular record from the output of Views UI. How to achieve this and will I require any hooks for this?
For example; My Views return result as 1,2,3,4. Now I don't want to show 1 in the result. I cannot change the query using hook_views_query_alter as 1 is being used in "where" clause.
Answer: An answer to this question very much turns on what record you want to exclude from the listing. But the typical route here is to use a Contextual Filter on your view.
A typical pattern is that you are displaying a View alongside a node, e.g. a view of items that are related to that node. In this case, you want to exclude the node itself. For this you create a contextual filter that provides a default value of the the current node when there is no filter value present in the URL. You then check the exclude box in the contextual filter configuration. (Detailed steps below.)
Update In comments, you give more detail about what you want to exclude. Or, put another way, what you want to include. In general terms, you want to include nodes that share ANY taxonomy terms with the current node. Specifically, if you have a Teacher content type and a Subject taxonomy, then your requirement is to show every teacher that shares ANY of the taxonomy terms (representing subjects taught) of the currently displayed teacher.
Contextual Filters can do this out of the box, although the configuration is not especially intuitive. The approach is to add a Content: Has taxonomy term ID contextual filter and then configure it so it pulls taxonomy terms out the current node. (Detailed steps below.)
Stage one: Exclude current node

Add a contextual filter Content: Nid (under ADVANCED to the right of the Views configuration page).
Under WHEN THE FILTER VALUE IS NOT IN URL select 'Provide a default value' and choose 'Content ID from URL'. (This gets the node id.)
In the MORE section check the box 'Exclude'. (This says instead of filtering to show only the node, filter to show anything but the node. Of course, the normal non-contextual filters also apply.)

You can add more than one Contextual filter to build up more complex conditions. And, as noted above, you can write PHP for the Contextual filter.

Stage two:  Include all nodes that share ANY of the taxonomy terms of the current node
(aka, exclude any nodes that don't have any common taxonomy terms with the current node, but include everything else)

Add a contextual filter Content: Has taxonomy term id.
Under WHEN THE FILTER VALUE IS NOT IN URL select 'Provide a default value' and choose 'Taxonomy term ID from URL'. (This is a powerful option and what it does depends on the next configuration steps.)
Uncheck the 'Load default filter from term page' box.
Check the 'Load default filter from node page, that's good for related taxonomy blocks'
You will usually want to check the 'Limit terms by vocabulary' box and then select the relevant vocabulary, e.g. 'Subjects'. You might skip this step if you know you only have term reference field on kinds of nodes you are interested in. But it does not harm to check it even in these cases.
Under Multiple-value handling select the 'Filter to items that share any term' option.
Further down the configuration find the 'Reduce duplicates' check box and check it.
Open up the MORE fieldset at the bottom of the configuration and check 'Allow multiple values'
Comment: I need to provide the content Id in my where clause. The scenario is as follows. Suppose A,B,C,D,E are Teachers and Subjects are Physics,Maths,Biology,Chemistry.Now the relations of subject and teachers A,B,C,D,E are as follows: - A teach Physics,Maths,Biology. B Teach Physics,Biology, C Teach Chemistry,Physics, D Teach Maths Biology, E Teach Chemistry.User comes to visit Teacher A .Now I want to display all the teacher who teach the subjects like A. So in my case B,C,D will be filtered because they have one or more subjects in common with A.
Comment: But Teacher E will be discarded as the subject is not common with A.In this scenario I need to give "ContentID"="A" in where condition and I don't want to display A again in the view. So the view will show B,C,D instead of A,B,C,D. I hope I am clear with my requirement. Please help me in achieving this
Comment: @user1843970 The extra detail you provide is helpful (and would be worth adding to the original question for other users). Based on extra detail I've updated my answer. I've tested the configuration with your sample data and get the specified results. And when you view, say, teach E, you are only shown teacher C; when view C, you are shown A, B and E. That is, it show all teachers with one or more subjects in common.
Comment: But I am using Node Reference Field instead of Taxonomy to relate Subject and Teachers. Subject Physics,Maths etc are nodes of "Subject" Content Type. I created it as nodes because there are many additional fields in it. I got your solution in case of Taxonomy but it doesn't work for node reference.
Comment: Is there a downside to simply adding extra fields to your subject vocabulary, rather than using a node? That's definitely a strategy to consider and it does mean you get various useful for behaviour for free or for the cost of (as in answer I've given) a bit of mildly fiddly configuration. If you need to go the Node Reference Route, you'll be able to reach your goal using a Contextual Filter. But I suspect you'll need PHP and that you will be, as it were, reinventing a wheel. (If you want help with this, I suggest modifying your question to narrow down your requirement.)
Comment: Actually I need to go via node reference field only as I need to attach Images to referred node and also there are 3-4 textfield with the node. So as per my requirement whenever any User creates a new Teacher then they able to attach existing subject to the teacher. Now one teacher is associated with multiple subject. When I come to any teacher page then I would able to show my user all other teachers who are related with the subject of current displaying teacher. I hope I am clear till now. I was able to get such view with the help of relationships.
Comment: The only problem is that I am also getting current displaying Teacher Name in that view which should not be there. If I add a hardcoded value of that nid in the filter criteria as suggested by Cassandra then my problem is solved but I cant pass static value there. Please say how should I reach my goal using PHP in contextual filter
Answer: I created sample block that display 5 articles (titles).
One way of ommit first article is go to:
Pager -> User pager and click on numers of element, than:

Specify offset to 1 to the job
Comment: I didnt get your solution. Can you please be more elaborate?The working view is being displayed inside a block.
Comment: @user1843970 Yes I will improve my answer
Comment: I cant do so because the record may come in any place due to dynamic sort criteria. I cannot handle offset as it can lead to loss of other records as well.
Answer: If there is something specific about the record you don't want to return, you can filter your results so that it excludes that record. For example, if you're returning nodes and you don't want to return the node with NID = 1, then add an entry to Filter Criteria where Content:Nid "is not equal to" the value of 1.
Comment: Well if I provide a fixed number as you mentioned then my problem is solved. But I cannot do so. I need to pass the content ID from URL to Content:Nid in Filter Criteria. Is there any way to pass dynamic filter criteria?
Comment: As @Obliquely said, Contextual filters are the way to go in this case.


Unexpected post-hoc result using binomial GLM

Question: I have a dataset that has a categorical factor and numerical response variables as proportions. A simplified deput() included at the end of the body. But, here is what the data looks like:
> head(df)
  ID treatment day alive prop
1  1         A   4     1    1
2  2         A   4     1    1
3  3         A   4     1    1
4  4         A   4     1    1
5  5         A   4     1    1
6  6         A   4     1    1

All together, there are 7 treatments (A:G) including a negative control (treatment A). Each replicate has an n=1 and prop is defined as the proportion of alive individuals / n. Therefore in prop, 1=alive, 0=dead.
I aim to look for differences in mean survival among treatments at day 4. Because my response variable is limited to values between 0-1, I believe I need to build a binomial glm. Here's what I have done:
df$treatment <- as.factor(df$treatment)
m <- glm(prop ~ treatment, data=df, family=binomial())
summary(m)

output:
Call:
glm(formula = prop ~ treatment, family = binomial(), data = df)

Deviance Residuals:
     Min        1Q    Median        3Q       Max
-2.52113   0.00013   0.29175   0.51678   0.96954

Coefficients:
              Estimate Std. Error z value Pr(>|z|)
(Intercept)  3.135e+00  1.022e+00   3.069  0.00214 **
treatmentB  -2.625e+00  1.105e+00  -2.375  0.01755 *
treatmentC   1.543e+01  1.331e+03   0.012  0.99075
treatmentD  -3.644e-15  1.445e+00   0.000  1.00000
treatmentE  -1.190e+00  1.193e+00  -0.997  0.31890
treatmentF  -1.526e+00  1.159e+00  -1.317  0.18797
treatmentG  -7.376e-01  1.261e+00  -0.585  0.55845
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

(Dispersion parameter for binomial family taken to be 1)

    Null deviance: 122.65  on 167  degrees of freedom
Residual deviance: 101.86  on 161  degrees of freedom
AIC: 115.86

Number of Fisher Scoring iterations: 17

Side questions:
#1: Not all of my coefficients are statistically significant. Is this an indication of how well the model fits the data for each coefficient?
#2: The deviance residuals at each quartile are not similar. Does this indicate that the model does not fit my data well? Is there a normality test equivalent for a binomial distribution that my data must pass before modeling?
To (attempt) to answer by question: 'Is there significant difference in mean survival among treatments?' I use anova using test='Chisq'.
a <- anova(m, test='Chisq')

output:

> a
Analysis of Deviance Table

Model: binomial, link: logit

Response: prop

Terms added sequentially (first to last)

          Df Deviance Resid. Df Resid. Dev Pr(>Chi)
NULL                        167     122.65
treatment  6   20.785       161     101.86 0.002005 **
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Based upon the p-value of the anova, I see that there is significant difference in mean survival among treatments.
My next question is to use a post-hoc by looking at pair-wise comparisons mean survival between treatments to detect separation of statistically similar groups.
g <- summary(glht(m, mcp(treatment="Tukey")))

output:
> g

     Simultaneous Tests for General Linear Hypotheses

Multiple Comparisons of Means: Tukey Contrasts

Fit: glm(formula = prop ~ treatment, family = binomial(), data = df)

Linear Hypotheses:
             Estimate Std. Error z value Pr(>|z|)
B - A == 0 -2.625e+00  1.105e+00  -2.375    0.170
C - A == 0  1.543e+01  1.331e+03   0.012    1.000
D - A == 0 -3.644e-15  1.445e+00   0.000    1.000
E - A == 0 -1.190e+00  1.193e+00  -0.997    0.941
F - A == 0 -1.526e+00  1.159e+00  -1.317    0.809
G - A == 0 -7.376e-01  1.261e+00  -0.585    0.996
C - B == 0  1.806e+01  1.331e+03   0.014    1.000
D - B == 0  2.625e+00  1.105e+00   2.375    0.170
E - B == 0  1.435e+00  7.475e-01   1.920    0.409
F - B == 0  1.099e+00  6.912e-01   1.589    0.636
G - B == 0  1.887e+00  8.504e-01   2.219    0.238
D - C == 0 -1.543e+01  1.331e+03  -0.012    1.000
E - C == 0 -1.662e+01  1.331e+03  -0.012    1.000
F - C == 0 -1.696e+01  1.331e+03  -0.013    1.000
G - C == 0 -1.617e+01  1.331e+03  -0.012    1.000
E - D == 0 -1.190e+00  1.193e+00  -0.997    0.941
F - D == 0 -1.526e+00  1.159e+00  -1.317    0.809
G - D == 0 -7.376e-01  1.261e+00  -0.585    0.996
F - E == 0 -3.365e-01  8.252e-01  -0.408    1.000
G - E == 0  4.520e-01  9.625e-01   0.470    0.999
G - F == 0  7.885e-01  9.195e-01   0.857    0.972
(Adjusted p values reported -- single-step method)

And none of the pairwise comparisons have significant differences in mean survival.
Which... surprised me.
So, I made a bar graph to visualize mean survival of each group.
t_means <- aggregate(df$prop, by=list(df$treatment), mean)
t_sd <- aggregate(df$prop, by=list(df$treatment), sd)
t_n <- aggregate(df$prop, by=list(df$treatment), length)
se <- t_sd$x / sqrt(t_n$x)
df_means <- cbind(t_means, se)
colnames(df_means) <- c('treatment', 'mean.survival', 'se')

ggplot(data=df_means, aes(x=treatment, y=mean.survival)) +
  geom_bar(stat='identity') +
  geom_errorbar(ymin=df_means$mean.survival - df_means$se, ymax=df_means$mean.survival+df_means$se)

And if I were to only look at this graph, it seems like at least B and C should separate, as in, have statistically different mean survival.
For lack of better words: What am I doing wrong?
My suspicions: Perhaps, the reason they are not separating is because all treatments have values 0 and 1, and there isn't 100% mortality and 100% survival.
Thanks in advance!
Here is deput()
> dput(df)
structure(list(ID = 1:168, treatment = structure(c(1L, 1L, 1L,
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L,
2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 3L, 3L, 3L,
3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L,
3L, 3L, 3L, 3L, 3L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L,
4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 5L, 5L, 5L,
5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L,
5L, 5L, 5L, 5L, 5L, 6L, 6L, 6L, 6L, 6L, 6L, 6L, 6L, 6L, 6L, 6L,
6L, 6L, 6L, 6L, 6L, 6L, 6L, 6L, 6L, 6L, 6L, 6L, 6L, 7L, 7L, 7L,
7L, 7L, 7L, 7L, 7L, 7L, 7L, 7L, 7L, 7L, 7L, 7L, 7L, 7L, 7L, 7L,
7L, 7L, 7L, 7L, 7L), levels = c("A", "B", "C", "D", "E", "F",
"G"), class = "factor"), day = c(4L, 4L, 4L, 4L, 4L, 4L, 4L,
4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L,
4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L,
4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L,
4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L,
4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L,
4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L,
4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L,
4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L,
4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L,
4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L,
4L), alive = c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
1L, 1L, 0L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 0L, 0L, 0L, 1L,
1L, 1L, 1L, 1L, 1L, 1L, 1L, 0L, 1L, 1L, 0L, 1L, 1L, 0L, 0L, 1L,
1L, 0L, 1L, 0L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
1L, 1L, 0L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 0L, 1L, 1L, 1L, 0L,
1L, 1L, 1L, 1L, 0L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 0L, 1L, 1L,
0L, 1L, 1L, 1L, 1L, 1L, 0L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
0L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
1L, 1L, 1L, 1L, 0L, 1L, 1L, 1L, 1L, 1L, 0L, 1L), prop = c(1L,
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 0L, 1L, 1L,
1L, 1L, 1L, 1L, 1L, 1L, 1L, 0L, 0L, 0L, 1L, 1L, 1L, 1L, 1L, 1L,
1L, 1L, 0L, 1L, 1L, 0L, 1L, 1L, 0L, 0L, 1L, 1L, 0L, 1L, 0L, 1L,
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 0L, 1L, 1L,
1L, 1L, 1L, 1L, 1L, 1L, 0L, 1L, 1L, 1L, 0L, 1L, 1L, 1L, 1L, 0L,
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 0L, 1L, 1L, 0L, 1L, 1L, 1L, 1L,
1L, 0L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 0L, 1L, 1L, 1L, 1L,
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 0L,
1L, 1L, 1L, 1L, 1L, 0L, 1L)), row.names = c(NA, -168L), class = "data.frame")

Edit for @AdamO's response.
Here I make a contingency table:
alive<- aggregate(df$alive, by=list(df$treatment), sum)
dead <- 24 - alive$x
data <- cbind(alive$x, dead)
colnames(data) <- c('alive', 'dead')
row.names(data) <- c('A', 'B', 'C', 'D', 'E', 'F', 'G')
data

output:

  alive dead
A    23    1
B    15    9
C    24    0
D    23    1
E    21    3
F    20    4
G    22    2

From here I use Fisher's Exact Test for a significant relationship between treatment and outcome (alive/dead).
test <- fisher.test(data)
test

output:
> test

    Fisher's Exact Test for Count Data

data:  data
p-value = 0.002345
alternative hypothesis: two.sided

From this I gather that there is a relationship between treatment and outcome...at day 4.
Answer: Nobody died in C. Great! It's easier to see what's going on with a cross tabs like here:
> table(dd$alive, dd$treatment)

     A  B  C  D  E  F  G
  0  1  9  0  1  3  4  2
  1 23 15 24 23 21 20 22

The odds ratio relating death to treatment has as the comparison of C to A $24 * 1 / (23 * 0) = \infty$. The formula for an OR is one every statistician should know off hand, in addition the variance of the OR = AD/(BC) is given by:
$$ \text{var}(\log \widehat{OR}) = 1/A + 1/B + 1/C + 1/D$$
so you tell me what happens when one of $A, B, C, D$ is 0!
R's fitter tells you this in weird ways. The actual OR estimate is $\exp(15.4) \approx 4,876,801$. In other words, this is some artificial value out in la-la-land when R decided to kill the GLM machine from spinning off into space. Unfortunately, just as the OR exploded, so did the standard error estimates:
> vcov(m)
            (Intercept) treatmentB    treatmentC treatmentD treatmentE treatmentF treatmentG
(Intercept)    1.043478  -1.043478 -1.043478e+00  -1.043478  -1.043478  -1.043478  -1.043478
treatmentB    -1.043478   1.221256  1.043478e+00   1.043478   1.043478   1.043478   1.043478
treatmentC    -1.043478   1.043478  1.77e+06(wtf)   1.043478   1.043478   1.043478   1.043478
treatmentD    -1.043478   1.043478  1.043478e+00   2.086957   1.043478   1.043478   1.043478
treatmentE    -1.043478   1.043478  1.043478e+00   1.043478   1.424431   1.043478   1.043478
treatmentF    -1.043478   1.043478  1.043478e+00   1.043478   1.043478   1.343478   1.043478
treatmentG    -1.043478   1.043478  1.043478e+00   1.043478   1.043478   1.043478   1.588933

You can either collect more data, or use some methods for sparse categorical data, like Agresti Coulli correction, median unbiased estimation, or Fisher's Exact Test.
Comment: Hi @Adam, thank you so much for your response. I have a few follow up questions. Please correct me where my logic is wrong. In my original post, I first built a glm which allowed me to detect significant differences in mean proportion alive at day 4 by comparing them to the reference (in this case, A, the control). After that, I wanted to test for significant differences in mean survival among treatments at day 4 among all treatments with an ANOVA. And finally, I wanted to detect separation among treatments using pairwise comparisons. I discovered an unexpected result when I failed to...
Comment: ... detect any separation among groups. Your insight suggested that because my data contains sparse categorical data (0 inflated data), that drove the OR into overdrive. I included what I tried next at the end of my question. Is the binomial glm still an appropriate model to use to compare to a reference group, given sparse categorical data? To me, it seems Fisher's exact test seems to answer the questions that ANOVA would. And lastly, is there a tool that I could use to handle pairwise comparisons of sparse categorical data? Sorry for the long response, I am doing my best to learn more stats.
Comment: @scott.pilgrim.vs.r your understanding is wrong on a few counts. Having lots of zeroes is not "zero inflation". ANOVAs do not factor in; whereas an ANOVA is just a linear regression, your binomial GLM suffices to estimate proportion differences by-group. The output from this GHLT is completely redundant; look closely that it's identical to your `summary.glm` output. This is what achieves precisely the inference you're after. FET is widely known and easily fit and understood in R and should handle the 0 failure cases easily.
Comment: thank you! That helps clarify a lot. Last question, if I wanted to ask "what treatments are statistically *similar* to say, treatment B (which is actually my positive control), how would I do that with this data. This was my reasoning for trying to use GHLT for multiple pairwise comparisons on top of the glm (should of included that, my apologies). Thanks!


IIS - login by domain name is ok; login by IP address fails

Question: I configured IIS server to use Windows authentication.
On a client computer, I used IE to open a website of IIS by

domain name - this resulted in automatic login.
IP address - a dialog box appeared asking for username/password. I entered the correct username/password and still the website refused access.

What is the cause and solution of this problem?
Thanks.
Answer: IE treats any IP address as Internet Zone by default. IE also doesn't allow automatic logon in the Internet Zone by default.  You can either change that setting, or you can add the IP address to Intranet Zones in IE.


modular reductions

Question: How do I use modular reductions to compute this: 11·18·2322·13·19(mod 7)?
I know the answer is 6 through 11=4mod7, 18=4mod7, 2322=5mod7, 13= -1mod7, and 19= 5mod7.
I'm curious as to how you can simplify 2322=5mod7 without using a calculator.
Comment: You can do it mentally.  $7$ divides $2100$ so you are down to $222$.  $7$ divides $210$ so you are down to $12$.
Comment: Otherwise, good old fashioned long division works just fine.
Answer: It gets a little better if you use
$$ 1001 = 7 \cdot 11 \cdot 13  $$ so
$$ 2322 \equiv 320 \pmod 7 $$
Next I suggest $350 = 7 \cdot 50,$ with $49 = 7 \cdot 7,$ so $350 - 49 = 301 \; $ is a multiple of $7.$ Thus
$$  320 \equiv 19 \pmod 7 $$
Then
$$  19 \equiv 5 \pmod 7 $$

modular reductions


JavaScript não cria cookie

Question:

function createCookie(name, value, days)
{
     var expires;
     if (days) {
        var date = new Date();
        date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
        expires = "; expires=" + date.toGMTString();
     }
     else {
        expires = "";
     }
    document.cookie = name + "=" + value + expires + "; path=/";
 }
   createCookie('arquivo','teste','1');

   function getCookie(c_name) {
    if (document.cookie.length > 0) {
        c_start = document.cookie.indexOf(c_name + "=");
        if (c_start != -1) {
            c_start = c_start + c_name.length + 1;
            c_end = document.cookie.indexOf(";", c_start);
            if (c_end == -1) {
                c_end = document.cookie.length;
            }
            return unescape(document.cookie.substring(c_start, c_end));
        }
    }
    return "";
}

alert( getCookie('arquivo'));
Comment: Se estiver a testar localmente tenha atenção pois alguns browser, como o chrome desabilitam os cookies.
Answer: Tenta desabilitar essa opção no seu Chrome.
Settings > Privacy > Content Settings e deixa a configuração igual essa imagem.

JavaScript não cria cookie


MYSQL LEFT JOIN with table name dependent by table column value

Question:
Table1:

======================
|   id    |id_feature|
======================
|    1    |    4     |
|    2    |    2     |
|    3    |    9     |
======================

Table_feature4

======================
|   id    |   size   |
======================
|    1    |   10000  |
|    2    |   12000  |
|    3    |    8000  |
======================

Table_feature2

======================
|   id    |  radius  |
======================
|    1    |    0.9   |
|    2    |     2    |
|    3    |    3.1   |
======================

MY QUERY:
SELECT * FROM Table1
LEFT JOIN (SELECT CONCAT("Table_feature",Table1.id_feature)) Feature ON Feature.id = Table1.id_feature

How can I make it work? Is there a way?
Errors I receive:

/* SQL Error (1109): Unknown table 'Tabel1' in field list */

And if I put 4 manualy in CONCAT and without alias it say

/* SQL Error (1248): Every derived table must have its own alias */

If I'll alias "(SELECT CONCAT("Table_feature",4)) Feature" in ON condition throw this error.

/* SQL Error (1054): Unknown column 'Feature.id' in 'on clause' */

I think the problem is here: "(SELECT CONCAT("Table_feature",4))" , it should return table name Table_feature4 but it only add me a column called CONCAT("Table_feature",4)
Comment: @clinomaniac to be fair, the only thing this question is missing is potential error messages, expected results, and achieved results. You can't really make an easy to reproduce MCVE of a database.
Comment: No, queries must contain direct references to tables. The only way it can "work" is to dynamically create the query; but to know how you want to construct such a query, you would have already had to query table1.
Comment: Agreed. But I am not sure what he is trying to do. The ID's from table1 do not corelate to the feature tables and I have no idea what is expected from the query.
Comment: I think the issue is that in `Table1` the "id_feature" column references the *table* the record is stored in. If my assumption is correct, this can't be done without dynamic SQL.
Comment: Please read and follow the posting guidelines in the help documentation. [mcve] applies here. We cannot effectively help you until you post your MCVE code and accurately describe the problem. We should be able to paste your posted code into a text file and reproduce the problem you described.
Answer: It's not clear what the expected output is but here is my go
SELECT t.id,
CASE t.id_feature
  WHEN 2 THEN (SELECT size FROM feature2 f WHERE f.id = t.id)
  WHEN  4 THEN (SELECT radius FROM feature4 f WHERE f.id = t.id)
END AS feature_value
FROM Table1 t

I have a slightly different naming here but this will output the id and the value column for the corresponding id_feature table
Comment: this should work fine but the problem is that I don't have only id_feature 2 and 4 , I have at least 60. I'll try dynamic SQL as @Jacob H said, maybe this should work. Thanks a lot
Comment: @user3617691 . . . It is only possible to answer the question that you ask.  If this works, I would suggest that you accept this answer and ask another question.  Dynamic SQL won't be much help for this.
Comment: /* SQL Error (1241): Operand should contain 1 column(s) */
Comment: I tested my query in MariaDb and it works there, could it really be different in MySQL? Did you change anything?
Comment: It worked ,I got error because I put * instead of size and radius,
Is there a method like:

`SELECT t.id,
CASE t.id_feature
  WHEN 2 THEN (SELECT * FROM feature2 f WHERE f.id = t.id)
  WHEN  4 THEN (SELECT * FROM feature4 f WHERE f.id = t.id)
END AS features_values
FROM Table1 t`
Comment: but output should have all fields from Table_feature4  when id_feature is 4 and Table_feature2 when id_feature is 2. Like in left join.
Comment: The only other column you have in the feature tables in your question is the id column and that one is already included in the query so no need for that.
Answer: In your subquery you have not a table1 (in subquery the outer table name is not in scope)
and Seems you missed the from clause in subquery
and last you have not an id column or alias in subquery so you don't have a feature.id for ON clause
try using  somthings like eg:
SELECT *
FROM Table1
LEFT JOIN (
    SELECT CONCAT("Table_feature", Table1.id_feature) , table1.id
    FROM Table1
    ) Feature ON Feature.id = Table1.id_feature

Comment: the database object  as table or column name can't be generated  dinamycally is sql  ..this possibile only with server side dinamyc sql generation tecniques .. but repeat  not in straight sql
Comment: `CONCAT("Table_feature", Table1.id_feature)` should look like `CONCAT("Table_feature", Table1.id_feature).radius` , it's table name not column
Comment: what do you mean  ?  you mean that are trying to build a table name dinamically using concat ?? .. this is not allowed  in sql


How can I make daemontools run a simple service without manually calling supervise?

Question: Based on various start guides on the web, the sequence of steps I'm using to go from no daemontools installed to having a simple service running automatically is the following (on Ubuntu 14.04):
$ sudo apt-get install daemontools
$ sudo apt-get install daemontools-run # not clear if this is necessary
$ sudo apt-get install csh             # unsure why csh would be needed to run dt
$ sudo mkdir /service
$ sudo mkdir /service/test
$ sudo chmod 1755 /service/test
$ vi /service/test/run                 # see below
$ vi /etc/rc.local                     # see below
$ # tried power cycling here too
$ sudo svstat /service/test            # Why is supervise not running here?
/service/test/: supervise not running
$ sudo supervise /service/test/ > /dev/null &
[1] 2747
$ sudo svstat /service/test/
/service/test/: up (pid 2758) 1 seconds

#########################################################

# contents of /service/test/run:
#!/bin/sh
echo Running service
exec echo hello

#########################################################

# contents of /etc/rc.local
#!/bin/sh -e
#
# rc.local
#
# This script is executed at the end of each multiuser runlevel.
# Make sure that the script will "exit 0" on success or any other
# value on error.
#
# In order to enable or disable this script just change the execution
# bits.
#
# By default this script does nothing.
csh -cf '/usr/bin/svscanboot &'
exit 0

Also, running svscanboot manually seems to terminate immediately (does not appear in ps aux output if I run in the background either). What set up steps am I missing, or what am I doing wrong?
Answer: I know this is an old question but I had the same problem while installing daemon tools from source.
I then installed the package daemontools-run and it started working.
I went still a little further and tried to look around what was new. I found a file at /etc/inittab with the following call:
    #-- daemontools-run begin
    SV:123456:respawn:/usr/bin/svscanboot
    #-- daemontools-run end


How to solve $3^x=3-x$

Question: Is it possible to solve for $$3^x=3-x$$ without graphing it?
This question is in the section: Solving Exponential equations in my math textbook.
I have tried to log both sides and solve for it however that just leads me back to the original equation.
Comment: Thank you sir. I like your feedback. Pardon me if I did not follow format, english is not my first language. I hope sir you understand.
Comment: Have you tried to solve $3^x + x = 3$?
Answer: HINT
Let consider
$$f(x)=3^x-(3-x)$$
and note that

$f(0)=-2$
$f(1)=1$

therefore by IVT there is a solution in $(0,1)$.
Can you show that this is the unique solution?
Comment: @jayant98 We can consider the sign of $f'(x)=3^x \log 3 +1$.
Comment: Yes Sir! Another way which is more simple and effective.
Comment: If I am correct then: for $x>1$ the term $3^x +x$ is more positive than '3' everywhere in that domain. Also, for x<0 the term $-3+x$ is more negative to be neutralized by $3^x$ as $3^x$ will then become in postive fraction number.
Comment: @jayant98 Call me simply gimusi! Bye
Answer: Sure. The solution can be expressed in terms of the Lambert W function. In general, graphing is not a way of "solving" an equation because it cannot give you an exact solution. Graphing the equations above will help you approximate $x \approx 0.742$ but cannot give you an exact value.

How to solve $3^x=3-x$


null principal returned by ServerRequest in webflux request handler

Question: I have set up authentication in a Spring WebFlux application. The authentication mechanism appears to work fine. For example the following code is used to set up security web filter chain:
@Bean
public SecurityWebFilterChain securityWebFilterChain(ServerHttpSecurity http) {

    return http.authorizeExchange()
            .pathMatchers("/path/to/resource").hasAuthority("A_ROLE")
            .anyExchange().authenticated()
            .and().httpBasic()
            .and().build();
}

This works as expected in conjunction with the UserDetailsRepositoryReactiveAuthenticationManager and MapReactiveUserDetailsService. If a user doesn't have the required authority a forbidden error code is returned and otherwise the request is passed on to the handler.
I have a requirement to apply fine grained permission checks within the handler itself and figured that I should be able to retrieve the authorities from the request as follows:
public Mono<ServerResponse> getMyResource(ServerRequest serverRequest) {

      Authentication authentication = (Authentication)serverRequest.principal().block();
      ...
}

However, I find that the principal is always null. First, is this the correct way to get a handle on the authorities, and if so is there possibly some upstream configuration I'm missing?
Answer: You are blocking the result before is available. You can simply flatmap it so that you don't have to block it.
public Mono<ServerResponse> getMyResource(ServerRequest serverRequest) {
    return serverRequest.principal().flatMap((principal) -> ServerResponse.ok()
            .body(fromObject("Hello " + principal.getName())));
}

UPDATE: If you want to retrieve the principal and body you could zip them.
public Mono<ServerResponse> getMyResource(ServerRequest serverRequest) {
    return Mono.zip(
            serverRequest.principal(),
            serverRequest.bodyToMono(String.class)
    ).flatMap(tuple -> {
        Principal principal = tuple.getT1();
        String body = tuple.getT2();
        return ServerResponse.ok().build();
    });
}

Comment: tell me please how retrieve `principal.getName()` and after do `bodyToMono` from request if I want work  witk login and body object ?;


Fazer ordenação de um Array

Question: Tenho minha class ItemList
    public class ItemListPropaganda {

        private int iconeRid;
        private String texto;
        private int valor;

        public ItemListPropaganda(String texto, int iconeRid, int valor) {
            this.texto = texto;
            this.iconeRid = iconeRid;
            this.valor = valor;
        }

        public int getIconeRid() {
            return iconeRid;
        }

        public void setIconeRid(int iconeRid) {
            this.iconeRid = iconeRid;
        }

        public String getTexto() {
            return texto;
        }

        public void setTexto(String texto) {
            this.texto = texto;
        }

        public int getvalor() {
            return valor;
        }

        public void setvalor(int valor) {
            this.valor = valor;
        }
}

Tenho na minha class principal:
private ArrayList<ItemListPropaganda > itens;

Como posso fazer para ordenar por valor ?
Answer: Você pode implementar a interface Comparator e usá-la para o Collections ordenar sua lista.
Por exemplo, na API 19:
Collections.sort(itens, new Comparator<ItemListPropaganda>() {

            @Override
            public int compare(ItemListPropaganda o1, ItemListPropaganda o2)
            {
                return Integer.compare(o1.getValor(), o2.getValor());
            }
});

Para fins de compatibilidade com APIs inferiores o Integer.compare(arg1, arg2) (só está disponível a partir da API 19) deve ser evitado, como abaixo:
Collections.sort(itens, new Comparator<ItemListPropaganda>() {

            @Override
            public int compare(ItemListPropaganda o1, ItemListPropaganda o2)
            {
                if(o1.getValor() < o2.getValor()) {
                    return -1;
                } else if (o1.getValor() == o2.getValor()) {
                    return 0;
                } else {
                    return 1;
                }
            }
});

Com isso, sua lista será ordenada de acordo com o atributo que você quiser.
Comment: estou utilizando API 19, poderia implementar um exemplo dessa condição?

Fazer ordenação de um Array


Apache Velocity $ vs $!{}

Question: For apache velocity, is there a difference between accessing variables with $ vs. $!{}. If so, what is it?
Answer: There's two differences, the second is formal and quiet.
Formal reference notations include the braces around the variable. The quiet notation includes the <code>!</code> and means to output nothing if the reference does not exist. When combining them, you create a formal and quiet notation.

Apache Velocity $ vs $!{}


Determine counterfeit in a collection of $3^n -1$ coins in n weighings

Question: Given a collection of $3^n -1$ coins, where up to one coin is counterfeit (meaning it weighs more than the rest), prove it is always possible to identify which coin is counterfeit using at most $n$ weighings.
Here's what I've been trying:
I know that when $n = 2$, i.e. in a collection of $8$ coins, it is possible to use $n$ weighings to determine the counterfeit using the intuition that we may exclude two coins and partition the remaining $6$ coins into two groups. We may first weigh these two groups, and weigh two coins in the appropriate group based on the result of this weighing.
Unfortunately, however, this approach does not seem to work in the case of determining a counterfeit in a collection of 80 coins, i.e., $\dfrac{78}{2} = 39$, for which if the process is repeated, we will be attempting to split $37$ coins into two equal groups. Any ideas?
Comment: With 80: You should leave out 26 coins and split the remains 27-27. (Do you see the pattern?)
Comment: Label each coin with numbers from $0$ to $3^n-1$. Write the labels in base $3$. In round $k$, weight the coins with $0$ in the $k$th digit against the coins with $1$ in the $k$th digit.
Answer: For n=2 you have 8  coins. Divide the coins in 3 groups of 2, 3, 3. compare the two sets of 3 coins.
If they are equal in weight then compare the two remaining ones and pick the heavier. Otherwise, if one set of three coins is heavier, then pick two out of 3 and compare them. If they weigh equal then the third one is the heavy coin, otherwise one of the two was heavier.
For n=3 you have 26 coins. Divide them in three sets of 8,9,9, and proceed as above. Compare the two sets of 9 coins and if one set is heavier divide that set in three sets. Otherwise work with the set of 8 coins.
For n=4 you have 80 coins. Divide them into three groups of 26, 27, 27 and compare the two sets of 27 and go from there.
For larger values of n, the same process works. First divide them into three groups of $3^{n-1}-1$, $3^{n-1}$, $3^{n-1}$ and proceed as above.
Answer: Lemma 1: Given a colection of $3^n$ coins, where exactly one coin is counterfeit (meaning it weighs more than the rest), prove it is always possible to identify which coin is counterfeit using at most $n$ weighings.
Proof: Induction by $n$, split the coins into three equal groups.
Lemma 2: Given a colection of $3^n-1$ coins, where at most one coin is counterfeit (meaning it weighs more than the rest), prove it is always possible to identify which coin is counterfeit using at most $n$ weighings.
Proof: Induction by $n$. To prove $P(n+1)$ split the coins into three groups of $3^n, 3^n$ and $3^{n}-1$ coins.
Weight the two equal groups. If the scale tips, thenyou know that there is an heavier coin on the heavier side, and you can apply Lemma 1.
If the scale doesn't tip, then can eliminate the two groups on the scale and apply $P(n)$.


SCCM 2012 - some remote clients unable to download some applications, 401.2 error

Question: I've got a small SCCM 2012 deployment with about 35 clients attached. Most of these clients are in the same network as the single SCCM host, but three are about 1000 miles away.
Oddly, these three clients have stopped being able to download some application packages over BITS. Publishing a new package works for all the other clients, but for these three it never seems to download. If I go to the software centre, it just hangs at "0% downloaded".
On the client, the DataTransfer.log says (repeatedly):
CDTSJob::HandleErrors: DTS Job '{2DCBBB4C-6D84-479A-9218-885B72C834B9}' BITS Job '{E78147DD-4A26-4942-B4FD-6EC3EB77EECD}' under user 'S-1-5-18' OldErrorCount 442 NewErrorCount 443 ErrorCode 0x80072EE2    DataTransferService 30/07/2012 09:27:41 2964 (0x0B94)
CDTSJob::HandleErrors: DTS Job ID='{2DCBBB4C-6D84-479A-9218-885B72C834B9}' URL='http://sccm-host:80/SMS_DP_SMSPKG$/Content_3e7f6982-6346-4f27-ae00-ad5dcb391455.1' ProtType=1   DataTransferService 30/07/2012 09:27:41 2964 (0x0B94)

Cas.log says (repeatedly):
Location update from CTM for content Content_3e7f6982-6346-4f27-ae00-ad5dcb391455.1 and request {AD041FCB-03D2-4FE6-A6FA-38A6B80FB2A1}  ContentAccess   30/07/2012 08:33:39 5048 (0x13B8)
Download location found 0 - http://lonsbrndsccm02.mcs.int.thomsonreuters.com/SMS_DP_SMSPKG$/Content_3e7f6982-6346-4f27-ae00-ad5dcb391455.1  ContentAccess   30/07/2012 08:33:39 5048 (0x13B8)
Download request only, ignoring location update ContentAccess   30/07/2012 08:33:39 5048 (0x13B8)

On the server, I've enabled failed request log tracing. The raw IIS log says the following:
2012-07-30 08:28:42 10.13.111.35 GET /SMS_DP_SMSPKG$/Content_3e7f6982-6346-4f27-ae00-ad5dcb391455.1/sccm /NSCP-0.4.0.172-x64.msi 80 - 10.2.27.19 Microsoft+BITS/7.5 401 2 5 293

Which is a 401.2 error, meaning access denied. The failed request log is large, but the punchline is that it chucks out a Unauthorized: Access is denied due to invalid credentials. message.
All clients are members of the same domain and appear to be (otherwise) working great. I've re-installed the SCCM client, deleted and re-added the computer to SCCM.
Some other packages seem to work fine, the daily anti-malware delta gets downloaded and patched without issue.
Why are these packages failing?
Comment: Make sure your application has a valid msiexec command. You can test it in an elevated command prompt.
Answer: Unsure if you resolved this yet, I'm dealing with similar issues but have found this article to help with some, but not all, clients having this issue.
http://support.microsoft.com/kb/2682514
Answer: Had a similar problem and I fixed it this way:

Log onto DP server
Go to IIS on server.
Select Server and open ISAPI and CGI Restrictions
If there is not an entry for SMS_DP add it with this path "C:\Windows\system32\inetsrv\smsfileisapi.dll"


ftell at a position past 2GB

Question: On a 32-bit system, what does ftell return if the current position indicator of a file opened in binary mode is past the 2GB point? In the C99 standard, is this undefined behavior since ftell must return a long int (maximum value being 2**31-1)?
Comment: If, as you said, it's undefined behavior,  there's no way to (safely or reliably) tell.  It could just return the right number, -1, 0, a random number, it could segfault, or it could send in a swat team.
Answer: on long int
long int is supposed to be AT LEAST 32-bits, but C99 standard does NOT limit it to 32-bit.
C99 standard does provide convenience types like int16_t & int32_t etc that map to correct bit sizes for a target platform.
on ftell/fseek
ftell() and fseek() are limited to 32 bits (including sign bit) on the vast majority of 32-bit architecture systems. So when there is large file support you run into this 2GB issue.
POSIX.1-2001 and SysV functions for fseek and ftell are fseeko and ftello because they use off_t as the parameter for the offset.
you do need to define compile with -D_FILE_OFFSET_BITS=64  or define it somewhere before including stdio.h to ensure that off_t is 64-bits.
Read about this at the cert.org secure coding guide.
On confusion about ftell and size of long int
C99 says long int must be at least 32-bits it does NOT say that it cannot be bigger
try the following on x86_64 architecture:
#include <stdio.h>

int main(int argc, char *argv[]) {
    FILE *fp;
    fp = fopen( "test.out", "w");
    if ( !fp )
        return -1;
    fseek(fp, (1L << 34), SEEK_SET);
    fprintf(fp, "\nhello world\n");
    fclose(fp);
    return 0;
}

Notice that 1L is just a long, this will produce a file that's 17GB and sticks a "\nhello world\n" to the end of it. Which you can verify is there by trivially using tail -n1 test.out or explicitly using:

dd if=test.out skip=$((1 << 25))

Note that dd typically uses block size of (1 << 9) so  34 - 9 = 25 will dump out '\nhello world\n'
Comment: It doesn't work this way for all `x86_64` archs. Specifically, long on 64-bit windows is still 32-bit in size.
Comment: Sorry but, Did you want to mean 64 instead 34? And as the type long is signed the file won't be 17GB, but 9GB instead right?
Answer: At least on a 32bit OS ftell() it will overflow or error or simply run into Undefined Behaviour.
To get around this you might like to use off_t ftello(FILE *stream); and #define _FILE_OFFSET_BITS 64.
Verbatim from man ftello:

The fseeko() and ftello() functions are identical to fseek(3) and ftell(3) (see fseek(3)), respectively, except that the offset argument of fseeko() and the return value of ftello() is of type off_t instead of long.
On many architectures both off_t and long are 32-bit types, but compilation with
   #define _FILE_OFFSET_BITS 64

will turn off_t into a 64-bit type.

Update:
According to IEEE Std 1003.1, 2013 Edition ftell() shall return -1 and set errno to EOVERFLOW in such cases:

EOVERFLOW
For ftell(), the current file offset cannot be represented correctly in an object of type long.
Comment: I think it does boil down to UB. In **section 6.5 paragraph 5** of the **C99 standard** (*ISO/IEC 9899:TC3*):

`If an exceptional condition occurs during the evaluation of an expression (that is, if the
result is not mathematically defined or not in the range of representable values for its
type), the behavior is undefined.`
Comment: @VilhelmGray: Thanks for looking up the Standard to proove this ... :-)
Comment: I've had some persons say `ftell` always returns `0` in such cases, but an overflow seems to imply the possibility of a negative return. Are overflows guaranteed to "wrap around" in the **C99** standard, or is this determined by the implementation?
Comment: @VilhelmGray:  I doubt it will return `0`, I see no reson for this. Propably the whole thing will run into UB? Just avoid it! However UB could lead to anything ...  it also might return 42 then! ;-)
Comment: However, is there anything in the standard to imply that `ftell` itself causes the overflow -- or is the value it returns for these cases unspecified?
Comment: Forgive me, I meant to ask for the C99 standard, not POSIX.
Comment: **Section 220.127.116.11 paragraph 3** of the C99 standard states: `On failure, the ftell function returns −1L and stores an
implementation-defined positive value in errno.` Unfortunately, I believe it leaves the definition of "*failure*" up to the implementation; so perhaps the return value is UB for 2GB?
Answer: There is no 64b aware method in C99 standard. What OS/environment are you using? On windows, there is _ftelli64.
On other platforms, look at http://forums.codeguru.com/showthread.php?277234-Cannot-use-fopen()-open-file-larger-than-4-GB
Comment: @AhmedMasud: I feel there is a misunderstanding here. I suspect "*There is no such method in C99 ...*" refers to something like `_ftelli64()` and **not** to `ftell()`.
Comment: @AhmedMasud: Please excuse, but requiring a `long` "*to be at least 32 bits long*" does mean it **can be exactly** 32 bits long. There is **no need** to have it being 64 bit. Also I *do* agree with you that it'll be quiet strange for a 64bit OS to have `long` being less then 64 bit long ... ;-) However, concluding from my argumentation the answer is correct, isn't it?
Comment: ftell is C89 and C99 standard
Comment: @alk i don't see a reference to _ftelli64() in the OP question so I still don't understand how your answer contributes.
Comment: @Yossarian your answer is still incorrect .. on 64 bit systems long int is 64-bit ; C99 only requires long int to be AT LEAST 32-bit it puts no limits on its maximum size, on a 64-bit system a long and therefore   ftell() offset would be 64-bit
Comment: let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/30430/discussion-between-ahmed-masud-and-alk)
Comment: On windows with visual c targeting x64, sizeof(long) == 4 (I just checked). In practice ftell is not useful for large files, which is why _ftelli64 exists. Thanks @Yossarian.
Answer: This worked for me on Windows32/MinGW to play with a 6GB file
#define _FILE_OFFSET_BITS 64
#include<stdio.h>

int main() {
    FILE *f = fopen("largefile.zip","rb");
    fseeko64(f, 0, SEEK_END);
    off64_t size = ftello64(f);

    printf("%llu\n", size);
}

gcc readlargefile.c -c -std=C99 -o readlargefile.exe

Every single detail, the macro, the compiler option, matters.

ftell at a position past 2GB


Show that the equation for a plane can be expressed with determinant

Question: Show that the equation for a plane through the points $(x_1,y_1,z_1),(x_2,y_2,z_2),(x_3,y_3,z_3)$ can be written as
$$\begin{vmatrix}x&y&z&1\\x_1&y_1&z_1&1\\x_2&y_2&z_2&1\\x_3&y_3&z_3&1\end{vmatrix}=0$$
Is there some clever way of doing this that is not just brute force calculations of the determinant and then calculate the norm vector for the plane, which will be the coefficients for x,y,z-values in the plane equation:
$$\begin{pmatrix}x_3-x_1\\y_3-y_1\\z_3-z_1\end{pmatrix}\times\begin{pmatrix}x_2-x_1\\y_2-y_1\\z_2-z_1\end{pmatrix}$$
and then calculate the equations constant by scalar multiply the norm vector with one of the points.
Answer: $$\begin{vmatrix}x&y&z&1\\x_1&y_1&z_1&1\\x_2&y_2&z_2&1\\x_3&y_3&z_3&1\end{vmatrix}=0$$ implies that the four columns $C_1,C_2,C_3,C_4$ are linearly dependent. And therefore that it exists $a,b,c,d$ non all equal to zero such that $aC_1 + bC_2+cC_3+dC_4=0$, i.e. that
$$ax+by+cz+d=0$$ is an equation of a plane containing the three initial points $P_1,P_2,P_3$.
Comment: Is this determinant equation a useful way to calculate the general equation for a plane through 3 points?
Comment: I think that using the cross product of $P_2-P_1, P_3-P_1$ is more efficient from a computation standpoint.
Comment: Thank you. I think my book want me to contemplate linear dependency, so that is what I will take form the problem.