Comando update não funciona

Question: Tenho três tabelas em um banco de dados, e tenho um método chamado alteraLinhaTabela em que tento atualizar uma das três tabelas por vez identificando-a pela variável tabela. Também passo mais duas classes que contém o conteúdo da atualização, mas para cada tabela uma classe diferente, uma vai ser null enquanto a outra não.
Ignorado o if (tabela == 1) {...}, tenho um segundo if em que escolhe a instrução SQL a ser executada para cada tabela. Crio o PreparedStatement e seto as variáveis de uma das classes (essa "setagem" acontece no método dadosDasLinhas, que uso também em outros métodos), executo, e fecho o PreparedStatement.
public void alteraLinhaTabela(int tabela, Tabela1 t1, Tabela2 t2) {

    String query = "";

    try {

        if (tabela == 1) {

            if (t1.getPagamentoTotal() == 0) {

                deleteLinha(t1.getId(), 1);

                tabela = 3;

                insereLinhaTabela(tabela, t1, t2);

                return;

            }

        }

        if (tabela == 1 || tabela == 3)
            query = "update tabela" + tabela + " set nome=?, dataPagamento=?, atrazo=?, pagamentoTotal=? where id=?";
        else if (tabela == 2)
            query = "update tabela" + tabela + " set endereco=?, telefone=?, cpf=?, produto=?, valorProduto=? where id=?";

        PreparedStatement stmt = getConexao().prepareStatement(query);

        dadosDasLinhas(stmt, tabela, t1, t2);

        if (tabela == 1)
            stmt.setInt(5, t1.getId());
         else if (tabela == 2)
            stmt.setInt(6, t2.getId());

        stmt.execute();

        stmt.close();

    } catch(SQLException e) {

        throw new RuntimeException(e);

    }

}

private void dadosDasLinhas(PreparedStatement stmt, int tabela, Tabela1 t1, Tabela2 t2) {

    try {

        if (tabela == 1) {

            stmt.setString(1, t1.getNome());
            stmt.setString(2, t1.getDataPagamento());
            stmt.setInt(3, t1.getAtrazo());
            stmt.setDouble(4, t1.getPagamentoTotal());

        } else if (tabela == 2) {

            stmt.setString(1, t2.getEndereco());
            stmt.setString(2, t2.getTelefone());
            stmt.setString(3, t2.getCpf());
            stmt.setString(4, t2.getProduto().toString().replace(" ", "")//retira espaços
                    .replace("[", "").replace("]", ""));//retira cochetes
            stmt.setString(5, t2.getValorProduto().toString().replace(" ", "")//retira espaços
                    .replace("[", "").replace("]", ""));//retira cochetes

        }

    } catch(SQLException e) {

        throw new RuntimeException(e);

    }

}

Considerando que eu só quero atualizar a primeira tabela (que tem as colunas nome, dataPagamento, atrazo e pagamento), se tenho uma linha com:

nome = Fulano dos Testes,
  dataPagamento = 2017-03-07,
  atrazo = 5,
  pagamento = 1450;

Altero somente o atrazo e executo o método alteraLinhaTabela.
Mas quando faço um SELECT vejo que não alterou nada. Se vejo o console, está em branco. Se tento pela linha de comando funciona. Se procuro um erro na instrução SQL, não encontro. Se vejo a conexão com o banco de dados, está tudo certo (e até insere linhas). Se faço um debug, vejo que ele passa por todas as linhas e não apresenta nenhum erro ou falta de dados em qualquer variável.
Fiquei sem ideias do que pode estar acontecendo.
O banco de dados é o Oracle Database 11g Express Edition. A IDE é o Eclipse.
Comment: O que há no seu método `getConexao()`? Estou com uma resposta escrita pela metade, mas não consigo terminá-la sem saber como este método está implementado.
Answer: Acoplamento de controle
Antes de responder a sua dúvida diretamente, permita-me falar um pouco sobre o acoplamento de controle.
Se você tem um método que tem um parâmetro que denota o que ele tem que fazer e lá dentro você tem um if ou um switch que com base neste parâmetro decide o comportamento desejado, ainda mais quando um tipo de comportamento tem pouca ou nenhuma relação com um outro tipo de comportamento, é porque deveriam ser métodos separados. Isso daí é um exemplo de acoplamento de controle.
O acomplamento de controle fica ainda pior quando alguns dos parâmetros servem só para alguns dos comportamentos enquanto os outros servem para outros comportamentos, mas todos eles estão na mesma assinatura de método. Um exemplo de um caso grave de acoplamento de controle seria isso:
public String desenharCirculoOuEscreverXML(int oQueFazer, Graphics g, Produto p) {
    if (oQueFazer == 1) {
        g.setColor(Color.RED);
        g.drawEllipse(20, 20, 50, 50);
    } else if (oQueFazer == 2) {
        return "<produto><nome>" + p.getNome() + "</nome><codigo>" + p.getCodigo() + "</codigo></produto>";
    }
    return null;
}

Observe que este método abriga e mistura duas funcionalidades completamente diferentes que não tem sentido de estarem juntas, o que resulta em código confuso, espaguete, amarrado, gambiarrado, difícil de se usar e difícil de se alterar. Tudo ficaria muito mais fácil se elas fossem separadas:
public void desenharCirculo(Graphics g) {
    g.setColor(Color.RED);
    g.drawEllipse(20, 20, 50, 50);
}

public String escreverXML(Produto p) {
    return "<produto><nome>" + p.getNome() + "</nome><codigo>" + p.getCodigo() + "</codigo></produto>";
}

Removendo o acomplamento de controle
Pois bem, o seu código tem um sério problema de acoplamento de controle, tanto no método alteraLinhaTabela quanto no método dadosDasLinhas. Para tanto, vamos primeiro separar as funcionalidades que estão misturadas:
public void alteraLinhaTabela1(Tabela1 t1) {
    if (t1.getPagamentoTotal() == 0) {
        deleteLinha(t1.getId(), 1);
        insereLinhaTabela3(t1);
        return;
    }

    try {
        String query = "update tabela1 set nome=?, dataPagamento=?, atrazo=?, pagamentoTotal=? where id=?";

        PreparedStatement stmt = getConexao().prepareStatement(query);

        dadosDasLinhas1(stmt, t1);

        stmt.setInt(5, t1.getId());
        stmt.execute();
        stmt.close();
    } catch(SQLException e) {
        throw new RuntimeException(e);
    }
}

public void alteraLinhaTabela2(Tabela2 t2) {
    try {
        String query = "update tabela2 set endereco=?, telefone=?, cpf=?, produto=?, valorProduto=? where id=?";

        PreparedStatement stmt = getConexao().prepareStatement(query);

        dadosDasLinhas2(stmt, t2);

        stmt.setInt(6, t2.getId());
        stmt.execute();
        stmt.close();
    } catch(SQLException e) {
        throw new RuntimeException(e);
    }
}

private void dadosDasLinhas1(PreparedStatement stmt, Tabela1 t1) {
    try {
        stmt.setString(1, t1.getNome());
        stmt.setString(2, t1.getDataPagamento());
        stmt.setInt(3, t1.getAtrazo());
        stmt.setDouble(4, t1.getPagamentoTotal());
    } catch(SQLException e) {
        throw new RuntimeException(e);
    }
}

private void dadosDasLinhas2(PreparedStatement stmt, Tabela2 t2) {
    try {
        stmt.setString(1, t2.getEndereco());
        stmt.setString(2, t2.getTelefone());
        stmt.setString(3, t2.getCpf());
        stmt.setString(4, t2.getProduto().toString().replace(" ", "")//retira espaços
                .replace("[", "").replace("]", ""));//retira cochetes
        stmt.setString(5, t2.getValorProduto().toString().replace(" ", "")//retira espaços
                .replace("[", "").replace("]", ""));//retira cochetes
    } catch(SQLException e) {
        throw new RuntimeException(e);
    }
}

Responsabilidade das classes
Acho que é um tanto óbvio que a funcionalidade que fornece o nome de um Produto deveria estar na classe Produto. Também é óbvio que esse nome deveria, se possível, vir adequadamente formatado para que outras classes não precisem ficar consertando-o. Entretanto, não é isso que o seu código mostra:
        stmt.setString(4, t2.getProduto().toString().replace(" ", "")//retira espaços
                .replace("[", "").replace("]", ""));//retira cochetes
        stmt.setString(5, t2.getValorProduto().toString().replace(" ", "")//retira espaços
                .replace("[", "").replace("]", ""));//retira cochetes

Isso indica que a classe Produto não fornece o seu nome em um formato correto, o que obriga outras classes a terem que consertá-lo. Ora, isso significa que a classe Produto não está fazendo a sua parte direito e que portanto outras classes acabam tendo que arrumar/consertar/corrigir aquilo que esta classe não está sabendo fazer direito mas que deveria saber, o que é uma gambiarra. Assim sendo, o ideal é que a classe Produto disponibilize um método que forneça o nome no formato correto. O mesmo pode ser dito sobre o valor do produto na classe Tabela2.
Aliás, isso tem tudo a ver com o princípio da inversão de dependência - O seu código está dependendo de detalhes do comportamento dos métodos, e não apenas em chamar os métodos. Desse princípio também pode ser inferida a regra não fale com estranhos - ou seja, o método não deve chamar outros métodos que não sejam de objetos diretamente relacionados. A melhor alternativa então seria colocar isso na classe Produto:
public String getNomeLimpo() {
    return toString().replace(" ", "").replace("[", "").replace("]", "");
}

E isso na classe Tabela2:
public String getNomeLimpoProduto() {
    return getProduto().getNomeLimpo();
}

public String getValorLimpoProduto() {
    return getValorProduto().toString().replace("[", "").replace("]", "");
}

E com isso, no método dadosDasLinhas2 temos:
        stmt.setString(4, t2.getNomeLimpoProduto());
        stmt.setString(5, t2.getValorLimpoProduto());

Segurança ao usar o PreparedStatement
O seu código não lida com o PreparedStatement adequadamente. Em especial, se o código lançar uma exceção, o PreparedStatement poderá permanecer aberto em um estado zumbi, assim como a conexão também. A forma ideal de lidar com este problema é usar o try-with-resources.
Aliás, não só o PreparedStatement, como a Connection também deve estar em um estado zumbi, uma vez que você não a finaliza e nem executa o commit. A conexão deve estar em modo auto-commit (e portanto o commit explícito é desnecessário), mas mesmo assim, ela deve ser adequadamente fechada. Esta deve ser a falha que você está relatando que faz com que nada apareça no banco de dados.
Também podemos mover as SQLs para campos estáticos.
private static final String ALTERA_LINHA_TABELA1_SQL =
    "UPDATE tabela1 SET nome = ?, dataPagamento = ?, atrazo = ?, pagamentoTotal = ? WHERE id = ?";

private static final String ALTERA_LINHA_TABELA2_SQL =
    "UPDATE tabela2 SET endereco = ?, telefone = ?, cpf = ?, produto = ?, valorProduto = ? where id = ?";

public void alteraLinhaTabela1(Tabela1 t1) {
    if (t1.getPagamentoTotal() == 0) {
        deleteLinha(t1.getId(), 1);
        insereLinhaTabela3(t1);
        return;
    }

    try (
        Connection c = getConexao();
        PreparedStatement stmt = c.prepareStatement(ALTERA_LINHA_TABELA1_SQL);
    ) {
        dadosDasLinhas1(stmt, t1);
        stmt.setInt(5, t1.getId());
        stmt.execute();
    } catch (SQLException e) {
        throw new RuntimeException(e);
    }
}

public void alteraLinhaTabela2(Tabela2 t2) {
    try (
        Connection c = getConexao();
        PreparedStatement stmt = c.prepareStatement(ALTERA_LINHA_TABELA1_SQL);
    ) {
        dadosDasLinhas2(stmt, t2);
        stmt.setInt(6, t2.getId());
        stmt.execute();
    } catch (SQLException e) {
        throw new RuntimeException(e);
    }
}

private void dadosDasLinhas1(PreparedStatement stmt, Tabela1 t1) throws SQLException {
    stmt.setString(1, t1.getNome());
    stmt.setString(2, t1.getDataPagamento());
    stmt.setInt(3, t1.getAtrazo());
    stmt.setDouble(4, t1.getPagamentoTotal());
}

private void dadosDasLinhas2(PreparedStatement stmt, Tabela2 t2) throws SQLException {
    stmt.setString(1, t2.getEndereco());
    stmt.setString(2, t2.getTelefone());
    stmt.setString(3, t2.getCpf());
    stmt.setString(4, t2.getNomeLimpoProduto());
    stmt.setString(5, t2.getValorLimpoProduto());
}

Gerenciamento de conexões
Eu parti da suposição que o seu método getConexao() devolva uma conexão recém-aberta, no modo autocommit (que é o padrão) e que deveria ser fechada em seguida após ser utilizada (conecta, faz alguma coisa, desconecta). Recomendo fortemente que faça isso caso não esteja fazendo.
Se não for este o caso e você quiser insistir em reutilizar uma conexão, então o início dos blocos try seria assim:
try (PreparedStatement stmt = getConexao().prepareStatement(ALTERA_LINHA_TABELA1_SQL)) {

Entretanto, lidar adequadamente com conexões já abertas anteriormente não é algo muito fácil de se fazer. A única coisa que é fácil nesse caso é a possibilidade de se fazer besteira. Vendo o nível de maturidade do resto do seu código, duvido que você tenha conexões reutilizáveis implementadas de forma correta, pois se estivesse não estaria tendo o problema que está tendo (desculpe-me a sinceridade).
Caso você fosse utilizar conexões já abertas anteriormente no seu método getConexao(), você provavelmente vai querer ter transações bem delimitadas, e com isso teria o auto-commit desabilitado e o commit() e o rollback() explícitos em algum lugar do seu código. Além disso, você teria que se preocupar em delimitar o escopo da transação, que normalmente corresponde a uma requisição no caso de um sistema web ou de uma action no caso de um sistema desktop. Com isso, para lidar corretamente com esses conceitos, você tem que saber lidar com ThreadLocals e limpar a conexão caso a thread em questão puder ser reutilizada (caso típico de aplicações web). Um outro problema além disso e mais complicado seria lidar com conexões em pool.
Assim sendo, recomendo que o seu método getConexao() devolva conexões que tenham acabado de ser abertas, com o autocommit habilitado e que sejam sempre utilizadas com o try-with-resources para garantir o fechamento adequado. Sugiro tentar um gerenciamento de conexões mais complexo apenas quando você já for um Cavaleiro Jedi no Java, porque isso não é coisa para padawans.
Outras possíveis melhorias
Provavelmente há mais melhorias que seriam possíveis, mas isso depende de mais informações sobre o seu projeto que não estão na sua pergunta. Em especial acredito que melhorias ainda cabem nas seguintes áreas:

Atraso se escreve com "s", e não com "z"!
O valor do produto deveria ser algo vindo de dentro do produto e não de Tabela2.
O fato de Produto e ValorProduto terem métodos toString() que produzem resultados que necessitam ser consertados depois é um tanto suspeito.
Não acho que o if (t1.getPagamentoTotal() == 0) { ... } esteja no lugar mais adequado.
Utilizar catch (SQLException e) { throw new RuntimeException(e); } provavelmente não é uma boa forma de se tratar erros.
Comment: Era esse o motivo de não funcionar, eu fiquei modificando várias classes que tinham esse acoplamento até chegar na classe em que faço a edição, e então percebi que estava fazendo isso, essa classe eu utilizo como Controller de um .fxml(javafx) que serve para inserir dados, então eu pensei em colocar para alterar dados também(já que ia praticamente duplicar a classe e o .fxml se fizesse separadamente), mas eu me esqueci de mudar a id que ficou igual a -1. Eu pensava que se eu colocasse para alterar, inserir, etc. todas as tabelas em um mesmo método ficaria melhor, mas só fez piorar o código.
Comment: A sua resposta me mostrou também que eu ainda tenho muito o que melhorar, pensava eu que já era um bom programador. Mas esse meu erro de português é injustificável(Como eu errei isso?).

Comando update não funciona


Create WAV file for each record in database

Question: I have table in database in which I'm storing wav files in longblob column.
I'm trying to create an folder and store all wav's of given user on the server. What I have so far is query to database and table and so far simple example of storing just one wav. I'm not much familiar with PHP and I'll need a little bit help on this.
$con=mysqli_connect("localhost","root","xxxx","testDB");

if (mysqli_connect_errno())
{
    echo "Failed to connect to MySQL: " . mysqli_connect_error();
}

$sql="SELECT recording FROM users WHERE accountID = '1234'";
$result=mysqli_query($con,$sql);

while ($result = mysqli_fetch_array($row)) {

    $data = $result["recording"];

    //mkdir('/var/spool/sounds/', 0755, true);

    $wavFileName = "/var/spool/sounds/wavfile.wav";
    $fh = fopen($wavFileName, 'w');
    fwrite($fh, $data);
    fclose($fh);
}

The snipped above is creating one wav in that directory.
If user has 5 saved wav files, how to create directory with name userID and file1.wav, file2.wav .. etc inside?
Answer: Just create the path and filename with concatenation of userid and number of files already created. Then, check if that path exists, otherwise create it.
$directory = "/var/spool/sounds/" . $userID;
$fileExtension = ".wav";
$fileNumber = 1;
while ($result = mysqli_fetch_array($row))
{
    $data = $result["recording"];
    if (!is_dir($directory))
        mkdir($directory, 0755, true);

    $wavFileName = $directory . "/file" . $fileNumber;
    /*
     *  if you need to check if the file already exists,
     *  you can rename the new file "/var/spool/sounds/userId/file1_copy.wav"
     *  or "/var/spool/sounds/userId/file1_copy_copy.wav" if a copy already exists and so on.
     */
    while (file_exists($wavFileName . $fileExtension))
        $wavFileName .= "_copy";
    $fh = fopen($wavFileName . $fileExtension, 'w');
    fwrite($fh, $data);
    fclose($fh);
    $fileNumber++;
}

Comment: maybe is better to create the user folder outside/before the while loop ?
Comment: @Pierre What if, for some reasons, the folder is deleted while looping?
Comment: Thanks for the help!
Comment: Just one question. What will happen if user has `file1.wav` saved in his directory, then the file is deleted from database and later is saved new one in database with that name. This will override the file in directory, right?
Comment: @Ivanov yes it will be
Comment: Then I'll need to check if the file is already exist. Can you show me simple example?
Comment: Yes, exactly. My solution blindly appends an incremented number to the file name. I'll edit my answer.
Comment: Thanks again for the help!
Answer: With the following code, will work :
$account_id = 1234;
mkdir('/var/spool/sounds/'.$account_id, 0755, true);
$sql="SELECT recording FROM users WHERE accountID = ".$account_id ;
$result=mysqli_query($con,$sql);
$i=0;
while ($result = mysqli_fetch_array($row)) {
    $i++;
    $data = $result["recording"];

    $wavFileName = "/var/spool/sounds/".$account_id."/file".$i.".wav";
    $fh = fopen($wavFileName, 'w');
    fwrite($fh, $data);
    fclose($fh);
}


How to interpret output shape printed in the summary of tensorflow model?

Question: I have simple multi-layer perceptron for MNIST data classification problem.
<code>model = tf.keras.Sequential([
  tf.keras.layers.Flatten(),
  tf.keras.layers.Dense(128, activation='relu'),
  tf.keras.layers.Dense(10, activation='softmax')
])
</code>
When printing summary i receive following output:
<code>_________________________________________________________________
Layer (type)                 Output Shape              Param #
=================================================================
flatten_8 (Flatten)          (None, 784)               0
_________________________________________________________________
dense_16 (Dense)             (None, 128)               100480
_________________________________________________________________
dense_17 (Dense)             (None, 10)                1290
=================================================================
Total params: 101,770
Trainable params: 101,770
Non-trainable params: 0
_________________________________________________________________
</code>
How do I interpret output shape printed in the summary? Why is there None therm in the output shape tuple? Why is it not just (784) in the first layer?
Answer: The "None" value refers to the number of input samples (the batch size). To allow you to train on different sized training sets, this value is None. If it were a number, let's say 50 for example, that means you can only train on exactly 50 samples which is usually not very useful (but does occasionally have applications).


Every Sylow subgroup is normal, then $G$ has a subgroup of order $m$ for every division $m$ of $|G|$

Question: Some trouble working out an algebra problem.
Suppose that every Sylow subgroup of a finite group $G$ is normal. Prove that $G$ has a subgroup of order $m$ for every divisor $m$ of $|G|$.
Comment: Title and question are two different things.
Answer: Let $|G| = n \in \mathbb{N}$ and let $n = p_1^{k_1} \cdot p_2^{k_2} \cdots p_r^{k_r}$ be the prime factor decomposition of $n$, where $r \in \mathbb{N}, k_i \in \mathbb{N}$ and $p_i$ is prime $\forall i \in \{1,2,3,\cdots,r \}$.
We know that if for every $i \in \{1,2,3,\cdots,r \}$ the $p_i$-Sylow subgroups of $G$ are normal, then there is a unique $p_i$-Sylow subgroup $S_i$ (because the $p_i$-Sylow subgroups are conjugate). This implies that there also exists an isomorphism $$f: S_1 \times S_2 \times \cdots \times S_r \to G,$$ with $f( (x_1, x_2, \cdots, x_r)) = x_1x_2\cdots x_r.$
Now, we also know that every $p$-group of order $p^t, t \in \mathbb{N}$ has a subgroup of order $p^k$ for each $k \in \{0,1,2,3,\cdots,t \}$ (A $p$-group of order $p^n$ has a normal subgroup of order $p^k$ for each $0\le k \le n$).
Now let $m$ be a divisior of $n$. Then, $m = p_1^{i_1} \cdot p_2^{i_2} \cdots p_r^{i_r}$, where $i_s \in \{0,1,2,\cdots, k_s \}, \forall s \in \{1,2,3,\cdots,r \}$.
Now, we have that the $p_1$-Sylow subgroup has a subgroup of order $p_1^{i_1}$, the $p_2$-Sylow subgroup has a subgroup of order $p_2^{i_2}$ and so on, every $p_u$-Sylow subgroup of $G, u \in \{1,2,3,\cdots,r \}$ has a subgroup of order $p_u^{i_u}$. The direct product from the isomorphism transfers this subgroup of $S_1 \times S_2 \times \cdots \times S_r$ to a subgroup of $G$.


Find a recurrence relation and associated generating function for the number of different binary trees with n leaves

Question: Find a recurrence relation and associated generating function for the number of different binary trees with n leaves.
I'm learning about recurrence relations, and I'm struggling more with defining my recurrence relation than solving it.
My gut tells me that the recurrence relation has something to do with the Catalan numbers. Is that the case? If so (or not so), can you explain how you come up with the recurrence relation?
Comment: It seems that your intuition that it had to do with Catalan numbers [was correct](https://mathoverflow.net/questions/16403/count-of-full-binary-trees-with-fixed-number-of-leaves). According to one of the answers on the linked question above, for $n+1$ leaves, the number of different trees possible is the $n^{\text{th}}$ Catalan number. I don't know how to derive that, though, although it might be explained in the link above.
Comment: Hint: Every tree is either a single leaf or a root with two subtrees.  If $f(x)$ is the generating function this means $f(x) = x + f(x)^2$...
Answer: I can answer your second question about
the generating function.
The recurrence equation is
$$B_n = \sum_{i=0}^{n-1}B_iB_{n-i-1}$$

If you count the number of different
binary trees with a few leaves, or use
the above recurrence relation for the first terms
you would get $1, 1, 2, 5, 14, 42$ etc.
and the generating function for the
binary tree with $n$ leaves or the catalan
numbers would be
$$C(x) = 1 + x + 2x^2 + 5x^3 + 14x^4 + 42x^4...$$
And we want to find a closed form for this.
Now we multiply $C(x)$ with it self:
$$C(x)^2 = 1 + 2x + 5x^2 + 14x^3...$$
Now
$$C(x) - 1 = x(1 + 2x + 5x^2+ 14x^3...)$$
And you recognize $C(x)^2$ inside the parenthesis.
$$C(x) - 1 = x \cdot C(x)^2$$
or
$$x \cdot C(x)^2 - C(x) + 1 = 0$$
and
$$C(x) = \frac{1 \pm \sqrt{1 - 4x}}{2x}$$
And it turns out that
$$C(x) = \frac{1 - \sqrt{1 - 4x}}{2x}$$
is the generating function.
You can use taylor series on this expression and arrive at
that the coefficients are
$$B_n = \frac{1}{n+1}\binom{2n}{n}$$
So the number of binary trees with, say, $50$ leaves would be
$$B_{50} = \frac{1}{50+1}\binom{2 \cdot 50}{50}$$


AngularJS ng-show directive not working on scope function like it should

Question: What is wrong with this simple ng-show directive? It should be simple as I have to buttons hidden using ng-show and when a third button is clicked these two buttons will show So they are hidden until a button is clicked
javascript
$scope.addQuestion = function () {
        $('button#addQuestion').click(function(){
            $scope.addQuestion = true;
            console.log("clicked");
        })
    }

HTML

   <button type="button" class="btn btn-remove"> add</button>
  <button type="button" class="btn btn-remove"> copy</button>

 <button id="addQuestion" type="button" class="btn btn-remove pull-left">
       question
  </button>

Comment: Try to avoid using jquery handlers while using angular.. Here you are registering a click event every digest cycle... Also note that your function on the scope and the scope variable are of same name...
Answer: You got a mix and match.. You just need this:-
No more jquery click event handler, just add a handler function, set the variable on the scope:-
$scope.addQuestion = function () {
      $scope.showQuestion = true;
}

and ng-show="showQuestion" on the section and ng-click="addQuestion()" on the trigger.

   <button type="button" class="btn btn-remove"> add</button>
  <button type="button" class="btn btn-remove"> copy</button>

 <button id="addQuestion" ng-click="addQuestion()" type="button" class="btn btn-remove pull-left">
       question
  </button>

Comment: @jmccommas You are welcome... Hope you got your issue resolved!!
Comment: @jmccommas Do you mind accepting the answer that helped you most?
Answer: If you want to modify the scope inside a Jquery function, you have to call the $apply method manually
$scope.addQuestion = function () {
        $('button#addQuestion').click(function(){
            $scope.addQuestion = true;
            $scope.$apply();
            console.log("clicked");
        })
    }

But I am pretty sure you don't need JQuery to accomplish what you want.
Comment: I have tried this but still is not showing the other two buttons
Comment: One more question, if I wanted to add a class on that click event would I add it like this: $scope.addQuestion = function (event) {
            $scope.showQuestion = true;
            $(event.target).addClass('disabled');
        }
Comment: @jmccommas You should just use angular to add class i.e use `ng-class` and bind it on some variable i.e `<button id="addQuestion" ng-class="{disabled:showQuestion}"` Similarly you could use `<button ng-disabled="showQuestion"`. If you really want to use event then you need to pass `$event` as argument from the view to the function handler


Differential calculus: integrate $\frac{1}{x \log^3 (x)}$

Question: I would like a step by step description of how to integrate $$\frac{1}{x \log^3 (x)}$$

I know that the answer is - $\frac{1}{2\log^2(x)}$
and that the integral of $\frac{1}{\log^2(x)}$ is $\frac{1}{\log(x)}$
and that the integral of $\frac{1}{\log(x)}$ is $\log(\log(x))$

But I don't see how these are obtained.
Comment: "I know that (...) the integral of $\frac{1}{\log^2(x)}$ is $\frac{1}{\log(x)}$ and that the integral of $\frac{1}{\log(x)}$ is $\log(\log(x))$" No, they are not. Did you try differentiating these, just for kicks?
Answer: For this problem:$$\int\frac{1}{x\log^3(x)}dx\tag{1}$$we can use the substitution:$$u=\log^3(x)\tag{2}$$$$\therefore \log(x)=u^{\frac{1}{3}}\tag{3}$$which leads to:$$du=3\log^2(x)\times\frac{1}{x}dx$$$$=3(u^{\frac{1}{3}})^2\times\frac{1}{x}dx=\frac{3u^{\frac{2}{3}}}{x}dx$$$$\therefore \frac{dx}{x}=\frac{du}{3u^{\frac{2}{3}}}\tag{4}$$Now we substitute this into (1) to get:$$\int\frac{1}{x\log^3(x)}dx=\int\frac{1}{3u^{\frac{2}{3}}\times u}du=\frac{1}{3}\int\frac{1}{u^{\frac{5}{3}}}du$$$$=\frac{1}{3}\int u^{-\frac{5}{3}}du=\frac{1}{3}\left(\frac{u^{-\frac{2}{3}}}{-\frac{2}{3}}\right)=-\frac{1}{2}\times\frac{1}{u^{\frac{2}{3}}}=-\frac{1}{2\log^2(x)}$$
Comment: Having seen the answer from @TimRaczkowski, I would use that substitution instead - it is much much simpler.
Answer: Make the substitution $u=\log x$, then $du=\frac1x\,dx$ and the integral becomes $\int u^{-3}\,du$.
Comment: Your substitution is much simpler than the one I proposed :)


Set "select" field on a node programatically

Question: I am creating nodes programmatically on a specific content type. The content type has a "select field" that I am trying to set value with and cannot do it. Below is my code:
<code> $node = \Drupal::entityTypeManager()->getStorage('node')->create(array(
      'type'  => 'level3',
      'title' => $file_name,
      field_level2_title => [
        'value' => 'Assessment'
      ],
      field_level3_title => $file_name,
      field_level3_readmore => [
        'uri' => $file_uri,
        'title' => $file_name
      ],
    ));
</code>
The select field name is "field_level2_title and I am unable to assign this. Any help?
Comment: A select element is a widget, not a field type. What type of field is it? (Entity Reference, Text, etc)
Comment: Then you need to assign it the ref ID.
Comment: It's an entity reference field.
Comment: Ahh instead of value I should assign refid?
Answer: Thanks for the comments above. the solution worked for me is as below:
field_level2_title => [
'target_id' => $ref_id_field
]


MongoDB slow initial connection

Question: I am facing a really weird scenario, the initial connection to mongoDb takes around 15 seconds.
My current setup is the following:

mongodb running inside an ubuntu vm on the same machine
mongodb is version 2.6.1
node.js installed using brew and it is version 0.10.28

Upon restarting nodemon the initial signin POST takes around 15 seconds
POST /api/v1/signin 200 14707ms - 56b

other POST to the same route without restarting the server is relatively fast:
POST /api/v1/signin 200 76ms - 56b

the reason why this bothers me is that because this project is still in development, nodemon tends to restart a lot and testing is being a pain.
I am using the following node modules which are related to db and authentication:

"express": "~4.2.0",
"mongoose": "3.8.8",
"passport": "0.2.0",
"passport-local": "0.1.6",
"bcrypt": "*"

this is the way i am connecting to mongo:
var mongoUrl = "mongodb://devmachine.local:27017/project";
mongoose.connect(mongoUrl, {auto_reconnect: true});

any help would be highly appreciated.
Thanks
Comment: Have you tried using the IP address instead of `devmachine.local` in `mongoUrl`?  15 seconds sounds like a DNS-related problem.
Comment: seems that  replacing the hostname by an IP solved the issue, weird, is that a mac os DNS issue????
Comment: No, it is most likely that devmachine.local can't resolve your machine.
Answer: Replace the hostname with IP
From:
var mongoUrl = "mongodb://devmachine.local:27017/project";
To:
var mongoUrl = "mongodb://127.0.0.1:27017/project";
Comment: +1 In my case I couldn't use the IP due to using TLS, but adding the IP and DNS in the `/etc/hosts` file solved the issue.
Answer: This would disturb your backend's functionality since the connection isn't right.
change the mongoURI to "mongodb://127.0.0.1:27017"
If this doesn't even work, try installing the MongoDB community server from here: https://www.mongodb.com/try/download/community
This also runs a MongoDB service in your machine, and that's what solved it for me. Remember to restart your backend after completing the steps.
Comment: I'm sorry but this is not a relevant answer
Comment: Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer).

MongoDB slow initial connection


How do I display a "Thank You" message after submitting a Webform 3.x form?

Question: I recently upgraded a Drupal 5 site to Drupal 6.  This upgrade also entailed upgrading the Webform module from version 2 to version 3.
I have a very simple webform setup that asks for a name and email address to sign up for a newsletter.  Before upgrading, the webform administration area had a textarea labeled Confirmation message or redirect URL, but I no longer see this option.
When the form is submitted, it just reloads the form with empty values.  The form is submitted properly, but I would like to be able to present a "Thank You" message instead of reloading the form page.
Answer: From the webform node, click the Webform tab, then the Form Settings sub-tab. There should be a large textarea labeled "Confirmation message".
If you are on node 1, the URL would be example.com/node/1/webform/configure.
Comment: I don't have any sub-tabs when I am on the Webform tab.
Comment: Make sure you have Webform 6.x-3.9 installed. I *just* installed it on a test site and it looked [like this](http://awesomescreenshot.com/01acsa61c).
Comment: I do have 3.9 installed and I do not see any of those sub-tabs.  I think it has to do with our theme because I do see them using the Bluemarine theme.
Comment: I was able to fix my theme by following the advice of **rank** here: http://drupal.org/node/329616


How to make my app unmovable from pc to another

Question: I created an application with python that i will be selling in the next few days, however I don't want anyone that buys it able to share it with other people as it is paid so everyone that wants the app should pay. i'm not finding a way of doing it, I hope you help me to do so!
can you recommend any tool/framework/method that will help me to achieve this.
I tried to search and wasn't able to find a good way.
I am using kivy for GUI and made with pure python.
Note: I will compile the app only for PCs and not mobile phones
Thanks in advance.
Comment: Any copy-protection mechanism you invent will likely inconvenience paying users and a determined hacker will ultimately break it.  So consider the trade-offs between making it ultra-hard to copy and the value of the application itself.  The easiest thing you could do is package your app for the Windows Store (or Steam) and just sell it there. Disclaimer - I have no idea what it would take to ship a python app through the store. But you could look at [this](https://learn.microsoft.com/en-us/windows/msix/desktop/desktop-to-uwp-run-desktop-app-converter)
Answer: A possible way to do that would be to have some sort of launcher that someone who paid for the app could type their credentials in and would pass along their windows username to you then pass that username over the internet to you and make it the first thing python checks before processing and have it check that it is the same username
lastly using [pyminifier] https://liftoff.github.io/pyminifier/ to make your code look unreadable you should either embed python in another language https://docs.python.org/3/extending/embedding.html or if that is too much of a hassle compile your username specific script into python bytecode but know that python bytecode alone isn't enough to stop anyone skilled in python from using a github script to get your source code minus actual variables and comments and sometimes doc


Contest math question about logarithmic and exponential functions

Question: Here's the question I'm trying to solve:
For what value of $k$ is the function $f(x)=k^x$ tangent to $g(x)=\log_k(x)$?
My Attempt:
Since $f(x)$ and $g(x)$ are inverses of each other and are therefore symmetrical on $y=x$, the tangent point must occur when $y=x$. By setting $f(x)=x$ and $g(x)=x$, we get $x=k^x$ and $x=\log_{k}x$ but these two equations are pretty much the same since $x=k^x \Rightarrow x=\log_{k}x$ so I can't find any unique solution. Most other approaches I've tried pretty much get me to the same two equations.
I've tried taking the derivative of both functions which have to be 1; $f'(x)=\ln(k)k^x=1$ and $g'(x)=\frac{1}{\ln(k)x}=1$ and since previously $k^x=x$ we have $x \ln(k)=1$ but we get the same issue where we get two equivalent equations.
After graphing it and trying to reverse engineer the answer I found that $1.4<k<1.5$ however this doesn't seem to correspond with any value one might expect either for example $\frac{e}{2}\approx 1.36$ or $\sqrt{e}\approx1.67$ or $\sqrt[3]{e}\approx 1.39$.
Note that this is a math competition question so should in theory (for this competition) be doable in about 5 minutes so I'm sure there's a trick to it that I have't figured out. (maybe Lambert W although I doubt it)
Answer: Here it goes:
As $f(x)$ and $g(x)$ are inverse of each other, for them to be tangent at one point, The slope at their point of intersection must be "$1$"
Let them meet at point $(x_1,y_1)$
hence, $f(x_1)=g(x_1)=x_1$ because, they both are also tangent to line $y=x$
putting the values
$$
k^{x_1} = \frac {\ln(x_1)}{\ln(k)}=x_1
\tag{1}
$$
now derivative of both curves at $x=x_1$ must equal "$1$"
$$
f'(x_1) = g'(x_1) = 1
$$
substituting values
$$
k^{x_1}\ln(k) = \frac{1}{x_1\ln(k)} = 1
\tag{2}
$$
using this, $$
x_1 = \frac{1}{\ln(k)}
\tag{3}
$$
substitute
$x_1 = \frac{1}{\ln(k)}$ in Equation (1)
hence
$$
\frac{\ln\Bigl(\frac{1}{\ln(k)}\Bigr)}{\ln(k)}
= \frac{1}{\ln(k)}
$$
by cross multiplying terms
$$
\ln\biggl(\frac{1}{\ln(k)}\biggr) = 1
$$
hence
$$
\frac{1}{\ln(k)} = e
$$
$$
\ln(k) = \frac{1}{e}
$$
which gives
$$
k = e^{\frac{1}{e}}
$$
substituting value of "$k$" in function yields
$$
f(x) = e^{\frac{x}{e}}
$$
and
$$
g(x) = e\ln(x)
$$
Answer: $f(x)=k^x. g(x)=\log_k (x) = \frac{\ln x}{\ln k}$
They intersect: $k^x=\ln x/\ln k$
Their slopes match: $\ln k \cdot k^x = \frac{1}{x \ln k}=1$
$\implies x= 1/\ln k $
$\ln k \cdot e^{x \ln k}=1$
$\implies \ln k = 1/e\implies k=e^{1/e}\approx 1.444668$

$\ln k\cdot  e^ {x \ln k}=\frac{1}{x \ln k}$
$x \ln k = W(1/\ln k)$
$\ln xe^{\ln x}=1/\ln k $
$\ln x = W(1/\ln k)$


Como traduzir o agenda header do Full Calendar?

Question: Saudações, amigos do Stack Overflow!
Estou a um passo de completar uma agenda utilizando o fantástico plugin do Full Calendar, no qual fico grato por existir. Porém, estou tendo alguns problemas de tradução com ele:
Infelizmente, a propriedade locale/language não está funcionando corretamente no meu código (estou usando C# com MVC5 e JS), logo, estou tendo que traduzir na mão:
<code>$('#calendar').fullCalendar({
    monthNames: ['Janeiro', 'Fevereiro', 'Março', 'Abril', 'Maio',
        'Junho', 'Julho', 'Agosto', 'Setembro', 'Outubro',
        'Novembro', 'Dezembro'],
    dayNamesShort: ['Dom', 'Seg', 'Ter', 'Qua',
        'Qui', 'Sex', 'Sab'],

    defaultDate: new Date(),
    locale: 'pt-BR',
    header: {
        left: 'prev,next today',
        center: 'title',
        right: 'month,agendaWeek'
    },
    columnFormat: 'ddd',
</code>
Até o momento está tudo supimpa, porém a única coisa que não estou conseguindo traduzir desta maneira é o "Agenda Header" - O danado se recusa a ficar em português, e não consegui encontrar na documentação/em outros sites uma maneira de formatar apenas esta propriedade.
Aqui tem uma imagem que mostra o que eu quero dizer:

Eu quero traduzir aquela partezinha do Dec 31, 2017 - Jan  6, 2018 para o português, e para o formato correto, mas como eu já disse, a propriedade Locale não está funcionando.
Outra coisa:
Estou ciente que a propriedade Locale só funciona com os JS de idiomas (pt-br.js) sendo chamados corretamente. Ele está devidamente referenciado na pasta locale e no BundleScript usado para este calendário.
Answer: Olá eu fiz da seguinte forma para traduzir tudo
ao descompactar o zip fullcalendar, você terá o endereço:
fullcalendar/locale/pt-br.js.
faça a chamada do arquivo na página em questão
<code><script src='js/fullcalendar361/fullcalendar.js'></script>
<script src='js/fullcalendar361/locale/pt-br.js'></script>
<script src='js/fullcalendar361/lib/moment.min.js'></script>

$(document).ready(function() {

    $('#calendar').fullCalendar({
        // no script setar "pt-br"
        locale:  'pt-br',
</code>
Espero ter ajudado
Comment: Infelizmente esta foi uma das primeiras coisas que fiz e não deu certo, Wilson! Talvez seja algum problema com o MVC, pois se eu fizer em um arquivo separado via Script direto, isso funciona.

Obrigado mesmo assim!
Comment: Alterei o código que fiz para incluir as chamadas dos scripts, você tentou desta forma também?


A can do the work in 15 days and B can demolish that work in 20 days. If they work on alternate day starting with A, how many days are required?

Question: A can do the work in 15 days and B can demolish that work in 20 days. If they work on alternate day starting with A, how many days are required to do the work?
Total unit of work= LCM(15,20)=60 units
A can do 4 units
B= -3 units( - because B demolishes the work)
Now, in 2 days 1 unit work will be completed. I understood till this point.
Now, in the solution it has been given that subtract the maximum work from 60 which gives us 56.
1 unit-2days
56 units-112 days
hence, total number of days is 113.
Help me understand this solution.
Comment: The last 4 units done by A the last day aren't going to be demolished because the work is done, that's why they are subtracted.
Comment: What an odd question.  It asks how many days are *required* which connotes the minimum possible number of days to complete the work with the available resources.  The minimum is achieved by having B take a vacation (it says "B can demolish", not "B will demolish"), allowing A to complete the work in 15 days.
Answer: The last few days of work take us close to completing the $60$ units of work. After $112$ days $56$ units have been completed, which is one day's worth of work by $A$ short of completion. And since $112$ is even, the next day is indeed $A$'s day to work and she can complete the project.
Comment: If it would have been for three people then?
Comment: A did work in 12 days and B in 20 days and suppose C demolishes it in 15days. So in 3 days it will complete 4 units of work. But how we will know who will work on the last date?
Comment: Since A and C both work on odd days. @Joffan
Comment: @CoderSingh You would have to specify the working order of participants and also work out which day of the cycle had the most-advanced work status. I suggest you accept whichever answer here helped you most (click the check mark on one answer) and then ask another question to get a proper answer to that.
Answer: As you say, the "net effect" of two days is one unit. Hence after 112 days, 56 units will be completed. You may think that 57 units are completed after 114 days, 58 after 116 days, 59 after 118 days, and finally all 60 after 120 days. But that would ignore that the constructive work done by A on day 113 already takes us to the final 60 units (for the first time).
Comment: But my question is why we assumed it to be 56 units. Why we didn't solve this question by taking 60 units itself? Why we have subtracted 4 units?
Comment: My answer according to me is 120 days @HagonvonEitzen


Updating to PHP 5.4 breaks Drupal 7.25 with Strict warning: Declaration on bootstrap.inc

Question: I tried updating to PHP 5.4, but got a few errors. These aren't critical errors right? seems like its only warnings.
I'm using Drupal 7.20 What do the following errors mean exactly? And how can they be resolved? Can I just upgrade my Drupal 7 to the latest 7.31 as of 2014-09-24 to fix these issues?
Strict warning: Declaration of Messaging_User_Destination::validate_address() should be compatible with Messaging_Destination::validate_address($address, $type = NULL) in _registry_check_code() (line 3080 of /home/xxx/public_html/includes/bootstrap.inc).

Strict warning: Declaration of Messaging_User_Destination::format_address() should be compatible with Messaging_Destination::format_address($address, $format = MESSAGING_FORMAT_PLAIN, $type = NULL) in _registry_check_code() (line 3080 of /home/xxx/public_html/includes/bootstrap.inc).

Strict warning: Declaration of Messaging_Mail_Address::validate_address() should be compatible with Messaging_Destination::validate_address($address, $type = NULL) in require_once() (line 208 of /home/xxx/public_html/sites/all/modules/messaging/messaging_mail/messaging_mail.inc).

Answer:
These aren't critical errors right?

No, it's just a warning. Not fatal. It comes from the E_STRICT error constant, which as of PHP5.4 was included in E_ALL. It's quite common to see those errors after upgrading 5.3 to 5.4 (not just for Drupal), as most people copy the bulk of their config from the previous version.
The constant itself provides this to error reporting:

Enable to have PHP suggest changes to your code which will ensure the best interoperability and forward compatibility of your code.

What do the following errors mean exactly?

In Drupal terms, it means one or more contrib modules you have installed contain code that targets older version of PHP (or at least hasn't been updated recently). Specifically, PHP is complaining that the arguments or access modification of a method on a child class doesn't match the same method on the parent class.

Can I just upgrade my Drupal 7 to the latest 7.31 as of 2014-09-24 to fix these issues?

In your case the warning is being caused by the messaging_mail module, so updating core won't do anything (though you should update ASAP, you're a long way behind). You could disable strict errors if you just want to hide the warning, but the best way forward is to report this as a bug to the appropriate module.
Comment: what are some other commonly known compatibility issues like this that would arise from upgrading to php 5.4?
Comment: The full list is [here](http://php.net/manual/en/migration54.incompatible.php), the most common one I've seen apart from the strict warning is that Call-time pass by reference was removed.  Some older libraries make heavy use of that. But it's quite rare in the Drupal world in my experience, you just happen to be using a module which needs a bit of attention. I've got loads of sites running on php5.5 without any problems for what it's worth
Comment: so you just ignore the disable strict errors by suppressing them? so would it be safe to say if im going to upgrade to 5.4 i might aswell go for 5.5? thanks clive!
Comment: Yeah you can suppress them (best not to obviously but life isn't always that clear cut), the warning is basically that at some point in the future doing that will probably raise a fatal error. You should be fine with 5.5, the [backwards incompatibilities](http://php.net/manual/en/migration55.incompatible.php) are unlikely to affect you I'd say


BladeCenter and HS21 iSCSI question

Question: Can one use the iSCSI built in HBAs on an HS21 Blade and have also IP traffic on the same NICs? or you have to add two more NICs to use for IP traffic? If so which Modules on the back bay 3,4 support which CFF Ethernet cards?
BladeCenter E, with HS21, LS20, and JS21 blades, HS21 is the one i am interested.
HS21 with Additional Gigabit Ethernet SFF cards
demos
Answer: Yes, iSCSI works across any TCP/IP connection, along with other TCP/IP traffic.
If you were to use ATA over Ethernet instead, that NIC would be dedicated to only disk traffic.
As far as I know, you can get any internal ethernet cards for your blades, and they will work with any ethernet router modules for the 3,4 network module slots. You may want to ask your IBM sales rep to be certain.
From what I've read, the only difference is that you want the flavors to match... don't get Infiniband network modules for Ethernet CFF cards, or the other way around.
You will need networking modules in slot 3 of your BladeCenter chassis if you want one additional blade-internal SFF or CFF network cards to function, and you will also need a networking module in the fourth slot if you want two additional internal cards to function.
Does this answer your question?
Disclaimer: I own a used BladeCenter E chassis, and thus all of my information comes from reading the docs, I've never had any contact with IBM support.

BladeCenter and HS21 iSCSI question


Não consigo deixar o footer em baixo

Question: Meu HTML e CSS:

body {
 background-image: url(img/fundonew.png);
 background-repeat: repeat-x;
 font-family: Arial;
 background-color: #003013;
}

#main {
 position: absolute;
 top:0px;
 left:50%;
 width: 770px;
 margin-left: -450px;

}

#logo {
 position: absolute;
 top:0px;
 left: -100px;
 width: 150px;
 height: 150px;

}
#btinicio {
 position: absolute;
 top:60px;
 left:340px;
 width: auto;
 height: 33px;
}
#btaquecimento {
 position: absolute;
 top:60px;
 left:470px;
 width: auto;
 height: 33px;
}
#btefeito {
 position: absolute;
 top:60px;
 left:670px;
 width: auto;
 height: 33px;
}
#btea {
 position: absolute;
 top:60px;
 left:810px;
 width: auto;
 height: 33px;
}
#conteudo {
 position: relative;
 top:150px;
 left:2px;
 width:900px;
 height: auto;
 background-color: #bcc1ad;
 color: #0024ff;
}

#conteudo p{
 font-size:20px;
 text-align: justify;
 margin-left: 10px;
 margin-right: 10px;
}

#footer {
 position:absolute;
 bottom: 0px;
 width: 100%;

}
<!DOCTYPE html>

  <title>Educãção Ambiental</title>
  <link rel="stylesheet" type="text/css" href="style.css" media="screen" />

     O planeta pede socorro

     Falta d'água. Falta de energia. Falta de área verde. Tudo isso gerado pela falta de consciência das pessoas.

     Estamos começando a sentir o mal que a Terra sente há anos, o elevado uso dos recursos naturais do Planeta está sobrecarregando-o, ultrapassando o limite, e se não respeitado esse limite, o que poderá ocorrer futuramente ?

     A reciclagem é uma de várias maneiras que podem ser colocada é prática para solucionar alguns problemas ambientais, é necessário que sempre tenhamos em mente que não devemos jogar lixo em qualquer lugar, um exemplo claro, é o lixo eletrônico.

     Hoje milhares de pessoas tem celular, e por causa da rápida obsolescência desses equipamentos, é comum jogarmos eles nos lixos de casa ou da rua, porém, é um hábito errado, que pode trazer várias doenças e impactos ambientais, o certo seria levar para estabelecimentos que fazem esse tipo de reciclagem para que não ocorra esses casos.

     A poluição do ar é preocupante , a emissão de CO2 aumenta a cada ano, entretanto, esse é um problema que só pode ser combatido em conjunto, ao invés de usar carros ou motos para sair, pode-se usar as bicicletas, pois além de fazer bem para a saúde, minimiza a emissão de dióxido de carbono na atmosfera.

     Fica claro, portanto, que os nossos maus hábitos estão trazendo inúmeros problemas ambientais que só podem ser resolvidos em conjunto.

     A mídia é um importante fator nesse cenário, pois ela precisa denunciar e esclarecer a sociedade sobre as nossas atitudes, mostrar os problemas que estamos gerando e o que poderá acontecer se não mudarmos os nossos hábitos.

     O governo deve criar medidas que cesse a poluição e o consumo exagerado. E é necessário que cada indivíduo tenha consciência do que está acontecendo e respeite o meio ambiente, evitando desperdício e reduzindo embalagens, porque o "planeta pede socorro".

Desenvolvido pelo grupo: Shadow - Para a semana Paulo Freire

Answer: Olá, como você está usando somente divs com "position:absolute", é só você setar o atributo "margin-top" com o valor total da altura dos demais conteúdos, fiz esse exemplo:
https://jsfiddle.net/q1wf5kLv/
Isso resolve seu problema nesse momento, entretanto, há muito a agregar, pois você não pode trabalhar um documento web dessa forma engessada, pois um dos recursos mais ricos da web é você poder redimensionar (é o que chamamos de site responsivo) sua aplicação para diversas formas de resolução.
Para começar, recomendo você tentar reescrever seu código com as colunas do Bootstrap, pois deixam o documento padronizado de forma mais profissional e auto ajustável para mobile. Aqui um tutorial legal: https://www.w3schools.com/bootstrap4/bootstrap_grid_system.asp
Espero ter ajudado, abraços
Comment: Oii boa noite, muito obrigado pelo ajuda. Sou iniciante na área, você me salvou. Já estava quase desistindo haha
Comment: hahaha, não desista parceiro! Pega o bootstrap p/ facilitar a vida do layout, aí você não precisa editar o css para editar o layout, só usar as classes; só sucesso. Se puder mandar thumbs up. Abs e boa sorte com seu projeto
Answer: Fiz algumas modificações no seu css e consertei o problema do footer.  Você tinha vários elementos posicionados de forma absoluta, inclusive o #main. Eu apenas removi o estilo de #main, o position:absolute do footer e algumas propriedades do #conteudo.
Segue o código modificado:

body {
 background-image: url(img/fundonew.png);
 background-repeat: repeat-x;
 font-family: Arial;
 background-color: #003013;
}

#logo {
 position: absolute;
 top:0px;
 left: -100px;
 width: 150px;
 height: 150px;

}
#btinicio {
 position: absolute;
 top:60px;
 left:340px;
 width: auto;
 height: 33px;
}
#btaquecimento {
 position: absolute;
 top:60px;
 left:470px;
 width: auto;
 height: 33px;
}
#btefeito {
 position: absolute;
 top:60px;
 left:670px;
 width: auto;
 height: 33px;
}
#btea {
 position: absolute;
 top:60px;
 left:810px;
 width: auto;
 height: 33px;
}

#conteudo {
 position: relative;
 margin-top:150px;
 background-color: #bcc1ad;
 color: #0024ff;
}

#conteudo p{
 font-size:20px;
 text-align: justify;
 margin-left: 10px;
 margin-right: 10px;
}

#footer {
 bottom: 0px;
 width: 100%;
}
<!DOCTYPE html>

  <title>Educãção Ambiental</title>
  <link rel="stylesheet" type="text/css" href="style.css" media="screen" />

     O planeta pede socorro

     Falta d'água. Falta de energia. Falta de área verde. Tudo isso gerado pela falta de consciência das pessoas.

     Estamos começando a sentir o mal que a Terra sente há anos, o elevado uso dos recursos naturais do Planeta está sobrecarregando-o, ultrapassando o limite, e se não respeitado esse limite, o que poderá ocorrer futuramente ?

     A reciclagem é uma de várias maneiras que podem ser colocada é prática para solucionar alguns problemas ambientais, é necessário que sempre tenhamos em mente que não devemos jogar lixo em qualquer lugar, um exemplo claro, é o lixo eletrônico.

     Hoje milhares de pessoas tem celular, e por causa da rápida obsolescência desses equipamentos, é comum jogarmos eles nos lixos de casa ou da rua, porém, é um hábito errado, que pode trazer várias doenças e impactos ambientais, o certo seria levar para estabelecimentos que fazem esse tipo de reciclagem para que não ocorra esses casos.

     A poluição do ar é preocupante , a emissão de CO2 aumenta a cada ano, entretanto, esse é um problema que só pode ser combatido em conjunto, ao invés de usar carros ou motos para sair, pode-se usar as bicicletas, pois além de fazer bem para a saúde, minimiza a emissão de dióxido de carbono na atmosfera.

     Fica claro, portanto, que os nossos maus hábitos estão trazendo inúmeros problemas ambientais que só podem ser resolvidos em conjunto.

     A mídia é um importante fator nesse cenário, pois ela precisa denunciar e esclarecer a sociedade sobre as nossas atitudes, mostrar os problemas que estamos gerando e o que poderá acontecer se não mudarmos os nossos hábitos.

     O governo deve criar medidas que cesse a poluição e o consumo exagerado. E é necessário que cada indivíduo tenha consciência do que está acontecendo e respeite o meio ambiente, evitando desperdício e reduzindo embalagens, porque o "planeta pede socorro".

Desenvolvido pelo grupo: Shadow - Para a semana Paulo Freire

Percebi que você tá tentando sempre posicionar os elementos de forma absoluta na tela. Isso é um problema, você deve sempre pensar que as telas têm tamanhos diferentes e que um layout dessa forma é muito difícil de manter.

Não consigo deixar o footer em baixo


Button not displaying in layout

Question: This is my XML:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/main_layout"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    tools:context=".MainActivity">

    <LinearLayout
        android:id="@+id/logoLayout"
        android:layout_width="150dp"
        android:layout_height="40dp"
        android:layout_marginLeft="120dp"
        android:layout_marginTop="25dp"

        android:orientation="vertical">

        <ImageView
            android:id="@+id/imageView3"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            app:srcCompat="@drawable/csr_logo2" />

    </LinearLayout>

    <LinearLayout
        android:id="@+id/lineLayout"
        android:layout_width="match_parent"
        android:layout_height="2dp"
        android:layout_below="@+id/logoLayout"
        android:layout_marginBottom="15dp"
        android:layout_marginTop="5dp"

        android:orientation="vertical">

        <ImageView
            android:id="@+id/imageView4"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:background="@drawable/dotted_line"
            app:srcCompat="@drawable/dotted_line" />

        <ImageView
            android:id="@+id/imageView5"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            app:srcCompat="@drawable/normal_line" />

    </LinearLayout>

    <android.support.design.widget.TabLayout
        android:id="@+id/tabLayout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@color/white"
        android:minHeight="?attr/actionBarSize"
        android:textColor="@color/black"
        android:theme="@style/AppTheme"
        app:tabMode="scrollable" />

    <com.example.sparsh.newcsraudit.CustomViewPager
        android:id="@+id/pager"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

    </com.example.sparsh.newcsraudit.CustomViewPager>

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <Button
            android:id="@+id/completeBtn"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentBottom="true"
            android:text="Complete Audit" />
    </LinearLayout>

</LinearLayout>

The 'Button' doesn't display in the layout.
My button needs to be displayed in every category of the layout.
Tried adding button to my activity that holds the categories, but it's not working.
Tried making adjustments, but didn't succeed.
Also, looked for similar questions online, but couldn't find the solution.
How do I make the button display in the layout.
Please help!
Comment: did you solved it
Answer: Try this change your root Layout to RelativeLayout and make your Button android:layout_alignParentBottom="true"
And make your
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/main_layout"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    tools:context=".MainActivity">

 <LinearLayout
     android:layout_width="match_parent"
     android:layout_height="wrap_content"
     android:orientation="vertical">

     <LinearLayout
         android:id="@+id/logoLayout"
         android:layout_width="150dp"
         android:layout_height="40dp"
         android:layout_marginLeft="120dp"
         android:layout_marginTop="25dp"
         android:orientation="vertical">

         <ImageView
             android:id="@+id/imageView3"
             android:layout_width="match_parent"
             android:layout_height="wrap_content"
             app:srcCompat="@drawable/kid_goku" />

     </LinearLayout>

     <LinearLayout
         android:id="@+id/lineLayout"
         android:layout_width="match_parent"
         android:layout_height="2dp"
         android:layout_below="@+id/logoLayout"
         android:layout_marginBottom="15dp"
         android:layout_marginTop="5dp"
         android:orientation="vertical">

         <ImageView
             android:id="@+id/imageView4"
             android:layout_width="match_parent"
             android:layout_height="match_parent"
             android:background="@drawable/ic_message"
             app:srcCompat="@drawable/ic_message" />

         <ImageView
             android:id="@+id/imageView5"
             android:layout_width="match_parent"
             android:layout_height="match_parent"
             app:srcCompat="@drawable/kid_goku" />

     </LinearLayout>

     <android.support.design.widget.TabLayout
         android:id="@+id/tabLayout"
         android:layout_width="match_parent"
         android:layout_height="wrap_content"
         android:background="@color/white"
         android:minHeight="?attr/actionBarSize"
         android:textColor="@color/colorPrimary"
         android:theme="@style/AppTheme"
         app:tabMode="scrollable" />

     <com.example.sparsh.newcsraudit.CustomViewPager
         android:id="@+id/pager"
         android:layout_width="match_parent"
         android:layout_height="wrap_content">

     </com.example.sparsh.newcsraudit.CustomViewPager>
 </LinearLayout>

        <Button
            android:id="@+id/completeBtn"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentBottom="true"
            android:text="Complete Audit" />

</RelativeLayout>

Button not displaying in layout


java.lang.RuntimeException: setOnItemClickListener cannot be used with a spinner

Question: mSpinner.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (id == 2) {
                    showToast(getString(R.string.added_alert));
                    checkBoxAlarm.setEnabled(true);
                } else {
                    checkBoxAlarm.setEnabled(false);
                    checkBoxAlarm.setChecked(false);
                }
                if (id == 3) {
                    showToast(getString(R.string.notify));
                    checkboxnotify.setEnabled(true);
                } else {
                    checkboxnotify.setEnabled(false);
                    checkboxnotify.setChecked(false);
                }
            }

            public void onNothingSelected(AdapterView parent) {
            }
        });

Answer: You can see in the error: setOnItemClickListener cannot be used
Use
setOnItemSelectedListener

instead of
setOnItemClickListener

Firstly you should change this. Then you can use position.
Answer: You have to use a position in place of id while you want to compare the position of the selected item in the spinner.
mSpinner.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (position == 2) {
                    showToast(getString(R.string.added_alert));
                    checkBoxAlarm.setEnabled(true);
                } else {
                    checkBoxAlarm.setEnabled(false);
                    checkBoxAlarm.setChecked(false);
                }
                if (position == 3) {
                    showToast(getString(R.string.notify));
                    checkboxnotify.setEnabled(true);
                } else {
                    checkboxnotify.setEnabled(false);
                    checkboxnotify.setChecked(false);
                }
            }

            public void onNothingSelected(AdapterView parent) {
            }
        });

Answer: You should use OnItemSelectedListener
https://developer.android.com/guide/topics/ui/controls/spinner#SelectListener


Capture a frame (image) from a video playing in a QT GUI

Question: I have written a simple video player GUI code in QT. The GUI allows the user to browse the local files and select a video for playing in the GUI. The GUI also has options for 'play', 'pause' and 'stop' to apply to the video selected.
I want to add another button 'Capture', that captures the current frame of the video that is being played, and displays this captured image next to the video (The video should should get paused at this point).
I looked into the documentation of QT, specifically:     this and this.    But I am still not able to understand how to implement this in my case.
Kindly guide.
My code so far is as follows:
#include "qtwidgetsapplication4.h"
#include <iostream>

QtWidgetsApplication4::QtWidgetsApplication4(QWidget *parent)
    : QMainWindow(parent)
{
    ui.setupUi(this);

    player = new QMediaPlayer(this);
    vw = new QVideoWidget(this);
    player->setVideoOutput(vw);
    this->setCentralWidget(vw);
}

void QtWidgetsApplication4::on_actionOpen_triggered() {
    QString filename = QFileDialog::getOpenFileName(this, "Open a File", "", "Video File (*.*)");
    on_actionStop_triggered();

    player->setSource(QUrl::fromLocalFile(filename));
    on_actionPlay_triggered();
    qDebug("Error Message in actionOpen");
    qDebug()<<player->mediaStatus();
}

void QtWidgetsApplication4::on_actionPlay_triggered() {
    player->play();
    ui.statusBar->showMessage("Playing");
    qDebug("Error Message in actionPlay");
    qDebug() << player->mediaStatus();
}

void QtWidgetsApplication4::on_actionPause_triggered() {
    player->pause();
    ui.statusBar->showMessage("Paused...");
    qDebug("Error Message in actionPause");
    qDebug() << player->mediaStatus();
}

void QtWidgetsApplication4::on_actionStop_triggered() {
    player->stop();
    ui.statusBar->showMessage("Stopped");
    qDebug("Error Message in actionStop");
    qDebug() << player->mediaStatus();
}

Answer: You can use QVideoProbe to capture QVideoFrame. Instantiate and connect videoFrameProbed signal to your slot before pausing video. Convert QVideoFrame to QImage in this slot using frame data.
QImage::Format imageFormat = QVideoFrame::imageFormatFromPixelFormat(frame.pixelFormat());
QImage image(frame.bits(), frame.width(), frame.height(), imageFormat);

Take a look at player example for reference. It uses QVideoProbe to calculate histogram of current frame.
Comment: Thank you for the answer. A follow-up question: So, in my case the connect function will be something like this?
`connect(m_audioProbe, &QAudioProbe::audioBufferProbed(QVideoFrame), ui->captureButton, on_captureButton_clicked(QVideoFrame));`

And then I define the on_captureButton_clicked slot to display the frame in a label.

Is this the correct approaach?
Comment: I just realized that I am using Qt 6.3, which does not have QVideoProbe anymore.
It has QVideoSink instead that looks similar. Could you give me an example to show how to use QVideoSink for this purpose?


Como usar C# Windows Forms com Firebird e Orientação a Objetos?

Question: Recentemente aprendi um pouco de orientação a objetos e c#. Porém estou tentando criar uma aplicação que seja desenvolvida em c# windows forms, com banco de dados firebird e orientada a objetos. Mas qual a maneira correta de se fazer isso? Como eu conecto meu banco a minha aplicação e como faço para que ele interaja com a interface do visual studio? Também já vi que é possível usar App.Config como no sql, mas como faço isso?

Por exemplo, atualmente eu tenho o repostório de uma classe e dentro dele crio eventos como adicionar, alterar e etc, geralmente eu faço assim:
public void Adicionar(Pais pais)
{
    string sql = "INSERT INTO PAIS (PAINOME) VALUES('" + pais.PaiNome+ ")";

    Conexao.Active(true);
    FbCommand cmd = new FbCommand(sql, Conexao.fbCnn);
    cmd.ExecuteNonQuery();
    Conexao.Active(false);
}

Dessa maneira toda vez que faço alguma alteração nas classes tenho que mudar em todos os repositórios, por exemplo, se eu adiciono um novo campo ao país eu teria que alterar em todas as strings sql adicionando o novo campo. Essa é a maneira correta de se fazer? Eu consigo deixar isso mais automático ou não?
Obrigado!
Answer: Legal seu interesse pela programação.
Porém, minha dica é: tente fazer as coisas um passo por vez. Aprenda a fazer a conexão através do C#, depois aprenda a usar Windows Forms, depois tente fazer a conexão com Firebird.
Entendo que a vontade de aprender e fazer algo só seu é grande. Mas as coisas acontecem em sequência.
Segue abaixo alguns tutoriais em português, nada difícil de encontrar no Google, e nada menos do que você encontrará por aqui, sendo sua pergunta tão genérica.
http://www.devmedia.com.br/conectando-em-uma-base-de-dados-firebird-com-c/11938
http://www.macoratti.net/08/09/c_fbd1.htm
https://stackoverflow.com/questions/4014097/how-to-connect-and-use-firebird-db-embedded-server-with-visual-c-sharp-2010
Comment: Obrigado pelas dicas e pela ajuda!
Comment: Da um up aí então, se você considerou como resposta ;)
Comment: Sou novo aqui e nem manjo muito! Foi mal.
Comment: É só clicar no icone ao lado da minha resposta, dizendo que é a resposta certa. Abraço


XAMPP permissions on Mac OS X?

Question: I installed XAMPP 1.7.3 on Mac OS X 10.6.8 without changing any defaults.
The webserver seems to work okay, but the permissions on the htdocs directory are set to "Read only" for everyone other than system.  So (a) I have to provide root password every time I copy in web content, and, more problematic, (b) NetBeans says it can't create a target directory, and doesn't even generate the index.php file in the source directory.
Do I just need to manually change permissions on the htdocs directory, or is there some more global XAMPP setting that should be changed?  Running NetBeans as root seems a bit extreme.
Answer: Tried the above but the option to amend the permission was not available for the htdocs folder,
My solution was:

Open applications folder
Locate XAMPP folder
Right click, get info (as described above)
In pop-up window locate the 'sharing & permission' section
Click the 'locked' padlock symbol
Enter admin password
Change 'Everyone' permissions to read & write
In the get info window still, select the 'cog' icon' drop down option at the very bottom and select 'Apply to enclosed items' this will adjust the permission across all sub-folders as well.
Re-lock the padlock symbol
Close the 'Get Info' window.

Task complete, this will now allow you to populate sub-folders within the htdocs folder as needed to populate your website(s).
Comment: Warning: if you do this on the main xampp folder, it will mess up things like phpmyadmin etc...  My solution was just to enable it on the htdocs directory only.
Comment: This had me stumped for a while - I had changed the permissions on my folder within 'htdocs', but the key was changing the permissions on the XAMPP folder itself.

Incidentally, this can also be done from the terminal using `chmod -R 0775 XAMPP/` from the `Applications` directory.
Comment: I did this on only my /wordpress_site/wp-content folder and it worked. Able to now install plugins and themes. Do you recommend changing file permissions back to originals before FTP'ing to online hosting provider?
Comment: This didn't work for me for all folders (annoyingly) but the other solution did https://stackoverflow.com/a/55412980/1391681
Answer: Make sure the XAMPP app is running then:

Under General Tab, in XAMPP app, click Open Terminal
A terminal will be launched with something like, root@debian:~#, on the terminal shell
on that terminal shell, type, chmod -R 0777  /opt/lampp/htdocs/ and enter
Exit, the terminal and you be good to go
Comment: Oh my lard it f-ing worked. Been testing so many suggestion. Thank you
Comment: You really shouldn't set web server folders to `777`, it introduces a major security risk.
Comment: worked like a charm, great work around just for local setup
Comment: @leSmooth Welcome. Happy coding. I am happy it worked for you.
Comment: Worked as other solutions did not - can't locate xampp folder and changing finder permissions didn't work for some folders - this did! Thanks
Comment: how to do this in windows
Answer: For latest OSX versions,

Right click on the folder
Select Get Info
Expand the Sharing & Permission section
Unlock the folder by clicking lock icon on bottom right-corner
Now, select the user list and enable Read & Write privilege for the users
Click on the + icon to add username
Finally click settings icon and select Apply to enclosed items...
Answer: Following the instructions from this page,

Open the XAMPP control panel (cmd-space, then enter manager-osx.app).
Select Manage Servers tab -> select Apache Web Server -> click Configure.
Click Open Conf File. Provide credentials if asked.
Change
<IfModule unixd_module>
#
# If you wish httpd to run as a different user or group, you must run
# httpd as root initially and it will switch.
#
# User/Group: The name (or #number) of the user/group to run httpd as.
# It is usually good practice to create a dedicated user and group for
# running httpd, as with most system services.
#
User daemon
Group daemon
</IfModule>

to
<IfModule unixd_module>
#
# If you wish httpd to run as a different user or group, you must run
# httpd as root initially and it will switch.
#
# User/Group: The name (or #number) of the user/group to run httpd as.
# It is usually good practice to create a dedicated user and group for
# running httpd, as with most system services.
#
User your_username
Group staff
</IfModule>

Save and close.
Using the XAMPP control panel, restart Apache.
Navigate to the document root of your server and make yourself the owner. The default is /Applications/XAMPP/xamppfiles/htdocs.
$ cd your_document_root
$ sudo chown -R your_username:staff .

Navigate to the xamppfiles directory and change the permission for logs and temp directory.
$ cd /Applications/XAMPP/xamppfiles
$ sudo chown -R your_username:staff logs
$ sudo chown -R your_username:staff temp

To be able to use phpmyadmin you have to change the permissions for config.inc.php.
$ cd /Applications/XAMPP/xamppfiles/phpmyadmin
$ sudo chown your_username:staff config.inc.php

Comment: I've followed for this instructions, but I have a problem with MySql Database can't be running.
Comment: Thank you, you've been really a great help
Comment: I did not have to change the ownership of logs, temp or config.inc.php.
I had to change the ownership of /Applications/XAMPP/xamppfiles/temp/mysql. I had to  set it to "everyone" . In addition to my_username or staff.
Comment: This was it, thank you! It's unbelievable that even after 4 years XAMPP staff still hasn't resolved this.
Answer: For new XAMPP-VM for Mac OS X,
I change the ownership to daemon user and solve the problem.
For example,
$ chown -R daemon:daemon /opt/lampp/htdocs/hello-laravel/storage

Comment: My solution is to: chown -R bitnami:root

I am using composer, and have one folder in htdocs called "apps".. and under my developing webapps. and to keep it even more simple if I run some updates trough composer to the apps, I created  a simple do_chown.sh script in root folder for easy access when clicking Terminal button, and it simply does a chown -R bitnami:root /opt/lampp/htdocs/Apps/
Answer: If you use Mac OS X and XAMPP, let's assume that your folder with your site or API located in folder /Applications/XAMPP/xamppfiles/htdocs/API. Then you can grant access like this:
$ chmod 777 /Applications/XAMPP/xamppfiles/htdocs/API

And now open the page inside the folder:
http://localhost/API/index.php

Comment: Both of those answers are incorrect, as setting folder permissions to 777 is a security risk. the correct answer would be following: https://stackoverflow.com/a/48931236/4766230
Comment: This is one of correct answers. It works for me. Use `sudo chmod -R 0777 /Applications/XAMPP/xamppfiles/htdocs/` if you need to do it recursively
Answer: Go to htdocs folder, right click, get info, click to unlock the padlock icon, type your password, under sharing permission change the priviledge for everyone to read & write, on the cog wheel button next to the + and - icons, click and select apply to all enclosed items, click to accept security request, close get info. Now xampp can write and read your root folder.
Note:

If you copy a new folder into the htdocs after this, you need to repeat the process for that folder to have write permission.
When you move your files to the live server, you need to also chmod the appropriate files & folders on the server as well.
Comment: So it seems like there's not a global XAMPP setting, and manually changing permissions is the way to go. Hmm ...
Comment: at the moment, yes. I haven't found any work around and xampp forums have no solutions. If u find a solution plz post it, I would like to know.
Comment: This worked for me on a 2020 M1 macBook.
Answer: Best solution for MAC OS Catalina Xampp

Open Finder
Press Cmd + shift + C
Macintosh HD => Users => copy {username}
Open /Applications/XAMPP/xamppfiles/etc/httpd.conf
Find User daemon edit  daemon => {username}
Xampp Manage Server => Restart all

If you encounter problems in phpMyAdmin:
1. Browser (Chrome) restart

Goodluck
Comment: Also best solution for older versions - El-Cap, in my case.
Answer: if you use one line folder or file
chmod 755 $(find /yourfolder -type d)
chmod 644 $(find /yourfolder -type f)

Comment: When you have too many files or folders, this fails with a "argument list too long". A better approach would be to do `find /yourfolder -type d -exec chmod 755 {} \;` and `find /yourfolder -type f -exec chmod 644 {} \;` which have the same effect.
Answer: You can also simply change Apache Conf file to a different User Name and keep the group:
Apache Conf Applications/Xammp/etc/..
User 'User' = your user name in Mac os x.
Group daemon
sudo chown -R 'User':daemon ~/Sites/wordpress

sudo chmod -R g+w ~/Sites/wordpress

Comment: So if you need to update plugins etc.. then 'Wordpress' can access the files. Otherwise Wordpress can not update the files. Note: For Mac OS X only..
Answer: What worked for me was,

Open Terminal from the XAMPP app,
type in this,

chmod -R 0777  /opt/lampp/htdocs/
Answer: If you are running your page on the new XAMPP-VM version of MacOS you will have to set daemon as user and as group. Here you can find a great step-by-step illustration with screenshots from aXfon on how to do this.
As the htdocs folder under XAMPP-VM will be mounted as external volume, you'll have to do this as root of the mounted volume (root@debian). This can be achieved through the XAMPP-VM GUI:
See screenshot.
Once you are running as root of the mounted volume you can as described above change the file permission using:
chown -R daemon:daemon /opt/lampp/htdocs/FOLDER_OF_YOUR_PAGE

Source (w/ step-by-step illustration): aXfon
Comment: dead link.
also on my macos version of xampp (xampp-osx-7.4.27-2)  htdocs is in: /Applications/XAMPP/xampfiles/htdocs (not /opt/lampp/ )
Answer: This Solved WordPress Filesystem Permissions in Bitnami XAMPP
By changing the file permissions in apps/wordpress folder mounted on MAC XAMPP-VM shown in the below screenshot.

sudo chown -R bitnami:daemon TARGET # [ Replace "TARGET" with your file/folder path ]
find TARGET -type d -print0 | xargs -0 chmod 775
find TARGET -type f -print0 | xargs -0 chmod 664
chmod 640 TARGET/wp-config.php

Source: bitnami
TARGET - Replace placeholder for your mounted filesystem wordpress path eg: '184.108.40.206/lampp/apps/wordpress'
Now you can edit your themes in VS-Code or any developer editor of your choice.

NOTE: This should be done only in your development environment.
  Production build permissions are different & above doesn't apply
Answer: The above worked only for some directories but didn't for all root files. To change root files permissions, open Xampp app, within Xampp app click button 'open terminal'. once there do the following:
 - go to root directory: cd ..
 - got to directory where lamp is located: cd opt
 - change lampp permissions: chown -R bitnami:root lampp

note: you can replace bitnami with your user, and root with your group.

as a second alternative that worked for some files:
go to your users folder in finder and find the .bitnami hidden folder, access xampp folder within it and change permissions:

/Users/username/.bitnami/stackman/machines/xampp
right click xampp folder under machines and change permissions to read & write
apply to enclosing folders with "cog icon"
Answer: If the xampp has the default settings, it is quite a mess. I expand a little the topic.
The problem is with directory and file permissions (they control whether users can read, write, or execute - access and run - files and directories.)
You are logged in as username:group (replace username and group with yours, for example username=joedoe, group=admin, so joedoe:admin) and the Apache runs as daemon:daemon (i.e. user=daemon and group=daemon).
So the problems is not only the read, write, execute... but also owner and group.
When a program save a file (for example, PHP file_put_content), will be saved with permission 644 and belong to daemon:daemon (you can see in terminal ls -al. To be able to save in a directory, the directory must have a permission to allow this. It was suggested in this thread 777 so many times, the last "7" belonging to "others" (owner, group, others) is responsible here as you and httpd/Apache are different users belonging to different groups.
Even if you save the file in that directory, you may still run into problems. In this example, you will not be able, for example, to use your editor to delete the files written in that directory by the program because they will have the permission 644 and do not belong to you.
Understanding the problem, you know how to fix it. Changing the ownership of all files to daemon:daemon may work if you do not work on that files in an editor. In addition, many other things will be problematic. For example, you may want to install something with brew (let's say xdebug) that works with XAMPP... what you install with brew will belong to user:group and you have XAMPP with daemon:daemon... I believe that is much better to do it the other way around.
Change the owner and group of XAMPP to your username:group.
In the thread there are instructions, on short:

open the httpd.conf (Manage Server > Configure > Open Conf File) and replace the user and group "daemon" with yours. (Something like "User daemon" and "Group daemon").
sudo chown -R admin:admin /path/to/xampp_root_directory

XAMPP permissions on Mac OS X?


Compute $\frac{d}{dx}(\frac{2x+1}{x+3})$ using definition of derivative.

Question:  Problem
Compute $f'(x)$ using definition of derivative when $f$ is defined as:
$$ f(x)=\frac{2x+1}{x+3} $$
 Attempt to solve
A derivative is defined as:
$$ f'(a)= \lim_{h\rightarrow 0} \frac{f(a+h)-f(a)}{h} $$
then we have:
$$ \lim_{h \rightarrow 0} (\frac{2(a+h)+1}{a+h+3}-\frac{2a+1}{a+3})\cdot \frac{1}{h} $$
$$ =\lim_{x \rightarrow 0} \frac{2a+2h+1}{h^2+ah+3h}- \lim_{h \rightarrow 0}\frac{2a+1}{ah+3h} $$
But then i get stuck from here. How do i factor $h^2+ah+3h$  in a way it cancels with $2a+2h+1$. Do they have a factor in common ?
Comment: You had to reduce to the same denominator.
Answer: hint
Observe that
$$f(x)=2-\frac{5}{x+3}$$
thus
$$f(a+h)-f(a)=$$
$$5\Bigl(\frac{1}{a+3}-\frac{1}{a+h+3}\Bigr)$$
and
$$\frac{f(a+h)-f(a)}{h}=$$
$$\frac{5}{(a+3)(a+h+3)}$$
The limit when $h\to 0$ is
$$f'(a)=\frac{5}{(a+3)^2}.$$
Answer: It's not legal to split a limit into two pieces unless both the pieces exist.  In your last displayed expression, you split the limit across a minus sign, but neither of the two resulting limits exist.
Instead, subtract those fractions and multiply out everything in the numerator.  Once you cancel everything in the numerator, you'll have
$$\frac{5h}{(a+h+3)(a+h)h}.$$


Sharp and natural in the same bar when key already has a sharp

Question: These pieces are from Victor's piano solo by Danny Elfman (from Corpse Bride by Tim Burton):
Fragment 1

Fragment 2 (lower stuff is in bass clef)

Here I want to know what keys on piano keyboard are red notes? My believe is that in the 1st fragment: upper D is E4 (white key) and lower D is E2 (white key) and in the 2nd case it is D4-sharp (black key)? Am I right?
Answer: No, accidentals are never added to the key signature. D# means D# regardless of the key.
Comment: Because there was a D natural earlier in the measure, and the notator is just being extra careful that the player doesn't accidentally keep playing D natural in the other octaves. In the first case, the #s aren't technically necessary, but helpful. In the second example the # is necessary because the preceding natural is in the same octave. @LRDPRDX
Comment: "Extra clear" confused me =)
Comment: Why then to write a sharp sign in the first case? There are no naturals in that bar.
Comment: Pat is correct.  Double sharps, when called for, have their own notation: either two sharp signs ##, or a symbol which looks like a bold "x" **x**.
Answer: You have all D#'s in red in both fragments due to the #. Those will be black keys.
The natural on the D in fragment 1 is up an octave (on the 4th line of the staff) and won't effect the D# below (just above middle C) but they give you a courtesy/reminder sharp to be extra clear.


URL amigável redireciona para index.php

Question: Estou tendo problema para direcionar minhas url amigáveis para as páginas específicas. Quando clico em revendas-autorizadas por exemplo, ele está me levando para index.php
Tenho o código vars.php
 <?php
    //var_dump($_SERVER);
function parse_path() {
  $path = array();
  if (isset($_SERVER['REQUEST_URI'])) {
    $request_path = explode('?', $_SERVER['REQUEST_URI']);

    $path['base'] = rtrim(dirname($_SERVER['SCRIPT_NAME']), '\/');
    $path['call_utf8'] = substr(urldecode($request_path[0]), strlen($path['base']) + 1);
    $path['call'] = utf8_decode($path['call_utf8']);
    if ($path['call'] == basename($_SERVER['PHP_SELF'])) {
      $path['call'] = '';
    }
    $path['call_parts'] = explode('/', $path['call']);

    $path['query_utf8'] = urldecode($request_path[1]);
    $path['query'] = utf8_decode(urldecode($request_path[1]));
    $vars = explode('&', $path['query']);
    foreach ($vars as $var) {
      $t = explode('=', $var);
      $path['query_vars'][$t[0]] = $t[1];
    }
  }
return $path;
}

?>

<?php
switch($path_info['call_parts'][0]) {
    case 'aunimed': include 'aunimed.php';
        break;
    case 'revendas-autorizadas': include 'revendas-autorizadas.php';
        break;
}

?>

Não
E tenho no meu .htaccess
<IfModule mod_rewrite.c>

      RewriteEngine on

      RewriteCond %{REQUEST_FILENAME} !-f

      RewriteCond %{REQUEST_FILENAME} !-d

      RewriteRule ^ index.php [L]

    </IfModule>

Dentro de cada página estou chamando
<?php require('vars.php'); ?>

Comment: Quando dizes "url amigável" é remover o ".php" do url?
Comment: Exatamente @Miguel
Answer: Nem precisa disso, só usar o .htaccess dessa forma:
<IfModule mod_rewrite.c>
RewriteEngine On
    #URL's Amigáveis - friendly urls
    RewriteRule ^index/?$ index.php [NC,L]
</IfModule>

Comment: Na outra linha embaixo de `RewriteRule ^index/?$ index.php [NC,L]` é só colocar `RewriteRule ^revendas-autorizadas/?$ revendas-autorizadas.php [NC,L]` Por exemplo. E assim você te que fazer em todas as páginas que você quer url amigável. Outra dica é usar `[QSA,L]` ao invés de `[NC,L]`, porque ai dá para usar o $_GET a vontade...
Comment: Alterei o código, mas quando vou acessar a URL aparece: The requested URL /revendas-autorizadas was not found on this server.
Comment: Bem, ai você tem que colocar a outra url tbm (/revendas-autorizadas).
Comment: Entendido. Agora funcionou. Muito obrigado pela ajuda!
Comment: You're walcome!

URL amigável redireciona para index.php


Abrir arquivo word pelo delphi

Question: Tenho um sistema que faz integração com o MS-Word eu consigo fazer quase tudo nele, só não conseguir abrir o documento e deixar ele como somente de leitura para que o usuário não possa fazer modificações. atualmente meu código esta assim:
//Cria objeto principal de controle
try
  with OleContainer do
  begin
    if OleObjectInterface <> Nil then
    begin
      DestroyObject;
    end;
    //Nome do arquivo usado para abrir o arquivo de entrevista
    vNomeArquivo  := DM.tbParamPASTA_BD.AsString+'\MODELOS\'+DM2.qryConsultasMODELO.AsString;
    try
      OleContainer.CreateObjectFromFile(vNomeArquivo, OF_READ);
      OleContainer.DoVerb(ovShow);
      Perform(WM_LBUTTONDBLCLK, MK_LBUTTON, 0);
    except
      //Fechar o arquivo
      DestroyObject;
    end;
  end;
finally
  Screen.Cursor := crDefault;
  OleContainer.TabStop := False;

end;

PS: Eu não quero abrir um documento que tenha o atributo ReadOnly eu
  quero impedir que o usuário não altere o documento tipo modo Protegido
  Irrestrito
Answer: Não usamos muito o olecontainer, mas para as nossas necessidades aqui quando precisamos deixar o documento readonly para o usuário nos usamos a seguinte linha..:
OleContainer.CreateObjectFromFile(vNomeArquivo, false);
OleContainer.DoVerb(ovShow);
OleContainer.OleObject.Protect(3);
Perform(WM_LBUTTONDBLCLK, MK_LBUTTON, 0);

Comment: Vou ver se funciona...
Comment: Cara ficou show!!!

Abrir arquivo word pelo delphi


Searching entity reference field value with Search API

Question: I am using Seach API, Solr Search modules in my website for searching.
I've created an index, say 'Blogs index',
I've selected blogs content type to index
Fields - title, body, Author are added to index.
Created the View for the search results.
Issue is when I search the name of the author, I'm getting no relevant results. Result should be the list of blogs written by the searched author.
field Author is an entity reference field referencing the content type 'Blog Author' and is a multi-valued field.
Any help is appreciated.
Answer: To allow nested Facet searches, based on referenced entity's titles ($target->field_title->value),
in our Drupal 8 site we defined a custom-field with a processor
(which create and sets our my_titles_field field);
Place the MyCustomProcessor.php file in modules/custom/my_module/src/Plugin/search_api/processor/ directory;
With contents like below:
<?php

namespace Drupal\my_module\Plugin\search_api\processor;

use Drupal\Core\Entity\EntityInterface;
use Drupal\search_api\Datasource\DatasourceInterface;
use Drupal\search_api\IndexInterface;
use Drupal\search_api\Item\Field;
use Drupal\search_api\Item\ItemInterface;
use Drupal\search_api\Plugin\PluginFormTrait;
use Drupal\search_api\Processor\ProcessorPluginBase;
use Drupal\search_api\Processor\ProcessorProperty;

/**
 * Allows finding by titles associated (with field_references entities).
 *
 * @SearchApiProcessor(
 *   id = "my_custom_processor",
 *   label = @Translation("My Custom Processor"),
 *   description = @Translation("Allows filtering by entity-reference's titles."),
 *   stages = {
 *     "add_properties" = 0,
 *   },
 *   locked = true,
 *   hidden = true,
 * )
 */
class MyCustomProcessor extends ProcessorPluginBase {

  use PluginFormTrait;

  const ENTITY = 'node';
  const DATASOURCE = 'entity:' . self::ENTITY;
  const FIELD_NAME = 'my_titles_field';

  /**
   * {@inheritdoc}
   */
  public function getPropertyDefinitions(DatasourceInterface $datasource = NULL) {
    $properties = [];

    // Ensures our field is in General section, else we would check:
    // ```
    // if ($dataSource && $dataSource->getEntityTypeId() == self::ENTITY) {
    // ```

    if (!$datasource) {
      $property = new ProcessorProperty([
        'label' => $this->t('Entity-title'),
        'description' => $this->t('Attached Entity-ref title list'),
        'type' => 'object',
        'is_list' => FALSE,
        'hidden' => FALSE,
        'processor_id' => $this->getPluginId(),
      ]);
      $properties[self::FIELD_NAME] = $property;
    }

    return $properties;
  }

  /**
   * {@inheritdoc}
   */
  public function addFieldValues(ItemInterface $item) {
    // Loads actual entity (which $item represents).
    $entity = $item->getOriginalObject()->getValue();
    if (!($entity instanceof EntityInterface)) {
      return;
    }

    // Generate searchable JSON object (that is returned to Search-API callers
    // and which we can edit as we like to fit our needs).
    $json = [];
    $references = $entity->get('field_references');
    foreach ($references->referencedEntities() as $key => $target) {
      $json[$target->id()] = [
        'value' => $target->field_title->value,
      ];
    }

    // At last, assign our custom filter-criteria value as an index field.
    $fields = $item->getFields(FALSE);
    $fields = $this->getFieldsHelper()
      ->filterForPropertyPath($fields, NULL, self::FIELD_NAME);
    foreach ($fields as $field) {
      $field->addValue($json);
    }
  }

  /**
   * {@inheritdoc}
   */
  public function preIndexSave() {
    // For General fields:
    $this->ensureField(null, self::FIELD_NAME);

    // For content this would look like:
//    foreach ($this->index->getDatasources() as $sourceId => $dataSource) {
//      if ($dataSource && $dataSource->getEntityTypeId() == self::ENTITY) {
//        $this->ensureField($sourceId, self::FIELD_NAME);
//      }
//    }
  }
}

Note that the field needs to added to your index by clicking Add fields in
/admin/config/search/search-api/index/__my_index__/fields route manually.
For Drupal-7 See also Cross-entity searches
Answer: I haven't tried this with Search API but if your "Author" is a separate content type and not the actual default Author field you need to add the Relationship for that Entity reference field (for the "Blog Author" content type).
Different Content types store data in different database tables. Relationships introduce that other table data into your Views.
You'll probably have to add the Title field using that Relationship (which is, I presume, your blog author name), and include that field in the Search API settings so it gets searched.
Entity reference fields only store the ID of the referenced entity, so using them alone won't let you search the actual Title field text of the referenced entity. You can only do that through the Relationship and the relevant Title field (or however you named that field).


when i run program, get error on (cmd.executenonquery)

Question: Private Sub BtnSave_Click(sender As Object, e As EventArgs) Handles BtnSave.Click

    cn.Open()
    cmd = New SqlCommand("insert into CandTable(Passport_No,Name,Father
    Name,Mother Name,Date_of_Birth) values('" & Candi.TxtPass.Text & "','" &
    Candi.TxtName.Text & "', '" & Candi.TxtFather.Text & "', '" &
    Candi.TxtMother.Text & "','" & Candi.TxtDob.Text & "')", cn)

    cmd.ExecuteNonQuery()
    cn.Close()
    MsgBox("Data Saved Successfully")

End Sub

Comment: I also recommend you look into parameterizing your SQL query. [Here is an example of doing it in VB](https://stackoverflow.com/a/542542/19818). Parameterization protects you against quotation marks in strings and other dangerous input, which could give an attacker access to your database.
Comment: I can imagine that this will work: take a quotation mark for the field names containing a whitespace: ChrW(96). Try this: \`Father Name\`,\`Mother Name\`
Answer: Try this......
Using sqlcon As New SqlConnection(strCaseConnString)
                sbSql.Append("insert into CandTable(Passport_No,Name,[Father Name],[Mother Name],Date_of_Birth) values(@Passport_No,@Name,@FatherName,@MotherName,@Date_of_Birth")
                Using sqlCmd As New SqlCommand(sbSql.ToString(), sqlcon)
                    sqlCmd.Parameters.Add("@Passport_No", SqlDbType.NVarChar).Value = Candi.TxtPass.Text
                    sqlCmd.Parameters.Add("@Name", SqlDbType.NVarChar).Value = Candi.TxtName.Text
                    sqlCmd.Parameters.Add("@FatherName", SqlDbType.NVarChar).Value =  Candi.TxtFather.Text
                    sqlCmd.Parameters.Add("@MotherName", SqlDbType.NVarChar).Value = Candi.TxtMother.Text
                    sqlCmd.Parameters.Add("@Date_of_Birth", SqlDbType.NVarChar).Value = Candi.TxtDob.Text
                    sqlcon.Open()
                    sqlCmd.ExecuteNonQuery()
                    sqlcon.Close()
                End Using
            End Using

Comment: I think, this will produce an error, too. See my comment above.


Prove that $\forall A \exists !B \big (B \subseteq A \wedge \forall C(C \subseteq A \rightarrow B \vartriangle C = A \setminus C)\big)$

Question:
Prove that for every set $A$ there is a unique set $B \subseteq A$ such that for every $C \subseteq A$, $B \vartriangle C = A \setminus C$.

Is this the correct way to convert the question to a logical form, and does the proof make sense?
$\forall A \exists !B \big (B \subseteq A \wedge \forall C(C \subseteq A \rightarrow B \vartriangle C = A \setminus C)\big)$
Proof: Let $A$ be arbitrary. Let $B = A$. Now let $C$ be arbitrary, and suppose $C \subseteq A$. Let $x$ be arbitrary. Suppose $x \in B \vartriangle C = A \vartriangle C$. Then $x \in A \setminus C \cup C \setminus A$. Suppose $x \in C \setminus A$. Then $x \in C$ and $x \notin A$. But since $C \subseteq A$ and $x \in C$, $x \in A$. This contradicts the fact that $x \notin A$, so $x \notin C \setminus A$. Since $x \in A \setminus C \cup C \setminus A$, we can conclude that $x \in A \setminus C$. Now suppose $x \in A \setminus C$. Clearly $x \in A \setminus C \cup C \setminus A$, and $x \in A \vartriangle C = B \vartriangle C$. Since $x$ was arbitrary, $B \vartriangle C = A \setminus B$.
To show that $B$ is unique, let $B'$ be arbitrary such that $B' \subseteq A$ and $\forall C (C \subseteq A \rightarrow B' \vartriangle C = A \setminus C)$. Taking $C = \emptyset \subseteq A$, we have $B' \vartriangle \emptyset = A \setminus \emptyset$. So $B' \cup \emptyset \setminus (B' \cap \emptyset)=A$. It follows that $B' \cup \emptyset \setminus (B' \cap \emptyset)=  B' \setminus \emptyset= B'=A = B$. $\square$
Answer: It's OK. Here's a quicker option. On the one hand, by inspection $C\subseteq A\implies A\vartriangle C=A\setminus C$. On the other hand, if $B$ is a proper subset of $A$ then $C:=A\setminus B\implies B\vartriangle C=A\ne A\setminus C$, so $B=A$ is the unique solution.
Comment: Thanks for your reply! I understand the first part, but why do we consider if $B$ is a proper subset of $A$? Which part of the statement does it prove? Also, what does the $:=$ mean in this context?
Comment: @lyeeke (1) Because that's the only alternative to $B=A$ (2) So it proves uniqueness (3) "Is defined as"
Comment: So since $B \subseteq A$, the first part is just assuming that $B = A$, then by assuming that $B \subset A$ we try to eliminate the other subsets as potential solutions? How does $C$ get defined as $A \setminus B$ though?
Comment: @lyeeke To provide a counterexample to the claim, for a given proper subset $B$ of $A$, that any subset $C$ of $A$ satisfies $B\vartriangle C=A\setminus C$. Indeed, $C=A\setminus B\implies B\vartriangle C=A,\,A\setminus C=B$.