TDE vs Disk Encryption

Question: We are a small business that host applications and data for clients.
Some of our clients are requesting we protect their data with 'encryption at rest' - although it's never very clear if they know what this really means.
The data is currently on an Azure VM running SQL Server Standard.
One option is for us to use TDE but this is only available in SQL Enterprise and the extra licencing cost would be a considerable for us.
The other is to use Azure Disk Encryption on the existing SQL Standard VM for free.
Is there much practical difference in the outcome between using TDE and Disk Encryption when it comes to reassuring the client that their data is encrypted at rest.
What differences should I be considering?
Answer: The threat is that somebody can get access to and/or copy the files that make up a SQL database and load them in another  SQL server, by-passing all access controls normally imposed by both the front-end application and the SQL server itself.
Disk encryption protects against such access in cases such as stolen or incorrectly disposed/decommissioned hardware and in a cloud environment against others that can get unauthorized access to the complete virtual disk image.
Since disk encryption is transparent (invisible) to the processes and users on both physical and virtual running servers, it does not protect against (unauthorized) data access that is either allowed by or by-passes the normal access controls and file system permissions imposed by the running operating system.
That is where TDE and similar application level encryption adds extra security: even when you can get access to the files on the file-system, you still can't access the data therein without the application encryption/decryption keys.
If enabling TDE is cost prohibitive organisations typically make a risk assessment and document any existing and new measures to sufficiently safeguard the data, to mitigate the risk of data leaks and accept any remaining risks.
Answer: Transparent Data Encryption is what is actually known as encrypting data at rest.
TDE works by performing real-time I/O encryption and decryption of the data and log files (data "at rest"). The database encryption key (DEK) stored in the database boot record for availability during recovery. The DEK is a symmetric key secured by using a certificate stored in the master database of the server or an asymmetric key protected by an EKM module.
Full Disk Encryption is encrypting the whole disk of your VM. That means everything residing on the disk, not only the sql database.
So that's the difference: everything vs the DB only. Since the client asked for DB encryption, any of the 2 is valid and since you can use Azure Disk Encryption for free you could do that.
Answer: All Azure managed disks are encrypted by defaul via Server-side Encryption, which qualifies as basic "data encryption at rest".
If this is sufficient or not depends on the threat model and the relative risk assessment.

TDE vs Disk Encryption


Binomial coefficients algebra

Question: I am trying to prove
$$\binom{n+1}{k} = \binom{n+1}{k-1}\frac{n-k+2}{k}$$ by using the following four equations:
\begin{align*}
\binom{n + 1}{k} & = \binom{n}{k} + \binom{n}{k - 1}\\
\binom{n + 1}{k - 1} & = \binom{n}{k - 1} + \binom{n}{k - 2}\\
\binom{n}{k} & = \binom{n}{k - 1}\frac{n - k + 1}{k}\\
\binom{n}{k - 1} & = \binom{n}{k - 2}\frac{n - k + 2}{k - 1}
\end{align*}
Assume the above equations are true and valid to use.
Answer: If in your last relation
$$\binom{n}{k - 1} = \binom{n}{k - 2}\frac{n - k + 2}{k - 1}$$
you substitute $n$ with $n+1$ and $k$ with $k+1$, then you get the desired relation.
Answer: Use the third equation, replacing $n$ by $n+1$.
Answer: For beginners to these kinds of proofs, sometimes it is just easier renaming the variables. For example:
I am trying to prove
$$\binom{n+1}{k} = \binom{n+1}{k-1}\frac{n-k+2}{k}$$
Assuming that the following is true
$$\binom{r}{s}=\binom{r}{s-1}\frac{r-s+1}{s}$$
Notice that this is just your third identity, expressed in $r,s$ instead of $n,k$. Now it's just a simple matter of replacing $r$ with $n+1$ and $s$ with $k$.

Binomial coefficients algebra


For $\Bbb K^{n \times n}$ matrices $A$ and $B$, $\exists p[p(A)=B] \implies \exists p[p(B)=A]$?

Question: For $\Bbb K^{n \times n}$ matrices $A$ and $B$, is it true that if there exists a matrix polynomial $p$ such that $p(A)=B$, then there exists another matrix polynomial $p$ (not necessarily the same) such that $p(B) = A$?
My attempt
Let $B = \displaystyle \sum_{k=0}^{n-1} a_k A^k$, where $a_k \in \Bbb K$.
From the Cayley-Hamilton theorem, there exists a polynomial $p$ of degree $n$ such that $p(A) = O$, so $A^m$ where $m \ge n$ can be expressed as linear combination of $\left\{ A^k \ | \ 0 \le k < n\right\}$.
So, we can express $B^m = \displaystyle \sum_{k=0}^{n-1} a_{mk} A^k$, where $a_{mk} \in \Bbb K$.
If $\{I, A, A^2, \cdots, A^{n-1}\}$ form a basis, then we can express a polynomial in $B$, $\displaystyle \sum_{k=0}^{n-1} b_k B^k$, as:
$$\begin{pmatrix}
a_{00} & a_{10} & a_{20} & \cdots & a_{(n-1)0} \\
a_{01} & a_{11} & a_{21} & \cdots & a_{(n-1)1} \\
a_{02} & a_{12} & a_{22} & \cdots & a_{(n-1)2} \\
\vdots & \vdots & \vdots & \vdots & \vdots \\
a_{0(n-1)} & a_{1(n-1)} & a_{2(n-1)} & \cdots & a_{(n-1)(n-1)} \\
\end{pmatrix}
\begin{pmatrix}
b_0 \\ b_1 \\ b_2 \\ \vdots \\ b_{n-1}
\end{pmatrix}$$
Since we want the polynomial to equal $A$, we would need to solve:
$$\begin{pmatrix}
a_{00} & a_{10} & a_{20} & \cdots & a_{(n-1)0} \\
a_{01} & a_{11} & a_{21} & \cdots & a_{(n-1)1} \\
a_{02} & a_{12} & a_{22} & \cdots & a_{(n-1)2} \\
\vdots & \vdots & \vdots & \vdots & \vdots \\
a_{0(n-1)} & a_{1(n-1)} & a_{2(n-1)} & \cdots & a_{(n-1)(n-1)} \\
\end{pmatrix}
\begin{pmatrix}
b_0 \\ b_1 \\ b_2 \\ \vdots \\ b_{n-1}
\end{pmatrix}
=
\begin{pmatrix}
0 \\ 1 \\ 0 \\ \vdots \\ 0
\end{pmatrix}$$

Until now I have transformed the problem into a problem in linear algebra, but is utterly useless. Firstly, $\{A^k \ | \ 0 \le k < n\}$ may not even be linearly independent.
Comment: Another fun example to add to the mix: any nonzero nilpotent matrix $A$ satisfies $A^{n} = 0$ for some sufficiently large $n$. Then $p(X) = X^{n}$ has $p(A) = 0$, but for any polynomial $q$, $q(0) = c_{0}I_{n}$ where $c_{0}$ is the constant coefficient of $q$, and hence cannot be $A$.
Answer: Take $A=\begin{bmatrix} 1&0\\0&-1\end{bmatrix}$, and let $p(x)=x^2$. Then $p(A) = I$, but there's no polynomial $q$ with $q(I) = A$.
Answer: In a word, no. Let
$A=\pmatrix{1&0\\0&-1}$ and $p(X)=X^2$.
Then
$$B=p(A)=\pmatrix{1&0\\0&1}.$$
How can there be a polynomial with $q(B)=A$?


How to implement a Rules Action to loop through quantity of a products bought?

Question: With the Drupal Commerce module, I created a new product type I use for selling points to my customers. The product has a custom field named "points" (field type integer) where I specify the amount of point to sell.
On checkout I grant the points to the user with this rule, using the Rules module (thanks to Vic, see "How do I sell points using a new product type?):

Rule Event: on payment completed Action: loop through the order
  line-items. Each line-item has an action to call the next component
  with parameters of order and the line-item.
Component Parameters:
  order, line-item Condition: data comparison line-item:type is Product
  (to expose line-item:commerce-product) Action: call next component
  with parameters of order and line-item:commerce-product
Component
  Parameters: order, product Condition: data comparison product:type is
  Product (to expose the product:field-points-to-add) • Action: add
  userpoints, number to add being product:field-points-to-add

The problem comes when the quantity of the products sold is more than 1 because the action loops only through line-item and not through line-item:quantity.
Any suggestion for looping through line-item:quantity?
Comment: Possible workaround: disallow buying many of the same. Create products for "bundles" of 5, 10, 20, 50 points and so on, with slightly deceasing cost per point, and people will not even try to add more than one.
Comment: That's why it's only a comment, and not posted as an answer. I would like to see it solved too as it might have more uses. I just thought that this suggestion may help you to get things up and running before issue gets solved the "proper way".
Answer: Consider this Rules Component (in Rules export format, use the Rules UI to import it in your own site):
{ "rules_grant_user_points_multiple_times" : {
    "LABEL" : "Grant user points multiple times",
    "PLUGIN" : "rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules", "userpoints_rules" ],
    "USES VARIABLES" : {
      "points_to_grant" : { "label" : "Points to grant", "type" : "integer" },
      "quantity" : { "label" : "Quantity", "type" : "integer" }
    },
    "DO" : [
      { "data_calc" : {
          "USING" : {
            "input_1" : [ "points-to-grant" ],
            "op" : "*",
            "input_2" : [ "quantity" ]
          },
          "PROVIDE" : { "result" : { "calculated_points" : "Calculated points" } }
        }
      },
      { "userpoints_action_grant_points" : {
          "user" : [ "site:current-user" ],
          "points" : [ "calculated-points" ],
          "tid" : "0",
          "entity" : [ "site:current-user" ],
          "operation" : "Insert",
          "display" : "1",
          "moderate" : "default"
        }
      }
    ]
  }
}

Some more details about this Rules Component:

It uses 2 parameters (both "integer"), i.e.:

Points to grant, which is like your custom field named "points".
Quantity, which is like your quantity of the products sold.

Rules Actions:

Calculate a new variable (= calculated_points), which is simply a multiplication of the above 2 parameters.
Grant user points for an amount equal to ... euh ... indeed: calculated_points (adapt the details of the actual transaction to fit your needs).

These User Points will be granted to the "current user". Optionally you could just make that yet another parameter for the Rules Component also. I.e. if "current user" is not the customer who bought the quantity of products (which would allow one customer to buy such points for another user should you want to allow that, similar to a gift-card).
With that, all that's left is to finds the right spot in your existing Rules logic (related to checkout), to use the above Rules Component.
Easy, no?


Is there a way to use preg_match_all without declaring variable first?

Question: Is there some fancy syntax I can use within the preg_match_all function to establish the new $matches variable at that time, rather than doing so beforehand as I have done below?
<code> $matches = '';
 preg_match_all('/[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}/', file_get_contents($eFetchURL), $matches);
</code>
Thanks in advance for your help!
Comment: It's generally good practice to declare your variables before you use them (even in cases where it may not be necessary).
Comment: When initializing you should initialize it to `array()`, as it will become an array afterwards.
Answer: Yes, namely this:
<code>preg_match_all('/[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}/', file_get_contents($eFetchURL), $matches);
</code>
Taking the reference of a non-existent variable in PHP is not an error. Rather, PHP automatically declares the variable for you and defines it as NULL.
Comment: +1 Good answer. Just an added note: as @Juhana pointed out in another  comment, "...variables _passed as a reference_ do not throw a notice..."
Answer: Not declare variables throws an E_NOTICE. Depending on the php.ini or runtime configuration, using error_reporting function, exception may be omitted or not.
Good practice is to have E_STRICT mode enabled in development environment.
Note:

Enabling E_NOTICE during development has some benefits. For debugging purposes: NOTICE messages will warn you about possible bugs in your code. For example, use of unassigned values is warned. It is extremely useful to find typos and to save time for debugging. NOTICE messages will warn you about bad style. For example, $arr[item] is better to be written as $arr['item'] since PHP tries to treat "item" as constant. If it is not a constant, PHP assumes it is a string index for the array.

Note:

In PHP 5 a new error level E_STRICT is available. As E_STRICT is not included within E_ALL you have to explicitly enable this kind of error level. Enabling E_STRICT during development has some benefits. STRICT messages will help you to use the latest and greatest suggested method of coding, for example warn you about using deprecated functions.

You can find more information in
http://php.net/manual/en/errorfunc.configuration.php
Comment: Except that variables passed as a reference do not throw a notice under any error reporting level.


Twitter-bootstrap - How to distribute content using "span" within a well if the well is already in it's own span?

Question: I created a span on the right side of the page that contains a well. Within that well I'm trying to align many lines of images and text using multiple div class="span__" commands. Everything gets placed properly, however it's pushed outside of the well by the first  within the well.

Heading
supporting text

Button left

Button middle

Button right

Comment: I'm not sure I understand your problem and you seem to be missing some code, can you create a jsFiddle to demonstrate?
Answer: Not a great solution, but may work in some situations:
create a new well (e.g. ".well-new") in CSS (so it doesn't screw-up other uses of "well" throughout your site) and give it much larger bottom padding (padding: 19px 19px 180px 19px;) and a correspondingly large negative margin-bottom (I used -168px;) - the effect is the bottom of the well extends much lower, incorporating the content below to well, into it.
I'm not sure how this affects renderings on mobile devices.
Better answers welcome!


Simular click com jQuery depois que inserir link via jQuery

Question: Tenho que abrir uma outra aba com um link que é retornavel para do PHP para jQuery. Eu usei window.open mas ele pede para liberar o popup e o cliente não gosto nada disso. Então pensei em fazer, quando o jQuery receber o link, ele altera um  para  e executa uma função para simular um click para abrir em outra aba. O problema é que fiz o código abaixo e não está funcionando, pois ele não abre a página em outra aba, agora não sei se é porque o link foi adicionado depois em uma ação jQuery (DOM).
HTML + jQuery
<button class="button" type="button" id="teste">Click</button>

Comment: Como você tava usando com `window.open`? Aqui pra mim (no Chrome) seu código abriu normal em outra aba com `window.open` e `_blank`. Veja no [fiddle](http://jsfiddle.net/gustavox/om0js91z/).
Comment: Sim, no meu também funcionou. Mas no do cliente pediu pra permitir popup. Acho que o dele era Safari
Answer: Ao invés de utilizar a função $(seletor).trigger("click");
use $(seletor)[0].click();.
Bom, mas porque?
Segundo a resposta do @The Alpha nesta pergunta, o que acontece é que no caso da função trigger() a execução não irá disparar uma evento de click propriamente dito e sim executar um manipulador de evento, se declarado, como por exemplo:
$(selector).click(function() {
    // some code...
});

Tá, mas porque utilizar o [0] antes do .click(); ?
Se faz necessário o uso do 0 entre colchetes, por que a função click() é nativa do javascript, sendo assim não pertence a um objeto jQuery. Se não utilizar [0] para pegar somente o elemento HTML a função click() terá a mesma funcionalidade da trigger().
Dessa maneira seu código funcionará.
$(document).ready(function(){
    $("#teste").click(function(){
        $("a#linkredirect").prop('href', 'http://www.google.com.br');
        $("a#linkredirect")[0].click();
    });
});

Veja funcionando também no jsfiddle
Comment: @AlissonAcioli irei adicionar a resposta o porque disto.
Comment: Obrigado, funcionou aqui seu código!!
Comment: Tudo bem ;).. Muito obrigado mesmo!


Is the set of closed points of a $k$-scheme of finite type dense?

Question: Let $k$ be a field.
Let $X$ be a scheme of finite type over $k$.
We denote by $X_0$ the set of closed points of $X$.
Is $X_0$ dense in $X$?
Motivation
See my comment to Martin Brandenburg's answer to this question.
Answer: Yes, the subset $X_0\subset X$ of closed points is dense in $X$: this is even true if you only assume that $X$ is a $k$-scheme locally of finite type.
Technically the subset $X_0$ has the property of being very dense in $X$, which means that the map sending an open subset of $X$ to its trace on $X_0$ is a bijection between the open subsets of  $X$ and those in $X_0$ (provided with the induced topology) .
The proof is not very difficult and uses the characterization of a closed point $x$ as one which has finite dimensional residual field, namely $[\kappa(x):k]\lt \infty$.
A detailed proof can be found in Görtz-Wedhorn's book, Proposition 3.35.
Edit: warning !
Beginners (and I   obviously don't mean  Makoto here!) should be astonished to read that the circle $x^2+y^2+1=0$, seen as a subset of $\mathbb A^2_\mathbb R$, has a dense subset of real closed points!
The paradox is solved by realizing that a closed point of that circle is not an inexistent pair $(r_1,r_2)\in \mathbb R^2$  satisfying $r_1^2+r_2^2+1=0$,  but a maximal ideal in $\mathbb R[X,Y]$ containing $X^2+Y^2+1$, like for example the maximal ideal $(X-2,Y^2+5)\subset \mathbb R[X,Y]$.
Comment: Dear @Makoto, you can find the result also in EGA IV,Troisième partie, §10.4.7. By the way, when I googled "Görtz-Wedhorn" the first result that appeared was a link to a PDF of the whole book!
Comment: Dear Georges Elencwajg, unfortunately we cannot read Proposition 3.35 of the linked book.
Answer: Lemma 1
Let $k$ be a field.
Let $A$ be an integral domain which is a $k$-algebra of finite type.
Let $\bar k$ be an algebraic closure of $k$.
Then there exists $k$-algebra homomorphism $\psi\colon A \rightarrow \bar k$.
Proof:
This is a special case of this question(take $b = 1$).
Lemma 2(weak Nullstellensatz)
Let $k$ be a field.
Let $A$ be a $k$-algebra of finite type.
Let $\mathfrak{m}$ be a maximal ideal of $A$.
Then $A/m$ is finite over $k$.
Proof:
Let $\bar k$ be an algebraic closure of $k$.
By Lemma 1, there exists $k$-algebra homomorphism $\psi\colon A/\mathfrak{m} \rightarrow \bar k$.
Since $A/\mathfrak{m}$ is a field, $\psi$ is injective.
Hence $A/\mathfrak{m}$ is algebraic over $k$.
Since it is of finite type over $k$, it is finite over $k$.
QED
Lemma 3
Let $k$ be a field.
Let $X$ be an affine $k$-scheme of finite type.
Let $x \in X$.
Then $k(x)$ is algebraic over $k$ if and only if $x$ is a closed point of $X$.
Proof:
Suppose $X = Spec(A)$, where $A$ is a $k$-algebra of finite type.
Let $P$ be a prime ideal which corresponds to $x$.
We can identify $k(x)$ with the field of fractions of $A/P$.
Suppose $x$ is a closed point of $X$.
Then $P$ is a maximal ideal.
Hence $k(x) = A/P$ is algebraic over $k$ by Lemma 2.
Conversely suppose $k(x)$ is algebraic over $k$.
Then $A/P$ is a finite algebra over $k$.
Since $A/P$ is an integral domain, $A/P$ is a field.
Hence $P$ is a maximal ideal.
QED
Lemma 4
Let $k$ be a field.
Let $X$ be a $k$-scheme locally of finite type.
Let $U, V$ be affine open subsets of $X$ such that $U\cap V \ne \emptyset$.
Let $x \in U \cap V$.
Suppose $x$ is a closed point of $U$.
Then $x$ is also a closed point of $V$.
Proof:
This follows immediately from Lemma 3.
Lemma 5
Let $k$ be a field.
Let $X$ be a $k$-scheme locally of finite type.
Let $U$ be a non-empty affine open subset of $X$.
Then any closed point of $U$ is a closed point of $X$.
Proof:
Let $x$ be a closed point of $U$.
Let $Z$ be the closure of $\{x\}$ in $X$.
Let $\{U_i\}$ be an affine open cover of $X$.
Since $Z = Z \cap X = \bigcup_i Z \cap U_i$, it suffices to prove that $Z \cap U_i = \{x\}$ whenever$Z \cap U_i$ is non-empty.
Suppose $Z \cap U_i$ is non-empty.
Then $x \in U_i$.
By Lemma 4, $x$ is a closed point of $U_i$.
Hence $Z \cap U_i = \{x\}$
QED
Proposition
Let $k$ be a field.
Let $X$ be a $k$-scheme locally of finite type.
Let $X_0$ be the set of closed points of $X$.
Then $X_0$ is dense in $X$.
Proof:
This follows immediately from Lemma 5.
Answer: Yes, this follows from the fact that such a scheme is Jacobson, because a field is Jacobson, and a finite type algebra over a Jacobson ring is Jacobson. One of the characterizations of a Jacobson space is that every closed subset is the closure of its subset of closed points.
Comment: If $X$ is affine, it's easy to see that $X$ is Jacobson.


Sobre Trigger no postgres

Question: Bom galera, meu problema é o seguinte, eu quero fazer um particionamento de tabela no postgres pois uma tabela tem zilhões de registros e a buscar nela demora muito (essa tabela tende a crescer consideravelmente nos próximos meses) e uma solução que eu encontrei foi fazer o particionamento de tabelas (Se alguém tiver outra solução) usando trigger só que até ai tudo bem, mas na hora que eu eu insiro um dado na minha tabela ele chama o gatinho, consigo pegar essas informações só que todos os dados vem como inteiro. Uns campos eu conseguir converter para text, mas outros como a data ele não converte nem para data e nem para string, a pergunta é como faço para deixar ele com seus tipos de dados padrões? Se não tiver como faço para deixa esse campo data com o tipo de date.
Comment: Raramente o particionamento é a solução, está demorando tem alguma outra coisa errada. Os índices tornam o acesso quase igual independente do tamanho da tabela. Mesmo que insista nesse erro, *trigger* provavelmente o pior recurso para se fazer isto. O resto parece confuso demais, e provavelmente desnecessário. Veja: http://pt.stackoverflow.com/q/35088/101, http://pt.stackoverflow.com/q/101065/101, http://pt.stackoverflow.com/q/32052/101, http://pt.stackoverflow.com/q/23348/101, http://use-the-index-luke.com/
Comment: Eu acho que você está enganado. Minha experiência e das outras pessoas é outra. E os dados de como eles funcionam mostram isto. Quando a tabela dobra de tamanho (não importa o tamanho) quando se usa índice é como se adicionasse uma única linha nova para pesquisar o que deseja. è tão ínfimo que mal dá para medir. Se fizer o que está pretendendo tornará todas gravações mais caras, o que em grande volume pode ser trágico. Reafirmo que se está tendo problemas de performance com índice é porque está fazendo algo errado.
Comment: O banco já tem quase 1 Tera de dados, só essa tabela tá com 4 gigas e a tendência dela é dobra nós próximos meses. Os índices ajudam, mas com o tempo ela vai ficando mais lenta. Se caso tiver outra solução.
Comment: Não importa a quantidades de linhas que eu tenha em uma tabela, os índices sempre vão melhorar, pois essa tabela tem mais 500 milhões de registros. O que vc sugere para eu melhorar, essa tabela já tem indices que no começo foi bom, mais agora nao ta adiantando muito.
Comment: Seria bom por a estrutura das tabelas na pergunta. Grande chance de ser problema de modelagem. Quanto ao particionamento com trigger, acho mau uso dos dois recursos (do trigger, e do particionamento).
Comment: @JohnatanDantas, porque vc não cria um clone da mesma tabela( digo chamar o create table sem as constraints e indices ) e faz insert select só dos dados que vc quer ou varre uma certa quantidade de dados utilizando o limit?
Answer: Amigo, combinando o recurso de herança, trigger e check, vc consegue particionar a tabela criando automaticamente uma nova tabela sem necessidade de fazer manual. A tabela particionada tamvem tera indices e isto tambem ajudara no desempenho. O particionamento é indicado para tabelas que possuem grandes volumes carregados em poucas vezes. Se for os falar em linhas, seria umas 50 milhoes de linhas por tabela , no minimo.
A sua modelagem tamvem precisa ser revista e se estiver usando hibernate, tera dificuldadesno insert pois ele nao identificara o registro inserido.
Para particionar, primeiro identifique o melhor criterio (o ano, o id do cliente, etc). Depois crie um script para criar as tabelas com o comando inherits. Assim a tabela filha herdara todas as colunas da tabela pai e ainda as alteracoes posteriores que houver.
crie um check() na tabela filha indicando o criterio de insercao/particionamento (ex. Ano).
Todas as consultas sql tera de conter o campo chave checado(ano) , do contrario nao havera melhoria de performance.
Comment: eu fiz um script para criar o particionamento de tabelas usando herança, o particionamento ficou legal e criei check no id do cliente. Queria ver se da certo pois não queria mexer na aplicação, delegar essa responsabilidade para o banco. Eu utilizo hibernate, será que dará problemas como vc falou? Se caso não de para fazer vai ser o jeito delegar essa responsabilidade para o java.

Sobre Trigger no postgres


Ajax button strange behaviour when clicked twice

Question: I have a form where there is a dropdown with names, a button to add the names to a table and a table showing the list of names.
When clicking the button, an AJAX request is fired, the selection is added to a database table, the html table is reloaded and updated.
Everything works fine for the first click. The assigned ajax callback routine is called.
When I like to add the second name, the ajax callback is NOT called, but the standard submit function is called instead.
Here is some sample code - first the elements for the form:
$form['auctionpersons']['add_person'] = array(
  '#type' => 'select',
  '#title' => t('Select person to add'),
  '#options' => $aPersons,
);
$form['auctionpersons']['add_person_btn'] = array(
  '#type' => 'button',
  '#value' => 'Add person',
  '#description' => 'Click button to add person',
  '#ajax' => array(
      'callback' => 'add_auction_person_ajax_callback',
      'effect' => 'fade',
  ),
);
...
$form['auctionpersons']['ptable'] = array(
  '#theme' => 'table',
  '#header' => $pheader,
  '#rows' => isset($aPersonsTable)?$aPersonsTable:null,
  '#disabled' => TRUE,
  '#title' => 'Users currently assigned',
  '#empty' => t('No users assigned yet!'),
  '#prefix' => '
',
  '#suffix' => '
',
);

Now the function for the ajax callback:
function add_auction_person_ajax_callback($form, &$form_state) {
  dpm('172: add_auction_person_ajax_callback');
  dpm($form_state);
  add_person_to_table($form_state['values']['add_person']);
  $aPersonsTable=get_person_table_rows();
  $form['auctionpersons']['ptable']['#rows']=$aPersonsTable;
  $commands = array();
  $commands[] = ajax_command_html('#ptable_wrapper', render($form['auctionpersons']['ptable']));
  return array('#type' => 'ajax', '#commands' => $commands);
}

Can anyone see the problem?
Answer: Problem solved!
The button must be of type "submit" instead of "button"! So the correct code is:
$form['auctionpersons']['add_person_btn'] = array(
  '#type' => 'submit',
  '#value' => 'Add person',
  '#description' => 'Click button to add person',
  '#ajax' => array(
      'callback' => 'add_auction_person_ajax_callback',
      'effect' => 'fade',
  ),
);

Thx for viewing this question :-)


Divisibility Problem: How many switches remain in their initial position?

Question: I have been working on this problem:
There is a set of $1000$ switches, which are ordered in a row so that each switch is given a distinct rank from $1$ to $1000$. For example, the $i$-th switch refers to the switch given rank $i$. Each switch has four positions, called $A, B, C$, and $D$. When the position of any switch changes, it is only from $A$ to $B$, from $B$ to $C$, from $C$ to $D$, or from $D$ to $A$. Initially each switch is in position $A$. The switches are labeled arbitrarily with the $1000$ different integers $(2^x)(3^y)(5^z)$, where $x, y$, and $z$ take on the values $0, 1, \ldots, 9$. At step $i$ of a $1000$-step process, the $i$-th switch is advanced one step, and so are all the other switches whose labels divide the label on the $i$-th switch. After step $1000$ has been completed, how many switches will be in position $A$?
My work so far:

For a switch labelled $2^{x}3^{y}5^{z}$, that switch will get flipped $(x+1)(y+1)(z+1)$ times.
The switches remaining in position $A$ after step $1000$ are the switches that have been flipped $4k$ times, so we want $(x+1)(y+1)(z+1) = 4k$

I am not sure how to continue from this? Any hints/help on how to do so would be greatly appreciated!
Answer: If I am not mistaken here, we have label $2^x3^y5^z$ dividing the label $2^a3^b5^c$ if and only if
$$
(x,y,z)\leq(a,b,c)
$$
by coordinatwise comparison, that is $x\leq a,y\leq b,z\leq c$. Thus the switch labelled $2^x3^y5^z$ will get flipped whenever we get to label $2^a3^b5^c$ with
$$
(x,y,z)\leq(a,b,c)\leq(9,9,9)
$$
so exactly $(10-x)(10-y)(10-z)$ times. So your question becomes:

For how many values of $(x,y,z)$ is $(10-x)(10-y)(10-z)$ a multiple of $4$?

Those can be constructed by dividing into three cases:

$x,y,z$ are all even
exactly two of $x,y,z$ are even
exactly one of $x,y,z$ is even and that one has $10-t$ divisible by $4$

The first one gives you $5^3$ cases. The second gives you another $\binom{3}2\cdot 5^3$ cases. The last one gives you $\binom31\cdot 2\cdot 5^2$ cases. The total number of switches in position $A$ must therefore be
$$
5^3+\binom{3}2\cdot 5^3+\binom31\cdot 2\cdot 5^2=650
$$
Unless I have made an error.

Here is a little program written in Python confirming this. If you follow the link and click on the play button, the program prints $650$ as the number of switches in position $0$ corresponding to $A$.
Comment: @ar0bx: By considering the inequality above. For instance $x\leq a\leq 9$ gives us following values for $a$: $x,x+1,...,9$. Thus $a$ has $10-x$ values to chose from.
Comment: How did you get (10-x)(10-y)(10-z)?


Runtime exception when calling dll function with parameter in Inno Setup

Question: I am successfully calling a function in a DLL from Inno Setup,  however upon returning I get a Runtime Error...Exception: Access violation at address XXXXXXX. Write of address XXXXXX.
The function is declared as:
function CompleteInstall(szIntallPath: String) :  Integer;
external 'CompleteInstall@files:InstallHelper.dll stdcall setuponly';

And called:
procedure CurStepChanged(CurStep: TSetupStep);
begin
   if CurStep = ssPostInstall then begin
      CompleteInstall('Parm1'); // ExpandConstant('{app}')
   end;
end;

There is no problem if I change the function to not take a parameter. It still occurs if I change it to take a single integer parameter or declare it as a function and change the function to be a void function with an integer parameter.
The called function does nothing but return:
__declspec(dllexport) int CompleteInstall(char* szInstallPath)
{
    //AfxMessageBox ("Got here" /*szInstallPath*/, MB_OK);
    return 1;
}

Answer: You have a mismatch of the calling conventions. Either make the DLL function use stdcall as well:
__declspec(dllexport) __stdcall int CompleteInstall(char* szInstallPath)
{
    //AfxMessageBox ("Got here" /*szInstallPath*/, MB_OK);
    return 1;
}

or change the function declaration to use cdecl instead of stdcall:
function CompleteInstall(szIntallPath: String) : Integer;
    external 'CompleteInstall@files:InstallHelper.dll cdecl setuponly';

Comment: That is a good thought. My project settings in Visual Studio 2008 when set to _stdcall (C++...Advanced...Calling Convention to __stdcall /Gz) results in a Cannot Import Runtime error (with stdcall being used in the iss script).  I tried again and it seems using __cdecl in the .iss script and c++ code is the only thing that works.  Thanks for your help.
Comment: @AlanKley, you really shouldn't change the calling convention for *everything*, just this one function. That is what adding __stdcall to the function's declaration on the C side is doing. Regardless, the function's implementation and the caller's assumptions about calling convention *must* agree.
Answer: Although according to mghie (see comments) it shouldn't make a difference in this case, you might want to use PChar instead of String as that would be the more accurate equivalent of the C-declaration char*.
String is a Pascal-native type which is usually managed quite differently than a PChar (though apparently not so much in Inno's PascalScript).
Comment: After having a closer look at uPSRuntime.pas in RemObjects Pascal Script I have to agree with you, they are not completely equivalent. The CodeDll.iss example just uses them in a way that the difference doesn't matter (both are treated as a const pointer to the first character), and I never used them in any other way either. I think that the difference would only matter if allocation and re/deallocation of strings would happen in different modules. For variables that don't have their length changed in the DLL it doesn't matter. Have you used such DLL functions?
Comment: As long as the length of the string is not changed both String and PChar are treated as pointer to first character in a null-terminated string. As long as this is writeable memory the contents can be changed. Using String for a DLL parameter is a bad idea, as then both DLL and host app would need to use the same memory manager. If parameters are PChars it is possible to declare and read them as String. Writing to them (as String) would lead to crashes. Inside of PS one would probably always change the length, so they should indeed be String, not PChar. For details see source in uPSRuntime.pas.
Comment: -1, wrong answer in the context of Inno Setup. See the CodeDll.iss example, the declaration of the MessageBox() API function. In Inno Setup scripting DLL function declarations *do* use String instead of PChar.
Comment: Just because that example uses String instead of PChar doesn't necessarily render my statement wrong. I always use PChar in InnoSetup scripts when calling API functions that expect string parameters and never had any issues with that. I hadn't looked at the CodeDll.iss example though... strange... wouldn't have expected that to work... Have you actually tried changing "String" to "PChar"?
Comment: Sorry, maybe my comment wasn't clear enough. I expect that PChar works just as well as String, they should result in the same internal representation in the scripting engine. However, this answer is not helpful for the OP, as the problem he has would manifest in just the same way if he used PChar instead of String. In the context of Inno Setup scripting these *are* equivalent. It's a strange thing, but it's the way it is. OTOH, using the real String type for functions exported from a DLL would be a bad idea, anyway.
Comment: Hmm, do you have any reference on that? I've spent a full hour googling and search the IS list archive but couldn't find any mention that PChar and String are identical in InnoSetup script. Unfortunately I'm currently not at a computer where I could simply try this myself. I just vaguely remember that I explicitly changed some function signatures from String to PChar in the past because it wasn't it working otherwise.
Comment: I will revoke the downvote if you edit your post (otherwise the vote's too old to be changed), as the answer seems more correct than not. However I still think it isn't helpful with regards to the problem the OP has.
Comment: Done. Could you maybe elaborate a little more on the difference between String and PChar in PascalScript? And does this only apply to DLL-parameters or the types as used in PS in general?


Populate a dynamic select menu with records from database in rails

Question: Im trying to populate a select menu based on the user selection in a previous menu. I'm only using one model in which i store all the records that the user is filtering through. The problem that i have is to only get unique records and not all records based on the previous choice.
schools_controller
    class SchoolsController < ApplicationController
  def region
    @user = current_user
    @regions = School.select(:region).uniq.order(:region)
  end

  def municipalities
    @municipalities = School.where(:region => params[:region]).uniq

  end
end

Model
    # == Schema Information
#
# Table name: schools
#
#  id           :integer          not null, primary key
#  region       :string(255)
#  municipality :string(255)
#  school       :string(255)
#  created_at   :datetime         not null
#  updated_at   :datetime         not null
#

class School < ActiveRecord::Base
  attr_accessible :region, :municipality, :school
  has_many :users
end

regions.html.erb
 <%= form_tag 'municipalities' do %>

<%= select_tag(:region, options_from_collection_for_select(@regions, 'region', 'region')) %>

<%= submit_tag 'Nästa', :class=> 'btn btn-primary' %>

<% end %>

municipalities.html.erb
<%= form_tag 'schools' do %>

<%= select_tag(:municipalities, options_from_collection_for_select(@municipalities ,:municipality ,:municipality )) %>

<%= submit_tag 'Nästa', :class=> 'btn btn-primary' %>

<% end %>

Answer: Take a look at Ryan's railscast on dynamic select menus http://railscasts.com/episodes/88-dynamic-select-menus-revised. Or take a look at the dynamic_form gem.
Both do the trick, the dyanic_form gem takes a lot of the coding out of the way as you'd expect, and uses more coffescript rather than javascript


Why parameters are encoded when sent through HTTP request?

Question: I am curious to know the reasons why the HTTP request encodes(URLEncoded) all the parameters before sending it across the network in POST request.
Comment: Does it really? Wouldn't depend on how you specify the  tag's content?
Comment: Yes, check with the fiddler or HTTPFox. Enter some text in textbox and say submit to server with . When received on the server side they are automatically decoded again so when on server we read say Request.params['key'] decoded value is displayed.
Comment: Yes but have you set the content type? Default is "application/x-www-form-urlencoded" if not.
Comment: O so if we set it to something else do we have to explicitly handle decoding on the server end ?
Comment: IF not asp.net will handle it, yes.
Answer: So that they are convertible among different systems, eg. windows client talking to unix server...
Comment: Why vote down? If you don't encode them they might not be readable among systems that have different character encodings.
Comment: Thats what we have Content-Encoding for in HTTP. URIEncoding doesn't prevent encoding incompabilities.
Comment: But Content-Encodig is just for the content, and you may use Unicode in uris which should be correctly encoded, right?
Comment: The stream is the content. We are talking about postdata ie, content. Not the query.


Examples of not-full functors between two categories in both directions?

Question: A functor F:C→D from a category C to a category D is said to be full if, for each pair of objects, x,y ∈ C, the function,
F:C(x,y)→D(F(x),F(y))
between hom sets is surjective.
What I am unsure about is, for categories C and D, can you have a functor that is not full in both directions? That is, a category F:C→D and G:D→C, such that both F and G are not full.
In particular, are there any simple examples of this?
Comment: There are a gazillion examples of this. Given any categories $C$ and $D$ and an object $d$ of $D$, there is a functor $F : C \to D$ that maps every object of $C$ to $d$ and every morphism of $C$ to $\mathrm{id}_d$. This functor will only be full if $D$ if $d$ has no non-trivial endomorphisms.
Answer: Simplest example: Let $C = D$ be the category with one object $x$ and two arrows $\text{id}_x$ and $f$ such that $f\circ f=\text{id}_x$. (This is the cyclic group of order $2$ viewed as a category.) Let $F=G\colon C\to C$ be the functor sending $x$ to $x$ and both arrows to $\text{id}_x$.


Issue with basic Python loop

Question: Issue with basic Python Loop.
I am trying to extract stock tickers from a PDF ... the PDF reads fine and converts to a string. Then once the code hits the for loop, the program runs for 5+ minutes (PyCharms).
import PyPDF2

pdfFileObj = open('JULY1919.pdf', 'rb')
pdfReader = PyPDF2.PdfFileReader(pdfFileObj)

i = 0
x = ''
while i < pdfReader.numPages:
    pageObj = pdfReader.getPage(i)
    i += 1
    x += pageObj.extractText()

y = 0
tickers = ['']
while y < len(x):
    ticker = x[y:y + 1]
    if ticker.isupper():
        print(ticker)
        tickers[y] = ticker

print(tickers)

Any Suggestions?
Comment: If neither `x` nor `y` change inside the `while y < len(x):` loop, there's no reason to expect it to ever finish looping. If you want to iterate over each element of `x`, use `for`, not `while`.
Comment: Welcome to stack overflow! I see two issues with what you've posted: First, there's no `for` loop in your code. Second, in your second `while` loop, you never increment `y`, so it never terminates your loop
Comment: Can you tell which loop it is stuck in?
Answer: while y < len(x):
    ticker = x[y:y + 1]
    if ticker.isupper():
        print(ticker)
        tickers[y] = ticker

You never change the value of y in the loop.  How do you expect to exit the loop?  Did you miss a y += 1, perhaps?
Also, note that x[y:y + 1] is the same as simply x[y]; what did you intend here?  If you truly want only the single letter, this is much easier as
for y, ticker in enumerate(x):
    if ticker.isupper():
        print(ticker)
        tickers[y] = ticker

Answer: Your problem is in the second while loop you didn't change the value of y in it.
For easily handling this loop go for for loop.
for y, ticker in enumerate(x):
    if ticker.isupper():
        print(ticker)
        tickers[y] = ticker

Issue with basic Python loop


How to create an HTML code to place two boxes one above the other in Tibco Spotfire?

Question: I want to make a text box with this specific outlook:
Desired Outlook
But I can't find resources on how to do it. Is there any help? Also in how to make the text boxes like that, which are kind of squares with text within. Especially, I have problems with changing the sizes (height and width) of these boxes. Even if I specifically mention it, it won't change
On my own, I was only able to whip out some basic HTML:

    <title>My HTML Page</title>

Cluster

<SpotfireControl id="b4969e13ff1449ebb42b49e887569e91" />

Answer: In the below code, pay attention to use margin: auto. Also you can change height in obj1 and obj2. for example use some another units like rem, em, % and etc...

    <title>My HTML Page</title>

Amir

Amir

Amir

Study some artiles and documentions like this article if you want to know more about layouts.
Comment: Hey thanks a lot for the answer. This seems to work, I just want to ask if its possible to like switch the title on top of the items? As it is, I modified it now and it looks like this:

Tipo Elemento: OBJECT
Direzione: OBJECT.

I kinda wanted to have the title on top. Also, is there a way to change the height of the objects directly? This program doesn't allow me to directly, maybe through HTML there is a way
Comment: Html default is at the top of the box so i will edit my solution.


play piano accompaniment for a new song - music by ear

Question:
Possible Duplicate:
What do I need to know and how do I need to practice to start playing by ear/improvising?

I have learned the basics of piano. Basic includes reading notes, major and few of the minor scales and chords.
But I still find it difficult to play "music by ear". How do I improve that skill?  Does it require years of practice.
PS: "music by ear" meaning being able to play piano accompaniment for a new song after hearing it a couple of times.
Comment: Hi John, check out this question and it's answers. http://music.stackexchange.com/questions/4825/learning-guitar-by-hearing
It would be quite applicable to your situation, despite a different instrument. Be prepared for it to be very slow going. You'll need to start by just picking out individual notes by ear, and you'll need to be practicing pretty frequently, and getting to know your way around the keyboard very well, and quickly. If not, it's still possible, but it'll make learning to play by ear much more difficult.
Answer: As Josh says, Learning Guitar by hearing will  have some helpful advice for you.
To extend it to piano, I think there are two core skills to learn:
Fitting chords to melodies
You can practice this by just playing triads as you hum a tune, or play triads with your left hand while playing the tune with your right.
Many, many tunes - from classical standards to rock, pop etc. - fit the "three chord trick" of the tonic chord, the major 4th and the major 5th. Try to get these chord sequences by ear. You can cheat by looking at a chord sheet to see whether there are other chords in there, but having done that, don't look at the sheet. When you can do three-chord songs, move on to more complicated ones. You'll start to spot common transitions.
Practice in lots of keys too. Try it in each of the white-key-root major keys, at least.
Interesting rhythm patterns
Although it's a good basis, triads being plonked out on the downbeats aren't very musically pleasing. You need to play more interesting patterns.
A simple and classic example is to play up-and-down arpeggios.
Another example is to play a root-chord-fifth-chord oom-pah-oom-pah pattern.
... and many more; copy the ones you like. If boogie-woogie is your thing, there are many books on it.
Listen to music you like, and pay attention to what the backing is doing -- it doesn't matter whether it's piano music or not; think about how you could get a similar feel from a piano accompaniment.
When playing from a score, don't just blindly play the notes. Analyse how the notes on the page correspond to a chord progression, and how you could steal that pattern and apply it to another tune's chord progression.
Try playing "three blind mice" over the triplet-triads accompaniment of Moonlight Sonata!
Answer: Yes, playing music by ear requires practice, patience and experiments.  It's a very useful skill to have.  In fact, Suzuki method encourages learning music by ear.  Go check it out.  Hope this helps.  Good luck!


Null pointer error on my code Android

Question: I am having a null pointer error when I am running this android code.
here is my stack trace
02-06 23:11:57.999  26610-26610/? E/Zygote﹕ MountEmulatedStorage()
02-06 23:11:57.999  26610-26610/? E/Zygote﹕ v2
02-06 23:11:57.999  26610-26610/? I/libpersona﹕ KNOX_SDCARD checking this for 10266
02-06 23:11:57.999  26610-26610/? I/libpersona﹕ KNOX_SDCARD not a persona
02-06 23:11:58.009  26610-26610/? I/SELinux﹕ Function: selinux_compare_spd_ram, SPD-policy is existed. and_ver=SEPF_SM-N910W8_5.1.1 ver=38
02-06 23:11:58.009  26610-26610/? I/SELinux﹕ Function: selinux_compare_spd_ram , priority [1] , priority version is VE=SEPF_SM-N910W8_5.1.1_0038
02-06 23:11:58.009  26610-26610/? E/Zygote﹕ accessInfo : 0
02-06 23:11:58.009  26610-26610/? E/SELinux﹕ [DEBUG] get_category: variable seinfo: default sensitivity: NULL, cateogry: NULL
02-06 23:11:58.019  26610-26610/? I/art﹕ Late-enabling -Xcheck:jni
02-06 23:11:58.049  26610-26610/? D/TimaKeyStoreProvider﹕ TimaSignature is unavailable
02-06 23:11:58.049  26610-26610/? D/ActivityThread﹕ Added TimaKeyStore provider
02-06 23:11:58.129  26610-26610/com.mohitkishore.guidemydough D/SecWifiDisplayUtil﹕ Metadata value : none
02-06 23:11:58.159  26610-26610/com.mohitkishore.guidemydough D/PhoneWindow﹕ *FMB* installDecor mIsFloating : false
02-06 23:11:58.159  26610-26610/com.mohitkishore.guidemydough D/PhoneWindow﹕ *FMB* installDecor flags : -2139029248
02-06 23:11:58.359  26610-26673/com.mohitkishore.guidemydough D/OpenGLRenderer﹕ Use EGL_SWAP_BEHAVIOR_PRESERVED: true
02-06 23:11:58.369  26610-26610/com.mohitkishore.guidemydough D/PhoneWindow﹕ *FMB* isFloatingMenuEnabled mFloatingMenuBtn : null
02-06 23:11:58.369  26610-26610/com.mohitkishore.guidemydough D/PhoneWindow﹕ *FMB* isFloatingMenuEnabled return false
02-06 23:11:58.389  26610-26610/com.mohitkishore.guidemydough D/SRIB_DCS﹕ log_dcs ThreadedRenderer::initialize entered!
02-06 23:11:58.399  26610-26673/com.mohitkishore.guidemydough I/Adreno﹕ EGLInit: QTI Build: 07/18/15, 588fe7e, I15bf295f1a
02-06 23:11:58.409  26610-26673/com.mohitkishore.guidemydough I/OpenGLRenderer﹕ Initialized EGL, version 1.4
02-06 23:11:58.419  26610-26673/com.mohitkishore.guidemydough D/OpenGLRenderer﹕ Get maximum texture size. GL_MAX_TEXTURE_SIZE is 16384
02-06 23:11:58.419  26610-26673/com.mohitkishore.guidemydough D/OpenGLRenderer﹕ Enabling debug mode 0
02-06 23:11:58.589  26610-26610/com.mohitkishore.guidemydough I/Timeline﹕ Timeline: Activity_idle id: android.os.BinderProxy@2c1f0005 time:129876203
02-06 23:11:59.619  26610-26610/com.mohitkishore.guidemydough D/ViewRootImpl﹕ ViewPostImeInputStage ACTION_DOWN
02-06 23:12:02.079  26610-26610/com.mohitkishore.guidemydough D/ViewRootImpl﹕ ViewPostImeInputStage ACTION_DOWN
02-06 23:12:04.079  26610-26610/com.mohitkishore.guidemydough D/ViewRootImpl﹕ ViewPostImeInputStage ACTION_DOWN
02-06 23:12:04.129  26610-26610/com.mohitkishore.guidemydough I/Timeline﹕ Timeline: Activity_launch_request id:com.mohitkishore.guidemydough time:129881742
02-06 23:12:04.159  26610-26610/com.mohitkishore.guidemydough D/PhoneWindow﹕ *FMB* installDecor mIsFloating : false
02-06 23:12:04.159  26610-26610/com.mohitkishore.guidemydough D/PhoneWindow﹕ *FMB* installDecor flags : -2139029248
02-06 23:12:04.179  26610-26610/com.mohitkishore.guidemydough D/SecWifiDisplayUtil﹕ Metadata value : none
02-06 23:12:04.179  26610-26610/com.mohitkishore.guidemydough D/PhoneWindow﹕ *FMB* isFloatingMenuEnabled mFloatingMenuBtn : null
02-06 23:12:04.179  26610-26610/com.mohitkishore.guidemydough D/PhoneWindow﹕ *FMB* isFloatingMenuEnabled return false
02-06 23:12:04.209  26610-26610/com.mohitkishore.guidemydough D/SRIB_DCS﹕ log_dcs ThreadedRenderer::initialize entered!
02-06 23:12:04.299  26610-26610/com.mohitkishore.guidemydough I/Timeline﹕ Timeline: Activity_idle id: android.os.BinderProxy@3c179391 time:129881916
02-06 23:12:04.569  26610-26610/com.mohitkishore.guidemydough V/ActivityThread﹕ updateVisibility : ActivityRecord{382632f6 token=android.os.BinderProxy@2c1f0005 {com.mohitkishore.guidemydough/com.mohitkishore.guidemydough.UI.HomePage}} show : false
02-06 23:12:05.759  26610-26610/com.mohitkishore.guidemydough D/ViewRootImpl﹕ ViewPostImeInputStage ACTION_DOWN
02-06 23:12:05.819  26610-26610/com.mohitkishore.guidemydough I/Timeline﹕ Timeline: Activity_launch_request id:com.mohitkishore.guidemydough time:129883434
02-06 23:12:05.849  26610-26610/com.mohitkishore.guidemydough D/PhoneWindow﹕ *FMB* installDecor mIsFloating : false
02-06 23:12:05.849  26610-26610/com.mohitkishore.guidemydough D/PhoneWindow﹕ *FMB* installDecor flags : -2139029248
02-06 23:12:05.859  26610-26610/com.mohitkishore.guidemydough D/AbsListView﹕ Get MotionRecognitionManager
02-06 23:12:05.859  26610-26610/com.mohitkishore.guidemydough E/MotionRecognitionManager﹕ mSContextService = android.hardware.scontext.ISContextService$Stub$Proxy@298ca5da
02-06 23:12:05.859  26610-26610/com.mohitkishore.guidemydough E/MotionRecognitionManager﹕ motionService = com.samsung.android.motion.IMotionRecognitionService$Stub$Proxy@2c073a0b
02-06 23:12:05.859  26610-26610/com.mohitkishore.guidemydough E/MotionRecognitionManager﹕ motionService = com.samsung.android.motion.IMotionRecognitionService$Stub$Proxy@2c073a0b
02-06 23:12:05.879  26610-26610/com.mohitkishore.guidemydough D/SecWifiDisplayUtil﹕ Metadata value : none
02-06 23:12:05.879  26610-26610/com.mohitkishore.guidemydough D/PhoneWindow﹕ *FMB* isFloatingMenuEnabled mFloatingMenuBtn : null
02-06 23:12:05.879  26610-26610/com.mohitkishore.guidemydough D/PhoneWindow﹕ *FMB* isFloatingMenuEnabled return false
02-06 23:12:05.929  26610-26610/com.mohitkishore.guidemydough D/AbsListView﹕ try again to check child on obtainview
02-06 23:12:05.929  26610-26610/com.mohitkishore.guidemydough D/AbsListView﹕ child is null again
02-06 23:12:05.929  26610-26610/com.mohitkishore.guidemydough D/AbsListView﹕ position = 0
02-06 23:12:05.929  26610-26610/com.mohitkishore.guidemydough D/AbsListView﹕ mAdapter =Adaptors.ProgressAdaptor@1bb65b63
02-06 23:12:05.929  26610-26610/com.mohitkishore.guidemydough D/AbsListView﹕ getChildCount = 0
02-06 23:12:05.929  26610-26610/com.mohitkishore.guidemydough D/AbsListView﹕ mAdapter.getCount = 3
02-06 23:12:05.939  26610-26610/com.mohitkishore.guidemydough D/AndroidRuntime﹕ Shutting down VM
02-06 23:12:05.939  26610-26610/com.mohitkishore.guidemydough E/AndroidRuntime﹕ FATAL EXCEPTION: main
    Process: com.mohitkishore.guidemydough, PID: 26610
    java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.ViewGroup$LayoutParams android.view.View.getLayoutParams()' on a null object reference
            at android.widget.ListView.measureScrapChild(ListView.java:1210)
            at android.widget.ListView.measureHeightOfChildren(ListView.java:1292)
            at android.widget.ListView.onMeasure(ListView.java:1202)
            at android.view.View.measure(View.java:18855)
            at android.widget.RelativeLayout.measureChild(RelativeLayout.java:698)
            at android.widget.RelativeLayout.onMeasure(RelativeLayout.java:482)
            at android.view.View.measure(View.java:18855)
            at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5908)
            at android.widget.FrameLayout.onMeasure(FrameLayout.java:436)
            at android.view.View.measure(View.java:18855)
            at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5908)
            at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1435)
            at android.widget.LinearLayout.measureVertical(LinearLayout.java:721)
            at android.widget.LinearLayout.onMeasure(LinearLayout.java:612)
            at android.view.View.measure(View.java:18855)
            at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5908)
            at android.widget.FrameLayout.onMeasure(FrameLayout.java:436)
            at com.android.internal.policy.impl.PhoneWindow$DecorView.onMeasure(PhoneWindow.java:3072)
            at android.view.View.measure(View.java:18855)
            at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:2380)
            at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1412)
            at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1655)
            at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1297)
            at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:6981)
            at android.view.Choreographer$CallbackRecord.run(Choreographer.java:777)
            at android.view.Choreographer.doCallbacks(Choreographer.java:590)
            at android.view.Choreographer.doFrame(Choreographer.java:560)
            at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:763)
            at android.os.Handler.handleCallback(Handler.java:739)
            at android.os.Handler.dispatchMessage(Handler.java:95)
            at android.os.Looper.loop(Looper.java:145)
            at android.app.ActivityThread.main(ActivityThread.java:6872)
            at java.lang.reflect.Method.invoke(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:372)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1404)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1199)

Also here is my code  :
package com.mohitkishore.guidemydough.UI;

import android.app.ListActivity;
import android.os.Bundle;
import android.widget.ImageView;
import android.widget.TextView;

import com.mohitkishore.guidemydough.R;

import Adaptors.ProgressAdaptor;
import Model.Goals;

public class ProgressActivity extends ListActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_progress);

        TextView progressItemNameTextView1 = new TextView(ProgressActivity.this);
        TextView progressDescriptionTextView1 = new TextView(ProgressActivity.this);

        ImageView progressItemImageView1 = new ImageView(this);

        TextView progressItemNameTextView2 = new TextView(this);
        TextView progressDescriptionTextView2 = new TextView(this);
        ImageView progressItemImageView2 = new ImageView(this);

        TextView progressItemNameTextView3 = new TextView(this);
        TextView progressDescriptionTextView3 = new TextView(this);
        ImageView progressItemImageView3 = new ImageView(this);

        progressItemNameTextView1.setText("Vacation");
        progressDescriptionTextView1.setText("Test 1");

        progressItemNameTextView2.setText("Home loan");
        progressDescriptionTextView2.setText("Test 2");

        progressItemNameTextView3.setText("Car loan");
        progressDescriptionTextView3.setText("Test 3");

        progressItemImageView1.setImageResource(R.drawable.goal_car);

        progressItemImageView2.setImageResource(R.drawable.goal_home);

        progressItemImageView3.setImageResource(R.drawable.goal_vaccation);

        Goals goal1 = new Goals( progressItemImageView1, progressItemNameTextView1, progressDescriptionTextView1);
        Goals goal2 = new Goals( progressItemImageView2, progressItemNameTextView2, progressDescriptionTextView2);
        Goals goal3 = new Goals( progressItemImageView3, progressItemNameTextView3, progressDescriptionTextView3);
        Goals[] goals = {goal1, goal2, goal3};

        ProgressAdaptor adaptor = new ProgressAdaptor(this, goals);
        setListAdapter(adaptor);
    }
}

Here is my XML
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
                xmlns:tools="http://schemas.android.com/tools"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:paddingLeft="@dimen/activity_horizontal_margin"
                android:paddingRight="@dimen/activity_horizontal_margin"
                android:paddingTop="@dimen/activity_vertical_margin"
                android:paddingBottom="@dimen/activity_vertical_margin"
                android:background="@color/app_background_color"
                tools:context="com.mohitkishore.guidemydough.UI.ProgressActivity">

    <ListView
        android:id="@id/android:list"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />
</RelativeLayout>

Also sorry for a lot of wage code with no reasons here. I am in a hackathon and this is all I have
Comment: Use xml layouts to define views, then use findViewById to get them.
Comment: And post your `activity progress.xml`
Comment: define `ViewGroup.LayoutParams params = new ViewGroup.LayoutParams(width, height)` and set these parameters to all these `TextView`s and `ImageView`s you created..like `progressItemNameTextView1.setLayoutParams(params);`
Comment: @ELITE what would width and height be ?
Answer: You can get width and height from dimens.xml file
int width = (int) getResources().getDimension(R.dimen.width);
int height = (int) getResources().getDimension(R.dimen.height);
ViewGroup.LayoutParams params = new ViewGroup.LayoutParams(width, height);
progressItemNameTextView1.setLayoutParams(params);

and define width and height in dimens.xml file
<dimen name="width">50dp</dimen>
<dimen name="height">50dp</dimen>

hope it'll work.

Null pointer error on my code Android


Criar várias sessões podem afetar a performance do usuário?

Question: Meu site cria sessões com nome para cada página para serem usados em requisições e armazenam tokens únicos gerados a cada vez que a página é acessada e outros dados.
Exemplo:
<code>$_SESSION['RSD']['page_username_id'] = ...
</code>
Porém se caso o usuário, abra uma nova guia do navegador com esta mesma página, a sessão é recriada com novos dados, sendo assim não é mais possível realizar requisições na mesma página anterior que ainda está aberta, pois o token da página foi alterado, e não quero isto! Gostaria que o usuário fosse livre pra acessar a mesma página em várias abas se preferir!
Pensei em gerar um nome único pra cada sessão assim que a página é carregada, porém isto criaria muitas, e muitas sessões.
Então gostaria de saber se criar várias sessões pode realmente afetar a performance do usuário, ou se tem outra solução na qual possa ter o mesmo resultado de criar algo que forneça o token único a cada vez q a página seja carregada e não impeça o usuário de abrir outras abas da mesma página, assim permitindo fazer requisições.
Comment: Se coloque na posição do usuário e veja se isso é bom. Eu, particularmente, não gosto, pq tira a liberdade do usuário. A não ser que seja algo estrito, que ele não possa abrir outra aba.
Comment: @Dvdsamm perdão, acho que me expressei mal, está acontecendo isto, e é justamente isto que quero resolver, como na pergunta pensei em adicionar mais caracteres únicos no fim do nome da sessão, para isto não acontece, porém acumularia muitas e muitas sessões até o usuário fechar o navegador. Atualizei a pergunta para ver se da mais sentido
Answer: Quando você cria uma sessão no PHP, ele cria um cookie no navegador que é retornado para você em toda requisição. Esses dados de sessão não são enviados para o usuário, ele recebe um código e reencaminha para seu servidor em outras requisições.
Resumindo: Esses dados ficam em um arquivo físico no Servidor e não no browser do seu cliente.
Eu já trabalhei muito com sessão no php, porém tive problema quando atingia grandes números de usuários simultâneos. E quando fui ver, tinha que fazer balanceamento de carga. E nessa hora a sessão me atrapalhou bastante, então comecei a estudar sobre como controlar sessões e vi diversas maneira, e achei uma bem interessante e segura que uso atualmente, caso se interesse dê uma olhada no JWT.
Mas respondendo sua pergunta, pode impactar em um nível geral caso possua muitos acessos, e vai impactar a todos uma vez pois o gargalo fica no servidor. Com o JWT, você não teria esse tipo de problema.
Comment: Uma dúvida, é sobre aquela chave que é usada pra confirmar os dados do JWT, utilizar sempre apenas uma não é legal em questão de segurança, caso alguém descubra. Seria seguro eu criar uma senha a cada vez que o usuário fizer login e armazenar apenas no banco de dados?
Comment: @ViníciusLima o objetivo do JWT é ser um token que se auto gerencia, ou seja não seria legal consultar seu banco de dados a cada requisição só para ver se o token é válido (salvo casos onde é feito controle de sessão na aplicação). Você pode bolar um controle de como a chave funciona, exemplo. A cada uma hora você gera uma chave nova, e o intervalo do seu token é de 20 minutos. Então você poderia checar a chave atual, e caso o tempo do token não tenha expirado você faz a checagem utilizando a chave anterior. Assim você pode rotacionar a chave, e criar um algoritmo para que ela seja gerada.


Linking/Re-Indexing Arrays

Question: I have a Main Array which has multiple arrays inside. What I'm trying to achieve is to link/add/push them to their upper/main array
Array
(
    [dates] => Array
        (
            [0] => stdClass Object
                (
                    [date] => 2014-02-28
                )

            [1] => stdClass Object
                (
                    [date] => 2014-03-03
                )

        )

    [times] => Array
        (
            [0] => Array
                (
                    [0] => stdClass Object
                        (
                            [start_time] => 17:30
                            [end_time] => 19:30
                        )

                    [1] => stdClass Object
                        (
                            [start_time] => 19:30
                            [end_time] => 21:30
                        )

                    [2] => stdClass Object
                        (
                            [start_time] => 21:30
                            [end_time] => 23:30
                        )

                    [3] => stdClass Object
                        (
                            [start_time] => 23:30
                            [end_time] => 01:30
                        )

                )

            [1] => Array
                (
                    [0] => stdClass Object
                        (
                            [start_time] => 14:00
                            [end_time] => 14:30
                        )

                )

        )

    [streamers] => Array
        (
            [0] => Array
                (
                    [0] => stdClass Object
                        (
                            [username] => usernamehere
                            [name] => namehere
                        )

                    [1] => stdClass Object
                        (
                            [username] => usernamehere
                            [name] => namehere
                        )

                )

            [1] => Array
                (
                    [0] => stdClass Object
                        (
                            [username] => usernamehere
                            [name] => namehere
                        )

                )

            [2] => Array
                (
                    [0] => stdClass Object
                        (
                            [username] => usernamehere
                            [name] => namehere
                        )

                )

            [3] => Array
                (
                    [0] => stdClass Object
                        (
                            [username] => usernamehere
                            [name] => namehere
                        )

                )

            [4] => Array
                (
                    [0] => stdClass Object
                        (
                            [username] => usernamehere
                            [name] => namehere
                        )

                    [1] => stdClass Object
                        (
                            [username] => usernamehere
                            [name] => namehere
                        )
                )
        )
)

Arrays under times[0] have to be linked/added to dates[0] and users[0] haveto be linked/added to dates[0]
I tried array_merge and array_push but I've never worked with something like this before so any help will be great.
Thanks!
Answer: Can you print_r instead of var_dump please ? (easier to read) and how do you want it to merge ? Let's say I put times[0] into dates[0] : Is it by appending ? Or merging the objects ?
I will try this meanwhile (appending) :
foreach ($big_array as $key1 => $array) {
    if ($key1 == 'times') {
        //Insert times into dates
        foreach ($array as $key2 => $val) {
           array_push($big_array['dates'][$key2],$val);
        }
    } else if ($key1 == 'users') {
        //Insert users into dates
        foreach ($array as $key2 => $val) {
           array_push($big_array['dates'][$key2],$val);
        }
    }
}

NOTE : You don't need to do 2 if, only 1 is enough (this is only for readability)
Answer: With BabyAzerty's help I tried this :
            foreach ($streams as $key1 => $array) {

                if ($key1 == 'times') {
                    //Insert times into dates
                    foreach ($array as $key2 => $val) {
                    //array has objects so I had to add this line
                        $test[] = $streams['dates'][$key2];
                        array_push((array)$test, (array)$val);
                    }
                } else if ($key1 == 'streamers') {
                    //Insert users into dates
                    foreach ($array as $key2 => $val) {
                        //var_dump($streams['times']);
                        //array_push($test, $val);
                    }
                }
            }

The output without adding users is :
Array
(
    [0] => stdClass Object
        (
            [date] => 2014-02-28
        )

    [1] => Array
        (
            [0] => stdClass Object
                (
                    [start_time] => 17:30
                    [end_time] => 19:30
                )

            [1] => stdClass Object
                (
                    [start_time] => 19:30
                    [end_time] => 21:30
                )

            [2] => stdClass Object
                (
                    [start_time] => 21:30
                    [end_time] => 23:30
                )

            [3] => stdClass Object
                (
                    [start_time] => 23:30
                    [end_time] => 01:30
                )

        )

    [2] => stdClass Object
        (
            [date] => 2014-03-03
        )

    [3] => Array
        (
            [0] => stdClass Object
                (
                    [start_time] => 14:00
                    [end_time] => 14:30
                )

        )

)

What I'm trying to achieve is :
Array
(
 [0] => Array
  (
    [0] => stdClass Object
        (
            [date] => 2014-02-28
        )

    [1] => Array
        (
            [0] => stdClass Object
                (
                    [start_time] => 17:30
                    [end_time] => 19:30
                )

            [1] => stdClass Object
                (
                    [start_time] => 19:30
                    [end_time] => 21:30
                )

            [2] => stdClass Object
                (
                    [start_time] => 21:30
                    [end_time] => 23:30
                )

            [3] => stdClass Object
                (
                    [start_time] => 23:30
                    [end_time] => 01:30
                )

        )
  )

 [1] => Array
  (
    [0] => stdClass Object
        (
            [date] => 2014-03-03
        )

    [1] => Array
        (
            [0] => stdClass Object
                (
                    [start_time] => 14:00
                    [end_time] => 14:30
                )
        )
   )

)

Thanks!

Linking/Re-Indexing Arrays


How is a generator matrix built?

Question: If I'm given a set of codewords (i.e. the codewords are known) and I know that the code is linear, how can I find the matrix $G$ of that code?
I believe that $G$ is defined as $$G = \left[ P_{k\times (n-k)} \ I_{k\times k}\right]$$
where $I$ is the identity matrix. But I don't know what $P$ is. I don't know how te calculate it either. In this site I've read that $P$ is built as a column of all $1$s, but I don't understand why.
So that's the question: how can one find a generator matrix $G$ given the codewords?
Answer: $P_{k\times(n-k)}$ is the parity check matrix for the code.

In this site I've read that $P$ is built as a column of all $1$s, but I don't understand why.

It is not always a column of $1$'s, it just is for that particular code because the parity check matrix makes sure that the sum of all the digits in the codeword are $0$.
So, if you know your parity check matrix, this is an easy way to construct a generator matrix. (It should also be noted that this formula is written for codes for finite fields of characteristic $2$. You need a negative sign in front of $P$ to make it work for all finite fields.)

So that's the question: how can one find a generator matrix $G$ given the codewords?

If you have your codewords in hand, then there is no reason to go through the formula above. You can just search your codewords for a set of $k$ linearly independent codewords, where $k$ is the dimension of your code. You can use these as the rows (or columns, depending on your choice of representation) of a generator matrix.
Comment: And how could one calculate the parity check matrix then? The problem is that if the codebook is very long, then finding linearly independent codewords would take a while. I thought that maybe that formula would be  a faster approach to the problem.
Comment: @Tendero To find the parity check matrix, you'd be determining the dual code and then a basis for *that* code. Honestly it is very rare that you should be presented with a code purely as a list of codewords. Are you sure you're not given a generating subset, or some other closed form of the elements?
Comment: To check if they are linearly independent, can I do the same thing I would do with vectors in $\mathbb{R}^n$? This would be Gauss elimination
Comment: @Tendero yes, that's right.
Comment: @Tendero I was running into the same problem. Does that mean I just stack all the valid codeword as row of a matrix amd then do Gaussian elimination to obtain the generator matrix ?
Comment: @TuongNguyenMinh That would be one way to do it, albeit a computationally expensive one.  You sure you don't have other tools at hand?
Comment: @rschwieb actually my codebook only have 10 codeword (using rref on gf(2) show that it has rank 6) to check, do you have any program that could do this task ?
Comment: @TuongNguyenMinh that can't be a *complete* code book: it doesn't have a power of $2$ elements.  But anyhow, I imagine any CAS worth a nickel can put a matrix in echelon form.  Do you even need a program? With 10 words it would not be hard.

How is a generator matrix built?


Load single value from multiple value image field in View

Question: I am trying to load a single value from a multiple value image field in View.
I am adding the field with a restriction to print only a single file. I am also filtering by delta(=0). Check the settings in the attachment.
However the view is loading all images attached to the field. How can I load only the 1st one?
Comment: Try to delete the delta field. You only need the content field and the restriction on the display values (like you did on the screenshot)
Comment: so what is your question?
Comment: @robin that was my initial approach which did not work.
Comment: @Robin this solved it, please make it an answer so I can mark it.
Comment: Potney Switters, posted it as an asnwer ;)
Answer: Try to delete the delta field. You only need the content field and the restriction on the display values (like you did on the screenshot).
Answer: I think should be using agregation and unique option at query options inside advanced tab
Comment: Aggregation is used when you want to group multiple rows. This example is multiple values in one row


Repeated measure clinical trial Linear mixed model

Question: I am working on a clinical trial testing an innovative rehabilitation therapy on patients and I would like some suggestions on how to analyse the data.
The study design is:
2-groups: conventional (n=17) vs innovative (n=15) treatment;
4-time points (pre-therapy, T0; halfway through the therapy period, T1; end of therapy, T2; 2 months follow-up, T3).
As output, we record a continuous variable: time (in seconds) to walk from point A to point B. We record multiple values for each subject at each time point (T0,T1,T2,T3).
I have seen articles where the authors used ANOVA to evaluate the change in performance within each group. However, I would also like to evaluate the difference between groups, preferably at each time point as well. I have noticed other studies using Linear Mixed Models.
I thought of setting as Fixed effect: Group, Time-point; Random effect: intercept per subject,
Group per subject.
However, I am not an expert of this technique and I do not really know how to apply it, or how to write it in R/Statsmodels. Can you please help me understand how to set it up and how to write it on a coding platform?
Thanks a lot in advance!
Comment: How is this part described in the statistical methodology part in the trial protocol and/or the statistical analysis plan?
Comment: Hi Michael. It is a very good point. This study is carried by several institutes, and the one where I work is not in charge of the statistical analysis. Unfortunately, I have no access to the info you asked. However, I want to learn how to do this analysis.
Comment: *"I thought of setting as Fixed effect: Group, Time-point; Random effect: intercept per subject, treatment per subject."*. You mention `Group` as a variable and also `treatment`, but aren't they the same ?
Comment: Yes, sorry. I change the question.
Answer: Based on your description, in R you would start with a model such as:
outcome ~ group * time-point + (group | subject)

This will estimate fixed effects for group, time-point and the interaction between them. If you have sufficient statistical power, this will enable you to answer the research questions. The main effect for group will estimate the difference in outcome between the two groups at time-point 0, the main effect for time-point (assuming this is a factor and not continuous) will have 3 estimates, each being the estimated difference in the outcome between each time-point estimate and time-point 0, in the conventional group (that is, if convetional is the reference level for group variable). The interactions will estimate the  difference in the outcome between the two groups for each time-point relative to time-poiht 0.
The model also fits random slopes for group which will allow the "effect" of group to be different for each subject (ie as an offset to the main effect for group)
Often in longitudinal studies you would also want the effect of time (and the interactions) to vary by subject, that is, to fit random slopes, but in this case with relatively few subjects and a time variable with 4 levels it is possible that such a model will not be supported by the data. An alternative would be to code time as continuous but then you would need to know the actual time points of each measurement and possibly allow for non linearity.
Comment: The interaction terms will inform you about that but they will be contrasts vs the reference level (which I have assumed will me 0. If you want contrasts vs the other levels then you can change the reference level. This introduces problems with multiple testing but I believe there are some additional packages that will handle that (`lsmeans` is one I am aware of though there are probably others). I would recommend some research around these methods first.
Comment: thanks for the clear explanation! You said that the main effect for group will estimate the difference in outcome between the two groups at time-point 0. What if I also what to know the difference between the two groups at other time points? Should I perform any PostHoc test to evaluate the difference among groups at other time points?
Answer: The model suggested by @RobertLong is a great start (+1). It has one quirk though that may be unintended: there is a treatment effect at each time point, including at time T0 (pre-therapy).
$$
\begin{aligned}
\operatorname{E}\left\{Y | \text{time} = T_0, \text{group} = C\right\} &= \beta_0 \\
\operatorname{E}\left\{Y | \text{time} = T_0, \text{group} = T\right\} &= \beta_0 + \beta_1
\end{aligned}
$$
However, the treatment can't have an effect on the outcome before the treatment is administered and if the assignment of subjects to a treatment group is randomized, the expected difference between the two groups at baseline is 0.
$$
\begin{aligned}
\operatorname{E}\left\{Y | \text{time} = T_0, \text{group} = C\right\} &= \beta_0 \\
\operatorname{E}\left\{Y | \text{time} = T_0, \text{group} = T\right\} &= \beta_0 \qquad
\end{aligned}
$$
For the other time points (T1, T2, T3) the model remains unchanged.
Here is how to specify this model in the R formula syntax. It's a bit wordy but gets the job done.
  outcome ~
    I(time == "T1") + I(time == "T2") + I(time == "T3")
    + I(group == "T" & time == "T1")
    + I(group == "T" & time == "T2")
    + I(group == "T" & time == "T3")
    + (group | subject)

The terms I(group == "T" & time == "Ti") are the contrasts between treatment and control for each time point Ti = {T1, T2, T3}. The benefit of this formulation is that we estimate the fixed effects more precisely, ie. with smaller std. error.
I ran a simulation to illustrate (full R code below). First the fixed effects from Model 1, which includes a treatment effect at T0:
#>               Estimate Std. Error t value
#> (Intercept)    0.09103    0.05012   1.816
#> groupT        -0.11822    0.06687  -1.768
#> timeT1        -0.06673    0.04887  -1.366
#> timeT2         0.05765    0.04887   1.180
#> timeT3         0.17911    0.04887   3.665
#> groupT:timeT1  0.21681    0.07137   3.038
#> groupT:timeT2  0.20880    0.07137   2.925
#> groupT:timeT3  0.39799    0.07137   5.576

Of primary interest are the contrasts between treatment and control at time points T1 to T3:
#> time = T1:
#>  contrast estimate     SE   df t.ratio p.value
#>  T - C      0.0986 0.0669 85.2   1.474  0.1441
#> time = T2:
#>  contrast estimate     SE   df t.ratio p.value
#>  T - C      0.0906 0.0669 85.2   1.355  0.1791
#> time = T3:
#>  contrast estimate     SE   df t.ratio p.value
#>  T - C      0.2798 0.0669 85.2   4.184  0.0001

And next the fixed effects from Model 2, which doesn't have a treatment effect at T0. The bottom three rows correspond to the contrasts T - C at time points T1, T2 and T3; the std. errors are smaller.
#>                                    Estimate Std. Error t value
#> (Intercept)                         0.02416    0.03357   0.720
#> I(time == "T1")TRUE                -0.03590    0.04561  -0.787
#> I(time == "T2")TRUE                 0.08849    0.04561   1.940
#> I(time == "T3")TRUE                 0.20995    0.04561   4.603
#> I(group == "T" & time == "T1")TRUE  0.15102    0.06069   2.488
#> I(group == "T" & time == "T2")TRUE  0.14301    0.06069   2.356
#> I(group == "T" & time == "T3")TRUE  0.33221    0.06069   5.474

Finally one more point. The comment

This study is carried by several institutes (...)

suggests this is a multi-center study. If this is the case, the model should account for "center effects" as well; whether as fixed or random depends on the details.

The simulation R code:
library("lme4")

set.seed(123)

# T0: T - C = 0.0 - 0.0 = 0.0
# T1: T - C = 0.2 - 0.0 = 0.2
# T2: T - C = 0.3 - 0.1 = 0.2
# T3: T - C = 0.6 - 0.2 = 0.3

sim_fixef <- data.frame(
  group = rep(c("T", "C"), each = 4),
  time = rep(c("T0", "T1", "T2", "T3"), times = 2),
  fixef = c(0.0, 0.2, 0.3, 0.6, 0.0, 0, 0.1, 0.2)
)

k <- 4 # time points
nC <- 17 # subjects in C (control group)
nT <- 15 # subjects in T (treatment group)
n <- nC + nT # subjects in study
r <- 4 # measurements taken per subject per time point
tau <- 0.1
sigma <- 0.3

sim_ranef <- data.frame(
  group = rep(c("C", "T"), c(nC, nT)),
  subject = seq(nC + nT),
  ranef = rnorm(nC + nT, sd = tau)
)

d <- merge(sim_fixef, sim_ranef)
sim_data <- d[rep(seq(n * k), r), ] # replicated each row r times
sim_data$outcome <- with(
  sim_data,
  rnorm(n * k * r, mean = fixef + ranef, sd = sigma)
)

fit1 <- lmer(
  outcome ~ group * time + (group | subject),
  data = sim_data
)

fit2 <- lmer(
  outcome ~
    I(time == "T1") + I(time == "T2") + I(time == "T3")
    + I(group == "T" & time == "T1")
    + I(group == "T" & time == "T2")
    + I(group == "T" & time == "T3")
    + (group | subject),
  data = sim_data
)

summary(fit1)
summary(fit2)

library("emmeans")
pairs(emmeans(fit1, ~group, by = "time"), reverse = TRUE)


Irregular bootstrap column wrapping

Question: Running Rails 4.1.4 with the latest releases of haml, haml-rails, sass, and bootstrap-sass. For a user display, my HAML is as such:
.tutors-listing
    .row
      - @users.each do |tutor|
        .col-xs-12.col-md-3
          .row.tutor
            .col-xs-offset-1.col-xs-4.col-md-12
              = image_tag tutor.photo, :class => 'img-responsive img-circle tutor-photo'
              %h4.tutor-name
                = tutor.first_name

             %p
                teaches
             %strong.tutor-skills
               = tutor.teachables

However, this markup results in the following glitch:

I'm hoping somenone can devine what's wrong here. At the medium breakpoint, there should be 4 columns evenly.
Comment: See my answer here: http://stackoverflow.com/questions/24571062/gap-in-bootstap-stacked-rows/24571644#24571644.  Here's a Bootply demo: http://www.bootply.com/jme11/U91pZvp81q#.  And, more detail about "conventional" responsive resets here: http://stackoverflow.com/questions/24494409/bootstrap-gaps-between-columns/24513710#24513710
Comment: http://getbootstrap.com/css/#grid-responsive-resets
Answer: This is caused by skills with 2 lines of text or more. It's a well-known bug when using float property. Here is a little picture to understand :

[Bootply] The issue
Option #1 : Force the height
Your first option is to force elements to have the same height :
.tutor {
    height: 500px;
}

[Pro] Simple and work everywhere
[Con] Use a magic number
[Con] Limit the number of lines in skills
[Con] Useless whitespaces on modile version

[Bootply] Force height
Option #2 : Use a clearfix
Your second option is to use a clearfix, and force the 5th element to be on a new line (same for the 9th, the 13th...) :
.tutors-listing > .row > .col-md-3:nth-child(4n+1) {
    clear: both;
}

[Pro] Doesn't limit the number of lines in skills
[Pro] No useless whitespaces
[Pro] No magic number
[Con] One CSS rule per size (xs/sm/md/lg)
[Con] The rule depends of your grid (.col-xx-3)

[Bootply] Clearfix
Comment: Great answer. I'd add that you can put the tutor's skills into another div and define a min-height for it, so even if it doesn't have much content, will maintain the heights.
Comment: Thanks. The problem is not the minimal height, but the maximal one. Whatever `min-height`, if one element is higher than its followers it'll break you grid.
Comment: @vipin8169 I don't see the problem. The #2 solution doesn't care about your rows' height. Even if it's changed dynamically, it'll work and push the whole next line down.
Comment: @zessx I just answered a similar question today and gave a more or less similar approach to your first one since it's a very common scenario. Personally, I tend to use a combo of max and min height for better control (this way I might give more room/spacing but use less coding on media queries). However, I want to add another approach for the OP: to simply limit the skills by character (instead of words) so they're always the same length, or to force a min number of lines. Either way, +1 for this answer and the explanation
Comment: @zessx, your clearfix option should set `clear: left`, not `clear: both`.
Comment: But it won't work if the height of the rows changes dynamically. I mean you don't know which child will  overflow it's parent
Answer: In my case I wanted to show 3 items per row on large screens, 2 on medium screens, and 1 on smaller screens.
You may also uncomment the background colors to verify when the effect is triggering.
http://www.bootply.com/QOor73wFAY#
/* fixes for columns wrapping in odd ways due to variable height */
/* when showing 2 items per row, clear #1, 3, 5 */
@media (min-width: $screen-sm-min){
    .cell-box:nth-child(2n+1){
        clear: both;
        /* background-color: rgba(0, 0, 255, .5); /* blue */
    }
}
/* when showing 3 items per row, clear #1, 4, 7 */
@media (min-width: $screen-md-min){
    .cell-box:nth-child(2n+1){
        clear: none;
    }
    .cell-box:nth-child(3n+1){
        clear: both;
        /* background-color: rgba(0, 255, 0, .5); /* green */
    }
}

Comment: This was exactly what I was looking for. Thanks! I modified it to suite my breakpoints and "items per line" in a single row (in loop).
Answer: Sometimes, I run into this issue as well. I recommend trying to overwrite any padding or margin that you do NOT need. Try changing the margin to 0 first. Then remove some of the padding. That has helped in some of my cases.
Answer: By the looks of it you are rendering all of the columns in a single row. You need to change it
so that it starts a new row every 4 columns i.e.
(in plain old erb)
  <% @users.each_slice(4).to_a.each do |chunk| %>

       <% chunk.each do |tutors| %>

           ...

       <% end %>

  <% end %>

You might not need the to_a on the first loop
Comment: The problem is then that they cannot switch from 3 to 4 columns easily on different screen sizes.
Comment: Thanks for the recommendation

Irregular bootstrap column wrapping


How to write an xcode user script to surround the string the cursor is inside with NSLocalizedString(, nil)

Question: I'm trying to figure out the best way to automatically add NSLocalizedString() around a string in xcode.
Ideally I'd like a way that I could position the cursor within @"foo", press a key binding, and it'd be turned into NSLocalizedString(@"foo", nil).
I've had a look at the documentation for user scripts and can't see an obvious way to get the current cursor position.
Did I miss something, or is there another way to achieve the same result?
Thanks!
Answer: You can use %%%{PBXSelectionStart}%%%
From the apple documentation:

Getting Text from the Active Window
  These variables are replaced by text in the active window:

%%%{PBXSelectedText}%%% is replaced by the selected text in the active text object.
%%%{PBXAllText}%%% is replaced by the entire text in the active text object.

Getting Information on the Contents of the Active Window
  These variables are replaced by information on the text in the active window:

%%%{PBXTextLength}%%% is replaced by the number of characters in the active text object.
%%%{PBXSelectionStart}%%% is replaced by the index of the first character in the selection in the active text object.
%%%{PBXSelectionEnd}%%% is replaced by the index of the first character after the selection in the active text object.
%%%{PBXSelectionLength}%%% is replaced by the number of characters in the current selection in the active text object.

Procrastination brought you this script.
It works and does what it should. But it is very basic, and there are bugs, and this is probably not the best way to do it.
Don't use @ and " in the strings you want to replace. If I were you, I wouldn't use it anyway. ^^
Script Input is Selection, Output is Replace Document Contents
#!/bin/sh
if [ %%%{PBXSelectionLength}%%% -gt 0 ]
  then
    echo "This does not work if you select text. Put your cursor inside a String." >&2
    exit
fi
Source=`cat "%%%{PBXFilePath}%%%"`
SelectionStart="%%%{PBXSelectionStart}%%%"
SelectionEnd="%%%{PBXSelectionEnd}%%%"
BOOL=1
StringStart=$SelectionStart
StringStop=$SelectionEnd
while [ $BOOL -eq 1 ]
 do
  tmpText=`echo "${Source:${StringStart}:1}"`
  if [ "$tmpText" = "@" ]
   then BOOL=0
   else StringStart=$(($StringStart - 1))
  fi
done
BOOL=1
while [ $BOOL -eq 1 ]
 do
  tmpText=`echo "${Source:${StringStop}:1}"`
  if [ "$tmpText" = "\"" ]
   then BOOL=0
  fi
  StringStop=$(($StringStop + 1))
done

StringToReplace=`echo ${Source:${StringStart}:$(($StringStop - $StringStart))}`
ReplacementString="NSLocalizedString($StringToReplace,nil)"
echo -n "${Source:0:${StringStart}}"
echo -n "$ReplacementString"
echo -n "${Source:${StringStop}}"

Comment: Thanks! I'd not appreciated that PBXSelectionStart had that meaning when I read the documentation. I wasn't expecting a whole script - works very nicely - the only downside is that (at least in xcode 3.2.4) it seems to result in the cursor being placed at the end of the document when you use it - any idea if there's a way to avoid that?
Comment: if you don't select anything you have to replace the whole document, so the cursor will be at the end of the document. No idea how to change this. To be honest, these were my first steps with xcode user scripts ^^
Comment: Ah right, I see - thanks! It's also my first time looking at the user scripts, I only discovered they existed this week :)
Comment: Thanks, fluchtpunkt! I used your script as a template for my own script. It inserts a super call for the current method. (https://github.com/yangmeyer/Xcode-extensions)
Answer: #!/bin/sh
echo -n 'NSLocalizedString(%%%{PBXSelectedText}%%%, nil)'

Make sure script input is "Selection" and output is "Repalce Selection"
Select string and run script.
This is not exactly you want, but I can't google this method, let it be here :)


Manipulated checkbox to checked using element of json callback from Ajax

Question: I use ajax in jquery to get some data like this :
$.ajax({
          url : "<?=  base_url('surveyor/c_surveyor_inspection/get_data_untuk_inspection_surveyor_dua'); ?>",
          type : "POST",
          data : {
              ID : id
          },
          dataType :'json',
          success : function(response){
              console.log(response);
          }
      });

Based this ajax, I got JSON like this :
{
"header ": [{
    "NO_INSPECTION": "55",
    "ID_CONDITION": "1",
    "NAMA_CONDITION": "DIRTY"
}, {
    "NO_INSPECTION": "55",
    "ID_CONDITION": "2",
    "NAMA_CONDITION": "DAMAGE"
}],
"transaction": [{
    "NO_INSPECTION": "55",
    "ID_ITEM_INSPECTION": "1",
    "NOMOR_ITEM_INSPECTION": "1",
    "NAMA_ITEM_INSPECTION": "Protection Box Cover",
    "CONDITION": "9",
    "ALIAS": "BE",
    "NAME_ITEM": "BENT"
}, {
    "NO_INSPECTION": "55",
    "ID_ITEM_INSPECTION": "2",
    "NOMOR_ITEM_INSPECTION": "2a",
    "NAMA_ITEM_INSPECTION": "Manhole LID, Fastening Bolts",
    "CONDITION": "7",
    "ALIAS": "B",
    "NAME_ITEM": "BROKEN"
}]

}
Please see in first element og this json named header
With this element, I want to manipulated a html's checkbox like this

     <input type="checkbox" value="1" checked="checked" name="condition[]">Dirty

     <input type="checkbox" value="2" name="condition[]">Damage

     <input type="checkbox" value="3" name="condition[]">Clean

     <input type="checkbox" value="4" name="condition[]">Off Hire

What should I do i success ajax ? Which is In JSON, I got value and item each '1', 'DIRTY' and '2','DAMAGE' that means its will be checked in html. Any help it so appreciated. Thanks a lot
Answer: You could do something like this:
var i;

// uncheck all checkboxes
$('input[type=checkbox]').prop('checked', false);

// check appropriate checkboxes
for (i = 0; i < response.header.length; i = i + 1) {
  $('input[type=checkbox][value=' + response.header[i].ID_CONDITION + ']').prop('checked', true);
}


Evaluating determinant $\det (\delta_{ij}+a_ia_j)_{ij}$

Question: Given $a_1, \cdots, a_n \in \mathbb R$, how can we evaluate this?
$$\det \left(\delta_{ij}+a_ia_j\right)_{ij}$$
I think the answer should be
$$1+a_1^2+\cdots a_n^2$$
and this question is motivated by computing the volume form of a Riemannian submanifold whose parametrization can be represented by a graph. (See Riemannian volume form on surface of a smooth function. In the last answer of the link, $\partial f/\partial x_i$ is just replaced to $a_i$ in my question.)
Aside: I am also curious whether there is an another way to find the volume form not by evaluating the above determinant.
Comment: Hint: [matrix determinant lemma](https://en.wikipedia.org/wiki/Matrix_determinant_lemma)
Answer: The determinant of a matrix is the product of its eigenvalues, and adding $\delta^i_j$ shifts all eigenvalues by $1$. Therefore, if $\lambda_1,\dots, \lambda_n$ are the eigenvalues of the matrix $(a^ia_j)$, we obtain $\det(\delta^i_j + a^ia_j) = \Pi_{k=1}^n (\lambda_k+1)$. Let $(v_k)_{k=1}^n$ be an orthogonal base, and $v_1 = a$. Then $(a^ia_j) v_k = a^ia_jv^j_k e_i= a^i<a,e_k>e_i = \delta^1_k |a|^2 a$, where $(e_k)_{k=1}^n$ denotes the standard base. Thus the eigenvalues are $|a|^2,0,\dots,0$, which yields $\det(\delta_{ij} + a_ia_j) = \det(\delta^i_j + a^ia_j) = 1 + |a|^2$.
The above computation can be interpreted in the context of the volume element of a graph as follows: Let $\nabla f(x), v_2, \dots, v_n$ be an orthogonal base of $T_x\mathbb{R}^n$. Now, $v_2,\dots,v_n$ are orthogonal to $\nabla f$, hence their pushforwards on the graph are just parallel transports of themselves, with the same length. The first vector, $\nabla f(x)$, transforms to $(\nabla f(x), |\nabla f(x)|^2)^T$, thus its stretched by a factor of $1+|\nabla f|^2$. Therefore, the volume element is stretched by a total factor of $1+|\nabla f|^2$.


Why does Pillow invert the colors when drawing via ImageDraw?

Question: I am trying to paste an image into another on that is 8 bits/pixel (L mode), but the colors get inverted. How to fix this? A sample code:
icon_bmp2 = Image.open("assets/test_penguin.png")
icon_bmp2 = icon_bmp2.convert("L")
im2 = Image.new('L', (650, 500), 0xFF) # this line cannot be changed
image_draw2 = ImageDraw.Draw(im2)
image_draw2.bitmap((0, 0), icon_bmp2)
im2.save('test.png') # inverted

The test image is from here: https://github.com/GregDMeyer/IT8951/blob/master/test/integration/images/sleeping_penguin.png, I'm using Python 3.7 and Pillow 7.2.0
Comment: You're using the wrong `ImageDraw` function — [`bitmap()`](https://pillow.readthedocs.io/en/latest/reference/ImageDraw.html#PIL.ImageDraw.ImageDraw.bitmap) draws a mask in the current fill color.
Answer: You should use the Image.paste() function instead of ImageDraw.bitmap() to paste the pixels of one image onto another. It's also simpler to use since there's no need to create an ImageDraw first in order to use it.
from PIL import Image, ImageDraw

icon_bmp2 = Image.open("sleeping_penguin.png")
icon_bmp2 = icon_bmp2.convert("L")

im2 = Image.new('L', (650, 500), 0xFF)  # This line cannot be changed.
im2.paste(icon_bmp2)
im2.save('test2.png')

Non-inverted result


Kendo for MVC Grid - Create success

Question: I would like to know if there is any way to validate if I can specify a success action after creating successfully using Kendo Grid for MVC.
I have the following line for Create action, and I would like to add a validation if it was succcess display a message.
<code> .Create(create => create.Action("Create", "Customer"))
</code>
Answer: I found the solution, I am not sure if it is the best one but it works.
I added the following event
<code> .Events(events =>
            {
              events.RequestEnd("checkResult");
            })
</code>
Then I created a javascript function
<code> function evaluateResult(e)
 {
         if (e.type == "create" && e.response.Errors==null)  { ... //success}
 }
</code>

Kendo for MVC Grid - Create success


Setting bootloader password in EL7

Question: Using this guide I am attempting to add a bootloader password to a CentOS7 install.

When prompted, enter the password that was selected and insert the
  returned password hash into the appropriate grub2 configuration
  file(s) under /etc/grub.d immediately after the superuser account.
  (Use the output from grub2-mkpasswd-pbkdf2 as the value of
  password-hash):

I've created the "superusers-accountpassword-hash" using grub2-mkpasswd-pbkdf2, but am not seeing where to add this line:
password_pbkdf2 superusers-accountpassword-hash

The only files in /etc/grub.d/ are binaries.   The guide says not to use /etc/grub.cfg since this is overwritten by grub2-mkconfig -o /boot/grub2/grub.cfg
Where does the password_pbkdf2 directive go?
Answer: You need to create /etc/grub.d/01_users file and place the info in there. This typically is created when GRUB boot loader password is used in a kickstart template but must be made manually otherwise.
Source:
https://access.redhat.com/documentation/en-US/Red_Hat_Enterprise_Linux/7/html/System_Administrators_Guide/sec-GRUB_2_Password_Protection.html

Setting bootloader password in EL7