Prove or disprove two groups are nonisomorphic

Question: This might be a really silly question, but how can one prove (or disprove) that $GL_2(\mathbb{R})$ and $GL_3(\mathbb{R})$ are nonisomorphic as groups? (Of course we know that they are nonisomorphic if we impose more structure. For example, if we view $GL_2(\mathbb{R})$ and $GL_3(\mathbb{R})$ as Lie groups, it's easy to see via a dimension argument that they are not isomorphic as Lie groups.)
Comment: Remark: an isomorphism between ${\rm GL}_2(\Bbb R)$ and ${\rm GL}_3(\Bbb R)$ would take the derived group of the first one isomorphically onto the derived group of the second one. So the question boils down to showing that ${\rm SL}_2(\Bbb R)$ and ${\rm SL}_3(\Bbb R)$ are not isomorphic as groups.
Comment: Try the paper [A Classification of Matrices of Finite Order over C, R and Q](https://www.jstor.org/stable/3219311).
Answer: For these specific groups, one can use representation theory of finite groups. That is, we can show that $GL_3(\mathbb{R})$ has different finite subgroups to $GL_2(\mathbb{R})$. If we can find a finite group that has a faithful $3$ dimensional real representation, but no faithful $2$ dimensional real representation, then we are done, so it suffices to find a finite group like this, and one can check using character theory that $A_4$ the alternating group on $4$ elements has this property.
Comment: I am not too familiar with the representation theory of finite groups, but can your approach be modified to show that $GL_m(\mathbb{R})$ and $GL_n(\mathbb{R})$ are nonisomorphic whenever $m\neq n$?
Comment: Yes, it can be generalized. Suppose for simplicity that $m>n>2$. Then the symmetric group $S_{m+1}$ has a faithful rational representation of degree $m$, but not $n$.
Answer: This is another way to solve this problem.
An easy computation shows that there are exactly three possibilities for centralizers of elements of the group $G=GL_2(\mathbb{R})$:

If $a=\alpha I$, then $C_G(a)=GL_2(\mathbb{R})$;

If $a$ is diagonalizable over the complex numbers, then $C_G(a)$ is an abelian group;

If $a$  is of the form
$$
a=\left(
  \begin{array}{cc}
    \alpha & 1 \\
    0 & \alpha \\
  \end{array}
  \right),
$$
then $C_G(a)$ is the group of upper triangular matrices.

In the first case the second commutant of $C_G(a)$ is $SL_2(\mathbb{R})$ and is therefore non-Abelian. In the second and third cases the second commutant of $C_G(a)$ is trivial.
Now consider the matrix $a\in GL_3(\mathbb{R})$
$$
a=
\left(
  \begin{array}{ccc}
    1 & 0 & 1 \\
    0 & 1 & 0 \\
    0 & 0 & 1 \\
  \end{array}
\right).
$$
We have
$$
C_{GL_3(\mathbb{R})}(a)=
\left(
  \begin{array}{ccc}
    x & y & z \\
    0 & u & v \\
    0 & 0 & x \\
  \end{array}
\right),\ x,y,z,u,v\in\mathbb{R},\ x,u\neq0.
$$
The second commutant of this group is an Abelian group consisting of matrices of the form
$$
\left(
  \begin{array}{ccc}
    1 & 0 & z \\
    0 & 1 & 0 \\
    0 & 0 & 1 \\
  \end{array}
\right),\ z\in\mathbb{R}.
$$
It follows that the groups $GL_2(\mathbb{R})$ and $GL_3(\mathbb{R})$ are non-isomorphic.


Complement of finitely many vector subspaces

Question: Let $F$ be a field and $V$ be a $n$-dimensional vector space over $F$.
For any subspace $W\subseteq V$ we say that $W'$ is a complement of $W$ if
$$ W + W' = V.$$
I have the following question. Consider $W_1,\ldots, W_l$ finitely many subspaces of the same dimension $k$, then prove that there exists a subspace $W'$ of dimension $n-k$ such that it is a complement for all $W_i$.
I have tried by considering basis $B_i$ of $W_i$ and extending to basis of $V$; but I do not really know how to "simultaneously" extend the basis so I can define the complement $W'$.
Comment: Maybe $F$ should be an infinite field? I guess the statement is false otherwise.
Comment: Have you tried a few examples.  For instance, $V = \mathbb{R}^2$, and $W_1$ and $W_2$ the subspaces generated by $e_1$ and $e_2$?  Then $W'$ can be the subspace generated by $e_1 + e_2$.  What if $V = \mathbb{R}^3$ with the same two subspaces?
Comment: I suppose you mean $\;W\color{red}\oplus W'=V$.
Comment: @Bernard, no I did not mean direct sum since I  am not requiring that $W \cap W' $ is trivial.
Comment: This is very unusual. In this case, $V$ itself is a complement of $W$.
Answer: I assume that $F$ is an infinite field, oherwise the statement is false.
By (backward) induction on $k$. If $k = n-1$, then pick any vector $v$ such that $v \notin W_j$ for every $j$ and let $W' = \mathrm{Span}(v)$.
Given $W_1, \dotsc, W_l$ of dimension $k$, take any vector $v$ such that $v \notin W_j$ for every $j$, and let $W'_j = \mathrm{Span}(W_j, v)$. Then $\dim W'_j = k+1$, and we apply the induction hypothesis on $W'_j$ to get $W'$ of dimension $n-k-1$ a complement for all $W'_j$. In particular this implies that $v \notin W'$, hence $\mathrm{Span}(W', v)$ is of dimension $n-k$ and is a complement for $W_1, \dotsc, W_l$.
Comment: Thanks @Hugo . Yes $F$ is infinite and I assumed that it was not needed. In fact, it is a crucial assumption.


SELECT COUNT returns 0

Question: There is table Departments
CREATE TABLE Departments
(
    id int NOT NULL IDENTITY(1, 1) PRIMARY KEY,
    name  nvarchar(100) NOT NULL,
    parentDepId int
);

I need to count the rows where parentDepId = NULL, but my query returns zero every time.
SELECT COUNT(id) as DepartmentsCount
from Departments
WHERE parentDepId = NULL;

What's wrong with it?
Comment: change the where clause to  WHERE parentDepId is NULL
Comment: Should return syntax error...
Answer: You need to use IS NULL.
SELECT COUNT(id) AS DepartmentsCount FROM Departments
 WHERE parentDepId IS NULL

That is the only way to compare to NULL (other operators do not work).
Comment: It wont work id will exclude null values even though you use is null in where
Comment: `id` is the primary key and cannot be null
Comment: ok sorry I thougt it is parentDepId thanks..
Answer: SELECT COUNT(Isnull(id,1)) AS DepartmentsCount
 FROM Departments
 WHERE parentDepId IS NULL

Comment: ISNULL is product specific, and no dbms is specified...
Comment: Also, `id` is the primary key, and cannot be null anyway.
Comment: yes I agree with you guys, no need of Isnull function here only if it is primary key
Answer: I use syntax where Column is null. Comparison with equals sign seems wrong

SELECT COUNT returns 0


RSS feed not updating using feeds module

Question: I have an RSS feed that has not been updated after the initial import. I actually managed to get it to update once using cron, but even that has since stopped working. Looking at the original feed, I see it is being updated, but I'm not getting the updates on my site.
My feed importer settings are as follows:

It is attached to a specific content type
The minimum refresh period is 15 minutes
The option "Import on submission" is checked
The fetcher is "HTTP"
The parser is set to "common syndication parser"
The processor is "node processor"
I respecify the content type in node processor settings
The input format is the default one
"Expire nodes" is set to "never"
"Update existing nodes" is set to "Update existing nodes (slower than replacing them)"

Is there anything else I need to do, maybe configure something in Job Scheduler? I couldn't find a UI for it.
EDIT: Upon checking admin/reports/dblog as per Jeremy's suggestion I found the following error:

Download of failed with code -1003.

Does anyone know what this means or how I can fix it?
Answer: If you look at /admin/reports/status does it say that cron is running?
If cron is running then looking at the watchdog entries (
admin/reports/dblog) around the time it is running may give you an insight.
If that dosn't work then you may have to start putting debug into the modules code to work out what is going wrong.
Comment: Yes, right now it says Last run "35 min 4 sec ago"...
Comment: Edited question with some more ideas.
Comment: Seeing as the problem turned out to be very specific and was not resolved in any conventional way, I will go with this response as at least it did offer helpful debugging advice. Thanks!


How to prove $x_{n+1}y_n-x_ny_{n+1}=2^{3n}\sqrt{7}$

Question: For $n \in \mathbb{N}$ let
$z_n=(1-i\sqrt {7})^n, ~x_n = Re~z_n,~y_n = Im~z_n$.
I want to show the following:
$x_{n+1}y_n-x_ny_{n+1}=2^{3n}\sqrt{7} ~~~(n \in \mathbb{N})$
My only idea was to show this using mathematical induction:
Basis: Show that the statement holds for n = 0.
$x_1y_0-x_0y_1=1 \cdot 0-(-\sqrt 7)=\sqrt 7= 2^{3\cdot 0}\sqrt{7}$
Inductive step: $n \rightarrow n+1$
Assume that it's true for n. Then one has:
$x_{n+2}y_{n+1}-x_{n+1}y_{n+2}=...$
How to go on?
Comment: write $x_n$ and $y_n$ as $\frac{z_n+\overline{z_n}}{2}$ and $\frac{z_n-\overline{z_n}}{2i}$ respectively. And then simplify.
Answer: Since
$${z_n}\overline{z_{n+1}}=(x_nx_{n+1}+y_ny_{n+1}) + i(x_{n+1}y_{n}-x_{n}y_{n+1})$$
you want to compute the imaginary part of $$ (1-i\sqrt 7)^n(1+i\sqrt 7)^{n+1}=\left((1-i\sqrt 7)(1+i\sqrt 7)\right)^n\cdot (1+i\sqrt 7).$$


wordpress admin login page field mandatory validation wordpress plugin

Question: wp-admin login page blank validation. When an admin does not input anything in the wp-admin login page @ time give the error like a please fill up input field.
Comment: Yes right it's default validation for login details if your fields are blank it gives an error it's correct its default WordPress functionality.
Comment: thanks for the reply but I want validation message when an admin does not insert any value and direct submit wp-admin login form message like please fill up user-name and password.
Answer: Paster this code in functions.php file . I hope it will be working fine
    add_action( 'wp_authenticate', '_catch_empty_user', 1, 2 );
function _catch_empty_user( $username, $pwd ) {
if (!empty($_POST)) {
    if (!is_user_logged_in()) {
        $username = $_POST['log'];
        $pwd = $_POST['pwd'];
        if (empty($username)  && empty($pwd)) {
        ?>

            ERROR: please fill up user-name and password.

        <?php
       }
    }
  }
}

Comment: direct display the message "please fill user name and password " on the page. just load the page.
Comment: @KishanPunjani I have edited code above please check now


Outlook using python win32com to iterate subfolders

Question: I have the following code which gets me the inbox of my shared folder, and all of the emails inside. This code works great and will print the subject of the last email.
outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI")
recip = outlook.CreateRecipient("firstname.lastname@example.com")
inbox = outlook.GetSharedDefaultFolder(recip, 6)
messages = inbox.Items
message = messages.GetLast()
print (message.Subject)

I can access other parent folders in email@example.com's mailbox (like Sent), but I can't get any subfolders of a folder within the inbox, or deeper than that. So if I want inbox\subfolder1, how do I access that? Using Outlook 2013 if that matters.
My main goal is to do:
message.Move(inbox\subfolder1)

Answer: Yeah its better to write it as the name of the folder instead of writing the folder numbers
Like my folder hierarchy is : Outlook_Mails > Inbox > Important
outlook = win32.com.client.Dispatch("Outlook.Application")
mapi = outlook.GetNamespace("MAPI")

your_folder = mapi.Folders['Outlook_Mails'].Folders['Inbox'].Folders['Important']
for message in your_folder.Items:
    print(message.Subject)

Comment: Is there an option to delete mails permanently using this pattern
Answer: This is the code I'm using to do a similar task.
outlook = win32com.client.Dispatch("Outlook.Application")
namespace = outlook.GetNamespace("MAPI")
root_folder = namespace.Folders.Item(1)
subfolder = root_folder.Folders['All'].Folders['Main Folder'].Folders['Subfolder']
messages = subfolder.Items

This finds the messages in the folder "All/Main Folder/Subfolder".
Comment: I love the idea for this, but do you know how to get it to work on a shared mailbox? I tried setting root_folder equal to outlook.GetSharedDefaultFolder(recip, 6) from my initial code, but no luck.
Comment: @nico With that change does `root_folder` have a `Folders` property? It seems like that would set the inbox as `root_folder` so a subfolder would be found with `root_folder.Folders['Subfolder']`. If not, I have no idea, sorry.
Comment: Although, `GetSharedDefaultFolder` should return a `Folder` who's API can be found here: [Folder API](https://msdn.microsoft.com/en-us/library/office/ff863890.aspx).
Comment: setting root_folder equal to GetSharedDefaultFolder(recip, 6) does set it equal to the inbox, and printing root_folder prints "Inbox". If it's returning a Folder, shouldn't I be able to access inbox\subfolder? Forgive my ignorance, but I don't understand why. The Folder API shows that it has a Folders attribute.
Comment: This is perfect and worked perfectly for me. Thank you!
Answer: Can't do that - Outlook caches shared default folders in the main OST file The subfolders are not cached. If the mailbox in question is added as a delegate store, you should be able to parse to the folder in question using Namespace.Folders or Namespace.Stores.
Otherwise you can use Redemption (I am its author) and its RDOSession.GetSharedDefaultFolder - the folder will be opened in the online mode with all of its subfolders (RDOFolder.Folders).
Comment: Well darn. That sucks. Thanks for the insight. Unfortunately I'm limited with what tools I can use, so I was trying to find a way to do this with just Python.
Answer: def processfolder(folder):

    ignoredfolders = []

    if not folder.Name in ignoredfolders:
        print("processing", folder.Name)
        count=0
        for mail in folder.Items:
               savemsg(mail)
               count += 1

        print(count, "Mails in folder")
        for fld in folder.Folders:
            processfolder(fld)

Answer: This is the way I did it. Have to add "Folders" attribute to each level down.
import win32com.client as client

outlook = client.Dispatch('Outlook.Application')
namespace = outlook.GetNameSpace('MAPI')
inbox = namespace.GetDefaultFolder(6)

for i in inbox.Folders:
    print('Top Folder is:', i)
    for folder in inbox.Folders[str(i)].Folders:
        print('2nd tier folder is:', folder)
        for nfolder in inbox.Folders[str(i)].Folders[str(folder)].Folders:
            print('3nd tier folder is:', nfolder)

Answer: Sir Tesla.
Actually, I followed up your code pattern & change it as per my current project.
Please find the below specimen code.
import win32com.client
outlook = win32com.client.Dispatch("Outlook.application")
mapi = outlook.GetNamespace("MAPI")
FirstFMB = mapi.Folders['FirstFMB'].Folders['Inbox']
SecondFMB = mapi.Folders['SecondFMB'].Folders['Another_folder']

<Hence other loops & operations as per requirement>

Here I got to know, one thing. When we need to perform with some kind Function Mail Boxes then we just need to put the name under mapi.Folder[] then just go with the flow.
Sir Tesla your code pattern was helpful for me instead of using Folder number.
On another side, this technique helps me to append mail reading & taking action within a certain time frame.
Answer: import win32com.client as win32

# new outlook object
outlook = win32.Dispatch("Outlook.Application")

# get user namespace *Important when reading email*
namespace = outlook.GetNamespace("MAPI")

# Default inbox folder either Folders.Item(1/2)
root_folder = namespace.Folders.Item(2)

# Use this function to display subfolders inside the current folder

def menu(outlookFolderItem):
    for i in range(0,20):
        try:
            print(i,outlookFolderItem.Folders(i).Name)
        except:
            pass

# example
menu(root_folder)

# navigate into the subfile by

sub_folder = root_folder.Folders(2).Folders(14)

Answer: I took Jared Goguen's answer and modified it.
outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI")
inbox = outlook.GetDefaultFolder(6)
root_folder = inbox.Folders(6)
messages = root_folder.Items

Where inbox.Folders(6) uses the index of my subfolder of interest to identify it. I was able to successfully iterate through the messages in the subfolder using this message.


Erro PHP - Não cadastra no banco de dados

Question: O PHP retorna 4 erros ao eu tentar cadastrar um usuário no banco de dados, os erros são

Warning: move_uploaded_file(fotos/2f66a74ededbbd39c3651c02e62998af.jpg): failed >to open stream: No such file or directory in C:\Program Files (x86)\EasyPHP->Devserver-17\eds-www\Sistema_Aluno\inseriraluno.php on line 63
Warning: move_uploaded_file(): Unable to move 'C:\Users\User\AppData\Local\Temp\phpD504.tmp' to 'fotos/2f66a74ededbbd39c3651c02e62998af.jpg' in C:\Program Files (x86)\EasyPHP-Devserver-17\eds-www\Sistema_Aluno\inseriraluno.php on line 63
Notice: Array to string conversion in C:\Program Files (x86)\EasyPHP-Devserver-17\eds-www\Sistema_Aluno\inseriraluno.php on line 66
Warning: mysqli_query() expects parameter 1 to be mysqli, resource given in C:\Program Files (x86)\EasyPHP-Devserver-17\eds-www\Sistema_Aluno\inseriraluno.php on line 67

PHP:

// Recupera os dados dos campos
$nome = $_POST['nome'];
$email = $_POST['email'];
$foto = $_FILES['foto'];
$senha = $_POST['senha'];
$turmaid = $_POST['idturma'];
$rm = $_POST['rm'];
// Se a foto estiver sido selecionada
if (!empty($foto["name"])) {

    // Largura máxima em pixels
    $largura = 1000;
    // Altura máxima em pixels
    $altura = 1000;
    // Tamanho máximo do arquivo em bytes
    $tamanho = 100000;

    $error = array();

    // Verifica se o arquivo é uma imagem
    if(!preg_match("/^image\/(pjpeg|jpeg|png|gif|bmp)$/", $foto["type"])){
       $error[1] = "Isso não é uma imagem.";
    }

    // Pega as dimensões da imagem
    $dimensoes = getimagesize($foto["tmp_name"]);

    // Verifica se a largura da imagem é maior que a largura permitida
    if($dimensoes[0] > $largura) {
        $error[2] = "A largura da imagem não deve ultrapassar ".$largura." pixels";
    }

    // Verifica se a altura da imagem é maior que a altura permitida
    if($dimensoes[1] > $altura) {
        $error[3] = "Altura da imagem não deve ultrapassar ".$altura." pixels";
    }

    // Verifica se o tamanho da imagem é maior que o tamanho permitido
    if($foto["size"] > $tamanho) {
        $error[4] = "A imagem deve ter no máximo ".$tamanho." bytes";
    }

    // Se não houver nenhum erro
    if (count($error) == 0) {

        // Pega extensão da imagem
        preg_match("/\.(gif|bmp|png|jpg|jpeg){1}$/i", $foto["name"], $ext);

        // Gera um nome único para a imagem
        $nome_imagem = md5(uniqid(time())) . "." . $ext[1];

        // Caminho de onde ficará a imagem
        $caminho_imagem = "fotos/" . $nome_imagem;

        // Faz o upload da imagem para seu respectivo caminho
        move_uploaded_file($foto["tmp_name"], $caminho_imagem);

        // Insere os dados no banco
        $insert = "INSERT INTO aluno (RM, Turma_ID, Foto, Nome, Email, Senha ) VALUES ('$rm','$turmaid','$foto','$nome','$email','$senha'";
        $sql = mysqli_query($conn,$insert);
        // Se os dados forem inseridos com sucesso
        if ($sql){
            echo "Você foi cadastrado com sucesso.";
        }
    }

    // Se houver mensagens de erro, exibe-as
    if (count($error) != 0) {
        foreach ($error as $erro) {
            echo $erro . "
";
        }
    }
}

HTML:

<fieldset>
  <input placeholder="RM" type="number" tabindex="1" name="rm" required autofocus>
</fieldset>
<fieldset>
  <input placeholder="Email" type="email" tabindex="2" name="email" required>
</fieldset>

<fieldset>
  <input placeholder="Nome" name="nome" type="text" tabindex="4" required>
</fieldset>
<fieldset>
  <input type="password" name="senha" placeholder="Senha" tabindex="5" required>
</fieldset>
 <fieldset>
  <input type="number" name="idturma" placeholder="ID Turma" tabindex="6" required>
</fieldset>

 <fieldset>
<input type="file" name="foto" placeholder="Foto"/ tabindex="7">

</fieldset>

<fieldset>
  <button name="submit" type="submit" id="contact-submit" data-submit="...Sending">Enviar</button>
</fieldset>

Answer: Olha na parte
"... VALUES ('$rm','$turmaid','$foto','$nome','$email','$senha'";
Faltou fechar o parenteses:
"... VALUES ('$rm','$turmaid','$foto','$nome','$email','$senha')";
Comment: Pois é amigo, eu percebi isso a pouco tempo atrás, entretanto os erros:
Warning: move_uploaded_file(fotos/7fd269490b7082594f1525d01dfff5b3.jpg): failed to open stream: No such file or directory in C:\Program Files (x86)\EasyPHP-Devserver-17\eds-www\Sistema_Aluno\inseriraluno.php on line 61

Warning: move_uploaded_file(): Unable to move 'C:\Users\User\AppData\Local\Temp\phpDAF4.tmp' to 'fotos/7fd269490b7082594f1525d01dfff5b3.jpg' in C:\Program Files (x86)\EasyPHP-Devserver-17\eds-www\Sistema_Aluno\inseriraluno.php on line 61
Persistem...


Como passar uma parâmetro/variável na inicialização de uma class PHP?

Question: Como faço para inicializar uma class PHP passando ao mesmo tempo um parâmetro. Igual ao PDO que é inicializado passando parâmetros como dados para a conexão com o banco de dados.
No meu caso eu quero simplesmente passar uma ID na inicialização. Ex:
$user = new User($id);

E depois de passado o parâmetro usando a função construct para carregar todas as informações desse usuário, sem a necessidade de de chamar alguma função manualmente para tal ação.
Answer: Usa um construtor:
class User {

   protected $id;
   public $dados;
   public function __construct($id) {
      $this->id = $id; // aqui já tens o teu id
      // echo $this->id; // vai imprimir 4 e podes fazer o que quiseres com ele ao longo dos metodos/atributos desta instância
      // aceder à base de dados, SELECT * FROM users WHERE id = $id, 4 neste caso

      // depois já terás os dados que queres acerca do utilizador
      $this->dados = array('id' => 4, 'nome' => 'Miguel', 'email' => 'firstname.lastname@example.com');
   }
}

$u = new User(4);
echo $u->dados['email']; // firstname.lastname@example.com

Neste caso $dados é só um exemplo de um retorno da informação da base de dados
DEMONSTRAÇÃO
Comment: O que faz o "protected" ?
Comment: @ThomsonTorvalds protected é para dizer que apenas esta e as classes que extendem esta têm acesso a esta propriedade, podes pôr private para que seja só esta se preferires
Comment: @ThomsonTorvalds, completei um pouco mais para veres ao certo o que podes fazer


Contar sem usar rowCount do PDO

Question: sou novo com PHP PDO, estou usando MVC e não consegui fazer a contagem de linhas no banco de dados usando $obj->rowCount();
Segue o meu código
model.php:
public function read($table, $fields, $where = null, $fetchMode = PDO::FETCH_ASSOC) {

    $where = isset($where) ? "WHERE {$where}" : "";

    $sql = $this->db->query("SELECT {$fields} FROM {$table} {$where} ");

    return $sql->fetchAll($fetchMode);

}

login_model.php
public function login() {
    $id = 1;
    $sql = $this->read('users', 'email', "id={$id}");
    print_r($sql);
    if (count($sql) >= 1) {
        echo 'é maior';
    } else {
        echo 'é menor';
    }
}

como viram estou usando count() para fazer a contagem, pois eu não consegui fazer usando rowCount(); por falta de lógica :/
Comment: [Contando linhas atingidas PDO](http://pt.stackoverflow.com/q/82168/91)
Comment: Olha a função, por exemplo `$sql = $obj->read(aqui a query)` não consigo fazer isso `$sql->rowCount()` '-'
Answer: No seu método retorna apenas $sql e não os resultados (fetchAll().
public function read($table, $fields, $where = null, $fetchMode = PDO::FETCH_ASSOC) {
    $where = isset($where) ? "WHERE {$where}" : "";
    $sql = $this->db->query("SELECT {$fields} FROM {$table} {$where} ");
    return $sql;
}

Na chamda faça:
$sql = $this->read('users', 'email', "id={$id}");
echo $sql->rowCount();

Comment: Não consigo usar assim `$sql = $this->read('users', 'email', "id={$id}");
echo $sql->rowCount();` não sei por que.
Comment: @GuilhermeAlves aparece algum erro?
Comment: sim, retorna isso `Call to a member function rowCount() on a non-object in`
Comment: @GuilhermeAlves sua consulta entao falhou.
Comment: Deu certo escrevi $sqls ao invez de $sql, apenas return $sql deu certo obrigado!
Answer:
PDOStatement::rowCount() returns the number of rows affected by the last DELETE, INSERT, or UPDATE statement executed by the corresponding PDOStatement object.
If the last SQL statement executed by the associated PDOStatement was a SELECT statement, some databases may return the number of rows returned by that statement. However, this behaviour is not guaranteed for all databases and should not be relied on for portable applications."

Fonte: http://php.net/manual/pt_BR/pdostatement.rowcount.php
EDIT (Tradução):
Se a ultima query de SQL executada através do PDOStatement foi uma query do tipo select alguns bancos de dados podem retornar o numero de rows selecionadas, no entanto, outros bancos de dados poderão não retornar e por isso o comportamento não é garantido para todos os bancos de dados e por isso não deve ser invocado em aplicações portateis.
Poderá não estar perfeito, mas encontro-me no trabalho de momento e isto é o melhor que consigo fazer para lhe ajudar.
Comment: Vou apenas traduzir a parte importante. Aguarde o edit no post principal
Comment: Poderia traduzir para pt?
Comment: Está editado e em português. boa sorte.
Answer: Se você estiver usando MySQL pode contornar a situação com o uso do sql_calc_found_rows e found_rows().
Segue um link de um artigo que faz uso desses recursos.
http://www.marcosborges.com/blog/2010/08/13/select-sql_calc_found_rows-no-mysql/
O mais interessante é que ele retorna o total de linhas encontradas mesmo utilizando as clásulas LIMIT e OFFSET. Eu utilizo muito esse recurso para fazer paginação nos sistemas que faço.

Contar sem usar rowCount do PDO


Why jQuery.each() and jQuery.grep() has different parameter orders?

Question: I have noticed there is a difference in parameter orders between callback function of .each() and .grep() functions in jquery.
jQuery.grep( array, function(elementOfArray, indexInArray), [ invert ] )

jQuery.each( collection, callback(indexInArray, valueOfElement) )

Do you have any idea of the possible reasons that they preferred to have indexInArray as the 1st parameter in .each() and as the 2nd in the .grep() function?
Thanks,
burak ozdogan
Answer: I don't know whether there is a real answer for this or not but lets have a look at the usage of the function:

In .grep, an element of an array is processed. The index of this element is not necessary to process the element. It is more or less optional and therefore the second parameter.
In .each, no parameter is really necessary. But as the element can be accessed via this inside the function, it makes sense that the element is set as second parameter. This way, one doesn't have to specify two variables only to use the index.
If the parameters were in reverse order and you want to use the index, you would have to specify a variable for the element and you might not be able to use this anymore (but I am not sure about that).

So in the end it is a matter of convenience.
Answer: Well, one might say that the arguments have the same order. If you look at the source code, you will see that in grep, the callback is called like this:
callback( elems[ i ], i ) )

whereas in each (when dealing with an array and not a map):
var value = object[0];
callback.call( value, i, value )

where value is the this object. This way of calling a method is used in order to override the value of this.
So I guess, the preferred way of using each is to use this in order to refer to the object.
In my opinion this difference isn't a good thing as it makes the life of the users harder. I've checked and both versions were introduced at 1.0 version, so it can't be justified that this was caused by two different opinions.


Question about libvirt autostart and virtual manager

Question: I'm running Ubuntu 10.04
I installed kvm and virtual manager and created a guest OS. Everything worked fine until I rebooted my pc. After reboot libvirt was not running despite of init script inside /etc/init.d
If I start it manually it works. It's just annoying to do it manually every time.
Is there a way I can debug why my libvirt fails to start automatically?
Second question:
As I said I'm using virtual manager to create and run my guest OS. Initially I installed my first os (Windows 7) from .iso file on USB drive, and when I disconnected that drive after guest OS installation, virtual manager complained about missing .iso file. Basically it fails to start without .iso.. If I plug back that USB drive - it works. Is it how it's suppose to be? I was thinking that once you installed your guest OS on a virtual hardrive space, you don't need .iso file any more..
Would appreciate any addition information on that topic.
Thanks a lot!
Answer: Merely having the initscript isn't enough; upstart also needs to know that it has to be started.
It doesn't need the .iso anymore, but you haven't told it that. Push the "Disconnect" button.
Answer: It turned out to be a virtual bridge problem. Libvirt was trying to start before bridge was created. So I modified upstart script (/etc/init/libvirt-bin.conf) to include addition check:
start on (runlevel [2345] and net-device-up IFACE=virbr1)
As for .iso issue I removed cdrom section using virsh edit VMNAME (which was pointing to my .iso file on USB drive) and it works just fine now.
Thanks for feedback on this question.


fat free framework and php -S: some URLs inexplicably not working

Question: I'm trying to run a F3 php app under php -S, php's builtin web server (for local testing).
I have the following routes:
GET /rest/1.0/team=TeamRestController->index
GET /rest/1.0/team/@id=TeamRestController->index

Accessing these fails with 404.
When I add these routes:
GET /rest/10/team=TeamRestController->index
GET /rest/10/team/@id=TeamRestController->index

access to them work. Looks like the dot is preventing something here. The 1.0 form does work under apache.
What is happening here?
Edit: Erm, this:
while (q > request->vpath) {
    if (*q-- == '.') {
        is_static_file = 1;
        break;
    }
}

I.e. if there is a dot anywhere in the URL path then php will only serve static content, not execute scripts. What were they thinking?
Answer: Looks like a bug in the built-in server: when calling /rest/1.0/team, PHP sets $_SERVER['SCRIPT_NAME'] to /rest/1.0 even though the called script is index.php...
The intention is probably to support such calls: /rest/index.php/team but in our case, this is irrelevant since:

the script name is already passed as an argument to the server
there's no such script called 1.0

You can workaround this bug by setting the correct $_SERVER['SCRIPT_NAME'] at the top of index.php:
<?php
$_SERVER['SCRIPT_NAME']=basename(__FILE__);
$f3=require('lib/base.php');
//etc...

Comment: In my case index.php isn't even executed - this won't workaround. I need to patch the php server code above to get anything executed - apparently it is only looking for static files where there is a dot anywhere in the path. (In my case index.php is in the root.)
Comment: How do you call `php -S`? It should look like `php -S localhost:8080 index.php`.
Comment: Without the index.php - then it almost works, as described. With the index.php it behaves completely different from under apache. (I'm not a wizard on these things.)
Comment: I encourage you to describe your issue on the [Google Group](https://groups.google.com/forum/#!forum/f3-framework) dedicated to the framework. That would be the proper place to debug your setup. But in short: under Apache, all requests are redirected to `index.php` thanks to [.htaccess](https://github.com/bcosca/fatfree/blob/master/.htaccess) ; when using the PHP built-in server, the same is achieved by providing `index.php` as an argument of `php -S`.
Comment: I've also encountered this, and filed it in the pkp-src repo for possible attention: https://github.com/php/php-src/issues/12604


Qual são as diferenças entre die, exit e __halt_compiler?

Question: Quais são as principiais diferenças entre die, exit e __halt_compiler?
Comment: Pergunta simples e que agrega informação muito útil pra comunidade +1
Answer: Sobre die e exit
Entre die e exit, não há diferença, eles são os mesmos, segundo o manual. Um é apelido para o outro.
Manual PHP para exit:

Note: This language construct is equivalent to die().

Manual PHP para die:

This language construct is equivalent to exit().

Sobre __halt_compiler:
Existe um mecanismo do PHP que permite embutir trechos de dados (inclusive dados binários) que não serão sequer interpretados pelo interpretador de PHP. Diferente do comando exit, que interrompe a execução do script, mas não interrompe o parser do PHP, existe o comando __halt_compiler, que ignora absolutamente tudo que esteja abaixo do ponto em que foi chamado.
A utilização deste recurso é pouco comum, mas permite, por exemplo:
Criação de scripts PHP auto-extratores (anexa um pacote de dados ao script)
Criação de arquivos que exigem autenticação para acesso, mas ficam em uma área pública na Web
Armazenar meta-informações sobre o script PHP.
O ideal, é que o próprio script consiga "ler" o que vem depois do ponto em que foi chamado o __halt_compiler. Para tanto, existe uma constante especial chamada __COMPILER_HALT_OFFSET__, que guarda a posição do primeiro byte que está após a chamada do __halt_compiler().
Veja um exemplo simples:
<?php

// Abrir o proprio arquivo para leitura
$f = fopen(__FILE__, 'r');

// Posicionar o cursor na posicao do __halt_compiler() + 1
// (+1 pois existe a quebra de linha)
fseek($f, __COMPILER_HALT_OFFSET__ + 1);

// Ler todo conteudo do cursor ate o final do arquivo e fecha-lo
$conteudo = stream_get_contents($f);
fclose($f);

// Fazer algo com o conteudo
echo $conteudo;
exit(0);

__halt_compiler();
tudo que vem aqui é ignorado!
blá blá blá

Fonte sobre __halt_compiler()
Answer: As funções die() e exit() são equivalentes, segundo a documentação, e servem para encerrar a execução do script, exibindo uma mensagem adicional.
Já o __halt_compiler() tem um finalidade diferente. Ele é utilizado para encerrar o parse do compilador após determinado ponto do arquivo. Se aplicados para o debug de código, o __halt_compiler() irá ignorar erros de sintaxe a partir de determinado trecho do arquivo, o que não acontece com o die() e exit().
Considere o seguinte script:
<?php

echo 'Estou debugando esse script';

die('bye_bye');

Aqui nessa parte existem erros de sintaxe!

Ele irá gerar o seguinte erro:

PHP Parse error:  syntax error, unexpected 'nessa' (T_STRING) in C:\www\chiqueirinho\halt.php on line 7
Parse error: syntax error, unexpected 'nessa' (T_STRING) in C:\www\chiqueirinho\halt.php on line 7

Agora, alterando o die para __halt_compiler():
<?php

echo 'Estou debugando esse script';

__halt_compiler();

Aqui nessa parte existem erros de sintaxe!

A saída será a seguinte:

Estou debugando esse script

O __halt_compiler() pode ser utilizado também para criação de templates, separando o código da aplicação do layout graças a constante __COMPILER_HALT_OFFSET__ que retorna o ponto exato onde o __halt_compiler() se localiza no arquivo.
Temos aqui um exemplo dessa técnica usada em templates, porém é mais comum encontrar esse tipo de construção de templates com arquivos separados, como foi aplicado nesse exemplo.


Allow ("null") to access your SoundCloud account

Question: I am currently trying to register a new client application. I have registered the app and input MyApp://oauth as stated in the docs
I changed the appropriate things in my .plist file and added the clientID and secret and the above redirectURL into my iOS initialization code in the AppDelegate:
[SCSoundCloud setClientID:@"..."

                   secret:@"..."

              redirectURL:[NSURL URLWithString:@"MyApp://oauth"]];

However, for some reason, even after doing all of this, I still get Allow ("null") to access your SoundCloud account in the SCLoginViewController.
What am I missing?
Answer: To show the your app name in that place SC UI uses CFBundleDisplayName from your info.plist.
You can add and get rid of "(null)".

Allow (“null”) to access your SoundCloud account


Adding elemnts in a list/array of dictionaries

Question: I have the following code in which i want to calculate the sum of wages in Departament of sales, but it appears to have an error
ang = [{'Id':1, 'Name':'John', 'Wage':1000, 'Dept':'Sales'},
     {'Id':2, 'Name':'Greg', 'Wage':1200, 'Dept':'Sales'},
     {'Id':3, 'Name':'Mary', 'Wage':3000, 'Dept':'Mgmt'},
     {'Id':4, 'Name':'Paul', 'Wage':900, 'Dept':'Sales'},
     {'Id':5, 'Name':'Lily', 'Wage':1200, 'Dept':'Finance'} ]
    d='Sales'
    s = 0
    for i in ang:
        if(i['Dept']=='Sales')
            s=s+i['Wage']
    print('Total wage for sales departament.', d, '=', s)

Comment: The error message matters
Comment: I agree; it does appear to have an error. Do you have a *question* about that error? Were you able to figure out where the error is? If not, my recommendation is that you start by *reading* the error message.
Answer: 'Wage' key isn't on first element in your list (raising a key error), use the .get() method to find the 'Wage' and return it's value or return a default value to sum.
s = 0
for i in ang:
  if i.get('Dept') == 'Sales':
    s += i.get('Wage', 0) # zero as default value

A shorten way to do it:
s = sum([i.get('Wage', 0) for i in ang if i.get('Dept') == 'Sales'])

Comment: thanks for your answer, the problem is that your piece of code calculates the total wage for all departaments and i want only for the sales departament
Comment: @OtiliaDomnea I didn't noticed that, I've changed my answer.
Answer: Because the top entry has no Wage key, you are most likely getting a KeyError when you use i['Wage']. Use i.get(<key>, <default>) instead.
Answer: The first entry in your list specifies Salariu instead of Wage.  If you fix that this works:
>>> ang = [{'Id':1, 'Name':'John', 'Wage':1000, 'Dept':'Sales'},
...      {'Id':2, 'Name':'Greg', 'Wage':1200, 'Dept':'Sales'},
...      {'Id':3, 'Name':'Mary', 'Wage':3000, 'Dept':'Mgmt'},
...      {'Id':4, 'Name':'Paul', 'Wage':900, 'Dept':'Sales'},
...      {'Id':5, 'Name':'Lily', 'Wage':1200, 'Dept':'Finance'} ]
>>> d = "Sales"
>>> print(f"Total wage for {d} department = {sum(a['Wage'] for a in ang if a['Dept'] == d)}")
Total wage for Sales department = 3100

Answer: The code should do what you want, assuming the 'Salariu' in ID1 is intentional.
It looks like there is a missing colon (:) on the if statement though
if(i['Dept']=='Sales'):
    s=s+i['Wage']

If you're still stuck please copy the error to give us all a clue!!


Como passar um ponteiro de função por parâmetro?

Question: Preciso que seja passado pelo argv[], na função main, o nome de uma função que será chamada pela mesma.
Não posso fazer comparações de strings, então devo fazer a chamada com variáveis.
Aqui está o meu código:
typedef void (*func)(void);
void A (void){ printf("*funcao A*\n"); }
void B (void){ printf("*funcao B*\n"); }
void fun(func fc){
    fc();
}

int main(int argc, char *argv[]){
    int i;
    for(i = 1; i < argc; i++){
        fun(argv[i]);
    }
    system("PAUSE");
    return 0;
}

Desta forma o algorítimo compila mas não executa.
Comment: Eu consigo compilar, mas nem sequer entra o ciclo `for`
Comment: `argc` não é _zero-based_? Nesse caso o `for` tem que começar em `i = 0`.
Comment: Já iniciei em i = 1 porque em argv[0] tem diretório do arquivo.
Comment: Se o exercício pede para *passar o* **nome** *de uma função*, acho difícil escapar de fazer comparações de strings em algum momento. Dá uma investigada nesse requisito.
Comment: @FightForWhat Dê uma olhada no [tour]. Você pode aceitar uma resposta se ela resolveu seu problema. Você pode votar em todos os posts do site também. Alguma lhe ajudou mais? Precisa que algo seja melhorado?
Answer: Eu não consegui nem compilar.
(func)argv[i]

Coloquei no GitHub para referência futura.
Não transforma magicamente uma string em um ponteiro para função. É impossível fazer esta transformação direta.
O melhor que você pode conseguir é montar uma tabela de lookup com os nomes das funções e os seus respectivos ponteiros. De alguma forma vai haver uma comparação de strings. Dá até para usar uma tabela hash para isto mas mesmo assim haverá comparação.
Se você entendeu certo o requisito quem criou este requisito ou não sabe como um computador funciona ou está pensando em algum truque capcioso.
Em linguagens que possuem metadados fica mais simples. Mas no fundo haverá comparação mesmo que você não esteja vendo ela. É possível usar alguma biblioteca em C para conseguir isto se carregar um módulo externo. Em DLLs existe algum metadado. Mas uma comparação ocorrerá, você só não verá ela.
Comment: Tem um outra possibilidade. Você não entendeu o requisito. Mas acredito mais em ser alguma proposta capciosa.
Comment: Meu professor de estrutura de dados ele até criou o primeiro sistema operacional no Rio Grande do Sul.
Comment: Não to defendendo o velho mas tem coisas que ele é bem sem noção...


Finding matching datasets in two separate spreadsheets (Excel/Pages)

Question: Using Pages (or Excel) I'd like to do the following:
I have a list of around 150 order numbers in one spreadsheet (A).
In another spreadsheet (B) I have a database of all customers (thousands) including their order numbers and their email addresses.
I need to find a way to match the order numbers in (A) with the associated email addresses in (B), i.e. I need a list of all email addresses of the orders in list (A).
I'm not very good at Excel/Pages. Does anyone have an easy solution for this? Thank you!
Answer: This is a common <code>=VLOOKUP</code> scenario. Without knowing more about the specific details of what you need it's difficult to write something for you.
As you say you're not very experienced I would recommend using the Insert Function Wizard to put something together, have a look at this guide on how to create a vlookup formula through the wizard: http://www.howtogeek.com/howto/13780/using-vlookup-in-excel/
Comment: Thanks so much! I've had a quick read through this and I can certainly see how this function could help, but I'm still struggling to apply it to my exact scenario. May I give you some more info? Spreadsheet 1 contains only one column with the selection of order IDs I need to find email addresses for, spreadsheet 2 contains column A with all order IDs (thousands) and column B with their associated email addresses. What I need to do is find the associated email addresses of the orders in spreadsheet 1.


Regexp Matching in Reducer

Question: I'm looking at reducers.
There is a nice example in the Tutor for counting words:
(0 | it + 1 | /\w+/ := S)

where S is some longer string with several words. The reducer returns the count of such words.
I was wondering how to capture the matched substring and use it in the accumulating expression, something like
("" | it + e | str e ... /\w+/ := S)

so that the result would be the concatenation of all matched substrings.
Any idea?
Answer: Yes, the capture syntax is with the <name:regex> notation:
("" | it + e | /<e:\w+>/ := S)
rascal>S  ="Jabberwocky by Lewis Carroll";
str: "Jabberwocky by Lewis Carroll"
rascal>("" | "<it>,<e>" | /<e:\w+>/ := S)[1..]
str: "Jabberwocky,by,Lewis,Carroll"

or use the for-template syntax instead of a reducer expression:
rascal>x = "<for (/<e:\w+>/ := S) {><e>;
>>>>>>>    '<}>";
str: "Jabberwocky;\nby;\nLewis;\nCarroll;\n"
rascal>import IO;
ok
rascal>println(x)
Jabberwocky;
by;
Lewis;
Carroll;

ok
rascal>

Comment: Just like that. The syntax is "pattern <- generator" so you could have`/regex/ <- myList` and the regex would be tested against every element in order, and every match in every string would trigger a single loop iteration.
Comment: Great. Just a tiny extension: There is this idiom to loop over a list with `<-`. How would I extend the reducer to match all strings from a list, e.g. `("" | it + e |  ... <- L)` where `L` would be a list of strings?

Regexp Matching in Reducer


Suppose that $x_n \to x$ in norm as $n \to \infty$. Does it follow that $\|x_n\| \to \|x\|$ as $n \to \infty$?

Question: H is an infinite dimensional Hilbert space with associated norm $\|\cdot\|$, and $(x_n)_{n\geq 1}$ is a sequence in $H$. $x\in H$.
Comment: Also, please use MathJax. You can start to familiarize yourself with the tool by taking a look at my edit of your post. Then there is a tutorial somewhere here in MathStackExchange
Comment: HINT: Use [Reverse triangle inequality](https://en.wikipedia.org/wiki/Triangle_inequality#Reverse_triangle_inequality).
Answer: The proposed claim is true. Indeed, one has
\begin{align*}
\|x\| = \|x - x_{n} + x_{n}\| \leq \|x - x_{n}\| + \|x_{n}\|
\end{align*}
Similarly, the following relation holds
\begin{align*}
\|x_{n}\| = \|x - x_{n} + x\| \leq \|x - x_{n}\| + \|x\|
\end{align*}
Gathering both results, one has that
\begin{align*}
|\|x\| - \|x_{n}\|| \leq \|x - x_{n}\|
\end{align*}
Since we know that $x_{n}\to x$, let $\varepsilon > 0$. Then there exists $n_{\varepsilon} \in \mathbb{N}$ such that
\begin{align*}
n\geq n_{\varepsilon}\Rightarrow |\|x\| - \|x_{n}\|| \leq \|x - x_{n}\| \leq \varepsilon
\end{align*}
whence we conclude that $\|x_{n}\|$ converges to $\|x\|$.
Hopefully this helps!
Comment: Do you mean <\epsilon??
Comment: It is usual to make use of $\epsilon$, but I prefer $\varepsilon$.
Comment: I didn't refer to the epsilon, but the equality. You wrote smaller or equal to, but isn't it just smaller than?
Comment: Both ways are correct.


How to separate a column in R with unequal character lengths and without separators

Question: I want to separate a column which contains dates and items into two columns.
V1
23/2/2000shampoo
24/2/2000flour
21/10/2000poultry
17/4/2001laundry detergent

To this
V1           V2
23/2/2000    shampoo
24/2/2000    flour
21/10/2000   poultry
17/4/2001    laundry detergent

My problem is that there's no separation between the two. The date length isn't uniform (it's in the format of 1/1/2000 instead of 01/01/2000) so I can't separate by character length. The dataset also covers multiple years.
Answer: One option would be separate from tidyr.  We specify the sep with a regex lookaround to split between digit and a lower case letter
library(dplyr)
library(tidyr)
df1 %>%
   separate(V1, into = c("V1", "V2"), sep="(?<=[0-9])(?=[a-z])")
#        V1                V2
#1  23/2/2000           shampoo
#2  24/2/2000             flour
#3 21/10/2000           poultry
#4  17/4/2001 laundry detergent

Or with read.csv after creating a delimiter with sub
read.csv(text = sub("(\\d)([a-z])", "\\1,\\2", df1$V1),
         header = FALSE, stringsAsFactors = FALSE)

data
df1 <- structure(list(V1 = c("23/2/2000shampoo", "24/2/2000flour",
      "21/10/2000poultry",
"17/4/2001laundry detergent")), class = "data.frame", row.names = c(NA,
-4L))

Comment: Thank you, this is exactly what I was looking for.
Answer: You could also use capture groups with tidyr::extract(). The first group \\d{1,2}/\\d{1,2}/\\d{4} get the date in the format you posted, and the second group [[:print:]]+ grabs at least one printable character.
library(tidyverse)

df1 %>%
  extract(V1, c("V1", "V2"), "(\\d{1,2}/\\d{1,2}/\\d{4})([[:print:]]+)")
          V1                V2
1  23/2/2000           shampoo
2  24/2/2000             flour
3 21/10/2000           poultry
4  17/4/2001 laundry detergent

Data:
df1 <- readr::read_csv("V1
23/2/2000shampoo
24/2/2000flour
21/10/2000poultry
17/4/2001laundry detergent")

Answer: You can also use :
data <- data.frame(V1 = c("23-02-2000shampoo", "24-02-2001flour"))

library(stringr)
str_split_fixed(data$V1, "(?<=[0-9])(?=[a-z])", 2)

     [,1]         [,2]
[1,] "23-02-2000" "shampoo"
[2,] "24-02-2001" "flour"

Comment: Typo: you created the data frame with `v1`, but split it with `V1`
Comment: @Gainz the same code could be used in `base R`. with `strsplit` `do.call(rbind, strsplit(as.character(data$V1), "(?<=[0-9])(?=[a-z])", perl = TRUE))`
Comment: @akrun Yes it is definitively an amazing package!
Comment: @akrun Yes! I didn't think of it you are right. I'm just used to the ``stringr`` package since it's a lot faster on the data I work with (500+ millions of rows) than base R. Thanks a lot!
Comment: @Gainz stringr wraps around `stringi` and stringi is very fast :=)


SQL: how to get only first users actions per user

Question: I have a table
actions
-------
user_id
action
date

How to select only first actions of each user?
Example data (action doesn't matter, let it be = 0):

1 0 2014-05-01
1 0 2014-05-02
1 0 2014-05-03
2 0 2014-05-01
2 0 2014-05-02
3 0 2014-05-08

Expected result:

1 0 2014-05-01
2 0 2014-05-01
3 0 2014-05-08
Comment: Not sure your allowed to name the field `date` without quotes. Edit: even if you can, not sure you should
Comment: What concrete database? Different databases handling thing a bit differently - even if they all use SQL as their query language... please update your tags with `oracle`, `mysql`, `postgresql`, `sql-server`, `db2` or whatever else you might be using
Comment: postgresql for example
Comment: I agree with vol7ron: `date` is a horrible name for a column. Not only because it's a reserved word, but mainly because it doesn't document the use of the column. Is that a "due date", a "done date", a "valid until date", ...?
Comment: it works without quotes
Answer: This can easily be solved using a window function (standard SQL)
select user_id,
       action,
       date
from (
   select user_id,
          action,
          date,
          min(date) over (partition by user_id) as min_date
   from actions
) t
where date = min_date
order by user_id;

Using window functions is most probably faster than a self join on the table.
Using Postgres' distinct on operator is most probably faster than the solution using a window function (but that is not portable a other DBMS).
select distinct on (user_id) user_id, action, date
from actions
order by user_id, date

SQLFiddle: http://sqlfiddle.com/#!15/ae67f/6
Answer: select a1.*
from actions a1
join
(
  select user_id, min(date) as mindate
  from actions
  group by user_id
) a2 on a1.user_id = a2.user_id and a1.date = a2.mindate

Comment: this query shows all actions by all users (I have added date to GROUP BY). Without it it shows error:ERROR:  column "actions.date" must appear in the GROUP BY clause or be used in an aggregate function
Comment: Please add example data and expected output to your question.
Comment: My query should return for every user a single record from the smallest date for each user. Does it not?
Comment: Your query shows error:ERROR: column "actions.date" must appear in the GROUP BY clause or be used in an aggregate function –
Comment: Please show your current query. I think you did not apply it correctly. Especially this part `min(date) as mindate`
Comment: yes, I've changed min to 'least', that's why it didn't work. Then I changed back to min. And it showed no error, but listed all actions of all users.
Comment: It works for me: http://sqlfiddle.com/#!15/ae67f/5 But you have a working solution anyway.


Constructing sigma algebras in countably many steps

Question: I'm learning about $\sigma$-algebras and was interested when my textbook briefly mentioned the impossibility of constructing the Borel $\sigma$-algebra of $\mathbb{R}$, $\mathcal{B}(\mathbb{R})$, from the open intervals in countably many steps. More precisely, let $\mathcal{L}_0$ be the collection of all open intervals $(a,b)\subseteq\mathbb{R}$. Given $\mathcal{L}_i$, we define $$\mathcal{L}_{i+1}=\bigg\{\bigcup_{k\in\mathbb{N}}A_k, \Big(\bigcup_{k\in\mathbb{N}}A_k\Big)^{c}\ :\ A_k\in \mathcal{L}_{i} \bigg\}\ \ \ \text{ and } \ \ \ \hat{\mathcal{L}}=\bigcup_{i\in\mathbb{N}}\mathcal{L}_i$$
Then my textbook says that $\hat{\mathcal{L}}\subsetneqq\mathcal{B}(\mathbb{R})$.
My question is this: can one (easily) exhibit a Borel set not in $\hat{\mathcal{L}}$? Is it necessary to use heavy machinery like AC or CH in order to construct such a set? I'm quite stuck.
Many thanks!
Comment: "Easily"? I doubt it; seems llke whatever $E$ is, showing that $E$ has not appeared at some finite stage is not going to be "easy". You might find a proof that such an example exists by looking for information on "descriptive set theory" or more specifically "Baire classes". For example the external references at https://en.wikipedia.org/wiki/Baire_function
Comment: CH is not involved in this, nor in the higher countable levels of the Borel hierarchy.
Comment: For reference: I think the textbook that contains this statement is "Measures, Integrals and Martingales" by René Schilling, chapter 3.
Answer: One can find proofs in many set theory texts for the stronger result that, for each countable ordinal level of the Borel hierarchy, there exist Borel sets not belonging to that level. Look in book indexes for "universal set". You can also google Borel + "universal set".
However, I've found very few published proofs that limit themselves to the finite levels situation that most measure theory texts state and which you have stated in your question. For this reason I've made note of such proofs when I've encountered them, and in case it could be of use to you or others, below are the only three such references that I currently know about.
[1] Patrick Paul Billingsley, Probability and Measure, 3rd edition, Wiley Series in Probability and Mathematical Statistics, John Wiley and Sons, 1995 [reprinted as "Anniversary Edition" in 2012], xiv + 593 pages.

On pp. 30-32 there is a detailed construction of a Borel set that does not belong to any of the finite Borel classes.

[2] Mikls Laczkovich, Conjecture and Proof, Classroom Resource Materials, Mathematical Association of America, 2001, x + 118 pages.

See pp. 98-101 and p. 105 and Exercise 17.7 on p. 106.

[3] Eric M. Vestrup, The Theory of Measures and Integration, Wiley Series in Probability and Statistics, Wiley-Interscience, 2003, xviii + 594 pages.

See Section 1.7 (pp. 28-34). Vestrup's construction is an expanded version of the construction given in the 3rd edition of Billingsley's book [1]. For the stronger version involving transfinite Borel classes, see Exercise 2.23 on p. 36 (and Notes on the Problems for 2.23, on p. 555).
Comment: @DanielWainfleet: The result is due to Lebesgue, who proved this in a lengthy 1905 paper that is well known for having one of the most famous errors ever made in a mathematics paper. The error is famous not just because it was by someone like Lebesgue or the fact that it's rather elementary, but rather because it was probably the single most significant driving force behind the development of descriptive set theory in the 1920s and 1930s. Lebesgue's error is discussed in detail in [this 29 July 2006 sci.math post](http://mathforum.org/kb/message.jspa?messageID=4967733) archived at Math Forum.
Comment: Math Forum took down their archive of hundreds of thousands of math posts a year or two ago, so the 29 July 2006 sci.math post link in my earlier comment no longer works. The corresponding google sci.math posts are still available --- [biography of Suslin](https://groups.google.com/g/sci.math/c/QKs4ivT-KRw/m/ffWOYd5HnfsJ) and [details of Lebesgue's error](https://groups.google.com/g/sci.math/c/QKs4ivT-KRw/m/rsftoqRHT3EJ) (both posted 29 July 2006).
Comment: I believe that the stronger version, that no countable level of the Borel hierarchy is all the real Borel sets, is due to Lebesgue or to Borel.
Comment: Relevant to my previous comment is [Is the image of a $G_\delta$ set under a continuous mapping of $\mathbb R^n$ a Borel set](https://math.stackexchange.com/questions/2954391) *AND* [Continuous images of open sets are Borel](https://math.stackexchange.com/questions/159840). Also relevant is [Borel hierarchy doesn't "collapse" before $\omega_1$](https://math.stackexchange.com/questions/509326).
Comment: I have heard of Lebesgue's famous error  and that its detection led to the discovery of the class of projective sets, but I had not seen his "proof" before, nor its rebuttal.
Answer: I published the proof given in (Billingsley, Probability and Measure, 3rd edition, pages 30-32) and people sent me to this thread. I have questions to this proof. I do not understand it. Somebody, please help if still interested in the topic.
Problem from the book Probability and Measure (by Patrick Billingsley), on constructing σ-Fields.


Google App Engine Go - Reddit API returns error 429

Question: I am trying to create a Reddit API in Golang in Google App Engine. My code:
package RedditAPI

import(
    "appengine"
    "encoding/json"
    "io/ioutil"
    "net/http"
    "appengine/urlfetch"
    "time"
    "net/url"
)

func GetTopSubmissions(c appengine.Context){
    one, two:=Call(c, "http://www.reddit.com/r/Bitcoin/top.json", "POST", nil);
    c.Infof("%v, %v", one, two);
}

func Call(c appengine.Context, address string, requestType string, values url.Values)(map[string]interface{}, error){
    req, err:=http.NewRequest("GET", address, nil)
    if err!=nil{
        c.Infof("Request: %v", err)
        return nil, err
    }

    req.Header.Add("User-Agent", "This is a very creative name for a Reddit bot v1.0 by /u/username")
    c.Infof("%v", req.Header.Get("User-Agent"))
    c.Infof("%v", req)
    c.Infof("%v", req.UserAgent())

    duration, err:= time.ParseDuration("60s")
    tr := &urlfetch.Transport{Context: c, Deadline: duration}

    resp, err:=tr.RoundTrip(req)
    if err != nil {
        c.Infof("Post: %v", err)
        return nil, err
    }
    defer resp.Body.Close()
    body, err := ioutil.ReadAll(resp.Body)
    if err != nil {
        c.Infof("ReadAll: %v", err)
        return nil, err
    }
    result := make(map[string]interface{})
    err = json.Unmarshal(body, &result)
    if err != nil {
        c.Infof("Unmarshal: %v", err)
        c.Infof("%s", body)
        return nil, err
    }
    return result, nil
}

Returns
2013/05/23 03:00:34 Unsolicited response received on idle HTTP channel starting with "H"; err=<nil>
2013/05/23 03:01:42 INFO: &{GET http://www.reddit.com/r/Bitcoin/top.json HTTP/1.1 1 1 map[User-Agent:[This is a very creative name for a Reddit bot v1.0 by /u/username]] <nil> 0 [] false www.reddit.com map[] <nil> map[]   <nil>}
2013/05/23 03:01:42 INFO: This is a very creative name for a Reddit bot v1.0 by /u/username
2013/05/23 03:01:42 INFO: map[error:429], <nil>
INFO     2013-05-23 03:01:42,720 server.py:584] default: "GET / HTTP/1.1" 200 81

What can be the cause of this error?
Comment: possible duplicate of [Error 429 when invoking Reddit api from Google App Engine](http://stackoverflow.com/questions/8963485/error-429-when-invoking-reddit-api-from-google-app-engine)
Comment: Are you aware of the jzelinskie's repo? https://github.com/jzelinskie/reddit
Answer: HTTP error 429 is 'too many requests': https://www.rfc-editor.org/rfc/rfc6585#section-4
At https://github.com/reddit/reddit/wiki/API, Reddit says "Make no more than thirty requests per minute. This allows some burstiness to your requests, but keep it sane. On average, we should see no more than one request every two seconds from you." They also say, "Don't hit the same page more than once per 30 seconds."
If you're requesting the same resource on every user hit to your app, you could use GAE's memcache support. If you're requesting a bunch of resources, the Reddit wiki page mentions "[r]equests for multiple resources at a time", so there may be some facility for batching requests (not sure, not versed in the API). If you're doing a cronjob, you could run it less frequently.
In any case, the remaining mystery is more of a Reddit API question than a Go question. The repo matthewbauer commented with (https://github.com/jzelinskie/reddit) or the Reddit API docs may have more.


Classes and vectors

Question: I have this classes below and I want to save a HomePC to a vector, what's the method that I can do that, and how can I print the first or the second element from the vector.

class PC
{
public:
    PC(string in_operatingSystem,int in_ramSlots,int in_pcieSlots,int in_totalRamSlots, int in_gbPerRam, int in_cpu, int in_ssd, int in_cost);

    virtual void Print() = 0;
    virtual void Upgrade() = 0;
protected:
    string operatingSystem;
    int ramSlots,pcieSlots,totalRamSlots,gbPerRam;
    int cpu,ssd;
    int cost;
};

class HomePC: public PC
{
public:
    HomePC(string in_operatingSystem,int in_ramSlots,int in_pcieSlots,int in_totalRamSlots, int in_gbPerRam, int in_cpu, int in_ssd, int in_cost, string in_model);

    void Print();
    void Upgrade();
private:
    string model;
};

Comment: Can you show your attempt to add an instance to a vector?
Answer: // create
std::vector<HomePC> homePcs;

// insert
homePcs.push_back(HomePC{...});
// or
homePcs.emplace_back(...);

// get and print
std::cout << homePcs[0] << " " << homePcs[1] << '\n';

I highly recommend learning how to use cppreference.com, as this site could have easily answered your question.
Comment: What's the format of the vector after that? for example if I push_back ("MacOS",2,3,4,...) what's the first element of the vector?
Comment: The first element of the vector is the first element which you inserted, then comes the second one which you inserted etc. Note that your syntax for `push_back` is false. You can use `emplace_back` to directly forward the arguments like in your example or you can use `push_back({"MacOs", 2, 3, 4, ...})` to keep it simple.
Comment: Undefined symbol: vtable for HomePC, got this, any idea?
Comment: Did you define, not just declare `HomePC::Print()` and `HomePC::Upgrade()` somewhere?
Answer: You can write something like this:
vector<PC*> myPCs;
myPCs.push_pack(new HomePC(...)); to create your vector and add HomePC object in this vector.
Also you need to include library for using vector: #include <vector> and write using namespace std; below including line.
Comment: You would need a `vector`, not `vector` for that. Also using a `vector>` and inserting `make_unique` would be much safer.
Comment: Yes, you are absolutly correct, thanks. I've edited my answer
Comment: [Why is "using namespace std;" considered bad practice?](https://stackoverflow.com/q/1452721/5910058)
Answer: //First create the vector which will store the objects
std::vector<HomePC> homePcs;

// Create the object to push into the vector
HomePC temp;  //i named it temp as it will be used only to pass the object

//After inputing data in temp with accessors/mutators , just store it in the vector created

homePcs.push_back(temp);

You can print easily by using a for loop and the .size() methods in vector , to know how many times the loop should iterate.
for(int i=0;i<homePcs.size();i++)
{
    std::cout<<homePcs[i]<<std::endl;
}

Comment: You can loop through a vector in a much prettier way by using a range-based for: `for (const auto &pc : homePcs) {std::cout << pc << '\n';}` Also the use of `std::endl`is excessive here, see [C++: "std::endl" vs "\n"](https://stackoverflow.com/questions/213907/c-stdendl-vs-n).

Classes and vectors


How to properly install ratchet using composer on windows?

Question: I've been trying to sort this out for weeks and still couldn't get it right. I just get to know composer once I started to explore Ratchet, thus its confusing as to where should get it installed.
1) Where to install composer.phar file? Soe says to the root of my project. Some says to where the php installed in my machine.
I installed composer.phar by clicking on the Composer-Setup.exe here:
https://getcomposer.org/download/
And this gets it installed in C:\ProgramData\ComposerSetup\bin\composer.phar
Now my ratchet project is located here: C:\projects\rachet\index.php
Currently there's no other file other than index.php which is empty.
2) How to install ratchet now into this path?
   path = C:\projects\rachet\index.php
3) in which command prompt I should type to install ratchet or composer in windows? Currently there are two. one is php.exe command prompt and the other is opened by typing cmd.
Answer: For those whom still looking for an answer for the above question, do the following:

click to download composer.exe from official composer page, the link also provided by ratchet

upon installation, the composer.phat is installed in your computers /AppData/ComposerSetup

open cmd, type composer install -d <path to your project> to set your project folder as your current path

then type composer require cboden/ratchet and wait

you'll see vendor folder inside your project folder now, do not close the terminal (cmd)

If you didn't do the step in 2) you'll see vendor folder created inside path mentioned in 2)

next create chat.php and socket.php outside of vendor folder: refer here for the files' content: https://web.archive.org/web/20161122141317/http://blog.samuelattard.com/the-tutorial-for-php-websockets-that-i-wish-had-existed/

open cmd, type php <path to your project>/socket.php :namely php c:/...../socket.php
This is to get the server script running.

in the same folder create a php file with this content taken from Ratchet:

Open console tab and see new messages displayed here.
How to type the message, install simple WebSocket client extension in Chrome and Firefox to type the message


RMySQL installation generating error in linux

Question: I am trying to install RMySQL in Ubuntu through R studio, but I am running into this error below. Can someone help me resolve this please.
Installing package into '/R_latest/lib/R/library'
(as 'lib' is unspecified)
--2015-11-18 11:40:26--  https://cran.rstudio.com/src/contrib/RMySQL_0.10.7.tar.gz
Resolving cran.rstudio.com (cran.rstudio.com)... 126.96.36.199
Connecting to cran.rstudio.com (cran.rstudio.com)|18.104.22.168|:443... connected.
HTTP request sent, awaiting response... 200 OK
Length: 52422 (51K) [application/x-gzip]
Saving to: '/tmp/Rtmp52166B/downloaded_packages/RMySQL_0.10.7.tar.gz'

     0K .......... .......... .......... .......... .......... 97% 1.73M 0s
    50K .                                                     100% 2276G=0.03s

2015-11-18 11:40:26 (1.77 MB/s) - '/tmp/Rtmp52166B/downloaded_packages/RMySQL_0.10.7.tar.gz' saved [52422/52422]

* installing *source* package 'RMySQL' ...
** package 'RMySQL' successfully unpacked and MD5 sums checked
Using PKG_CFLAGS=
Using PKG_LIBS=-lmysqlclient -lz
------------------------- ANTICONF ERROR ---------------------------
Configuration failed because libmysqlclient was not found. Try installing:
 * deb: libmysqlclient-dev | libmariadb-client-lgpl-dev (Debian)
        libmysqlclient-dev | libmariadbclient-dev (Ubuntu)
 * rpm: mariadb-devel | mysql-devel (Fedora, CentOS, RHEL)
 * csw: mysql56_dev (Solaris)
 * brew: mysql-connector-c (OSX)
If libmysqlclient is already installed, check that 'pkg-config' is in your
PATH and PKG_CONFIG_PATH contains a libmysqlclient.pc file. If pkg-config
is unavailable you can set INCLUDE_DIR and LIB_DIR manually via:
R CMD INSTALL --configure-vars='INCLUDE_DIR=... LIB_DIR=...'
--------------------------------------------------------------------
    install.packages('RMySQL',type='source')
    ERROR: configuration failed for package 'RMySQL'
        * removing '/R_latest/lib/R/library/RMySQL'
        Warning in install.packages :
          installation of package 'RMySQL' had non-zero exit status

        The downloaded source packages are in
            '/tmp/Rtmp52166B/downloaded_packages'

Answer: Just do
 sudo apt-get install r-cran-rmysql

as we do have an Ubuntu package RMySQL (and yours truly is the maintainer for the underlying Debian package).
We maintain those as binaries for a reason: so that you don't kill yourself trying to figure out to do it by hand.
Comment: this also helped resolve: sudo apt-get install libmysqlclient-dev http://stats.stackexchange.com/questions/194515/r-package-rmysql-installation-returns-a-configuration-failed-error
Comment: In my case, I had already installed mysql in Ubuntu, so I only needed to do: sudo apt-get install libmysqlclient-dev
Comment: Thanks, this worked like charm for me. Nice for posting the solution.
Comment: I had the same problem. Tried to install from source but this is much better
Comment: The answer didn't worked for me. I ran these commands then the it worked: sudo apt-get install libmysqlclient-dev and sudo-apt-get install libmariadb-client-lgpl-dev
Comment: You do *not* need clients for both MySQL and MariaDB. The latter is preferred. And there still is a pre-built binary package too.


Finding k in this logarithmic model

Question:
Problem 6: The amount of a certain medicine in the bloodstream decays exponentially
  with a half-life of 5 hours. In order to keep a patient safe during a one-hour procedure,
  there needs to be at least 50 mg of medicine per kg of body weight. How much medicine
  should be administered to a 60kg patient at the start of the procedure?

(from MIT 18.03 OCW)
Let $x(t)$ be the amount of the medicine in mg present in the bloodstream at time
$t$ in hours.
Then we have the model: $x(t) = x_0e^{-kt}$
I wonder how in the solution they found $k = \frac{\ln2}{5}$.
How I tried: We know that after $t=5$ hours, the initial amount is halved, so $x(5) = (1/2)x_0$.
Then we use that information to solve for $k$:
$$
(1/2)x_0=x_0e^{-k(5)}
$$
And then:
$$
ln(1/2) = -5k
$$
Etc. so that $k=-\frac{\ln(1/2)}{5}$.
However in the given solution they leave out the minus sign when finding k (which I can understand) and more importantly, they find $k = \frac{\ln2}{5}$, where I have $\ln(1/2)$ in the numerator.
Comment: Note that $\ln a =-\ln a^{-1}$, so both answers are same.
Answer: $$ - \frac{\ln(1/2)}{5} = - \frac{\ln 2^{-1}}{5} = \frac{\ln (2^{-1})^{-1}}{5} = \frac{\ln 2}{5}. $$

Finding k in this logarithmic model


Limit of a series of $1$ and $-1.$

Question: If I know that $\lim_{n\to\infty}\sum_{i=1}^n y_i > 0$, where $y_i$ can take the value of $-1$ or $1$, can I assume that the series $\rightarrow \infty$? In other words, if I know the limit is positive, does this remove the possibility that the series contains infinitely many $1$'s and infinitely many $-1$s and hence oscillates?
Comment: some people say that diverging to infinity means the limit doesn't exist. That's fine, as long as you are consistent.
Comment: Well, if the limit exists, it goes to either $\pm\infty$, so yes.
Comment: I kind of agree with you.  If I see a phrase $\lim_{n\to  \infty}a_n >0$ I tend to think that means there is a positive real number so that $\lim_{n\to \infty}a_n = L$.  But on the other hand if I see $L < \infty$ I take it in the spirit and meaning that it was meant. In any event though if $y_i =\pi$ then it is not possible for $\lim \sum y_i=L$ for any real $L$ (JC Colette's answer). So either the series diverges to plus or minus infinity or.... well, I'm not sure oscillating is the right word but your point is taken.
Comment: If there are infinitely many $1$s and infinitely many $-1$s, it does not follow that the series oscillates. For example, you could have $10$ ones and then a minus one, then $100$ ones and then a minus one, then $1000$ ones and then a minus one, and so on. $\qquad$
Comment: Simpler example of non oscillation with infinitely many of both is simply two $1$s followed by one $-1$ repeated infinitely.  Also I'm not sure if you have a arbitrary number of terms but one never "overpowers" the other but there is no regularly occurring pattern that "oscillating" is the correct word (is it?)... But no matter.  There is no possible real limit. So either it diverges to $\pm$infinity or ... it doesn't but fails to converge.
Comment: I think my discomfort with this is a matter of vocabulary; I'm used to saying that if a limit goes to $\pm\infty$, then the limit does not exist. But I know that if the limit is unbounded, it's different than having no limit, i.e., oscillates between values.
Comment: @fleablood that makes sense to me. Then, can I say that if $\lim_{n\to\infty} \sum_{i=1}^{n} y_i > 0$, then either  $\sum_{i=1}^{n} y_i \rightarrow \infty$ as $n\rightarrow \infty$, or it doesn't and there is no convergence. Thus the only possible limit is $+\infty$?
Answer: If the limit is $\ell$ a real number, $\lim_{n\rightarrow +\infty} \sum_{i=1}^{n} y_i=\ell > 0$
then $\lim_{n\rightarrow +\infty} y_n=\lim_{n\rightarrow +\infty}\left(\sum_{i=1}^{n} y_i-\sum_{i=1}^{n-1} y_i\right)=\ell-\ell=0$
If $y_n$ can only take $-1$ or $1$ as value, it is impossible that $\lim_{n\rightarrow +\infty} y_n=0$. We can see that in the definition of the limit by taking $\varepsilon <\frac12$
Hence if the limit of $\left(\sum_{i=1}^n y_i\right)_n$ exists (in $\overline{\mathbb{R}}$), it can only be $+\infty$ (or $-\infty$).
Comment: Yes but the hypothesis is $\lim_{n\rightarrow +\infty} \sum_{i=1}^{n} y_i>0$, so it is supposed that the limit exists in $[-\infty,+\infty]$
Comment: ... if it exist. There's also the possibility that it does not exist.
Comment: I agree with the proof but not the conclusion. The limit is undefined but not necessarily $\pm \infty$. Take Grandi's series for example: $1-1+1-1+\ldots$. I wouldn't assign that series the value of $\pm\infty$.
Comment: That was basically my question. Under the assumption that the limit is positive, we know it is not an oscillating series that does not tend toward anything (any number, infinity, or otherwise)?

Limit of a series of $1$ and $-1.$


At a minimum what resources should someone check before posting here?

Question: I want to try out our idea for list-based questions.
So I figured I'd try it here in the Meta.
Please suggest either a single textbook, website, or resource that a user should check before posting here.
Answer: Wikipedia
This is the obvious one. Most good questions will not be easily answerable with a visit here. But many bad questions ("please explain this basic concept in an excruciating level of detail") could pretty much be answered by copying and pasting from that site.
Comment: Contrary to Statistics, Wikipedia on Economics is rather mediocre. I wouldn't advise it.
Comment: I wouldn't advise it for quality posts either. But many "Why do we need a central bank"-type questions would be answered there, so it works as a good first broad filter.
Comment: what about [Investopedia](http://www.investopedia.com) ?
Answer: https://economics.stackexchange.com/search
It's a tired cliche, but people should definitely search this site for similar questions before posting a new one.
Also, newcomers to Stack Exchange should check out our Welcome to Economics.SE! post.
Answer: Let's for once "appeal to authority".
MIT has the MIT OpenCoursWare website.
http://ocw.mit.edu/courses/economics/
Answer: For micro theory questions:
Mas-Colell, Whinston, and Green (1995): Microeconomic Theory, Oxford University Press, Oxford.
Not everybody should be checking this, of course, but  if you are a grad student+ then you should probably own this book. Moreover, since grad school is basically all about learning to figure things out for yourself you should probably at least look in MWG and try to understand what you find there.
That said, some of this material is tricky, so I am okay with questions liek "Eeek! I saw this in MWG and don't understand it."
Comment: Not an Answer: The question was about "minimum resources that someone should check". You're providing "Grad students should own this book".
Comment: @FooBar I am saying that people who ask the kinds of questions this book can answer should check it. How does that not answer the question?
Comment: I see, that was not clear. I thought the question was about one unique resource that everyone should check against.
Comment: @FooBar I see, my understanding was that each answer should contain one resource.
Comment: @FooBar, FWIW, that's what I meant by the question, each answer should be a resource, then we can take the top answers and add them somewhere to the documentation.
Comment: Right. But how do we understand each resource in the list? I understood that we generate a list of minimum requirements that *everyone* has to check against before asking *any* question. Clearly, with MWG, that doesn't make sense. I would prefer a list of very few items that are relevant for all posters over a longer list with specialized suggestions (Undergrads: Wikipedia, Krugman/Obstfeld, Grads: MWG).
Answer: The first page of google queries on the topic.
Comment: You should have used lmtgfy. :)
Comment: yeah ;) thought of it but then got "lazy" (way to save 10 seconds...).
Answer: Mankiw, N. (2012). Principles of Macroeconomics (6th ed.).
I like all three of the Mankiw texts I've read so far, but I thought this one provided a great foundation.
Comment: Extremely expensive. I won't expect people to go to the next scientific library to have a peak.
Comment: I got it for $5 used.


Is it valid to simulate a Poisson process with a sequence of Bernoulli trials?

Question: In order to better understand some statistical concepts I generally try to run simulations to get to those results and see how the results match the theory.
While reviewing the Poisson and the Exponential distributions I decided to simulate a Poisson process following my understanding of it. However I ended up using Bernoulli trials and I have doubts I might be missing something.
As far as I understood the idea behind this model is that we have some events occurring at an average constant rate, so that on any time slot $t$ (of fixed size $s$) we have on average $\lambda$ events ocurring.
To replicate this scenario I ended up using a sequence of Bernoulli trials $B_1, B_2,... B_n$ with probability $\lambda/s$. Then, for every timestamp $t_i$ if $B_{t_i}$ = 1 then the event takes place, otherwise that timestamp is spent waiting.
In this way I feel I ensure a constant rate and it also seems that the results I get are in line with the probability mass function of a random variable $\sim Poisson(\lambda)$, which is where I wanted to get. However, I cannot stop thinking that I am using Bernoulli trials and that maybe I am rather modelling a Bernoulli process, making a small conceptual mistake somewhere.
Can someone tell me if my implementation is wrong and where?
Answer: Your simulation looks like a good approximation of a Poisson process. Of course, it can only be an approximation since the Poisson process is a continuous process while your simulation is discrete.
A case in point is the event count random variable for any given interval, which, as you have mentioned, would have to be Poisson and thus give positive probabilities for arbitrarily large counts. Your simulation can only approximate this. But, of course, no simulation would be able to accurately produce this behavior.
Another possibility to simulate a Poisson process would be to use the fact that the length of the time interval between two consecutive events would be an exponential random variable. So you might sample from the exponential distribution and simulate the time of the $k$th event as the sum of your first $k$ samples from the exponential random variable.
Comment: Thanks! As for sampling from an exponential distribution, I was aware of it but it seemed cool and convenient to me that with the simulation I designed I could compute both number of events and time between the events and show how these two random variables follow the Poisson and the Exponential distributions, respectively!
Answer: You used the Poisson approximation of the Bernoulli distribution. For large values of $n$ probability close to zero, you get that the Bernoulli distribution is approximately equal to a Poisson distribution.
In the limit (infinitely many Bernoulli variables) you have the Poisson limit theorem.
$$\lim_{n \to \infty} {n\choose k} (\lambda/n)^k(1-\lambda/n)^{n-k} = e^{-\lambda k} \frac{\lambda^k}{k!}$$
It is valid to approximate a Poisson distribution with a binomial distribution (a sum of Bernoulli distributed variables) but the other way around is more common. The Poisson distribution is easier than the binomial distribution.


jQuery and colorbox "is not a function"

Question: This is strange. I have thouroghly searched for an answer, the funny thing is I have another page on this site that colorbox is working.
Relevant header code:

<link rel="stylesheet" href="colorbox/example5/colorbox.css" />

I am getting the error on the $(".lightbox").colorbox statement.
Comment: Example is at http://www.crossroadsoflearning.com/staging/overview.php
Comment: Working page is http://www.crossroadsoflearning.com/staging/catalog-lcw.php
Answer: You have jquery included twice on the page that fails.  Versions 1.10.2.min and 1.9.0.min.  1.10.2.min is the only one included on the page that works.  Multiple versions of jquery mess all sorts of stuff up.
This is the guy giving you trouble:

Answer: I'm getting the following error.
Uncaught TypeError: Object [object Object] has no method 'colorbox'

Did you include the colorbox library?

jQuery and colorbox “is not a function”


Administrator/Guest Account Status "Not Applicable"?

Question: I've never seen this before, and hope someone here can help explain this.
The following screenshots were taken on a computer that is not a member of any domain, and therefore not having any Group Policy imposed.  The logged in account at the time was the built-in Administrator.  The system is running Windows XP SP3.
From secpol.msc in Security Settings -> Local Policies -> Security Options:

Usually these settings are Enabled or Disabled.  I've seen some policies as "Not Defined" before, but that's usually when it is the default for that item.  For these, the defaults are Enabled for Administrator and Disabled for Guest.  I've never seen "Not Applicable" in a security policy setting, let alone would I expect to see it in one as basic as this.
What could have caused this, and how can I make the policy changeable again without having to re-build or restore from backup?
Answer: Interesting. I haven't seen this behavior before, either. I can only find a couple of references from Microsoft in documentation to such behavior (the Windows XP Professional with SP2 Security Configuration Guide and the Windows Server 2003 with SP2 Security Configuration Guide) and the documentation is unhelpful, stating "If this setting is shown as Not Applicable in the Local Security Policy, it may be necessary to right-click the Security Settings node and select Reload in order to refresh the policy settings."
Out of curiosity, what happens when you "Reload" per their instructions?
Comment: Went back to the system today, re-opened `secpol`, (same effect as "Reload" I presume) and found the policies were showing their appropriate settings already.  Thanks again.
Comment: Had the same problem on Windows 10.  Logging off, then back on to the machine resolved the problem.


Profiles-2--user-edit-page

Question: I made my custom user-profile-edit.tpl.php using
function mytheme_theme($existing, $type, $theme, $path)
{

$hooks['user_profile_form'] = array(
                                // Forms always take the form argument.
                                'arguments' => array('form' => NULL),
                                'render element' => 'form',
                                'template' => 'templates/user-profile-edit',
                                );
return $hooks;
}

Now I want in user-profile-edit.tpl.php to render the account form (default Drupal form for users) and my profiles2 forms, from the forms i created without click the upper links.
Does anyone know how I can achieve this?
Answer: After creation template you need only implements form_alter and set this custom theme for whole form - $form['#theme'] = 'user_profile_form' and then you will be able to build form structure inside your template.
You can check diff module ( 'diff_node_revisions' theme ) as an example.

Profiles-2--user-edit-page


Differential baseline bias vs Heterogenous treatment effect

Question: Where it says 'Differential baseline bias only', I see both a differential baseline bias and a differential treatment effect bias. From my understanding, to have no differential treatment effect bias, $y_i^{1}$ -  $y_i^{0}$ has to be the same for both the treatment group and the control group. However it is (20-10 = 10) and (20-0 = 20) in the first panel.
Also please refer to the comment on the first answer by Dimitry.

Stephen L. Morgan and Christopher Winship "Counterfactuals and Causal Inference. Methods and Principles for Social Research". Cambridge University Press.
Comment: Please edit your post to include the `self-study` tag: self-study questions are treated differently. See http://stats.stackexchange.com/tags/self-study/info
Answer: In case anyone is paying attention, or comes across this page, the resolution is simple:  it is a mistake!
As explained on the Errata page for the second edition here:
http://socweb.soc.jhu.edu/faculty/morgan/papers/Errata_2nd_Edition.pdf
the first cell of the second row should be 10.  The other cells then change in that panel in response to this change, which results in an example that actually follows what is claimed in the panel label:  an example where bias is restricted only to baseline bias.
Please do not hesitate to contact me directly if you find other things that appear to you to be mistakes.  You may be correct!  (In this case, thanks to Dave Harding and his students for noticing this one.)
Comment: Welcome to the site! And thanks for clearing this up. While you're here, why not take our [tour] to learn more about CV. And perhaps share some of your wisdom on other questions.
Comment: Excellent textbook and thanks for the clarification, Ive accepted your answer
Answer: I also found this baseline vs. differential treatments effect distinction confusing.
The $v$s are the potential outcomes centered around their population-level expectations. We are worried about a relationship between $d$ (being selected for treatment) and the $v$s since they are in the error term. When $v$s are large in absolute value, the individual is fairly different in terms of his potential outcome. When the $y$s are the same for both individuals, the $v$s for that state of the world will be zero.
The OLS regression error term is equal to $v^0$ for those in the control and $v^1$ for those in the treatment. In the first panel, there's no relationship between $d$ and $v^1$ and a positive relationship between $d$ and $v^0$, which is the baseline, no-treatment potential outcome. Hence this is called baseline bias. People who have a lower outcome in the no-treatment world are more likely to be in the control group.
In the second panel, you have a relationship between $d$ and $v^1$, which is the treated potential outcome. That is the differential treatment bias: people who really benefit from treatment are likely to receive it. In the third panel, you have both kinds of biases simultaneously.
These are different from heterogeneous treatment effects (people respond differently to the treatment), which you have in all 3 panels. Here are two examples that may make the distinction clearer.
Suppose you have a job training program for 2 bicycle messengers that was given on a first-come, first-served basis with limited availability: only one training slot was available. Once it is announced, the fast biker shows up first since he can pedal quickly (at 10 vs 0). But the program does not really help him more (relative to the slow biker): everyone treated cycles at 20.
Contrast that with a job training program for 2 math students (aka math camp). Only the student who enjoys math signs up because she is going to learn a lot. For her the program has a huge payoff in terms of getting better at taking derivatives. After the camp, she can differentiate at 20. The student who didn't sign up would spend the class time napping and he would not learn all that much (only up to 15). If the cost of the program was foregone income from a job selling hot dogs on the boardwalk, the student with the higher return would sing up, while the other may not. Without the program, everyone would have the same level of math skills (10), so the baseline is the same.
You can have selection into treatment based on two types of potential outcomes: the first is the untreated outcome, the second is the treated outcome. In either case, however, if you were to pluck a random biker or student from a population to train, you would get a pretty different effect from the naively estimated one.
Comment: Hey Dimitry, if you have access to the book, kindly refer to the end of page 47. Differential treatment effect bias is defined as the difference in the expected value of treatment between those in D=1 and D=0. This definitions seems conflicting with the the original table and your answer.
Comment: @garciaj I am not sure what the conflict is. Have you calculated $v^1$ and $v^0$ and looked at their relationship with $d$? If that does not resolve things, please clarify what the conflict is exactly.
Comment: My lecturer's given a different version of the definition, hence the confusion. In his version, he defines the DTEB as what you said to be the 'heterogenous treatment effect'. His version kind of makes sense to me, even though I know you're answer is in fact correct. Is there a way I can clearly show that his version goes wrong somewhere?
Comment: I don't know what your lecturer told you, so it is hard to answer. On its own, heterogeneous treatment effects are not a problem. They are only a problem if the heterogeneity is systematically and substantially related to the treatment assignment.


How do I get the account name from UserPrincipal?

Question: I am using Active Directory login in one of my Winforms applications. I get a UserPrincipal object but I'm not sure how to get the proper accountname from this object? I can see that there is a SamAccountName that is the same as my account name but it states that this is for old versions of Windows. So how do I get the proper account name no mather old or new Windows systems?
This is the code I use to get the object
if (ADUserName.Length > 0)
    context = new PrincipalContext(ContextType.Domain, ADServer, null,  ADUserName, ADUserPassword);
else
    context = new PrincipalContext(ContextType.Domain, ADServer);

UserPrincipal.FindByIdentity(context, account)

Answer: SamAccountName is the "account name" as it was used in Windows even before Active Directory was introduced.
It's "legacy" in that it has been supplemented by additional info - your "distinguished name" in the LDAP context etc. - but it is the Windows account name ("short name") - and it's still a mandatory field for any new user being created - just use it!
See User naming attributes for more details on which name is used for what in an AD context.


What is the name of this instrument?

Question: While watching this exceptional video, I noticed the instrument used to do the whistling at 0:33. It looks like a long ocarina, but I wonder what the exact name of this instrument is (I am also intrigued, although more trivially, by the "wind" machine at the beginning).
Comment: I'm voting to close this question as off-topic because identification questions are off topic.
Answer: Looks like an Alto Ocarina, very much like this one.

What is the name of this instrument?


Why does the graph of $x^3/x^3$ not have a horizontal asymptote?

Question: I am a graduate student studying math, and am actually teaching College Algebra right now. But every once in a while, I come upon something new in a subject that I have supposedly mastered.
Why does the graph of $$y=\frac{x^3}{x^3}$$ not have a horizontal asymptote at $y=1$? Or does it? What am I missing?
Comment: Possible typo? The function $y = y(x)$ is not defined for $x = 0$, and has value of $1$ everywhere else.
Comment: Ok. I guess I was missing the knowledge that a rational function can intersect its horizontal asymptote.
Comment: Apart from the removable singularity at $x=0$, $y=x^3/x^3$ _is_ that asymptote...
Comment: The graph is basically a horizontal asymptote at $y = 1$, apart from when $x = 0$
Comment: I feel as though this is quite a confusing question but I'd agree with the other replies. I'd also say that the graph doesn't approach $y=1$ asymptotically (but is already touching it) because $y$ identically $1$ for all nonzero $x$.
Answer: It depends on what your definition of a horizontal asymptote is.
The calculus book I've used says that the graph of $y = f(x)$ has a horizontal asymptote at $y = b$ iff $\displaystyle\lim_{x \to \infty}f(x) = b$ or $\displaystyle\lim_{x \to -\infty}f(x) = b$.
In this case, $\displaystyle\lim_{x \to \infty}\dfrac{x^3}{x^3} = \lim_{x \to \infty}1 = 1$, so $y = \dfrac{x^3}{x^3}$ has a horizontal asymptote at $y = 1$.
Wikipedia's article on Asymptote says that "an asymptote of a curve is a line such that the distance between the curve and the line approaches zero as they tend to infinity. Some sources include the requirement that the curve may not cross the line infinitely often, but this is unusual for modern authors." If you don't include that requirement, then $y = 1$ is a horizontal asymptote of $y = \dfrac{x^3}{x^3}$.
Comment: While I was intrigued to discover that old and "unusual" requirement, and even more intrigued that it is rooted in the original meaning of the word asymptote, nonetheless I think the Wikipedia page has erred in giving that old meaning such prominence. The word is now used just as you have written; that old prohibition is completely gone in modern usage.


Python scatter plot with numpy-masked arrays

Question: I'm stuck trying to mask data for a scatter plot.  All data seems to plot.
I'm using numpy arrays as shown in the snippet below.  I'm thinking that perhaps I cannot mask on the "c" array.  I can't seem to find any documentation for doing this.  I'll try with the "s" array.
Any help is greatly appreciated.

yy = NP.ma.array(yy)
xx = NP.ma.array(xx)
zz_masked = NP.ma.masked_where(zz <= 1.0e6 , zz)
scatter(xx,yy,s=15,c=zz_masked, edgecolors='none')
cbar = colorbar()
show()

Answer: Works for me.  Each call to scatter() gets its own colorbar since each scatter()'s colors are normalized to its own data.  Which version of matplotlib are you using?
import pylab as plt
import numpy as np

x = np.linspace(0, 1, 100)
y = x**2
z = y
z_masked = np.ma.masked_where(z > 0.5, z)

plt.scatter(x, y, c=z, s=15, edgecolors='none')
plt.colorbar()
plt.scatter(x+1, y, c=z_masked, s=15, edgecolors='none')
plt.colorbar()
plt.show()

Comment: I realized that I forgot to change the zz array to a numpy array.
zz = NP.ma.array(z)  When I make this change is works fine.  My mistake.  Thank you for your reply Matt.


How do I add static html files to my Aegir install

Question: I have Aegir install running on a rack space server. In addition to the Drupal sites I am running, I would also like to be able to create static websites and server them from the same server. What steps do I need to do to get this to work with Aegir.
I tried the following
1.create a new file within vhostd containing
<code><VirtualHost *:80>
DocumentRoot /var/www/vhosts/mysite
ServerName mysite.mydomain.com

# Other directives here

</VirtualHost>
</code>

add html file to var/www/vhosts/mysite
3 restart apache ? (actually i'm not sure how to do this form aegir)
Answer: Your static websites cannot be managed by Aegir, so you should setup them separately on your server.
If you really need to restart apache from Aegir interface, just run 'Verify' task for any of the websites installed (hostmaster will work too). On verify, Aegir runs 'apache2ctl graceful' which effectively restarts apache.


$Z=X+Y$ is Gaussian, $X$ & $Y$ are not, $X$ & $Y$ are independent. Example?

Question: Suppose $X$, $Y$ and $Z$ are random variables, with $Z=X+Y$.
Suppose further that $Z$ is Gaussian, $X$ and $Y$ are non-Gaussian, and that $X$ and $Y$ are independent.
What distribution could $X$ and $Y$ have? Any example would do!
Answer: No such $X$ and $Y$ exist.
A well-known characterization of the Gaussian distribution is given by Cramer's theorem:

Theorem. If the sum $X+Y$ of the random variables $X$ and $Y$ is normally distributed and these variables are independent, then each of $X$ and $Y$ are normally distributed.
Comment: I dimly remembered there being a result to do with this. I thought I must have imagined it though!