$3$ independent events $ A, B, C $ what is the $P(AB\cup C)$?

Question: $A, B, C$ are mutually independent. What is the $P(AB\cup C)$?
My guess
$$P(AB \cup C)=P(AB)+P(C)=P(A)P(B)+P(C) $$
Is this correct or do I have to add some subtraction [$-P(A\cap B \cap C)$]? I guess, I don't have a full understanding of independent events.
Comment: It is not correct because you're assuming C and (A and B) are disjoint.
Answer: You have to subtract $P(A \cap B \cap C)$ since the term need not be zero.
\begin{align}
P(AB \cup C)&=P(AB)+P(C)-P(ABC)\\&=P(A)P(B)+P(C)-P(A)P(B)P(C)
\end{align}
A particular examples of $A,B,C$ that are mutually independent and are not mutually exclusive are whether you get heads from 3 independent coin tosses.
Comment: yes, thank you. I knew I had to be missing something.


Agrupar DataFrame por Data Máxima de cada mês considerando a coluna de nome com Python

Question: Olá!
Estou tentando agrupar um df a partir da data máxima de cada mês considerando a coluna NOME.
Tenho o seguinte data frame:
NOME     DATA
ABC   05/01/2023
ABC   07/01/2023
DEF   01/02/2023
DEF   09/02/2023
DEF   25/01/2023
DEF   03/01/2023
ABC   02/02/2023

A saída esperada seria:
NOME     DATA
ABC   07/01/2023
ABC   02/02/2023
DEF   25/01/2023
DEF   09/02/2023

Considerando para cada nome a data mais recente em cada mês.
Já tentei utilizando o groupby, grouper, drop_duplicates porém nenhum deles traz a relação considerando o nome, trás somente o último nome considerando a data mais recente.
Poderiam me ajudar por favor?
Comment: Por favor, esclareça seu problema ou forneça detalhes adicionais a fim de destacar exatamente o que você precisa. Da forma como está escrito atualmente é difícil dizer com exatidão o que você está perguntando.
Comment: Bom dia! Preciso agrupar o dataframe considerando a data máxima de cada mês para cada nome citado na coluna "NOME", parece simples e de fato é, porém não consigo agrupar usando o groupby considerando a data máxima de cada mês, somente a data máxima pra cada nome ou a data máxima por mês sem considerar a coluna NOME.
Answer: Primeiro transformei sua coluna DATA para o formato datetime com .to_datetime. Depois dentro do groupby agrupei os dados por NOME e por mês (utilizando a função grouper para transformar as datas dentro de um mês em um único valor). Com o groupby montado calculei a maior data. O primeiro reset_index é para excluir os dados do grouper e o segundo é para transformar o valor NOME em coluna
df['DATA'] = pd.to_datetime(df['DATA'], dayfirst = True)
df = (
    df.groupby([pd.Grouper(key="DATA", freq="1M"), 'NOME'])
      .agg(max_data= ('DATA', 'max'))
      .reset_index(level=['NOME'])
      .reset_index(drop=True)
    )
df.head()
    NOME    max_data
0   ABC     2023-01-07
1   DEF     2023-01-25
2   ABC     2023-02-02
3   DEF     2023-02-09

Comment: Muuuito obrigada pela ajuda! É exatamente isso que eu precisava :)
Answer: import pandas as pd

# Criar DataFrame
df = pd.DataFrame({'NOME': ['ABC', 'ABC', 'DEF', 'DEF', 'DEF', 'DEF', 'ABC'],
                   'DATA': ['05/01/2023', '07/01/2023', '01/02/2023', '09/02/2023', '25/01/2023', '03/01/2023', '02/02/2023']})

# Converter coluna de data para tipo datetime
df['DATA'] = pd.to_datetime(df['DATA'], format='%d/%m/%Y')

# Criar coluna de mês
df['MÊS'] = df['DATA'].dt.month

# Agrupar o DataFrame pelas colunas NOME e MÊS
grouped = df.groupby(['NOME', 'MÊS'])

# Selecionar a data mais recente em cada grupo
result = grouped['DATA'].max().reset_index()

# Exibir resultado
print(result)


Confidence level for clusters

Question: I have a sample, set of outcomes of some random variable. I divide it into "clusters", using some determinate approach. One of the clusters considered to be "correct", usually it is the one that has the most number of outcomes in it, but not always. I want to mark each cluster with some "confidence level", based on the number of outcomes it has. The formulae should depend on the number of outcomes in each cluster totally, and in the current one.
Say, if the outcome numbers, for each cluster sequentially, are: 220, 31, 28, 21, then the first cluster should have very high confidence level, something close to 100%, but not exactly 100%. But if the distribution is 113, 110, 106, 103, then all the confidences should be almost equal - and not even close to 100% - since there are several similar clusters, we cannot mark each of them as "probably correct".
I cannot use just relative proportion to the maximum, because it will cause highest cluster to have always exactly 100% confidence level, and it shouldn't be.
Is there some approach, or formulae, that gives such estimations? Thank you.
Comment: The most direct measure would be the proportion of outcomes in that cluster, not relative to the maximum but to the sum, so in your examples it would be `0.733, 0.103, 0.093, 0.070` and `0.262, 0.255, 0.245, 0.238`, respectively. If that doesn't suit your purposes, you should say in what way you want it to differ from that. Would you want the cluster with `220` to have a higher confidence level than 73%?
Comment: @joriki This approach is sensitive to the sum, not to the actual numbers and their differences. Firstly, for first example 73% is too low, it should be more than 90%. But this sentence is not so mathematically strict. Secondly, what's more important, if there's one cluster with `100` outcomes, and ten with `10` outcomes each, then first will be measured as 50% confidence, when in reality in such situation first cluster is almost always correct. So, more "noise" - more confidence that not-noisy cluster is correct.
Answer: You could use the conditional probabilities for the outcomes to be the correct outcomes under a prior assumption that the correct outcome occurs with some probability $p$ and all incorrect outcomes occur with probability $q=(1-p)/(n-1)$, where $n$ is the number of different outcomes. Then the probability for outcomes $a_i$ with sum $\sum_ia_i=S$ if answer $k$ is correct is proportional to $p^{a_k}q^{S-a_k}$, so you could assign confidence levels
$$c_k=\frac{p^{a_k}q^{S-a_k}}{\sum_i p^{a_i}q^{S-a_i}}=\frac{p^{a_k}q^{-a_k}}{\sum_i p^{a_i}q^{-a_i}}\;.$$
You can choose the parameter $p$ according to your needs. For $p=q=1/n$, you'll get $c_k=1/n$ (which makes sense, since if you assume that people are just guessing, no amount of clustering will raise your confidence in one of the outcomes). For $p$ near $1$, you'll get sharply peaked confidence levels even for moderate differences in the outcome counts. In the limit $p\to1$, $q\to0$ the confidence level for the outcome with the highest count will go to $1$ and the others will go to $0$, since you can multiply through by the lowest number of factors of $q$ and the other terms in the sum go to zero.
If you want the confidence level in your first example to be noticeably different from $100\%$, you'd have to choose $p$ quite close to $1/n=25\%$. Here are some values for your examples:
$$
\begin{array}{|c|c|c|c|c|c|}
p&q&220&31&28&21\\
\hline
0.253&0.249&
0.879&0.043&0.041&0.037\\
\hline
0.256&0.248&0.994&0.002&0.002&0.002\\
\hline
0.259&0.247&1.000&0.000&0.000&0.000
\end{array}
$$
$$
\begin{array}{|c|c|c|c|c|c|}
p&q&113&110&106&103\\
\hline
0.253&0.249&
0.270&0.258&0.242&0.230\\
\hline
0.256&0.248&0.291&0.264&0.233&0.212\\
\hline
0.259&0.247&0.312&0.270&0.224&0.194\\
\hline
0.265&0.245&
0.354&0.280&0.204&0.162\\
\hline
0.280&0.240&0.458&0.288&0.156&0.098\\
\hline
0.310&0.230&0.632&0.258&0.078&0.032
\end{array}
$$
Comment: @joriki, accounts issue aside, welcome to stats.SE!
Comment: Why do you have the same photo as a [different user](http://math.stackexchange.com/users/6622/joriki) on math.SE?
Comment: My question is: why do I have a different name here? :-) I'm the same person, but here my real name is being displayed and on math.SE my screen name is displayed -- I have no idea why this happened; if you know how I can change it I'd appreciate it :-)
Comment: Interesting -- the screen name was set to my real name. That shouldn't happen.
Comment: Well, that's a good alternate question! No, I don't know the answer. But, perhaps the moderators do. It's probably some account merging issue. I'll flag them and maybe they can help.
Comment: Yes, I agree. That should not happen. May be good to alert meta.SO.
Comment: I've flagged this post to get the duplicate accounts figured out. It appears to me @joriki has made a seperate account for the German language site, and that was the one that was associated when answering this question. I assume you would want all the accounts merged?
Comment: OK, thanks! I will use p = (max a_k / Sum a_k) + 2-3%, it works fine.
Comment: @joriki You just don't have those accounts associated; this probably mean you used different OpenID here and different on Maths and SO. One way of solving this would be to go to your [profile on Maths](http://math.stackexchange.com/users/6622/joriki), clicking "add openid" and then choosing "log in with StackExchange" and log in using your web.de email (this is the OpenID you use here, I can't see that used on Maths and SO). This should trigger automatic association procedure; you would get a +100 reputation bonus here and be able to log in with either of openids.

Confidence level for clusters


Show there exists a Cauchy subsequence

Question: Let $X$ be a separable reflexive real Banach space and $\{\psi_n\}$ be a dense sequence in
$$\{\psi\in X' : ||\psi||_{X'} \leq 1\}.$$
Consider in $X$ the scalar product defined by
$$(x | y)_0 = \sum_{n=1}^\infty 2^{-n} \langle \psi_n,x \rangle\langle \psi_n,y \rangle.$$
Show every bounded sequence in $X$ admits a Cauchy subsequence with respect to the norm $||\cdot||_0 $ (norm induced by $(x| x)_0$) .
Proof:
Since $X$ is reflexive, by Banach–Alaoglu theorem, every bounded sequence $\{x_j\}$ in $X$, there exists a weakly convergent subsequence $\{{x_j}_k\}$ to some $x$.
To show that ${{x_j}_k}$ is Cauchy under $||\cdot||_0$, it is sufficient to show that the sequence ${{x_j}_k}$ converges to $x$ under  $||\cdot||_0$.
Observe that if ${x_j}_k \rightharpoonup x$, then $||{x_j}_k||_X \leq C$ and
$$|\langle \psi_n,{{x_j}_k} - x \rangle| \leq ||\psi_n||_{X'}||{{x_j}_k} - x ||_X \leq 2C$$
Now let $\epsilon$ be given,
$$||{x_j}_k - x||_0^2 = \sum_{n=1}^\infty 2^{-n} {\langle \psi_n,{x_j}_k - x \rangle }^2$$
we split the sum into two parts at $N$ such that
$$\sum_{n=N}^\infty 2^{-n} {\langle \psi_n,{x_j}_k - x \rangle }^2\leq \sum_{n=N}^\infty 2^{-n} (2C)^2 \leq \epsilon/2.$$
Now for the first $N-1$ terms, choose $K$ such that for $k\geq K$ we have
$$\sum_{n=1}^{N-1} 2^{-n} {\langle \psi_n,{x_j}_k - x \rangle }^2 \leq \epsilon/2,$$
the reason we could choose such $K$ is because $\langle \psi_n,{x_j}_k - x \rangle$ goes to zero as $k$ goes to $\infty$ for each of the $N-1$ terms.
Combine the two, we have for each $k\geq K$
$$||{x_j}_k - x||_0^2 = \sum_{n=1}^{N-1} 2^{-n} {\langle \psi_n,{x_j}_k - x \rangle }^2+ \sum_{n=N}^\infty 2^{-n} {\langle \psi_n,{x_j}_k - x \rangle }^2\leq  \epsilon/2 + \epsilon/2.$$
Questions:

Is my proof correct? Is there an easier way to do this? I know my proof is quite long.. Thank you for reading it!
What is the significance of $\psi_n$ being dense? I did not use this fact in my proof.
Comment: When equipped with the weak topology, the whole space $X$ is not metrizable, but if we restrict the weak topology to a bounded subset of $X$, we obtain a metrizable topological space (as you proved). This says that there exist unbounded nets (not sequences!) in $X$ which converge weakly. See [here](http://math.stackexchange.com/a/158933/58818) for an example (the same argument works with "weak" in place of "weak*")
Comment: A quick comment: In your solution, you are basically proving that the inner product $(\cdot|\cdot)_0$ induces the weak topology on bounded subsets of $X$.
Comment: @LuizCordeiro And that is why I am a bit unsure about my proof, since I know that weak topology is not metrizable. Could you explain this please, thank you!
Comment: @LuizCordeiro Thank you very much!
Answer:
It looks fine.
I think the denseness is used implicitly when you want to show that $\|\cdot\|_0$ is a norm.

Show there exists a Cauchy subsequence


Angular 1.X - Accessing controller variable through directive using $watch

Question: Within a controller I have an ajax call that populates $scope.main_data. I want to within a directive get that data when it populates. However the two issues I'm having is:

I cannot seem to access $scope.main_data from the directive.
$scope.watch doesn't seem to work because of this.

How can I print the data from the directive once the data arrives?
CONTROLLER:
app.controller('myCtrl', ['$scope','$http',  function($scope, $http) {

$scope.main_data = [];

$http.get("some_url").success( function(data) {
  $scope.main_data = data;
 });

}]);

DIRECTIVE:
app.directive('myDir', function($compile, $rootScope) {
    return {
        restrict: 'A',
        scope: {
            items: '=items'
        },
        link: function($scope, element, attrs, ctrl) {

           $scope.$watch($scope.main_data ,function(newValue,oldValue){

             if (newValue){
                  console.log($scope.main_data);
             }

           });

        }
    };
});

HTML:

The directive in the html exists within the controller but for some reason I can't access the controller scope through $scope but $scope.$parent.
Comment: Shouldn't it be `$scope.$watch("main_data" ,function(newValue,oldValue){`? - Even better, why not pass `main_data` in as a 2 way binding, then watch that variable instead?
Answer: You've almost got it.
app.directive('myDir', function($compile, $rootScope) {
return {
    restrict: 'A',
    scope: {
        items: '=items'
    },
    link: function($scope, element, attrs, ctrl) {
       $scope.$watch("items",function(newValue,oldValue){
         if (newValue){
              console.log($scope.main_data);
         }
       });
    }
};
});

And html:

Even though you can "hack" around and access main_data using series of$parent calls on your scope and using some other methods, just pass it in to your directive with = binding, so it will be updated when controller scope is updated. In fact you don't even need $watch in this case, you will always have actual data.
Comment: This doesn't seem to work since the watch method calls twice on page reload. One with the empty data [] and two with the loaded data.
Comment: Anyway it works though if I put - if (newValue && newValue.length != 0){...} God I love javascript......
Comment: you can change it to `<div myDir items='main_data' ng-if='main_data' ...` this way you will only render directive when `main_data` is available


Iterative proportional fitting with constraints

Question: I am trying to determine if it is possible to conduct iterative proportional fitting with some constraints. To give a dummy example of my goal:
Say I had data for two towns, A and B, on the ice cream purchasing habits of boys and girls:

Town
Sex
Chocolate cone
Vanilla cone
No ice cream

A
Male
20
30
10

A
Female
100
30
10

B
Male
10
50
70

B
Female
30
20
40

I want to preserve the relationships between variables found in the data but want to apply these relationships to new marginal distributions. For example:

Town
Sex
Chocolate cone
Vanilla cone
No ice cream
New marginal

A
Male
20
30
10
100

A
Female
100
30
10
200

B
Male
10
50
70
80

B
Female
30
20
40
300

New marginal

100
400
180

However, I have two other pieces of data I want to preserve: For each of town A and B, I know the total ice cream bought. For example, I know that a total of 200 cones (chocolate + vanilla) were purchased in town A, and 300 were purchased in town B, but I don't know how many of each.
My question is: is there a way to make sure the IPF output conforms to this known total?
Thank you, and I'm sorry if I did something wrong. This is my first time posting on stack exchange.
Answer: $
\def\LR#1{\left(#1\right)}
\def\trace#1{\operatorname{Tr}\LR{#1}}
\def\qiq{\quad\implies\quad}
\def\m#1{\left[\begin{array}{r}#1\end{array}\right]}
\def\c#1{\color{red}{#1}}
\def\CLR#1{\c{\LR{#1}}}
\def\fracLR#1#2{\LR{\frac{#1}{#2}}}
\def\S{\sum_{i=1}^4\sum_{j=1}^3}
\def\o{{\tt1}}
$You can tackle the problem iteratively.
Start with the raw data and the new marginals
$$
M = \m{
20 & 30 & 10 \\
100 & 30 & 10 \\
10 & 50 & 70 \\
30 & 20 & 40 \\}
,\qquad
x=\m{100\\200\\80\\300}
,\qquad
y=\m{100\\400\\180}
$$
and perform iterative proportional fitting
$$
M = {\rm ipf}(M,x,y) = \m{
7.76773 & 80.92905 & 11.30322 \\
59.26354 & 123.48897 & 17.24749 \\
1.42600 & 49.52330 & 29.05070 \\
31.54273 & 146.05868 & 122.39859 \\
}$$
Next, define three matrices
$$
A=\m{1 & 1 & 0 \\
1 & 1 & 0 \\
0 & 0 & 0 \\
0 & 0 & 0 \\
}
,\qquad
B = \m{
0 & 0 & 0 \\
0 & 0 & 0 \\
1 & 1 & 0 \\
1 & 1 & 0 \\
}
,\qquad
C = \m{
0 & 0 & 1 \\
0 & 0 & 1 \\
0 & 0 & 1 \\
0 & 0 & 1 \\
}
$$  and the double-dot product
$$\eqalign{
M:A \,=\, \S M_{ij}A_{ij} \,=\, \S \big(M\odot A\big)_{ij} \\
}$$
in terms of which your extra constraints are $\;A:M=200,\;\;B:M=300$.
Note that $(A,B,C)$ are orthogonal with respect to the double-dot $(:)$ and Hadamard $(\odot)$ products, and idempotent with respect to the Hadamard product
$$\eqalign{
&A:B \;= 0,\quad&B:C \;= 0,\quad&C:A \;= 0 \\
&A\odot B = 0,\quad&B\odot C = 0,\quad&C\odot A = 0 \\
&A\odot A = A,\quad&B\odot B = B,\quad&C\odot C = C  \\
}$$
Use the Hadamard product to rescale the associated
sub-matrices and enforce the extra constraints
$$\eqalign{
M &= M\odot\LR{\frac{200\,A}{M:A} + \frac{300\,B}{M:B} + C}
 = \m{5.72315 & 59.62738 & 11.30322 \\
43.66454 & 90.98493 & 17.24749 \\
1.87180 & 65.00522 & 29.05070 \\
41.40359 & 191.71939 & 122.39859 \\}
}$$
but now the proportional fitting is wrong, so do it again
$$
M = {\rm ipf}(M,x,y) = \m{
7.42221 & 76.17635 & 16.40144 \\
57.23093 & 117.47554 & 25.29352 \\
1.52160 & 52.05550 & 26.42289 \\
33.82525 & 154.29260 & 111.88215 \\
}$$
then rescale, then refit, then rescale, $\:\ldots\,$ eventually this process converges to
$$\eqalign{
M_* = \m{
5.85211 & 55.98920 & 38.15869 \\
47.42063 & 90.73806 & 61.84131 \\
1.97478 & 62.97797 & 15.04726 \\
44.75249 & 190.29477 & 64.95274 \\
}
}$$
or if you require an integer solution
$$\eqalign{
\biggl\lfloor M_* \biggr\rceil = \m{
6 & 56 & 38 \\
47 & 91 & 62 \\
2 & 63 & 15 \\
45 & 190 & 65 \\
} \\\\
}$$

NB: $\,$ The process described above assumes that you are using a black-box IPF function.
If you are rolling your own code, then it will be much more efficient to enforce the new constraint by appending
an $\,\c{\rm extra}\,$ step to the function's inner loop.
For example, if $(\oslash)$ denotes element-wise division and
$\{u,v\}$ are all-ones vectors the same size as $\{x,y\}$ then
the inner loop of the IPF function would be
$$\eqalign{
&M = M \odot (xv^T) \oslash (M\,vv^T) \\
&M = M \odot (uy^T) \oslash (uu^TM) \\
&\c{M = M\odot\LR{\frac{200\,A}{M:A} + \frac{300\,B}{M:B} + C}} \\
}$$
A single call to the modified function will return $M_*$ directly.
Comment: @greg I actually posted a similar question on MathStacked, but instead wondered if we could enforce less defined constraints; for instance, if we know that entries in one columns should be distributed in a given way (https://math.stackexchange.com/questions/4551874/implementing-value-constraints-on-iterative-proportional-fitting-procedure). Could the above readily extend to such cases?
Comment: Thank you so, so much! I really appreciate your thorough response, it is so helpful.


Erro ao fazer upload de foto

Question: Tentei aplicar as instruções de fazer upload de fotos ao banco com este artigo.
Apenas adaptei para a extensão MySQLi. O código da conexão abaixo:
$conecta = new MySQLi = ("localhost", "root", "", "forum-ti-1");

Porém foram exibidos os erros que a figura abaixo mostra:

Undefined variable erro in ... line 32
Array to string conversion in ... line 38
Undefined variable erro in ... line 45

Abaixo está o código:
<?php
include_once('conexao/conexao.php');

if(($_SERVER["REQUEST_METHOD"] == "POST") and ($_POST["editar"])){

    $foto = $_FILES['foto'];
    $nome = $_POST['nome'];
    $login = $_POST['login'];
    $email = $_POST['email'];
    $senha = $_POST['senha'];
    $data_nascimento = $_POST['data_nascimento'];

    if(!empty($foto["name"])){
        $largura = 1600;
        $altura = 1900;
        $tamanho = 500000;
        if(!preg_match("/^image\/(pjpeg|jpeg|png|gif|bmp)$/", $foto["type"])){
       $error[1] = "Isso não é uma imagem.";
    }
        $dimensoes = getimagesize($foto["tmp_name"]);
        if($dimensoes[0] > $largura) {
            $error[2] = "A largura da imagem não deve ultrapassar ".$largura." pixels";
        }
        if($dimensoes[1] > $altura) {
            $error[3] = "Altura da imagem não deve ultrapassar ".$altura." pixels";
        }
        if($foto["size"] > $tamanho) {
        $error[4] = "A imagem deve ter no máximo ".$tamanho." bytes";
        }
        //Linha 32
        if (count($error) == 0) {
            preg_match("/\.(gif|bmp|png|jpg|jpeg){1}$/i", $foto["name"], $ext);
            $nome_imagem = md5(uniqid(time())) . "." . $ext[1];
            $caminho_imagem = "photos/" . $nome_imagem;
            move_uploaded_file($foto["tmp_name"], $caminho_imagem);
            //Linha 38
            $sql = $conecta->query("UPTADE usuario SET usuario.foto = '$foto', usuario.nome = '$nome', usuario.login = '$login', usuario.senha = '$senha', usuario.data_nascimento = '$data_nascimento' WHERE usuario.id = 4");

            if ($sql){
                header('location: index.php');
            }
        }
        //Linha 45
        if (count($error) != 0) {
            foreach ($error as $erro) {
                echo $erro . "
";
            }
        }
    }
}

?>

<!DOCTYPE html>

    <meta charset="utf-8">
            <meta http-equiv="X-UA-Compatible" content="IE=edge">
            <meta name="viewport" content="width=device-width, initial-scale=1">
    <title></title>
            <link rel="stylesheet" href="css/style.css">

    <?php
                include('templates/header.html.php');
    ?>

            <?php

                $query_perfil = "SELECT nome, login, email, senha FROM usuario WHERE id = 4";

                $rs_perfil = $conecta->query($query_perfil);
                        while($lista_perfil = $rs_perfil->fetch_array()){

            ?>

                        <form class="form_profile_user" action="<?php echo $_SERVER['PHP_SELF'] ?>" enctype="multipart/form-data" method="post" style="margin-top: 130px; margin-left: 330px;">

Alterar o Perfil

                                Foto

                                    <input type="file" name="foto">

                                Nome:
                                    <input type="text" name="nome" value="<?php echo $lista_perfil['nome']; ?>">

                                Login:
                                    <input type="text" name="login" value="<?php echo $lista_perfil['login']; ?>">

                                Email:
                                    <input type="email" name="email" value="<?php echo $lista_perfil['email']; ?>">

                                Senha:
                                    <input type="password" name="senha" value="<?php echo $lista_perfil['senha']; ?>">

                                Data de Nascimento:
                                    <input type="date" name="data_nascimento">

                                <input type="submit" value="Confirmar" name="editar">
                                <input type="submit" value="Cancelar" name="cancelar">
                        </form>

            <?php

                        }

            ?>

            <?php
                include('templates/footer.html.php');
    ?>

E abaixo está o formulário:

//Linha 32
if (count($error) == 0) {

//Linha 38
$sql = $conecta->query("UPTADE usuario SET usuario.foto = '$foto', usuario.nome = '$nome', usuario.login = '$login', usuario.senha = '$senha', usuario.data_nascimento = '$data_nascimento' WHERE usuario.id = 4");

//Linha 45
if (count($error) != 0) {

Comment: Indique quais são as linhas 32, 38 e 45
Answer:
Array to string conversion in

Se objetivo é gravar o nome da imagem passa a variável quem o nome da imagem já modificado que é $nome_imagem, se for um blob use file_get_content() e jogue esse valor para o banco de dados.
$foto = $_FILES['foto'];

//código omitido
 $sql = $conecta->query("UPTADE usuario SET
                            usuario.foto = '$nome_imagem',
                            usuario.nome = '$nome',
                            usuario.login = '$login',
                            usuario.senha = '$senha',
                            usuario.data_nascimento = '$data_nascimento'
                          WHERE usuario.id = 4")

Para tratar o o undefined variable error, defina ela antes do primeiro if como um array vazio.
$error = array();
if(!empty($foto["name"])){

O erre acontece porque $error so é criada se entrar em algum if, caso isso não ocorra é avaliada como não criada/definida na linha abaixo.
if (count($error) == 0) {

Comment: Esta perfeito.. nao tinha visto o erro do nome da imagem
Answer: Eu nao fiz o teste... entao posso estar enganado e tomar uns negativos.. mas acho que vc poderia declarar esta array error antes do primeiro if.. e em cada if vc pode usar o array_push.. provavelmente  isso resolve..
   $error = array();

    if(!empty($foto["name"])){
    $largura = 1600;
    $altura = 1900;
    $tamanho = 500000;
    if(!preg_match("/^image\/(pjpeg|jpeg|png|gif|bmp)$/", $foto["type"])){
   array_push($error, "Isso não é uma imagem.");
}
    $dimensoes = getimagesize($foto["tmp_name"]);
    if($dimensoes[0] > $largura) {
         array_push($error,"A largura da imagem não deve ultrapassar ".$largura." pixels");
    }
    if($dimensoes[1] > $altura) {
        array_push($error,"Altura da imagem não deve ultrapassar ".$altura." pixels");
    }
    if($foto["size"] > $tamanho) {
     array_push($error,"A imagem deve ter no máximo ".$tamanho." bytes");
    }

Erro ao fazer upload de foto


Running Drush Launcher on Windows

Question: When I run Drush in the command line on my Windows 10 computer or Windows Server 2016 servers, I get the following error:
drush : The term 'drush' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.
At line:1 char:1
+ drush
+ ~~~~~
    + CategoryInfo          : ObjectNotFound: (drush:String) [], CommandNotFoundException
    + FullyQualifiedErrorId : CommandNotFoundException

I've downloaded drush launcher and made sure that it was located in my PATH. Why is this error message showing and how do I get passed it?
Answer: The error message occurs because the command must be drush.phar and prefaced by the php command. In the same folder as Drush Launcher, you'd have to run php drush.phar to get it to work. Elsewhere, you'd have to run php /path/to/drush.phar (which can be just as, if not more, annoying that vendor/bin/drush).
To get it to work, create a folder called drush.bat in the same folder as drush.phar and include the following two lines of code:
@echo off
php %~dp0\drush.phar %*

This file is executed by the command drush since it is in your PATH and will then execute the proper php command passing the correct parameters. You'll then be able to run drush from anywhere on your computer.
Answer: Did you change the file name of drush.phar to just drush? After that put it in your path.
I just got it working for me on windows 10. I downloaded drush.phar from: https://github.com/drush-ops/drush-launcher/releases/tag/0.6.0
Then I changed the name of the file to just drush and put it in my system and user path and now I can call drush from composer built drupal site.

Running Drush Launcher on Windows


Are adult male sopranos / trebles counter tenors?

Question: Under some rare conditions a man's voice does not break as he moves from boyhood through adolescence into adulthood; two examples of such conditions are puberphonia and Kallmann's syndrome.
For example, singers with an unbroken adult male voice include Michael Maniaci and Jon Anderson.

I was under the impression that the term counter tenor referred to singers who had trained their falsetto voice to be powerful enough and to have sufficient range to cover much of the music written for castrati (and of course the twentieth and twenty-first century music written especially for the counter tenor voice). I think of Alfred Deller as the pioneer of this voice type on stage (though I believe it was common in English church choirs before then).

With this definition adult male sopranos or trebles whose voice never broke are not countertenors. Perhaps a similar question is whether castrati are counter tenors, and I think the answer is clearly "no".
Are adult male trebles counter tenors?
Comment: I'd have said castrati. Maybe not sexually, but certainly vocally.
Comment: I think a term like castrato is about the biology of the singer. I'd like to understand if the term 'counter tenor' is a description of the way that the vocal range is attained or a description of the range itself. I'm guessing that the definition of the term 'counter tenor' is not yet settled enough to authoritatively answer the question but it's worth a try.
Answer: "Countertenor" is not a well-defined term.  It was sort of coined by Alfred Deller, having a more masculine flair than "male alto" (originally just "alto" as differentiated from the female "contralto").  Deller's beard also served to stress the "male" character of the singer.  Male altos at the time were quite established in English choiral singing but not typical for solistic performances.
As the term is of comparably recent origin, it does not really apply to music types before its time and does not really have a useful musicological definition.  It is a marketing term.  Depending on their stylistic choices, some high register singers rather label themselves "male alto" or "male soprano".
Regarding the vocal character, singers preferring the "male alto" label usually are firmly in the "sounds like a female" camp whereas the rare "male soprano" tends to be harder to characterize as his vocal type is due to more than "just training".  If they even have a "real voice" type, it tends to be the rare "true tenor" which has no problems scouring even higher tenor passages in chest voice or somewhat lightened head voice.


probability df of Y and expected value of Y

Question: Let $Y =2(X-1)^2 - 1$, where $X$ is uniformly distributed over the interval $[0,2]$. Determine the pdf of $Y$ and the expected value of $Y$.
so the pdf is like $f_Y(x)=\frac{f_Y}{2}$? right? and so i get $\frac{2(X-1)^2-1}{2}$? is this the right start?
Answer: ${\begin{align}
\text{Given:}
\\[1ex]
f_X(x) & = \frac 1 2 \; \mathbf 1_{[0,2]}(x)
\\[2ex]
Y & = \left(2(X-1)^2 -1\right)\; \mathbf 1_{[0,2]}(X)
\\[1ex]
\text{By inversion:}& \;\text{Note that there are two possible $X$ values corresponding to each $Y$ value.}
\\[1ex]X_1 & = \left(1 - \sqrt{(Y+1)/2\;}\right) \; \mathbf 1_{[-1,1]}(Y)
\\[1ex]X_2 & = \left(1 + \sqrt{(Y+1)/2\;}\right) \; \mathbf 1_{(-1,1]}(Y)
\\[2ex] \text{Now use:} & \text{ the Change of Variables Transformation, and Law of Total Probability}
\\[1ex]
f_Y(y)
& = \left|\frac{\mathrm d x_1}{\mathrm d y}\right|f_X(x_1) + \left|\frac{\mathrm d x_2}{\mathrm d y}\right|f_X(x_2)
\end{align}}$


Implementation of hash algorithm converts string to number

Question: I have to implement hash table,
I got scheme that shows how to convert string to number (hash function):
abcdef... -> ((256*a+b) XOR (256*c+d)) XOR (256*e+f) ...

I'm writing this question, because I'm not sure if this code (mainly loops) works in a proper way.
int hash(char *s){
    int len = strlen(s);
    int i, result = 0;
    for(i = 0; i < len-1; i=i+2) {
            result ^= ((256*s[i])+s[i+1]);
    }
    if(s[i]!=0) {
            result ^= (256*s[i]);
    }
    return result;
}

Comment: http://stackoverflow.com/questions/7666509/hash-function-for-string
Comment: Generated a lot of collisions for me using string permutations.  Unless you really need to reinvent the wheel use a proven hash function.
Answer: Hash functions technically belong to the branch of Cryptography, this has to do with the (questionable) definition and the (strict) requirements of the Hashing.
Hence, it's highly recommended that you don't roll your own hashing algorithm and stick to existing (tested) algorithms that minimize collisions.
Converting a string to a number isn't hashing... although it's probably a good way to experience collisions and ending up with untraceable issues when you think you came up with a unique value...
Unless this isn't a school assignment where you were given some stub "hash" algorithm that's actually meant to satisfy an assignment (and not a real life implementation), try looking up real hashing algorithm. All of them come with pseudo code and most of them come with the C implementations that were used for testing.
For example, SipHash is a very common string hashing algorithm used in some standard libraries (i.e. Ruby and Rust).
Good Luck!
EDIT
Some people believe that using cryptographic hash functions is sub optimal. You should consider your use case, but... If you are using the hash to assume equity, I would suggest paying the performance price. If you're using the hash as an unsafe indicator, it might not matter.
Here's a page with some non-cryptographic hash functions.
P.S.
Here's an implementation I wrote for the SipHash I mentioned... My code isn't well tested, so if you find any issues, feel free to post them here.
#include <stdlib.h>
#include <stdint.h>

#define SIPHASH_DEFAULT_KEY                         \
  (uint64_t[]) { 0x0706050403020100, 0x0f0e0d0c0b0a0908 }

uint64_t siphash24(const void *data, size_t len, uint64_t iv_key[2]);

// clang-format off
#if !defined(__BIG_ENDIAN__) && !defined(__LITTLE_ENDIAN__)
#   if defined(__has_include)
#     if __has_include(<endian.h>)
#      include <endian.h>
#     elif __has_include(<sys/endian.h>)
#      include <sys/endian.h>
#     endif
#   endif
#   if !defined(__BIG_ENDIAN__) && !defined(__LITTLE_ENDIAN__) && \
                __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__
#      define __BIG_ENDIAN__
#   endif
#endif

#ifndef __unused
#   define __unused __attribute__((unused))
#endif
// clang-format on

/** 64Bit left rotation, inlined. */
#define _lrot64(i, bits)                                                       \
  (((uint64_t)(i) << (bits)) | ((uint64_t)(i) >> (64 - (bits))))

#ifdef __BIG_ENDIAN__
/* the algorithm was designed as little endian */
/** inplace byte swap 64 bit integer */
#define sip_local64(i)                                                         \
  (((i)&0xFFULL) << 56) | (((i)&0xFF00ULL) << 40) |                            \
      (((i)&0xFF0000ULL) << 24) | (((i)&0xFF000000ULL) << 8) |                 \
      (((i)&0xFF00000000ULL) >> 8) | (((i)&0xFF0000000000ULL) >> 24) |         \
      (((i)&0xFF000000000000ULL) >> 40) | (((i)&0xFF00000000000000ULL) >> 56)

#else
/** no need */
#define sip_local64(i) (i)
#endif

uint64_t siphash24(const void *data, size_t len, uint64_t iv_key[2]) {
  /* initialize the 4 words */
  uint64_t v0 = iv_key[0] ^ 0x736f6d6570736575ULL;
  uint64_t v1 = iv_key[1] ^ 0x646f72616e646f6dULL;
  uint64_t v2 = iv_key[0] ^ 0x6c7967656e657261ULL;
  uint64_t v3 = iv_key[1] ^ 0x7465646279746573ULL;
  const uint64_t *w64 = data;
  uint8_t len_mod = len & 255;
  union {
    uint64_t i;
    uint8_t str[8];
  } word;

#define _bs_map_SipRound                                                       \
  do {                                                                         \
    v2 += v3;                                                                  \
    v3 = _lrot64(v3, 16) ^ v2;                                                 \
    v0 += v1;                                                                  \
    v1 = _lrot64(v1, 13) ^ v0;                                                 \
    v0 = _lrot64(v0, 32);                                                      \
    v2 += v1;                                                                  \
    v0 += v3;                                                                  \
    v1 = _lrot64(v1, 17) ^ v2;                                                 \
    v3 = _lrot64(v3, 21) ^ v0;                                                 \
    v2 = _lrot64(v2, 32);                                                      \
  } while (0);

  while (len >= 8) {
    word.i = sip_local64(*w64);
    v3 ^= word.i;
    /* Sip Rounds */
    _bs_map_SipRound;
    _bs_map_SipRound;
    v0 ^= word.i;
    w64 += 1;
    len -= 8;
  }
  word.i = 0;
  uint8_t *pos = word.str;
  uint8_t *w8 = (void *)w64;
  switch (len) {
  case 7:
    pos[6] = w8[6];
  case 6:
    pos[5] = w8[5];
  case 5:
    pos[4] = w8[4];
  case 4:
    pos[3] = w8[3];
  case 3:
    pos[2] = w8[2];
  case 2:
    pos[1] = w8[1];
  case 1:
    pos[0] = w8[0];
  }
  word.str[7] = len_mod;
  // word.i = sip_local64(word.i);

  /* last round */
  v3 ^= word.i;
  _bs_map_SipRound;
  _bs_map_SipRound;
  v0 ^= word.i;
  /* Finalization */
  v2 ^= 0xff;
  /* d iterations of SipRound */
  _bs_map_SipRound;
  _bs_map_SipRound;
  _bs_map_SipRound;
  _bs_map_SipRound;
  /* XOR it all together */
  v0 ^= v1 ^ v2 ^ v3;
#undef _bs_map_SipRound
  return v0;
}

#undef sip_local64
#undef _lrot64

(the switch case fall through is intentional)


Windows file backup software

Question: I'm looking for the backup software for Windows servers aswell as for the workstations.
We always used Acronis but backup&recovery 10 is slow as hell and has too many bells and whistles (i.e. their new metainfo) so I would be really happy to throw it away.
The software requirements:

should work on win7 aswell as on win server 2008 r2
should be simple and fast, we are backing up only the individual files, no partition backups, but it would be nice to store only a changed parts of the large files instead of storing changed files fully when doing incrementals
backing up the open/busy files is required. also on the encrypted (truecrypt/bestcrypt) drives, where windows volume shadow copy doesn't work.
no any complex backup metadata, if I remove all backups from the backup folder, it should automatically understand the full backup is required, then do an incrementals until I clear/rotate the backup folder again. I would like to control backup rotation manually instead of using any complex rotation and consolidation systems.
backup encryption (including the filenames) - aes256+password.
tape support is nice but not required. We do backups only to the network and local drives.
mounting backups as a drives is nice but also not necessary.

So something like Acronis TrueImage 9 or before. More simple - much better. Client/server is not required.
Answer: You may want to look at Cobian backup.  It uses volume shadow copy and seems to be very reliable from my experience.
Comment: No advanced file field/block level delta/SIS features, but very straight forward.
Comment: unfortunately it even can't stable do an incremental backups.
Comment: Really!? Never experienced it having any problems with incremenatals, as that is the way we usually set it up.
Answer: Take a look at Amanda. Best of all it's open-source, and if you want to have it supported, you can go up to the commercial zmanda
Comment: As far as I know, Amanda/Bacula have a client/server architecture, aren't they? Too complex for our tasks I guess.
Answer: Have you considered the Windows backup features with Windows 2008R2? There has been significant changes from the old NT Backup, a lot of it may actually meet your identified requirements.
Comment: sorry, forgot to notify in my question - the software should be able to work with bestcrypt/truecrypt encrypted drives, Windows backup can't.

Windows file backup software


How to fix 'the virtualbox DHCP server has not assigned an ip address to the virtual device'

Question: I can't start virtual device in Gennymotion or VirtualBox.
This is for a config VirtualBox, enable DHCP server address 192.168.56.100, subnetmark 255.255.255.0, lower address bound 192.168.56.101, upper address bound 192.168.56.254. adapter ipv4: 192.168.56.15
Answer: I was having the exact same issue, misleading me to think about virtual networking.
Oracle VirtualBox virtualization won't work alongside with Microsoft's Hyper-V features. Remove Hyper-V features from Windows Features, reboot your machine and try again.
Source: https://www.genymotion.com/help/desktop/faq/#run-genymotion-windows-hyperv


Flutter Apply Color to Text in Custom Theme

Question: I am using Flutter + Dart to make a mobile app. I have defined a CustomTheme class which looks like the following
class CustomTheme {
  static ThemeData lightTheme = ThemeData(
      primaryColor: Colors.red,
      colorScheme: ColorScheme.fromSwatch().copyWith(
          primary: Colors.red,
          secondary: Colors.green),
      textTheme: lightTheme.textTheme.copyWith(
          displayMedium:
              lightTheme.textTheme.displayMedium!.copyWith(color: Colors.blue)),
      useMaterial3: true,
      fontFamily: GoogleFonts.merriweather().fontFamily);
}

I am trying to change the color of my displayMedium but the color is not being applied. I am using it as follows:
Text("Hello", style: Theme.of(context).textTheme.displayMedium)

How can I get the color to apply?
Answer:
Use this I hope it worked

class CustomTheme {
      static final TextStyle _displayMediumTextStyle = TextStyle(color: Colors.blue);

      static ThemeData lightTheme = ThemeData(
      primaryColor: Colors.red,
      colorScheme: ColorScheme.fromSwatch().copyWith(
      primary: Colors.red,
      secondary: Colors.green,
      ),
      textTheme: TextTheme(
      displayMedium: _displayMediumTextStyle,
      ).copyWith(
      headline4: _displayMediumTextStyle, // Example: Apply the same style to headline4
      ),
      useMaterial3: true,
      fontFamily: GoogleFonts.merriweather().fontFamily,
  );
}

Comment: As it's currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer).


Viewflipper setOutAnimation not showing

Question: I'm trying to set my ViewFlipper animations. The flipper works correctly, it's just that the outanimation is not showing, only the inanimation, which looks wierd. Instead of the screen sliding out it just disappears and the new view comes in.
Here's the code in Java.
vf.setInAnimation(this, R.anim.in_from_left);

vf.setOutAnimation(this, R.anim.out_to_right);

vf.showNext();

And here it is in XML
<set xmlns:android="http://schemas.android.com/apk/res/android"
     android:shareInterpolator="false" >
<translate
    android:duration="1400"
    android:fromXDelta="0%"
    android:fromYDelta="0%"
    android:toXDelta="100%"
    android:toYDelta="0%" />

</set>

As I said the flipper is working but it would be nice if the screen would slide out to the side. I would be very greatful for help. I have been Googling for it but haven't seen anyone else with this problem. Thank you!
Comment: Animation `fromYDelta="0%"` to `toYDelta="%0"` ?! :D
Comment: I assume Y is for vertical, it's supposed to go horizontal, the X-values. I tried changing the Y-values but it didn't do anything.
Answer: Editing toYDelta="%100" should fix your problem :)

Viewflipper setOutAnimation not showing


PuppetDB: unable to get local issuer certificate

Question: I'm attempting to use puppetdb on but I'm running into some issues.
I have a node called puppet. It is the master as well as where I've installed puppetdb. It's also a node that puppet manages.
When I run puppet -t on the puppet node I get:
Warning: Unable to fetch my node definition, but the agent run will continue:
Warning: Error 400 on SERVER: Could not retrieve facts for puppet.example.com:
Failed to submit 'replace facts' command for puppet.example.com to PuppetDB at
puppet:8081: SSL_connect returned=1 errno=0 state=SSLv3 read server certificate
B: certificate verify failed: [unable to get local issuer certificate for
/CN=puppet.example.com]

I'm assuming that something is wrong w/ the SSL but I'm not sure what to change or where to look.
Comment: What process did you follow to set up PuppetDB's cert (step 3, A or B [here](https://docs.puppetlabs.com/puppetdb/latest/install_from_source.html#step-3-option-a-run-the-ssl-configuration-script))?
Answer: It looks like problem with hostname on PuppetDB (master) server. Make sure that hostname -f outputs address that is resolvable from all node where puppet agent runs.
From the error log it seems that the hostname is just puppet:
Failed to submit 'replace facts' command for puppet.example.com to PuppetDB at
puppet:8081

Then move old certificates

for PuppetDB 2.x:
mv /etc/puppet/puppetdb/ssl/ /etc/puppet/puppetdb/ssl-old
puppetdb-ssl-setup -f

for PuppetDB 3.x and newer:
mv /etc/puppetlabs/puppetdb/ssl/ /etc/puppetlabs/puppetdb/ssl-old
puppetdb ssl-setup -f

Finally restart the service:
service puppetdb restart


Count the no of people who viewed a particular blog

Question: Is there any module that could count the no of people who viewed a particular blog?
Answer: Enable the statistics module and using views module create a mini report. Other modules you could use in combination with the statistic module are Visitors module and Counter module
Answer: Google Analytics:

Adds the Google Analytics web statistics tracking system to your website.
Answer: We would have to simply use to Statistic module that's there in the core. Enabling the module  would give you the view count of a node page.
In case if we want to track the activity of the user, we can use Google Analytics module.


Trouble Loading Method in React Component

Question: React NOOB issue I'm having:
I have a JSX file that uses Axios to make an API call:
fetch-api-data.jsx:

import * as axios from 'axios';

export class FetchApiData {
  constructor() {
    console.log('FetchAPIData loaded');
  }

  shareMyStoryData(URL) {
    return axios.get(URL)
    .then(function (response) {
      console.log(response.data);
    })
    .catch(function (error) {
      console.log(error);
    });
  }
}

I have a component that references that API call:
share-my-story.jsx

import * as React from 'react';
import * as DOM from 'react-dom';
import PropTypes from 'prop-types';
import './share-my-story.scss';
import FetchApiData from './fetch-api-data';

class ShareMyStory extends React.Component {

  componentDidMount() {
    const URL = '/js/feed/sms.json';
    const smsData = FetchApiData.shareMyStoryData(URL);
    console.log('shareMyStory.jsx - componentDidMount: load: ' + URL);
  }

  render() {
      return (

{headline}

{name}

{link}

      );
  }
}

ShareMyStory.propTypes = {
  name: PropTypes.string,
  headline: PropTypes.string,
  link: PropTypes.string,
}

DOM.render(
    <ShareMyStory/>, document.getElementById('share-my-story'));

However, when webpack compiles the items and they are run in the browser, I get the following error:
TypeError: Cannot read property 'shareMyStoryData' of undefined
Is there some reason why the shareMyStoryData() method isn't available in the share-my-story.jsx file? Both of the files are in the same folder, and I can see that both the fetch-api-data.jsx and share-my-story.jsx file are getting properly bundled together in my bundle.js file.
Answer: You have 3 problems in your fetch-api-data.jsx:

You should you export default instead of export.
You made the spelling mistake in constructor method.
You added shareMyStoryData class method but used it without creating a class instance. Maybe it should be static?

Check out the fixed example:

import * as axios from 'axios';

export default class FetchApiData {
  constructor() {
    console.log('FetchAPIData loaded');
  }

  static shareMyStoryData(URL) {
    return axios.get(URL)
    .then(function (response) {
      console.log(response.data);
    })
    .catch(function (error) {
      console.log(error);
    });
  }
}
Comment: Yes, you are correct! - not creating the class instance and not using static was the issue. Thanks so much!
Comment: Even accounting for the constructor typo, still get the same error with this change: `Uncaught TypeError: Cannot read property 'shareMyStoryData' of undefined`
Comment: @TWLATL I updated the answer, added `static` keyword to `shareMyStoryData`.
Comment: @TWLATL I'm glad to help. You could also create a class instance, or create utils module without using `class` notation.
Answer: You should export your class as default or import it with brackets.
const myFunc = () => {...};
export default myFunc;

import myFunc from 'myfunc.js';

const myFunc = () => {...};
export myFunc;

import  { myFunc } from 'myfunc.js';


Stylesheet for specific page overwritten by standard css

Question: In my subtheme.info I have :
stylesheets[all][] = css/style.css

And in my template.php I have:
function subtheme_preprocess_page(&$vars) {
    $path = current_path();

    if ($path == 'user/login') {
        drupal_add_css(drupal_get_path('theme', 'subtheme') . "/css/login.css");
    }
}

But when I load the page, my style.css is declared after my login.css. So my styles in login.css are overwritten by styles.css. How can I make sure the login.css is declared after the styles.css?
Comment: Can't you just style what you need using `#user-login` ID or `.page-user-login` class in CSS? Simpler code, faster execution, easier caching...
Comment: The problem is that my login page is totally different from my other pages. So I need the bg-color of my body and such..
Comment: `.page-user-login` is (or at least should be) a class set on a `` element - I still fail to see a problem.
Answer: Add weight to the CSS:
drupal_add_css(drupal_get_path('theme', 'subtheme') . "/css/login.css", array('weight' => 100));

See the drupal_add_css() API page for more info. The group option may also be relevant as this also affects the weight.
Also if the specificity of a rule in style.css overrules a rule in login.css it won't matter what order the CSS files are included.
Comment: The problem is that my login page is totally different from my other pages. So I need the bg-color of my body and such... This isn't possible with this solution.
Comment: @nielsv if the code in your question makes it possible, then changes suggested by Felix Eve simply cannot break this possibility. How could they?
Comment: @nielsv What makes you say that isn't possible with this solution? I can guarantee you it is.
Comment: I'm very sorry. I didn't now that the body tag had a class "page-user-login". I'm still in the very beginning of learning drupal. Your solution works perfect and accepted!


If $\Sigma \vdash \varphi$ then $\Sigma \vdash \forall x \varphi$. Why when $(\varphi \implies \forall x \varphi)$ is not true?

Question: In the book of first order logic I'm reading they say that if $(\varphi_1,...,\varphi_n)$ is a proof from a set of formulae $\Sigma$, then so is $(\varphi_1,...,\varphi_n,\forall x \varphi_j)$ for all $1\leq j \leq n$. They assume that as an axiom but it doesn't make sense to me. Why if $\varphi$ is true then so is $\forall x \varphi$? For example if $\varphi$ is $x=1$ that wouldn't mean that $\forall x : x=1$ , or would it?
Maybe what I don't understand is: why $(\Sigma \vdash \varphi \implies \Sigma \vdash \forall x \varphi)$ is true but $(\varphi \implies \forall x \varphi)$ is not true?
The book is this: https://www.springer.com/cda/content/document/cda_downloaddocument/9781447121756-c2.pdf?SGWID=0-0-45-1192238-p174141200
Comment: **NO**; the rule of *Universal generalization* holds provided that $x$ is not free in $Σ$.
Comment: Which book are you referring to? Please [edit] the question to include the details.
Comment: "For example if φ is $x=1$ that wouldn't mean that $∀x (x=1)$, or would it?" Correct; the issue is that $x=1$ is not provable from e.g. arithmetical axioms.
Comment: @MauroALLEGRANZA but $\Sigma \cup \varphi$ is a set of formulae and $\varphi$ is provable from it so.. Maybe my doubt is: What does $x=1$ even mean?
Comment: As already commented,, you need to add the assumption that $x$ does not occur free in $\sum$. Also it's a bad title - sounds like you're saying $\phi\to\forall x\phi$ is a theorem, which is certainly not so. You meant to say that if $\sum\vdash\phi$ then $\sum\vdash\forall x\phi$.
Comment: @DavidC.Ullrich but if $\Sigma \vdash \phi$ and $\Sigma \vdash \forall x \phi$ wouldn't $\phi \rightarrow \forall x \phi$ be a tautology and therefore be provable from $\Sigma$?
Comment: @Rubena No. II can't imagine why you think that -  you're making up your own rules.
Comment: More details into the post [Elliott Mendelson, Introduction to Mathematical Logic : Gen-rule and logical consequence](https://math.stackexchange.com/questions/580796/elliott-mendelson-introduction-to-mathematical-logic-fourth-edition-gen-rul).
Answer: A proof of $\varphi$, with $x$ as a free variable, treats $x$ as an arbitrary element of its domain of discourse. This is exactly how we obtain a proof of $\forall x ~ \varphi$—introduce a variable $x$ and, knowing only those properties of $x$ that hold of all elements in its domain of discourse, prove $\varphi$. This is essentially the content of the $\forall$-introduction rule (a.k.a. universal generalisation).
If you could prove $x=1$ knowing nothing about $x$ than that it is an element of its domain of discourse, then it would indeed be true that $\forall x (x = 1)$ is true. But of course this is only going to be true if the domain of discourse of $x$ is $\{ 1 \}$. (Or $\varnothing$, I suppose.)
Now if you're doing first-order logic, it's likely that your domain of discourse is some ambient set theoretic universe, in which case $x=1$ will almost certainly not be provable, but formulae like $\varnothing \subseteq x$ and $x \in \{ x \}$ are provable.
Comment: @Rubena No! It's not true that if $x=1$ then all elements in the domain must equal $1$.  Nobody has said that. You keep on leaving out that crucial hypothesis. What's true is that _if it's possible to **prove** $x=1$ **without** assuming anything about $x$ **then** all elements in the domain must equal $1$_.
Comment: The book I'm using doesn't seem to mention anything about a domain of discourse though.. And isn't set theory an extension of first order logic?
Comment: @Rubena: Regarding your second question, a model of a first-order theory is a set together with certain structure (constants, functions, etc.). This means that a model $V$ of (say) ZFC set theory is externally a *set*, even though internally it is a proper class. But then if you're doing first-order logic, you must be working within some meta-theory, which in all likelihood is itself a model of the theory of sets.
Comment: Regarding your first question, first-order logic is just a formal system for manipulating symbols, so the variable $x$ doesn't necessarily refer to an element of any set—it's just a symbol. But *semantically* the variable $x$ must refer to an element of a set, and it is this set that is the domain of discourse of $x$.
Comment: But then what's the difference between $x=1$ and $\forall x (x=1)$ ? If $x=1$ then all elements in the domain of discourse of $x$ are equal to 1? Then how does it differ from $\forall x(x=1)$ ?
Comment: The formula $x=1$ has a free variable, but the formula $\forall x ~ x=1$ does not.
Comment: You seem to be taking for granted that we all realize that $x$ must not occur free in $\Sigma$; in fact it seems clear that the problem is precisely that the OP is leaving this out.
Answer: Edit: It turns out that the system you're dealing with is very different from the systems I'm familiar with. Hence more or less everything below is wrong, with regard to that system. I'd simply delete the whole thing but I can't since it's "accepted"...
The reason your version makes no sense is it's false. You're leaving out a crucial hypothesis; what's true, and what it had better say in the book, is this:

If $\Sigma\vdash\phi$, where $x$ does not occur free in $\Sigma$, then $\Sigma\vdash\forall x\phi$.

That makes much more sense. Informally, saying $x$ does not occur free in $\Sigma$ means that the formulas in $\Sigma$ do not say anything about $x$. So saying $\Sigma\vdash \phi$ where $x$ does not occur free in $\Sigma$ means "you can prove $\phi$ without assuming anything about $x$".
Now it makes sense. If you can prove $\phi$ from a set of assumptions that don't mention $x$, then $\phi$ follows from your assumptions regardless of what $x$ is, so $\forall  x\phi$ "should" also follow from the same assumptions.
Taking $\phi$ to be $x=1$ is a bad example, because it's hard to imagine a system where you can prove $x=1$ without assuming anything about $x$. Instead imagine you have some axioms describing how the real numbers work, and you want to prove $\forall x(x>1\to x^2>1)$. If you can prove $x>1\to x^2>1$ without assuming anything special about $x$ then $\forall x(x>1\to x^2>1)$ follows. (That is how people prove $\forall x\phi$ in actual math: prove $\phi$ without assuming anything about $x$.)
Hmm. An example of a $\Sigma$ where $\Sigma\vdash x=1$ but $x$ is not free in $\Sigma$ would be $\Sigma=\{\forall y (y=1)\}$. Yes, $\forall y (y=1)$ implies $x=1$, and it also implies $\forall x (x=1)$.
Another example, illustrating how if $x$ does occur free in $\Sigma$ then all bets are off: It's true that $x=1\vdash x=1$. But $x=1\not\vdash \forall x(x=1)$. If you leave out that "where $x$ does not occur free in $\Sigma$" then you're going to conclude that in fact $x=1\vdash\forall x(x=1)$, which is nonsense; luckily $x=1\vdash\forall x(x=1)$ does not follow from the correct version of the result we're talking about.
Comment: But the exposition of FOL used by the OP is "Mendelson-like" : no restriction on Gen rule. The restriction is on the Deduction Th. So $(x=1) \vdash \forall x (x=1)$ is formally correct in the system; what is not is to apply DT to it to get : $\vdash (x=1) \to \forall x (x=1)$.
Comment: Oh. All I know about logic is what I read in Enderton years ago; the notion of a system were $x=1\vdash\forall x(x=1)$ makes no sense to me. As sort of a check on whether it's "$x=1$" or $"\vdash$" that's totally different: what about $x=1\models\forall x(x=1)$?
Comment: Only browsed the text... it seems to me that is not defined. But $\mathfrak A \vDash \varphi(x)$ iff $\mathfrak A \vDash \varphi(x) [h]$ for every evaluation $h$ and thus $\mathfrak A \vDash \varphi(x)$ iff $\mathfrak A \vDash \forall x \varphi(x)$. So, no problem...
Comment: @MauroALLEGRANZA but then in "Mendelson-like logic" what is the difference between $(x=1)$ and $\forall x (x=1)$ ? What do those formulas mean?
Comment: @Rubena - consider $\mathbb N$ as domain of the interpretation. $\mathbb N \nvDash \forall x (x=1)$, obviously, while for $(x=1)$ we need a variable assignment $h$. If $h(x)=1$ then $\mathbb N \vDash (x=1)[h]$, while for $h'$ such that e.g. $h'(x)=0$ we have that $\mathbb N \nvDash (x=1)[h']$. So the semantics is Ok: we are licensed to asserts $\mathfrak A \vDash \varphi(x)$ only if **every** variable assignment $h$ gives the same truth value.


Relate $Var(y)$ with $Var(y)_{(i)}$

Question: How can I relate $Var(y)$ with $Var(y)_{(i)}$ where $Var(y)_{(i)}$ is de variance of the data with the ith item removed. It is necesary first relate $\bar{y}$ with $\bar{y}_{(i)}$ and it complicates the variance relationship.
Comment: Is $y$ a scalar or a vector? And what do you mean with 'item'?
Comment: Do you mean sample variance with full dataset versus one observation removed?
Comment: Yes, y is the vector $y=(y_1, y_2, ..., y_i,...y_n)$ and $y_{(i)}$ is the vector $y_{(i)}=(y_1, y_2, ..., y_{i-1},y_{i+1}...y_n)$ with the i-th element removed
Answer: I think that I have found the solution by myself:
$Var(y)_{(i)}=\frac{n}{n-1}(Var(y)-\frac{(\bar{y}-y_i)^2}{(n-1)})$
Where:

$y_i$ is the i-th observation removed;
n is the number of observations in $y$;
$\bar{y}$ is de mean of $y$

Relate $Var(y)$ with $Var(y)_{(i)}$


Why android alarm triggers (plays sound) while the time is set to backward?

Question: The problem with my alarm clock is it plays alarm ring even I set the time backward.
The alarm mainly starts when a user toggle the switch.
Another problem with that is toggling the switch OFF doesn't stop the alarm. And it only happens while alarm triggering at the idle of the device or app. That means when the device is idle and alarm triggers, I have to open the alarmClock app to switch off the alarm, at that time pressing the toggle switch doesn't stop the sound.
In another situation other than triggering alarm at idle of the device the alarm clock works fine and I can toggle the button to stop the alarm.
Please help me with those issue.
MainActivity:
package com.mycompany.alarmclock;

import android.support.v7.app.ActionBarActivity;

import java.util.Calendar;

public class MainActivity extends Activity {

    AlarmManager alarmManager;
    private PendingIntent pendingIntent;//an action to be performed by other/foreign application
    private TimePicker alarmTimePicker;//In where the user set the time
    private static MainActivity inst;
    private TextView alarmTextView;//the area where alarm message/notification will be displayed

    public static MainActivity instance() {
        return inst;
    }

    public void onStart() {
        super.onStart();
        inst = this;
    }

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        alarmTimePicker = (TimePicker) findViewById(R.id.alarmTimePicker);
        alarmTextView = (TextView) findViewById(R.id.alarmText);
        ToggleButton alarmToggle = (ToggleButton) findViewById(R.id.alarmToggle);
        alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
    }

    public void onToggleClicked(View view) {
        if (((ToggleButton) view).isChecked()) {//if toggle button is "ON" do the alarming function
            Log.d("MainActivity", "Alarm On");
            Calendar calendar = Calendar.getInstance();
            calendar.set(Calendar.HOUR_OF_DAY, alarmTimePicker.getCurrentHour());
            calendar.set(Calendar.MINUTE, alarmTimePicker.getCurrentMinute());
            Intent myIntent = new Intent(MainActivity.this, AlarmReceiver.class);
            pendingIntent = PendingIntent.getBroadcast(MainActivity.this, 0, myIntent, 0);
            alarmManager.set(AlarmManager.RTC, calendar.getTimeInMillis(), pendingIntent);

        } else {
            AlarmReceiver.stopRingtone();
            alarmManager.cancel(pendingIntent);
            setAlarmText("");
            Log.d("MyActivity", "Alarm Off");
        }

    }

    public void setAlarmText(String alarmText) {
        alarmTextView.setText(alarmText);

    }
}

Alarmreceiver:
package com.mycompany.alarmclock;

import android.support.v4.content.WakefulBroadcastReceiver;

import java.net.URI;

public class AlarmReceiver extends WakefulBroadcastReceiver {

    private static Ringtone mRingtone=null;
    @Override
    public void onReceive(final Context context, Intent intent) {

        MainActivity inst=MainActivity.instance();
        inst.setAlarmText("\n                  Alarm!\n           Get Up! Get up!");
        Uri alarmUri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM);

        if (alarmUri == null) {
            alarmUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
        }
        Ringtone ringtone = RingtoneManager.getRingtone(context, alarmUri);
        mRingtone=RingtoneManager.getRingtone(context,alarmUri);
        mRingtone.play();
        //ringtone.play();

        //this will send a notification message
        ComponentName comp = new ComponentName(context.getPackageName(),
                AlarmService.class.getName());
        startWakefulService(context, (intent.setComponent(comp)));
        setResultCode(Activity.RESULT_OK);
    }
    public  static void stopRingtone(){
        mRingtone.stop();
    }
}

AlarmService:
    package com.mycompany.alarmclock;

import android.support.v4.app.NotificationCompat;

public class AlarmService extends IntentService {

private NotificationManager alarmnotificationManager;

    public AlarmService(){
        super("AlarmService");
    }

    @Override
    protected void onHandleIntent(Intent intent) {
        sendNotification("Get up! Get up!");

    }
    private void sendNotification(String msg){

        Log.d("AlarmService","Sending notification...:"+msg);
        alarmnotificationManager=(NotificationManager)this.getSystemService(Context.NOTIFICATION_SERVICE);

        PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
                new Intent(this, MainActivity.class), 0);

        NotificationCompat.Builder alamNotificationBuilder = new NotificationCompat.Builder(
                this).setContentTitle("Alarm").setSmallIcon(R.drawable.ic_launcher)
                .setStyle(new NotificationCompat.BigTextStyle().bigText(msg))
                .setContentText(msg);

        alamNotificationBuilder.setContentIntent(contentIntent);
        alarmnotificationManager.notify(1, alamNotificationBuilder.build());
        Log.d("AlarmService", "Notification sent.");

    }

}

Answer: From the docs for set() method:

If the stated trigger time is in the past, the alarm will be triggered immediately.

Sources of Android alarm clock may be useful also.
Comment: Sergey Glotov,thank you for your quick look! In fact I haven't used that method. Besides, it's not good, because no user wants their alarm triggers at past time! Ok, can you please look on my second problem?
Comment: I see `alarmManager.set()` in your code. Didn't you use it?
Comment: Ahh u meant that? ya sorry! here is it: alarmManager.set(AlarmManager.RTC, calendar.getTimeInMillis(), pendingIntent); i used it. is there any alternative method to avoid this irritating thing (triggering alarm in past time)? However, my important concentration is on my second problem now.
Comment: about the second part: try to move ringtone stuff to the service.
Comment: the whole onReceive method?
Comment: `onReceive()` should be in the receiver :) Did you read the [documentation](https://developer.android.com/reference/android/support/v4/content/WakefulBroadcastReceiver.html)? Receiver should start the service, service should do the work.
Comment: [How it is done in the system alarm clock](https://github.com/android/platform_packages_apps_alarmclock/blob/master/src/com/android/alarmclock/AlarmKlaxon.java)


Extended chords in keys

Question: I understand the most popular & first-learnt chords & how to associate them with the keys they belong to.
I'm looking at other chord types now such as Am6.
I believe that Am6 can only go into the key of A, because no other key has A,C#,E,F# notes, is this correct?
Comment: I don't know if it helps you, but Am6 has a C, not a C#.
Answer: Am6 would be a minor chord with the 6th scale degree included: ACEF#. This chord occurs naturally in the Dorian Mode and the Ascending Melodic Minor scale.  Most commonly I find this chord associated with Dorian.
As you may have noticed in other circumstances, chords and other notes used within a piece of music do not have to stay within the key specified.  This most commonly is accomplished with a Modulation (moving to another key), or some sort of borrowing/secondary function.  Within the Jazz idiom, you often find that most Major7 chord are built off Lydian, with #11, and most Minor7 chords are built off Dorian, with 13.  So you may also find that openness or darkness, depending on voicing, of the Minor6 chord may just be used as the overall sound used for minor chords within a piece, as opposed to only being used on a specific minor chord within the scale that would naturally have the major 6th degree.
Comment: I would like to make sure that the Jazz concept I presented isn't taken too far.  That concept typically applies to Bebop and beyond and not to earlier Jazz.  Early Jazz is actually more likely to use Major 6 or Minor 6 chords, where more modern Jazz began using Major 7 and Minor 7 chords.  It is also not entirely uncommon to see modern Jazz not utilizing this sort of approach but it is typically characteristically different in such a way that you can hear this difference.  As with all music, there is no wrong, except if you are trying to imitate a specific style, so have fun with it!
Answer: That sounds rather confused.  Am6 does not contain C#, and the natural A minor mode does not contain an F#.
So it is not clear how you derive your rule.  Assuming that you base your rule on the melodic minor scale (the only A minor scale actually containing F#), Bm6 is equally "in scale" with melodic A minor as Am6 is.
Comment: A Dorian would also contain an F#...

Extended chords in keys


Como fazer um join no C#

Question: Galera estou com uma dúvida, consigo fazer um comando SQL (Ex.: select * from T_TABELA) no meu repositório do C# igual faço no banco, porém gostaria de saber se da para fazer um comando join no C# igual faço no banco?
Estava tentando esse comando, mas sempre da erro, o que estou fazendo de errado?
select * from tblModelo modelo join tblMarca marca on marca.IdMarca = modelo.IdModelo;

No meu banco SQL SERVER este comando funciona!
Código no C#:
 public List<clsModelo> listar()
        {
            strQuery = "select * from tblModelo join tblMarca on IdMarca = IdModelo";
            List<clsModelo> result = db.Database.SqlQuery<clsModelo>(strQuery).ToList();
            return result;
        }

Classe Marca:
public class clsMarca

    {
       [Key]
       public int IdMarca { get; set; }

       [Required(ErrorMessage = "Informe o nome da marca")]
       [MinLength(3), MaxLength(50)]
       public string Marca { get; set; }

       public virtual ICollection<clsModelo> Modelos { get; set; }
    }

Classe Modelo:
public class clsModelo
    {
        [Key]
        public int IdModelo { get; set; }

        [Required(ErrorMessage="Informe o nome do Modelo")]
        [StringLength(40, MinimumLength = 3, ErrorMessage = "O nome do modelo precisa ter no mínimo 3 letras")]
        public string Modelo { get; set; }

        [Display(Name = "Marca")]
        public int IdMarca { get; set; }

        [ForeignKey("IdMarca")]
        public virtual clsMarca Marca { get; set; }

        List<clsModelo> lstModelo { get; set; }
    }

Um erro que aparecia dizia que IdMarca não pertence ao contexto de Modelo, sendo que eu informei q ela é uma chave estrangeira.
Comment: Não seria só assim então: `strQuery = "select * from tblModelo join tblMarca on IdMarca = IdModelo"`;
Comment: Da uma olhada nesse link (obs: stackoverflow em ingles): https://stackoverflow.com/questions/9005095/establish-foreign-key-connection-using-entity-framework-with-sql-queries
Comment: Qual é o erro?.
Comment: Como você está tentando fazer no c#?
Comment: Esse trecho é do SQL ou do C#? Você quer fazer um Join no Linq?
Comment: coloca o código pois em c# existem n maneiras de buscar dados em um DB.
Comment: Este comando Join é o mesmo jeito q estou fazendo no c# e no banco, quais são as maneiras de fazer uma unica busca em duas tabelas?
Comment: Mostre o seu código!
Comment: `strQuery = "select * from tblModelo join tblMarca on marIdMarca = modIdModelo";` essa SQL pode dar problemas tem que colocar os nomes ou alias por isso do problema! Apesar que você não relatou o erro que está retornando ...
Comment: Desculpa, editei a pergunta, vê se da para entender agora.
Comment: Existe uma resposta usando lambda aqui: https://pt.stackoverflow.com/questions/17618/join-com-tres-ou-mais-tabelas-com-lambda
Comment: Eu estava adaptando para colocar na pergunta e esqueci de alterar
Comment: Não deu certo? qual foi a exceção lançada?
Answer: Possivelmente o retorno não será do tipo "clsModelo", porque vai conter os campos da tblModelo + tblMarca.
Tenta executar o sql sem usar este cast para o tipo clsModelo. Algo parecido com isso:
var result = db.Database.SqlQuery(strQuery).ToList();

Comment: SqlQuery está incorreto. O certo seria SqlQuery onde "TIPO" pode ser um objeto ou int ou string etc...

Como fazer um join no C#


Best mobile theme for iOS devices?

Question: Can anyone please tell me the best mobile theme I could use for iOS devices? I tried the iUI theme but it doesn't display the table with the info properly :)
Answer: jQuery Mobile or Omega themes
Comment: Thanks, but these don't exactly fit naturally. I was looking something more like iUI - that actually takes table info and puts it into an iOS look; making it not look like a website. The only problem I have with iUI is that it doesn't display the NavigationViewControllerBar as it should.
Comment: jQuery Mobile does exactly that. http://drupal.org/project/jquerymobile - We've used it along with ThemeKey to display this theme on mobile devices for a natural iOS look. There is even a jQm skin for iOS. http://taitems.tumblr.com/post/7240874402/ios-inspired-jquery-mobile-theme-jquery-mobile

Best mobile theme for iOS devices?


Static media images are not displaying in Django

Question: I am working on an online bookstore app. I have a book details page that displays book information in a table, including the book cover image. I am having an issue where the images display correctly when I runserver, however a team member is unable to get the images to display after pulling my code from Github.
all books template:
{%  extends 'bookstore/main.html' %}
{% load crispy_forms_tags %}
{% load static %}
from .models import Product

{% block content %}

            GeekText Complete List of Books

            Click the Book Name for More Details

                    ID #
                    Book Title
                    Genre
                    Cover Image
                    Author

                {% for item in items %}

                    {{ item.id }}
                    {{ item.name }}
                    {{ item.genre }}

                    {{ item.author }}

                    Add To Cart

                {% endfor %}

        {% endblock %}

views.py
from django.shortcuts import render, redirect
from django.db.models import Q
from django.views.generic import TemplateView, ListView, View
from .models import Product
from .models import Author
from .models import Genre
from .models import CartProduct
from .models import Cart
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger

def all_books(request, id=None):
    item = Product.objects.get(id=id)
    context = {
        'items': Product.objects.all().order_by('id'),
        'id': item.id,
        'name': item.name,
        'cover': item.image,
        'author': item.author,
    }

    return render(request,'bookstore/all_books.html', context)

urls.py
from django.urls import path
from . import views
from django.conf import settings
from django.conf.urls.static import static

urlpatterns = [
    path('all_books/', views.all_books, name="all_books"),
    path('book_details/', views.book_details, name="book_details"),
    path(r'^book_details/(?P<id>\d+)/$', views.book_details, name="book_details_with_pk"),
    path('books/', views.books, name="books"),
    path(r'^book_author/(?P<id>\d+)/$', views.book_author, name="book_author"),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

settings.py
INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'crispy_forms',
    'apps.users',
    'apps.bookstore',
    'django_filters',
]

STATIC_URL = '/static/'
MEDIA_URL = '/media/'
STATICFILES_DIRS = [
    os.path.join(BASE_DIR, 'static')
]

models.py
class Product(models.Model): # model to create table on database products

    genre = models.ForeignKey(Genre,related_name='products',on_delete=models.CASCADE)
    author = models.ForeignKey('Author',related_name='authors',on_delete=models.CASCADE)
    name = models.CharField(max_length=200, db_index=True)
    slug = models.SlugField(max_length=200, db_index=True)
    image = models.ImageField(upload_to='static/media',blank=True)
    image2 = models.ImageField(upload_to='media/%Y/%m/%d',blank=True)
    image3 = models.ImageField(upload_to='media/%Y/%m/%d',blank=True)
    publisher = models.CharField(max_length=100, db_index=True)
    release_date = models.DateTimeField(null=True)
    description = models.TextField(blank=True)
    price = models.DecimalField(max_digits=10, decimal_places=2)
    created = models.DateTimeField(default=timezone.now)
    updated = models.DateTimeField(auto_now=True)

Comment: `MEDIA_ROOT = os.path.join(BASE_DIR, 'static/images')` Add this line to settings.py and try if it works
Answer: models.ImageField - these are media files, not static.
They get affected by settings: MEDIA_ROOT, MEDIA_URL
What the docs say about MEDIA_ROOT:

Absolute filesystem path to the directory that will hold user-uploaded files.
Warning
MEDIA_ROOT and STATIC_ROOT must have different values.

And media files should not be mixed with static files in folders.
Media files should be referenced like that

here image - your field name, for image2 it would be item.image2.url
You have mixed static and media files  by these field options:
image = models.ImageField(upload_to='static/media',blank=True)
image2 = models.ImageField(upload_to='media/%Y/%m/%d',blank=True)
image3 = models.ImageField(upload_to='media/%Y/%m/%d',blank=True)

now some of media files (image2, image3) are reachable through MEDIA_URL (because they belong to MEDIA_ROOT folder), some (image) are not - because they belong to STATIC_ROOT folder. You have found a workaround - you reference image field by "{% static item.image %}" trick which can help overcoming wrong setup but is also not a right way.
Also, your teammate might be having troubles with accessing "static" files because the term static is being misused. Again, files stored in the ImageFields are not static and are not part of your project. They are supposed to be uploaded by users and never stored in git. If you want to share them - you have to share files already uploaded to your local /media/... folders somehow.
Static files are/can be something like:

favicon.ico
main.css
robots.txt
popup.js
top_banner.jpg

So:

change upload_to for image field
move already uploaded files to new folder (under media folder), update file paths in the db
fix the way you reference these media files in templates to ...image.url

see also:

how to access imagefield contents
about static files options


Possible to learn and process audio using Tensorflow?

Question: I'm just starting to look into Deep Learning for an idea I have for a project. I'm very new to it and have a general question I hope someone can answer for me before I start down what is undoubtedly going to be a long dark path.
If I provide the NN (for example ) 1000 unprocessed audio files and then 1000 processed audio files (the same files but processed in a specific way)
could it generate an algorithm that I could then provide a new unprocessed audio file - and it, in turn, attempts to generate the processed version? or is that just some next level stuff.
Comment: you found any code example? I need the same thing
Answer: Yes, look at the Magenta project


How to manage different versions of PostgreSQL servers on the same host?

Question: I have PostgreSQL 9.4 and 9.5 on the same host with Ubuntu 14.04. My problems are:

When I run service postgresql start|stop, both versions start/stop. But I want to control which one to do.
When I use psql to connect to PostgreSQL, it always connects to 9.4. But I want to control which server to do. I know I can connect by different port, 5432 for 9.4 and 5433 for 9.5. But I want to connect by peer auth, that is via Unix socket.

I managed to find these clues for above two questions separately but haven't resolved my problems:

I find a command pg_ctlcluster may do the work but I don't know how to specify correct parameters, say, cluster-name. How could I figure it out? Or you have some other way?
Unix socket can be configured by unix_socket_directories = '/var/run/postgresql'. But both versions have the same config dir, within which there're subdirs 9.4-main.pg_stat_tmp  9.4-main.pid  9.5-main.pg_stat_tmp  9.5-main.pid for different versions. When I do psql -h /var/run/postgresql, it just connects to the old 9.4 version.

Could anyone help? Thanks!
Comment: Related: https://serverfault.com/q/582499/95758, https://serverfault.com/q/250192/95758
Comment: I guess I put the question & answer in the wrong place. Maybe SuperUser is the place where it should go. Could any admin help to make a move?
Answer: Well, after some more effort, I get the answers myself:

Ubuntu and Debian offer a pg_ctlcluster as well as a serial pg_xxxcluster commands to manage multiple versions/instances of PostgreSQL on the same host. To find out the version and cluster name, just do pg_lscluster, which outputs like

9.4 main    5432 online postgres /var/lib/postgresql/9.4/main /var/log/postgresql/postgresql-9.4-main.log
9.5 main    5433 online postgres /var/lib/postgresql/9.5/main /var/log/postgresql/postgresql-9.5-main.log

For example, to stop 9.4, you use pg_ctlcluster stop 9.4 main. BTW, to disable autostart 9.4, edit /etc/postgresql/9.4/main/start.conf
psql need a --port, -p option to know which instance to connect, even for peer auth by Unix Socket, since all versions have the same unix_socket_directories. For example, psql -p 5433 dbname can connect by Unix Socket to version 9.5 running with port 5433, while default psql dbname connects to default port 5432, which belongs to my old 9.4 version.

That's it!
Comment: psql doesn't need --port if you use --cluster or the PGCLUSTER env variable. See `man pg_wrapper`. Incidentally this will also automatically select the version of psql that corresponds to the target instance.
Comment: For a machine with postgres 10 as well as 9.6, the `pg_ctlcluster` command arguments had to be inverted: `pg_ctlcluster 9.6 main stop` (i.e., stop at end)
Comment: Your command `pg_lscluster` is missing the final 's': `pg_lsclusters`
Answer: On Debian-based distributions like Ubuntu, psql (and a few other PostgreSQL commands) is a symlink to pg_wrapper, which offers the --cluster option. See man pg_wrapper for details.
For local connections, you can use
psql --cluster 9.4/main
psql --cluster 9.5/main

To see your versions, clusters and ports, use pg_lsclusters. Sample output:
# pg_lsclusters
Ver Cluster Port Status Owner    Data directory               Log file
9.6 main    5432 online postgres /var/lib/postgresql/9.6/main /var/log/postgresql/postgresql-9.6-main.log
11  main    5433 online postgres /var/lib/postgresql/11/main  /var/log/postgresql/postgresql-11-main.log

And to set the default, you can set your preferred version to use port 5432 in /etc/postgresql/*/main/postgresql.conf, and to some other port for the other version.
(This was also answered here: Running multiple versions of PostgreSQL on the same Ubuntu server )


Generators of a direct product of $\Bbb Z_2$ with $\Bbb Z_4$.

Question:
Given two groups :
$$\mathbb{Z} _{2} \;( =\mathbb{Z}/2\mathbb{Z})$$
$$\mathbb{Z}_{4} \;( =\mathbb{Z}/4\mathbb{Z}) $$
We define the direct product :
$$G =\mathbb{Z} _{2} \times \mathbb{Z}_{4}  $$

I know $G$ is not cyclic as there is no element of order eight.

But can we find two elements that generate $G$?

Thanks in advance for your help
Comment: Yes, of course. The element that generates $\mathbb{Z}_2$ and the element that generates $\mathbb{Z}_4$.
Answer: Two generators that go together are $([1]_2, [0]_4)$ and $([0]_2, [1]_4)$, where $[a]_n:=\{a+bn\mid b\in\Bbb Z\}.$
Comment: No, @SkyLand77, since then the group would be cyclic.
Comment: Does (1,1) work ?
Comment: Alright thanks :) .
Answer: $\Bbb Z_2\times\Bbb Z_4=\langle (1,0),(0,1)\rangle $.


How to create VHD file fixed size of window 2003 server

Question: I am trying to create a VHD file fixed size of window 2003 R2 server.
As Hyper V role and Azure CLI is not supported i am not able to create it.
Though Disk2VD creates VHD file but it is dynamic.
Can someone tell me how to create VHD file of window 2003 R2 server fixed size ?
I am trying to migrate aws EC2 window 2003 to azure.
Answer: You can convert the VHD with Hyper-V Manager.

Launch the Edit Disk action within Hyper-V Manager then select the
  dynamic VHD. On the Action screen, shown here, select the Convert
  option to make the dynamic VHD a fixed VHD. You'll be prompted for a
  new name for the fixed VHD.
Comment: As per the microsoft doc. Hyper V role is not supported in Win 2003 server. https://docs.microsoft.com/en-us/windows-server/virtualization/hyper-v/supported-windows-guest-operating-systems-for-hyper-v-on-windows
Comment: @GovindGupta You're not understanding. You use Disk2VHD to create your 2003 server disk, then you use Hyper-V on a supported server to convert it. Or use Powershell. You don't perform the conversion on the 2003 server.
Answer: You can use Hyper-V Manager to make the conversion:

select the Edit Disk option within Hyper-V Manager
select the dynamic VHD
on the Action screen select the Convert option to make the dynamic VHD a fixed VHD
give a new name for the fixed VHD.

Alternately, from powershell you could use Convert-VHD cmdlet:
<code>Convert-VHD -Path D:\HardDiskDyn.vhd -DestinationPath D:\HardDiskFixed.vhd -VHDType Fixed
</code>
For the command to work, you need to Import-Module ServerManager
Comment: As per the microsoft doc. Hyper V role is not supported in Win 2003 server. https://docs.microsoft.com/en-us/windows-server/virtualization/hyper-v/supported-windows-guest-operating-systems-for-hyper-v-on-windows
Comment: @GovindGupta You're not understanding. You use Disk2VHD to create your 2003 server disk, then you use Hyper-V on a supported server to convert it. Or use Powershell. You don't perform the conversion on the 2003 server.
Comment: @Govind Gupta - you said you want to concert an image of Windows 2003 server, not that you try to accomplish this from a Windows 2003 server.
Comment: @Overmind - I have created a VHD file by using disk2VHD tool within the window 2003 server but that vhd file is dynamic so i have downloaded that vhd file on my windows 10 client server and convert is to fixed size vhd using Hyper V on the window 2010.  Is this is right approach ? as i am migrating this server to azure.
Comment: Yes, that should be fine. You can do the conversion on anything supporting Hyper-V Manager.


Which soccer/association football statistic gives the most comprehensive assessment of a player in his or her position?

Question: There are defenders, midfielders, forwards and goalkeepers. If I want to compare non-keeper player to player, which statistic is the best?
In reply to answers below, if the synergy is important, is there a bundle or even a single statistic(s) to compare non-keeper player 1 to player 2 in the synergy of team A and synergy of team B. For example, (p1,sA) to (p2,sA) and (p1,sB) to (p2,sB). As we see there are two variables, are there statistical models to slot all four pairs of numbers and compare among themselves?
Answer: There isn't one, or at least you need to define "best" much more precisely.
To take a naive example: imagine you have four forwards. Two of them are excellent finishers and will score lots of goals if given opportunities, and two of them will create lots of opportunities for other players, but not score that many goals themselves. The best team will have have one of the finishers and one of the creators, and it is the synergy between the players which gives them a lot of their value.
Now of course, football is a much more complicated game than just "creators" and "finishers", and that makes the concept of a single statistic which can be used to compare players even less valid.


How to include specific roles in auto-complete search?

Question: I am using the auto-complete module for searches. It works like a charm. I am looking for to learn how to show only specific roles on the results it pulls. There are advanced areas in the configuration and I think something could be used there, yet I am not sure what.
Answer: The best way to do this is create a View of the search results you would want. e.g. If you create a view of Users with role, "editor", then Autocomplete can be used to pull only from that view. Using the Filters ability of views, this should be a relatively simple task.
http://drupal.org/project/search_autocomplete supports this feature.
Comment: Auto-complete shows results as you type. What you suggest is great but it will require that the user actually searches for something. What I need is that under the "User" search they only see as-you-type results that include only specific roles.
Comment: I am aware that autocomplete searches as you type. That's the whole purpose of autocomplete. :)

I think this bullet point from the project page makes the most sense to what I was trying to say...

"Uses either static data, external or internal URL callback or an embeded view style to easily create your suggestions set."

That means you can have a view filtered by roles and when the user starts typing it uses that view as the "suggestion set"

Hope that clarifies it a bit.
Comment: Aha! Sorry about that friend. I totally understood AND made it work 100%. THANKS for your help! :O) @webkenny


How to statically assess impact of trade volume on a rate?

Question: I have about 50,000 information about historical foreign exchange trades. For each trade I have the equivalent USD amount, the rate at which it was traded and the market rate. I am trying to understand what is the "optimal USD amount" at which we get the best rate.
So I calculated the percentage difference between the traded rate and market rate. Plotting everything on a graph, USD amount on x axis, and percentage difference on y doesn't really help because there are too many points.
So I thought about splitting the trades into groups and calculate the average:
from
0 to 100,000
100,000 to 200,000
200,000 to 300,000
etc
Then the problem I have then is that I have loads of trades in the first groups like 10,000, and just a few in the higher groups. So I am kind of feeling that this is statically wrong.
So what I also tried is to split the trades in group with the same number of trades in each one, so I have group :
0 to 20,000
20,000 to 50,000
...
1,000,000 to 2,000,000
The problem by bucketing trades like this, is that the result is greatly influenced by the choice of the buckets, that's why I don't think any of these method is 'mathematically' correct.
What would be a better method to understand the impact of the amount of currency you trade on the rate you get ?
Answer: If your question is just about how to make a graph that shows the relationship clearly, then one method I found useful is to have parallel boxplots with equally spaced groups but also have a histogram underneath, to show the size of each group.  I have a picture of this on slide 46 of this presentation (along with SAS code, if you are using SAS).


Why is my URL called in JavaScript opening as pop-up

Question: Browser settings vary for allowing popups and I want my URL which is called within a JavaScript function to open in a new tab and not be considered a popup.I am opening the url as:
window.open(my_global_link,'_blank');
In IE and FireFox, when I click on the image I get a notification Pop-up blocked and only by Allowing pop-up for the site the URL would open in a separate tab. How can I make it open in a separate tab and not consider it a pop-up?
Comment: Just check http://stackoverflow.com/questions/2587677/avoid-browser-pop-up-blockers
Answer: It is a browser setting . try  finding navigation options for new tabs in the browser you are using and set it to open in a new tab instead off a new window.


Is $(n+1)(h/R)^n$ monotically decreasing when $0< h < R$ and how to prove it?

Question: I have the following alternating series where $R$ is a positive constant:
$$\sum_{n=0}^{\infty}(-1)^n (n+1)\left(\dfrac{h}{R}\right)^n$$
I'm trying to use the "Alternating Series Estimation Theorem" to calculate the sum error at a certain term. To use the theorem on a series $\sum(-1)^{n-1}b_n$ two conditions has to be met first:

$b_{n+1} \le b_n\qquad$ (decreasing terms)
$\lim_{n\to\infty} b_n = 0$

The second condition can be proved easily by using the ratio test:
\begin{align*}
\lim_{n\to\infty} \left| \dfrac{b_{n+1}}{b_n} \right| &= \lim_{n\to\infty} \left| \dfrac{(n+2)\left(\frac{h}{R}\right)^{n+1}}{(n+1)\left(\frac{h}{R}\right)^n}\right|\\
&= \lim_{n\to\infty} \left(\dfrac{n+2}{n+1}\right) \left|\dfrac{h}{R}\right| \\
&= \dfrac{h}{R}\qquad h > 0
\end{align*}
By the ratio test the series converges absolutely when $\lim_{n\to\infty}|b_{n+1}/b_n| < 1$ therefore the series converges when $h < R$ and:
$$ \lim_{n\to\infty} (-1)^n(n+1)\left(\dfrac{h}{R}\right)^n = 0 \qquad h < R$$
Now $b_n = (n+1)\left(\dfrac{h}{R}\right)^n$ is positive continuous and convergent when $0 < h < R$, but does that means it's also decreasing? if not how do I prove that it's decrerasing?
Answer: You have proved that
$$\lim_{n\to\infty} \left| \dfrac{b_{n+1}}{b_n} \right|=\dfrac{h}{R},$$ with $\dfrac{h}{R}<1 $ then one can see that there exists $N$ such that for all $n\ge N$,
$$
\left| \dfrac{b_{n+1}}{b_n} \right| <1
$$ or
$$
|b_{n+1}|<|b_n|, \quad n\ge N,
$$ thus the given sequence is decreasing (from $N$ onward).
Comment: But does that satisfy the alternating series estimation theorem condition?
Comment: @razzak Yes, the two conditions are satisfied: the series can be split as $\sum_{n=1}^\infty=\sum_{n=1}^{N-1}+\sum_{n=N}^\infty.$
Comment: By writing $\sum_{n=0}^\infty=\sum_{n=0}^{N-1}+\sum_{n=N}^\infty$, we have that $\sum_{n=0}^{N-1}$ is finite and convergent, it does not impact the conclusion.
Comment: @razzak Do you know that you have a closed form for this series:$$ \sum_{n=0}^\infty(n+1)(-1)^n x^n=\frac1{(1+x)^2},\quad |x|<1.$$
Comment: I was working on the formula $F=mgR^2/(R+h)^2$ to calculate when the error percentage would be less than 1%, so I had to convert it to a Maclaurin series first :)
Comment: @razzak Ok, so the results match :)


HTTPS health monitoring on rackspace cloud load balancer

Question: I was using rackspace cloud load balancer to switch between two of my nodes. It was basically a active-passive setup in which the switch would take place in case primary node fails the http health monitoring. Everthing was working fine till I was using http port 80. (I basically had an apache as a proxy on the 2 nodes).
Later I decided to switch over from http to https port 443. However the https health monitoring detects both my nodes as unhealthy now. How do I debug this??
I have a *.example.com certificate configured on both the nodes in a particular virtual host for a particular servername abc.example.com .Is this issue related to certificate??
How do I debug this situation?
When I try switching everything over to http it works again, but I want to get this working over https.
Answer: When you create a Rackspace Cloud Load Balancer you configure the protocol and port to be balanced:

Now you need to edit the configuration to support your new protocol (HTTPS).  You have a couple of options:
Serving HTTPS directly from the servers
If you are serving HTTPS on port 443 from the servers themselves and just using the LB to pass the traffic, rather than offloading SSL to the LB, you need to edit the load balancer to use that port and protocol.

You should also look at your node list for the node IP addresses and test from one node to the other to make sure your site is indeed reachable on the expected port.
Serving HTTPS from the Load Balancer
If instead of hosting your certificate directly on your servers you want to host it on the LB, set your protocol on the LB back to HTTP on port 80, and edit the Secure Traffic (SSL) setting in Optional Features:

Your load balancer will cost a bit more if you do this, but it may also serve to solve your issue if you are having trouble configuring your servers to serve HTTPS over port 443 directly.