text:
Q: Como funciona o algoritmo de criptografia AES? Gostaria de entender como funciona o algoritmo de criptografia AES (Advanced Encryption Standard). Procuro respostas didáticas, que me façam compreender os processos utilizados pelo algoritmo passo-a-passo, dando ênfase a parte lógica e matemática, e se possível, as operações com bits.
Note que não peço exemplos de código, embora sejam válidos para a explicação.

A: O AES é uma primitiva criptográfica destinada a compor sistemas de cifragem e decifragem simétrica (i.e. mesma chave para cifrar e decifrar). É uma cifra de bloco, ou seja, opera em blocos de tamanho fixo (128 bits, ou 16 bytes). Como toda cifra de bloco, pode ser transformada numa cifra de fluxo (de modo a operar em dados de tamanho arbitrário) através de um modo de operação, mas isso não vem ao caso aqui. Pode trabalhar com chaves de 128, 192 ou 256 bits (o algoritmo Rijndael, que originou o AES, permite mais tamanhos de chaves).
Em outras palavras, é um algoritmo cuja função direta (cifragem) recebe como entradas um bloco de 128 bits (a mensagem) e uma chave do tamanho escolhido, e devolve uma saída também de 128 bits (a cifra). A função inversa (decifragem) recebe como entrada um bloco de 128 bits (a cifra) e devolve como saída um bloco de 128 bits. Se a chave for a chave correta, essa saída será idêntica à mensagem original.
O objetivo de uma cifra bem sucedida é que seja impraticável se descobrir a mensagem original caso somente se possua a mensagem cifrada, mas não a chave de criptografia. Para isso, busca-se minimizar qualquer correlação visível entre a entrada e a saída, de modo que a mesma (e/ou a chave) possa ser deduzida simplesmente observando-se um número muito grande de cifras (ou de pares mensagem/cifra). Para isso, usa-se uma série de "rodadas" (ou rounds) em que os bytes sofrem transformações não lineares, porém reversíveis (i.e. para decifrar, simplesmente se executa o inverso das mesmas operações, em ordem inversa).
Corpos Finitos
Todas as operações no AES tratam os bytes de entrada como um corpo finito (finite fields, ou Galois fields) em 28. Isso significa que:

*

*Há um conjunto [0,255] (que são todos os valores possíveis para um byte) e um desses elementos é chamado "zero" (no caso, o próprio 0);

*Há uma operação, que chamaremos de "adição", que se aplica a quaisquer dois elementos nesse conjunto e cujo resultado também é um elemento desse conjunto. Essa operação precisa ser associativa, comutativa, possuir elemento neutro, e cada elemento deve ter um inverso;

*

*Nesse caso, definimos a "adição" como o "OU exclusivo" - XOR.

*Há uma operação, que chamaremos de "multiplicação", com características semelhantes à "adição". Exceto pelo elemento "zero", que não tem inverso (e o elemento neutro da multiplicação é chamado de "um"). A multiplicação também precisa ser distributiva em relação à adição.

*

*A "multiplicação" será definida adiante.

Para quem não tem experiência com matemática, é bom frisar que estamos definindo "adição", "multiplicação", "zero" e "um" - esses nomes não têm necessariamente nada a ver com as operações aritméticas usuais que fazemos no conjunto dos números Naturais ou Reais (os Naturais ou Inteiros, por exemplo, não formam corpos com o + e * usuais, pois não existe x dentro desses conjuntos tal que 2*x=1; os Reais formam um corpo, só que infinito). Não há "subtração", "divisão", etc.
A adição, como já foi dito, foi definida como sendo o XOR. A multiplicação é mais complexa: primeiro trate cada operando como se fosse um polinômio com base na sua representação binária (ex.: 6 - 110 - vira x^2 + x, e 11 - 1011 - vira x^3 + x + 1), multiplique-os, depois divida o resultado por um "agente redutor". O resto da divisão (interpretado novamente como um número) será então o resultado da multiplicação. No caso do AES, o agente redutor escolhido foi:
x^8 + x^4 + x^3 + x + 1

De modo que multiplicar 6 por 11 é o mesmo que fazer
(x^2 + x)*(x^3 + x + 1) mod (x^8 + x^4 + x^3 + x + 1)
=[(x^5 + x^3 + x^2) + (x^4 + x^2 + x)] mod (x^8 + x^4 + x^3 + x + 1)
=(x^5 + x^4 + x^3 + x) mod (x^8 + x^4 + x^3 + x + 1)
=111010 mod 100011011
=111010
=58

Note que os coeficientes são "somados" usando o XOR, não a soma comum: quando se somou x^2 com x^2 o resultado é zero, e não 2*x^2. Pense nessa soma como 1*x^2 + 1*x^2 = (1 xor 1)*x^2 = 0*x^2 = 0. O corpo GF(2^8) foi construído com base no GF(2) (corpo binário, onde a soma é XOR e a multiplicação é AND), de modo que seus polinômios possuem somente 0 ou 1 como coeficientes. Para mais detalhes, a Wikipedia em inglês possui um artigo sobre aritmética em corpos finitos, inclusive uma subseção específica sobre o Rijndael.
A Wikipedia possui um algoritmo simplificado que é equivalente a essa multiplicação de polinômios, porém bem menos custosa (veja no final da seção).
Ou seja, uma implementação [não otimizada] do AES poderia por exemplo criar um tipo de dado distinto para representar cada byte das entradas/saídas/chaves e dar sua própria implementação da "adição" e "multiplicação" (sobrecarregando as usuais, se a linguagem de programação permitir). Isso simplificaria a lógica, às custas da performance.

big disclaimer: não estou sugerindo que leigos implementem AES [para usar na prática] - eu não confio em mim mesmo pra implementar algoritmos criptográficos, muito menos em quem estiver lendo isso... Coloquei isso apenas para fins didáticos, uma implementação real precisa se preocupar inclusive com coisas como side channel attacks (ex.: timing e fault).

*

*Nota: A partir de agora, sempre que eu falar em "adicionar" ou "multiplicar" eu me refiro a operações em GF(28), exceto quando houver indicação em contrário.

Rijndael S-Box
Com base nessa aritmética em corpo finito, foi concebida uma tabela de consulta (lookup table) chamada Rijndael S-Box, destinada a transformar um byte em outro diferente, de uma forma não linear. Duas tabelas são usadas: uma para a função direta e outra pra inversa.

*

*Em primeiro lugar, calcula-se o inverso multiplicativo do byte (i.e. um byte tal que multiplicado por ele resulta em "um"). O zero não tem inverso, então ele mapeia pra zero mesmo.

*Em seguida, os oito bits do resultado são submetidos a uma transformação afim, para tornar o método mais resistente contra ataques algébricos:
[1 0 0 0 1 1 1 1][b0]   [1]
[1 1 0 0 0 1 1 1][b1]   [1]
[1 1 1 0 0 0 1 1][b2]   [0]
[1 1 1 1 0 0 0 1][b3] + [0]
[1 1 1 1 1 0 0 0][b4]   [0]
[0 1 1 1 1 1 0 0][b5]   [1]
[0 0 1 1 1 1 1 0][b6]   [1]
[0 0 0 1 1 1 1 1][b7]   [0]

Essa tabela foi projetada com o objetivo de ser resistente à criptanálise linear ou diferencial, e permitindo a substituição da transformação afim por outra caso se descubra algum backdoor no futuro. Para efeitos práticos, é uma função invertível cuja saída não se assemelha em nada à entrada (i.e. pequenas alterações na entrada produzem diferenças aparentemente aleatórias na saída).
Expansão da Chave
Como foi dito, o AES possui várias rodadas de cálculo, que parte da mensagem original, aplica uma série de transformações na mesma, e chega ao resultado final (a cifra). Chamarei os dados sendo trabalhados de "estado" (state):
estado = mensagem
estado = round(estado)
estado = round(estado)
estado = round(estado)
...
estado = round(estado)
cifra = estado

Em cada estado, não se usa a chave original de criptografia, mas sim uma série de chaves derivada da mesma. Essa derivação usa um algoritmo chamado Rijndael Key Schedule, e é complexo por si só para ser totalmente explicado aqui (apesar da implementação ser aparentemente curta). Darei apenas uma visão geral, portanto:

*

*O AES opera em blocos de 128 bits, como visto, mas usa chaves de 128, 192 ou 256 bits; o algoritmo de expansão de chaves produz portanto um conjunto de sub-chaves de 128 bits - uma para cada round do algoritmo (que por sinal também depende do tamanho da chave: são 10, 12 ou 14 rounds, respectivamente).

*Partindo-se da chave original, é feita uma série de operações envolvendo a rotação (shift) dos últimos 4 bytes, sua transformação conforme o S-Box, e a adição com uma potência de 2. Há uma pequena variação nas etapas conforme o tamanho de chave utilizado.

*

*Por "potência de 2", me refiro a 2 multiplicado por si mesmo N vezes, em GF(28). Como se pode ver nessa tabela, os valores são bem diferentes da aritmética em números inteiros.

*Uma vez que se produziu bytes suficientes para todos os rounds do algoritmo, conclui-se a expansão da chave.

Rodadas
O algoritmo funciona em rodadas, ou rounds, de modo que em cada uma delas uma série de operações reversíveis é feita em cima do estado. O objetivo é que cada byte da entrada seja "combinado" com vários bytes da chave, de modo que pequenas alterações tanto na chave quanto na mensagem provoquem mudanças significativas na cifra (ver confusion and diffusion). Em outras palavras, se quer evitar que parte da cifra dependa somente de parte da chave, o que permitiria quebrar o problema de decifrar uma chave grande em se decifrar várias chaves menores (o que poderia ser feito por força bruta).
Nota: os bytes do estado são comumente representados em uma matriz 4x4. Essa matriz é por coluna, não por linha (como na maioria das linguagens de programação populares). Ou seja, os 16 bytes são dispostos da seguinte forma:
b0   b4   b8   b12
b1   b5   b9   b13
b2   b6   b10  b14
b3   b7   b11  b15

Quando for mencionado "linha" ou "coluna", refere-se aos 4 bytes do estado correspondentes à representação acima.

*

*Na primeira rodada, o estado é adicionado à chave daquela rodada;
estado = estado ^ chave(0)

*Nas rodadas subsequentes:

*

*cada byte do estado é transformado conforme o S-Box;
para cada byte b no estado:
    estado[b] = S(estado[b])

*Depois as linhas são rotacionadas à esquerda, da seguinte forma:
a00 a01 a02 a03   <<0   a00 a01 a02 a03
a10 a11 a12 a13   <<1   a11 a12 a13 a10
a20 a21 a22 a23   <<2   a22 a23 a20 a21
a30 a31 a32 a33   <<3   a33 a30 a31 a32

*Depois em cada coluna da matriz seus bytes são combinados com todos os outros bytes da mesma coluna; essa etapa não ocorre na última rodada.
A descrição detalhada essa etapa pode ser vista aqui. O que é feito é pegar cada coluna da matriz e multiplicá-la por uma matriz fixa, resultando nos novos valores da coluna:
[a00]   [2 3 1 1][a00]
[a10] = [1 2 3 1][a10]
[a20]   [1 1 2 3][a20]
[a30]   [3 1 1 2][a30]

a00 = 2*a00 ^ 3*a10 ^ 1*a20 ^ 1*a30
a10 = 1*a00 ^ 2*a10 ^ 3*a20 ^ 1*a30
a20 = 1*a00 ^ 1*a10 ^ 2*a20 ^ 3*a30
a30 = 3*a00 ^ 1*a10 ^ 1*a20 ^ 2*a30

... (idem pras demais colunas)

Pelo meu entendimento, a multiplicação continua sendo a multiplicação em GF(28), mas nesse caso há uma descrição mais simples da mesma: x*1 é x, x*2 é x<<1 e x*3 é x<<1 ^ x. Se o resultado for maior que 255, fazer x ^ 0x1B.

*Por fim, soma-se a chave da rodada ao estado.
estado = estado ^ chave(i)   # onde i é o número da rodada

Resumo
Essa série de operações (adicionar chave, substituir, misturar/permutar) é chamada "Substitution-Permutation Network", ou SP-network. Aqui está uma representação gráfica do processo, com 3 rounds:

Decifragem
O processo de decifrar consiste simplesmente na aplicação do inverso dessas mesmas operações, na ordem inversa naturalmente. Muitas vezes não muda nada entre cifrar e decifrar (ex.: a xor b xor b = a), em outras é necessário alguma adaptação:

*

*Em vez de começar com estado = mensagem e terminar com cifra = estado, agora começamos com estado = cifra e terminamos com mensagem = estado;

*A expansão da chave é igual; no início de cada round se adiciona a chave do round correspondente (lembrando que agora estamos fazendo os rounds de trás pra frente), e no final se adiciona a chave do primeiro round;

*Para se desfazer a etapa 3 (mistura de colunas) de cada round em que ela se aplica (i.e. todos exceto o primeiro e o último), usa-se a matriz inversa àquela descrita anteriormente:
[a00]   [14  11  13   9][a00]
[a10] = [ 9  14  11  13][a10]
[a20]   [13   9  14  11][a20]
[a30]   [11  13   9  14][a30]

(como dessa vez não há "atalhos" para a multiplicação, é comum se utilizar outra lookup table em vez de se fazer a conta na hora. Aqui tem as tabelas relevantes.)

*A etapa 2 é simplesmente um shift pra direita em vez da esquerda...

*Para se desfazer a etapa 1, usa-se uma lookup table que corresponde ao inverso da S-Box.

A: Antes de mais nada, minha resposta pretende apenas acrescentar conteúdo a resposta do mgibsonbr, que já é bem completa. Eu tive que fazer uma fundamentação teórica para o meu Trabalho de Conclusão de Curso. Penso que seria muito egoísmo meu, deixar tudo o que eu escrevi somente no papel, então, portanto, resolvi compartilhar o que escrevi com a comunidade. Ainda são necessários alguns aprimoramentos e penso que posso ter cometido alguns deslizes, pois o algoritmo é muitíssimo complexo. Se isto acontecer, sinta-se livre para editar a minha resposta.
1 - Criptografia
Segundo Bond et al. (2003), criptografar dados significa convertê-los de modo que só possam ser decifrados e lidos por usuários autorizados, portanto, a criptografia dos dados exige que um algoritmo seja aplicado a estes dados.
A forma de escrever a lógica é denominada de algoritmo, que, segundo Cormen et al. (2002, p. 3), nada mais é do que qualquer procedimento computacional bem definido que toma algum valor ou conjunto de valores como entrada e produz algum valor ou conjunto de valores como saída. Portanto, um algoritmo é uma sequência de passos computacionais que transformam a entrada na saída. Desta forma, um algoritmo de criptografia é um procedimento matemático que contém uma entrada, os dados a serem criptografados, efetua um processamento
matemático com base em uma chave, e gera uma saída: os dados criptografados (KUROSE; ROSS, 2010; BOND et al., 2003; RAPPAPORT, 2009; STALLINGS, 2008; FOROUZAN; FEGAN, 2008). Forouzan e Fegan (2008) explica alguns termos utilizados quando nos referimos a criptografia, segundo ele:

*

*Cifra: são os algoritmos de criptografia e decriptografia

*Chave: é um número ou conjunto de números sobre o qual a cifra opera.

2 - Criptografia Simétrica
A criptografia simétrica é o tipo de criptografia que utiliza a mesma chave para cifrar e decifrar os dados (FOROUZAN; FEGAN, 2008). Geralmente algoritmos de criptografia simétrica são bastante sofisticados e utilizam chaves de 56 ou 128 bits. Devido ao tamanho e a probabilidade matemática do número e complexidade da chave, um algoritmo de  criptografia não pode ser revertido com facilidade, isto significa que, sem a chave, o dado criptografado demoraria centenas de anos para ser decifrado em um ataque de força bruta, isto se, somente se, o algoritmo que criptografou este dado for suficientemente robusto (BOND et al., 2003).
A criptografia simétrica é usada para garantir a confidencialidade de determinado dado e garante que apenas os destinatários autorizados, aqueles que conheçam a chave de decifração, possam recuperar os dados originais (BOND et al., 2003).
Um exemplo de cifra simétrica é o algoritmo AES, do inglês: Advanced Encryption Standard, que é uma evolução do DES e foi desenvolvido porque a chave do DES era muito curta. O AES é uma cifra cíclica muito complexa e foi projetado com três tamanhos de chave: 128, 192 ou 256 bits (FOROUZAN; FEGAN, 2008).
3 - Criptografia Assimétrica
A criptografia assimétrica é aquela que utiliza algoritmos diferentes de criptografia simétrica e exige o uso de duas chaves: a chave privada, que é mantida em segredo pelo proprietário e utilizada para criptografar dados, e a chave pública, que é conhecida por pessoas autorizadas pelo proprietário da chave privada e é utilizada para decifrar os dados (FOROUZAN; FEGAN, 2008). Porém, se um dado é criptografado com a chave pública, somente o proprietário da chave privada pode decifrar este dado (BOND et al., 2003)
4 - O Algoritmo AES
O algoritmo Advanced Encryption Standard, ou simplesmente AES, é um algoritmo de criptografia simétrica por blocos de 128 bits (16 bytes), desenvolvido desde 1997 por Vincent Rijmen e Joan Daemen, e anunciado em 26 de novembro de 2001 pelo NIST, (National Institute of Standards and Technology) Instituto Nacional de Padrões e Tecnologia dos EUA em tradução livre (NIST, 2001)1.
O algoritmo AES possui chaves de 128 bits, 192 ou 256 bits ou 16, 24 e 32 bytes respectivamente. Entende-se por chave o conjunto de dados digitais sobre o qual a cifra opera (FOROUZAN; FEGAN, 2008). Por se tratar de um algoritmo de criptografia simétrica com blocos de 128 bits, a função de cifragem, que é a função responsável por transformar e embaralhar os dados, recebe blocos de 16 bytes (128 bits) por vez e devolve, também, 16 bytes por
vez. Chama-se o conjunto de blocos que será encriptado de "mensagem", e o conjunto retornado pela função de cifragem de "cifra". O processo de decifragem é feito de forma análoga, porém, contrária ao de cifragem e, portanto, recebe um conjunto de blocos cifrados (cifra) e devolve a mensagem idêntica a original, se, somente se, a chave for a mesma que foi utilizada
para encriptar os dados. O processo de cifragem também pode ser chamado de encriptação ou mesmo "criptografia", da mesma forma que o processo de decifragem é sinônimo de "decriptação"ou "descriptografia"(NIST, 2001). A Figura 1 mostra um pseudocódigo do algoritmo AES, as etapas do algoritmo são explicadas posteriormente.
Figura 1 - Pseudo código do AES

Fonte: Adaptado de NIST (2001, tradução nossa)
5 - O Estado
Internamente, as operações do algoritmo AES são realizadas em uma matriz bidimensional de bytes chamadas de "Estado" (s). O Estado consiste em um array organizado em 4 colunas de bytes, cada uma contendo 4 bytes, 16 bytes ao todo, sendo que os valores de cada byte variam de 0 a 255. Durante o processo de cifragem ou decifragem, os blocos de 128 bits (16 bytes) são copiados para este array, para que sejam efetuadas as operações responsáveis
pelo funcionamento do algoritmo nesta cópia (NIST, 2001). A Figura 2 ilustra os blocos de entrada, o array Estado e os blocos de saída, sendo que cada item corresponde a um byte:
Figura 2 - Blocos de entrada, Estado e blocos de saída

Fonte: Adaptado de NIST (2001, tradução nossa)
6 - Operação de adição ⊕
A adição nada mais é do que uma soma dos bits, conhecida como operação XOR (OU
Exclusivo), também chamada de "disjunção exclusiva". É uma operação lógica entre dois operandos que resulta em um valor lógico verdadeiro se, e somente se, exatamente um dos operandos possui valor verdadeiro. Pode ser sintetizado como um detector de diferenças entre dois operandos lógicos (NIST, 2001) e é representada por ⊕.
7 - Operação de multiplicação ⊗
Em se tratando do algoritmo AES a multiplicação é a representação polinominal GF(28) (indicado por ⊗), ou seja, corresponde a multiplicação de polinômios modulo em polinômios irredutíveis de grau 8. Um polinômio é irredutível se seus únicos divisores são um e ele mesmo (NIST, 2001, tradução nossa). Para o algoritmo AES, este polinômio irredutível é: 2

ou {01}{1b} na notação hexadecimal.
Por exemplo, 57 ⊗ 83 = c1, pois:

O x7 + x6 + 1, obtido como resultado, pode ser escrito como x7 + x6 + 0x + 0x + 0x + 0x + 0x + 1 corresponde a: {11000001} em binário, que é equivalente a {c1} hexadecimal.
Os agentes 2x2 e 2x foram cortados pois estes polinônimos só possuem 0 e 1 como fatores, de modo que fatores pares viram 0 e fatores ímpares viram 1.
A redução modular por m(x) garante que o resultado será um binário polinomial de grau inferior a 8, e, assim, pode ser representado por um byte. Ao contrário disso, não há nenhuma operação simples no nível de byte que corresponde a esta multiplicação (NIST, 2001, tradução nossa)3.
Portanto, de forma simples, entende-se que a operação de multiplicação é a representação do polinômio na sua representação binária, feito uma multiplicação dos agentes dessa equação e posteriormente divididos pelo agente redutor (operação de módulo). O resto desta divisão será então o resultado da operação de multiplicação. No caso do AES, foi escolhido o
agente redutor citado na Equação 2.1
8 - Rijndael S-Box e a Etapa de SubBytes
O Rijndael S-Box, ou simplesmente S-Box, trata-se de uma matriz quadrada, não-linear, utilizada como tabela de substituição em diversas transformações de byte. Também é utilizada em rotinas de expansão de chaves de valores um-para-um em bytes. No algoritmo AES é utilizada na etapa de SubBytes e durante a expansão de chave (Key Expansion)4 (NIST, 2001, tradução nossa).
A etapa de SubBytes, ou transformação de SubBytes, é uma substituição não linear que opera de forma independente em cada byte do array de estado usando a tabela de substituição Rijndael S-Box (NIST, 2001, tradução nossa). A Rijndael S-Box é revertível, e é construída pela composição de duas transformações5:

*

*Calcula-se o inverso multiplicativo do byte, ou seja, um byte tal que multiplicado por
ele mesmo, resulta em 1. O elemento 0 (zero) é mapeado para ele mesmo.

*Aplica-se uma transformação afim, que pode ser expressa de forma de matriz como:

Transformação afim do Rijndael S-Box

Fonte: Adaptado de NIST (2001)
Durante a etapa de SubBytes, os bytes do array Estado são substituídos a partir da S-Box, gerando valores diferentes e, aparentemente aleatórios. A S-Box utilizada nesta etapa é apresentada na Figura 3.
Figura 3 - S-Box em notação hexadecimal

Fonte: Adaptado de NIST (2001)
Por exemplo, se temos a posição Estado1,1 = {53}, então o valor da substituição será determinado pela intersecção da linha de índice 5 e coluna de índice 3, ilustradas na Figura 3. Portanto, o resultado da substituição na posição Estado1,1 será de {ed}.
9 - Etapa de ShiftRows
Na etapa ShiftRows, os bytes das três últimas linhas do Estado são deslocados ciclicamente ao longo de diferentes números de bytes (offsets) 6 (NIST, 2001, tradução nossa). Somente a primeira linha, não é deslocada. A Figura 4 ilustra este processo e destaca os bytes que foram transpostos.
Figura 4 - A etapa ShiftRows

Fonte: Adaptado de NIST (2001)
10 - Etapa MixColumns
A etapa MixColumns opera sobre o Estado coluna por coluna, e trata cada coluna como um polinômio de quatro termos (NIST, 2001, tradução nossa), conforme a equação a seguir7:

As colunas são consideradas como polinômios e multiplica-se pelo módulo x4 + 1 com um polinômio fixo a(x), dada pela equação:

Portanto, o resultado da etapa MixColumns sobre o array Estado, que é representado por s´(x), é a multiplicação do polinômio descrito na Equação 2.9 por elementos do array de Estados s(x) que pode ser escrito como:

Sendo a(x) e s(x) a representação de matrizes, e elementos dessas matrizes, é possível representar a Equação 2.10 em forma de uma multiplicação de matrizes, tal qual como no artigo do NIST sobre o AES, assim sendo, a representação equivalente pode ser vista na Figura 5 (NIST, 2001).
Figura 5 - Representação em forma de matriz para a etapa MixColumns

Fonte: Adaptado de NIST (2001)
Com o resultado desta multiplicação, os quatro bytes de uma coluna são substituídos, elemento a elemento, como é mostrada na Figura 6, logo a seguir:
Figura 6 - Elementos a serem substituídas na etapa MixColumns

Fonte: Adaptado de NIST (2001)
Após a multiplicação, os elementos s0,c , s1,c , s2,c e s3,c do array Estado, que juntos formam uma coluna c, são substituídos pelos elementos s'0,c , s'1,c , s'2,c e s'3,c , concluindo a etapa
MixColumns, como é mostrado na Figura 7.
Figura 7 - A etapa MixColumns

Fonte: NIST (2001)
11 - Etapa AddRoundKey
A etapa AddRoundKey consiste em adicionar uma sub-chave em cada byte do array
Estado, por meio de uma operação XOR bit a bit (adição). A chave é expandida a cada rodada usando a expansão de chaves do AES, de forma que em cada rodada utiliza-se uma chave diferente, derivada da chave original, conforme é visto na Figura 8.
Figura 8 - A etapa AddRoundKey

Fonte: NIST (2001)
12 - Decriptação
A decriptação consiste em um processo análogo ao de encriptação, porém seguindo a ordem inversa. O algoritmo AES recebe o conteúdo encriptado e se a chave for a mesma que a utilizada para encriptar, o resultado final será a mensagem original. Todas as operações do AES são facilmente invertíveis. De uma forma simples, é possível, por exemplo, rotacionar as colunas ao Estado original na etapa de ShiftRows, ou saber qual o byte original verificando a
linha e coluna que contém o byte na etapa de SubBytes e recontruindo o Estado anterior.
Notas:

*

*A referência original do algoritmo pode ser obtida através do link: http://csrc.nist.gov/publications/fips/fips197/fips-197.pdf

*In the polynomial representation, multiplication in GF(28) (denoted by ⊗) corresponds with the multiplication of polynomials modulo an irreducible polynomial of degree 8. A polynomial is irreducible if its only divisors are one and itself. For the AES algorithm, this irreducible polynomial is:

*The modular reduction by m(x) ensures that the result will be a binary polynomial of degree less than 8, and thus can be represented by a byte. Unlike addition, there is no simple operation at the byte level that corresponds to this multiplication.

*Non-linear substitution table used in several byte substitution transformations and in the Key Expansion routine to perform a one-for-one substitution of a byte value.

*The SubBytes() transformation is a non-linear byte substitution that operates independently on each byte of the State using a substitution table (S-box). This S-box (Fig. 7), which is invertible, is constructed by composing
two transformations.

*In the ShiftRows() transformation, the bytes in the last three rows of the State are cyclically shifted over different numbers of bytes (offsets). The first row, r = 0, is not shifted.

*The MixColumns() transformation operates on the State column-by-column, treating each column as a fourterm polynomial as described in Sec. 4.3. The columns are considered as polynomials over GF(28 ) and multiplied modulo x 4 + 1 with a fixed polynomial a(x), given by:
Fontes:
BOND, Martin et al. Aprenda J2EE em 21 dias. [S.l.]: Pearson Education do Brasil, 2003.
CORMEN, Thomas H. et al. Algoritmos: teoria e prática. Rio de Janeiro: Ed. Elsevier, 2002.
FOROUZAN, Behrouz A.; FEGAN, Sophia Chung. Comunicação de Dados e Rede de
Computadores. [S.l.]: McGraw-Hill, 2008.
KUROSE, James F.; ROSS, Keith W. Rede de Computadores e a Internet: uma abordagem top-down. [S.l.]: Pearson Education, 2010.
RAPPAPORT, Theodore S. Comunicação sem fio: princípios e aplicações. [S.l.]: Pearson Prentice Hall, 2009.
NIST. Announcing the advanced encryption standard (aes). Federal Information - Processing Standards Publication 197, n. 197, p. 51, 2001. Disponível em: <csrc.nist.gov/publications/fips/fips197/fips-197.pdf>.
Agradecimentos:
Ao usuário mgibsonbr que respondeu inicialmente esta pergunta e se mostrou solidário tirando minhas dúvidas nos comentários e no chat privado. Muitíssimo grato! Sem o seu conhecimento e a sua solidariedade, jamais teria elaborado essa resposta e meu conhecimento sobre o algoritmo AES (que ainda não é completo e ainda preciso estudar muito) tenderia a zero.

A: Em criptografia, o Advanced Encryption Standard (AES, ou Padrão de Criptografia Avançada em português), também conhecido por Rijndael, é uma cifra de bloco adotada como padrão de criptografia pelos EUA.
Espera-se que seja utilizado em todo o mundo e analisado extensivamente, assim como foi seu predecessor, o data Encryptation Standard (DES). O AES foi anunciado pelo NIST (Instituto Nacional de Padrões e Tecnologia dos EUA) como U.S. FIPS PUB (FIPS 197) em 26 de novembro de 2001, depois de 5 anos de um processo de padronização. Tornou-se um padrão efetivo em 26 de maio de 2002. Em 2006, o AES já é um dos algoritmos mais populares usados para criptografia de chave simétrica.
O AES tem um tamanho de bloco em 128 bits e uma chave com tamanho de 28, 192 ou 256 bits, enquanto o Rijndael pode ser espeficiado com chaves e tamanhos de bloco de qualquer múltiplo de 32 bits, com um mínimo de 128 bits e um máximo de 256 bits.
A chave é expandida usando-se o agendamento de chaves do Rijndael. A maioria dos cálculos do AES é feita em um campo finito próprio. O AES opera sobre um arranjo bidimensional de bytes com 4x4 posições, denominado estado (as versões do Rijndael com um tamanho de bloco maior têm colunas adicionais no estado).

Para criptografar, cada turno do AES (exceto o último) consiste em quatro estágios (como já estão ilustrados nas demais respostas):

*

*AddRoundKey - cada byte do estado é combinado com a subchave própria do turno (RoundKey); cada subchave é derivada da chave principal usando o algoritmo de agendamento de chaves.

*SubBytes - é uma etapa de substituição não linear onde cada byte é substituído por outro de acordo com uma tabela de referência.

*ShiftRows - é uma etapa de transposição onde cada fileira do estado é deslocada de um determinado número de posições.

*MixColumns - é uma operação de mescla que opera nas colunas do estado e combina os quatro bytes de cada coluna usando uma transformação linear. O turno final substitui o estágio de MixColumns por um novo estágio de AddRoundKey.


text:
Q: Latex + Source Code Import I'm using Latex to write a program listing all my code and I am following this:
http://texblog.wordpress.com/2008/04/02/include-source-code-in-latex-with-listings/
It works, but my code runs of the side of the page. How can I fix this?
Additional question: How can I get it to highlight syntax? I do have lang set to Java.

A: Try something like this:
\documentclass{article}

\usepackage{listings}
\usepackage{color}
\usepackage{textcomp}
\definecolor{listinggray}{gray}{0.9}
\definecolor{lbcolor}{rgb}{0.9,0.9,0.9}
\lstset{
    language=c,
    basicstyle=\scriptsize,
    upquote=true,
    aboveskip={1.5\baselineskip},
    columns=fullflexible,
    showstringspaces=false,
    extendedchars=true,
    breaklines=true,
    showtabs=false,
    showspaces=false,
    showstringspaces=false,
    identifierstyle=\ttfamily,
    keywordstyle=\color[rgb]{0,0,1},
    commentstyle=\color[rgb]{0.133,0.545,0.133},
    stringstyle=\color[rgb]{0.627,0.126,0.941},
}

\begin{document}

\begin{lstlisting}

#include <stdio.h>

int main()
{
    // A line comment
    printf("A really, really, really, really, really, really, really, really, really, really, really, really, really, really, really, really, REALLY long line. && & \n");
    return 0;
}

\end{lstlisting}

\end{document}

which produces:
alt text http://img260.imageshack.us/img260/1608/codes.png

A: Did you consider
\lstset{...}
breaklines=true -> sets automatic line breaking
breakatwhitespace=false -> automatic breaks happen at whitespace

?

A: You want to turn on line breaking with
\lstset{breaklines=true}

in the command options. Now you might no like its choices but that is another question.

A: Instead of including the source directly, include it from a file:
\lstinputlisting{/Volumes/docs/p2k_files_in_qt.sh}

You'll save lots of work doing it that way. Alternatively, if you have to include source into the file, there's lgrind.
\lstset{ %
language=C,                             % choose the language of the code
basicstyle=\footnotesize,       % the size of the fonts that are used for the code
numbers=left,                   % where to put the line-numbers
numberstyle=\footnotesize,      % the size of the fonts that are used for the line-numbers
stepnumber=1,                   % the step between two line-numbers. If it's 1 each line will be numbered
numbersep=5pt,                  % how far the line-numbers are from the code
%backgroundcolor=\color{Blue},  % choose the background color. You must add \usepackage{color}
showspaces=false,               % show spaces adding particular underscores
showstringspaces=false,         % underline spaces within strings
showtabs=false,                 % show tabs within strings adding particular underscores
frame=single,                   % adds a frame around the code
tabsize=2,                          % sets default tabsize to 2 spaces
captionpos=b,                   % sets the caption-position to bottom
breaklines=true,                % sets automatic line breaking
breakatwhitespace=false,        % sets if automatic breaks should only happen at whitespace
escapeinside={\%*}{*)},         % if you want to add a comment within your code
% size, font
commentstyle=\fontsize{7}{7}\selectfont,
basicstyle=\ttfamily\fontsize{7}{7}\selectfont,
keywordstyle=\color{red},
commentstyle=\color{blue},
stringstyle=\color{green}
}

A: Use breaklines=true e. g.:
\lstnewenvironment{bash}
    {\lstset{language=bash,breaklines=true,frame=trBL}}
    {}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Find $h'(0)$ given $h(z)=(e^{z\,g(z)})/(g^2(z)+1)$ and $h'(0)=2\,h(0)$
Let $g$ and $h$ two entire functions such that $$h(z)=\frac{e^{z\,g(z)}}{g^2(z)+1}$$ and $$h'(0)=2\,h(0)$$
Find $h'(0)$

Here is my attempt below. Could someone check if it is correct? Many thanks.
The function $h$ is entire, so has no pole. It also has no zero since $e^{z\,g(z)}\gt0, \forall z\in \mathbb{C}$.
I also note that $h$ is of the form $h=e^{\phi}\,\psi$ with $ \phi(z)=z\,g(z)$ and $\psi=1/(g^2(z)+1)$.
The function $g$ is entire and so is $z\,g(z)$. Hence, $\psi$ and $h$ have the same number of poles and zeros, i.e. none. Hence $\log(h(z))$ is well defined.
Therefore, by the argument principle, $\oint_C{\frac{h'(z)}{h(z)}}=\log(h(z))=2\pi i\,(N-P)$ with $N=0$ and $P=0$ around an arbitrary closed path $C$ in $\mathbb{C}$.
So I get
$$\log(h(z))=z\,g(z)-\log(g^2(z)+1)=0$$ and for $z=0$
$$\log(g^2(0)+1)=0$$
Since $$h'(0)=2\,h(0)=1/(g^2(0)+1)$$ I obtain $$\log(2/h'(0))=0$$
That is, $h'(0)=2$.

A: It is true that there is a well defined branch of $\log h$, and this implies $\int_\gamma{h'(z)\over h(z)}\>dz=0$ for closed curves $\gamma$, but it does not imply $\log\bigl(h(z)\bigr)=0$, as claimed in your argument.
Since $h$ is entire and $e^{z g(z)}\ne0$ it follows that the entire function $g$ is $\ne\pm i$ for all $z\in{\mathbb C}$. From this we conclude by Picard's theorem that the function $g$ is in fact a constant. It follows that
$$h(z)={e^{gz}\over g^2+1},\qquad h'(z)=g h(z)\ ,$$
so that the equation $h'(0)=2h(0)$ leads to $g=2$, and this in turn gives
$$h'(0)=2h(0)=2\cdot {1\over 4+1}={2\over5}\ .$$


text:
Q: django-hvad - how should I set a translated field value while saving a model instance? Background: I use django-hvad and have a TranslatableModel. In its TranslatedFields I have a slug attribute which should be automatically created using the title attribute while saving the model.
Problem: It is difficult to set the value of one of the TranslatedFields while saving the instance. A solution that works is to override the save_translations method of my TranslatableModel as follows. Only the second last line differs from the original:
    @classmethod
    def save_translations(cls, instance, **kwargs):
        """
        The following is copied an pasted from the TranslatableModel class.
        """
        opts = cls._meta
        if hasattr(instance, opts.translations_cache):
            trans = getattr(instance, opts.translations_cache)
            if not trans.master_id:
                trans.master = instance
            # The following line is different from the original.
            trans.slug = defaultfilters.slugify(trans.title)
            trans.save()

This solution is not nice, because it makes use of copy and paste. Is there a better way to achieve the same?

A: The following answer assumes that you are using the admin system to auto-generate slug from title.  This may or may not be your exact situation but it may be relevant.
This is an extension of the explanation within the Django-hvad project pages.
The way to implement your feature is within the the admin.py file within your app.  You need to extend the __init__() method of the TranslatableAdmin class.
Say, for example, your model is called Entry.  The simplified code in models.py could be along the lines of the following:
from django.db import models
from hvad.models import TranslatableModel, TranslatedFields

class Entry(TranslatableModel):
    translations = TranslatedFields(
        title=models.CharField(max_length=100,),
        slug=models.SlugField(),
        meta={'unique_together': [('language_code', 'slug')]},
    )
    def __unicode__(self):
        return self.lazy_translation_getter('title')

Your corresponding admin.py file should then be as follows:
from django.contrib import admin

from hvad.admin import TranslatableAdmin

from .models import Entry

class EntryAdmin(TranslatableAdmin):
    def __init__(self, *args, **kwargs):
        super(EntryAdmin, self).__init__(*args, **kwargs)
        self.prepopulated_fields = {'slug': ('title',)}

admin.site.register(Entry, EntryAdmin)

A: Using django-hvad 1.5.0.
Use case: setting the value of a TranslatableModel field outside outside the Django Admin.
# self is a TranslatableModel instance with `translations`
# this first line will initialize the cache if necessary
slug = self.lazy_translation_getter('slug')
translation = get_cached_translation(self)
translation.master = self
translation.slug = defaultfilters.slugify(self.title)  # whatever value
translation.save()


text:
Q: How to flip an Android image All I what to do is change my texture so it facing the other way in the x direction. I tried making the scaleX to be -1 and I also tried making RotX = 1 and angle = 180, but when I changed the values of scaleX or rotate, it also change my positions which I do not want. here is my code for the draw method. is my format wrong?
public void draw(GL10 gl) {

gl.glLoadIdentity();
    gl.glTranslatef(position.x, position.y, 0);
    gl.glRotatef(angle, rotX, rotY, rotZ);
    gl.glScalef(scaleX, scaleY, scaleZ);

    gl.glBindTexture(GL10.GL_TEXTURE_2D, textureId[0]);

    gl.glEnableClientState(GL10.GL_VERTEX_ARRAY);
    gl.glEnableClientState(GL10.GL_TEXTURE_COORD_ARRAY);
    gl.glEnable(GL10.GL_BLEND);

    gl.glVertexPointer(2, GL10.GL_FLOAT, 0, vertexsBuffer);
    gl.glTexCoordPointer(2, GL10.GL_FLOAT, 0, textureBuffer);

    gl.glDrawElements(GL10.GL_TRIANGLES, indices.length, GL10.GL_UNSIGNED_SHORT, indexBuffer);

    gl.glDisableClientState(GL10.GL_VERTEX_ARRAY);
    gl.glDisableClientState(GL10.GL_TEXTURE_COORD_ARRAY);
    gl.glDisable(GL10.GL_BLEND);

    if(animation == true){
        PlayAnimations();
    }

}

A: Set the matrix mode to GL_TEXTURE and issue a glScalef(-1.0, 1.0, 1.0) before rendering.


text:
Q: What is the use of TNS_ADMIN variable in Oracle? Please tell me what is the use of TNS_ADMIN parameter in Oracle? I am working on Unix using oracle database.
Is this parameter is required to locate the sqlplus. I am executing a script in which a update query is executed on Oracle Database.
The script fails with 127 error code when executed with crontab.
The script contents I suspect (eval) failing are
----------
cmd='sqlplus ${ORALOGIN} < SQLS
----------
eval $cmd

A: TNS_ADMIN tells sqlplus where to find the tnsnames.ora file.
If you are running sqlplus from a crontab then the normal reason for having difficulty are:

*

*Incorrect path

*Not having the correctly set ORACLE_SID or other Oracle connection information

*A startup/login script that is getting executed when you login to the system that is interfering with your cron execution

*Some script that you run from the command line when you login that sets up your Oracle environment that is not getting executed in your crontab.

Check these things and other environment related items.  It always takes me a number of passes to get crontab and Oracle to work happily together.


text:
Q: Composite ID in hierarchical REST API Suppose the following:
Building has 0...n Rooms, Room has 0...n Seats.
I am implementing a REST API which accepts data from different companies, with the caveat that the companies must be able themselves define the id (reference) of the entity. I'm generally unable to make any assumptions about those ids, other than being compatible with a HTTP URL. This means there's no guarantee ids are unique across companies, or even within a company (e.g. two rooms could have the same id but be linked to different buildings).
Since its possible that two companies would have the same id for a Building, I've decided to treat companyId and buildingReference as a composite id. The API endpoints I came up with are as follows:
buildings/
buildings/{companyId}/{buildingReference}/rooms
buildings/{companyId}/{buildingReference}/rooms/{roomReference}/seats
etc.
I have some doubts whether this is a good idea. Among other things:

*

*Most APIs I've come across only use a singular id

*If I ever decide to expose GET /rooms or /seats, I'd have to return more and more fields to make the resource uniquely identifiable, companyId, buildingReference, roomReference for room and companyId, buildingReference, roomReference, seatReference for seat

I could possibly get rid of companyId by requiring that the buildingReference be some kind of String concatenation of the two, e.g. CompanyOne-1234, but that doesn't strike me as a great idea either.
Are composite keys like this a good idea? Are there better alternatives?

A: One alternative is to generate ids that you use yourself. Have the companies POST something, they get the URI for that resource. They don't really have to know how it is managed on your side, do they?
Also, if you are doing a straight CRUD thing, you might get away with a database with a HTTP interface. You don't have to code anything.

A: Composite keys are a pain in the arse and should be avoided.
But what to do here, where you have a clear "human use" Id's Room "1A" in building "North Terminal"?

*

*Force a system assigned GUID and use the eternal ID as a separate 'Name' field which is only used for display.
Great for APIs, but you lose the nice human readable url

*Reject item creation if the ID conflicts with another company/building
Likely simply forces the user to start making composite IDs

*Search on the human ID but use other meta data to work out which one you want. ie you may know the company the user is assigned to from their login.
Fails for users that can see more than one company and doesn't help with duplicates within a company such as buildings.
In almost all cases solution 1 is the best. The only down side is that the API isn't human readable. but APIs are not designed to be used by humans anyway.
Solution 2 is arguably better, but relies on the user understanding the potential problems with different ID creation schemes. You don't want annoyed and confused users who have created rooms 1 through 4 but now find they cant use "5" because its been used by someone else.

A: The scenario you outline is quite messy so you'll need to put some order in there yourself.
First things first: resources.
I believe your resources are the fallowing:

*

*companies

*buildings

*rooms

*seats

So you should have the fallowing CRUD endpoints:

*

*/companies and /companies/:companyIternalID

*/buildings and /buildings/:buildingInternalID

*/rooms and /rooms/:roomInternalID

*/seats and /seats/:seatInternalID
Now you can have nesting if you wish too:

*

*/companies/:companyIternalID/buildings

*/buildings/:buildingInternalID/rooms

*/rooms/:roomInternalID/seats
I think it's better avoid any further nesting like /companies/:companyIternalID/buildings/:buildingInternalID/rooms because it's kinda ugly and you can as well start with the buildings resource since the companyIternalID in this case won't add any useful information to the selection.
Ok so now you have your cool CRUD endpoints based on your own unique identifiers you can start from!
The idea that clients should make up their own unique identifiers is quite weird itself right? I mean UUIDs are created when you insert data in the DB so it's perfectly normal for companies to make up their not-so-unique identifiers themselves (because it's not their job to make up unique ones!).
So now the problem is how to select all the rooms in a given building of a given company like you wrote in your endpoint?
buildings/{companyId}/{buildingReference}/rooms
my suggestion is to use query-string parameters to define filters like this:
/rooms?company=companyId&building=buildingReference
This would return any room that has a given company and building reference.

A: You can do something like this:
/business/{businessId}/building/{buildingId}/room/{roomId}
Alternatively, if you do not want to expose hierarchy via URL then you can always do something like:

*

*/business/{businessId}

*/building/{businessId}-{buildingId}

*/room/{businessId}-{buildingId}-{roomId}
This of course assumes that dash - can not be a part of an Id so it will not work with Guid identifiers.
Of course if you can use your own internal IDs then its simple because you are in control.


text:
Q: How can I add a border to an image that has padding? I have an image on my webpage that I added padding to so it wouldn't be in the corner. I also wanted to give it a border but the border is showing up around the empty space instead of just the image... What am I doing wrong?
The image also has a float attribute.
img {
  float: right;
  width: 300px;
  padding: 25px;
  border-style: solid;
  border-color: #fdb924;
}

A: Give the image a margin instead of padding:

img {
  float: right;
  width: 300px;
  margin: 25px;
  border-style: solid;
  border-color: #fdb924;
}
<img src="https://via.placeholder.com/250">

A: Change the padding to margin. padding is the space between the border and the image, while margin is the space between the border and everything outside of it: https://jsfiddle.net/632t5g8x/


text:
Q: How can I unpublish/delete a comment of an Facebook Ad? I need a solution where I can unpublish/delete comments on Facebook Ads. There are paid tools which have this feature, like this one:
https://www.agorapulse.com/blog/comments-facebook-dark-unpublished-posts

"Finding and responding to these comments was a major headache, so we
  went digging on Facebook's API and found a solution to include all
  comments made on dark/Unpublished posts and we included them in our
  unified Facebook Inbox."

With the normal command endpoint I can't get the commands for ads.
How I can access and manage the commands, which API endpoints I need?

A: There are a few endpoints you'll most likely be interested in:
1) Your ads are connected to a page, so you'll need to get data for your Page. See https://developers.facebook.com/docs/pages/managing for reference.
2) Your page contains the posts. See the section titled "Getting Page Posts" in the link from step 1.
3) The posts contain comments. Using the id of the post, make the appropriate API calls to get its posts. See https://developers.facebook.com/docs/graph-api/reference/v2.9/object/comments/ for reference.
4) Once you find the comment you want to delete, make the appropriate DELETE call on it. See graph-api/reference/v2.9/comment/ for reference.


text:
Q: Can not add library after import project from Eclipse to Android Studio I have recently imported project from Eclipse to Android Studio and now I am trying to add third-part library to my project in Android Studio, and here is my problem.
My code is below:
apply plugin: 'com.android.library'

dependencies {
compile ('com.google.android.gms:play-services:7.8.0'){
    force = true
}
compile 'com.sromku:simple-fb:4.0.6'
compile files('libs/android-async-http-1.4.2.jar')
compile files('libs/google-api-client-1.4.1-beta.jar')
compile files('libs/FlurryAgent.jar')
}

android {
compileSdkVersion 22
buildToolsVersion "23.0.0 rc3"

sourceSets {
    main {
        manifest.srcFile 'AndroidManifest.xml'
        java.srcDirs = ['src']
        resources.srcDirs = ['src']
        aidl.srcDirs = ['src']
        renderscript.srcDirs = ['src']
        res.srcDirs = ['res']
        assets.srcDirs = ['assets']
    }

    instrumentTest.setRoot('tests')

    debug.setRoot('build-types/debug')
    release.setRoot('build-types/release')
}
}

In this case I have a problem with adding 'com.sromku:simple-fb:4.0.6'.
On each sync Android Studio is displaying this message:
Error:(8, 13) Failed to resolve: com.sromku:simple-fb:4.0.6

My top-level build.gradle file is:
buildscript {
repositories {
    jcenter()
}
dependencies {
    classpath 'com.android.tools.build:gradle:1.2.3'
}
}

Any idea how to resolve this problem?

After long reasearch I find the solution ;)
As you see on the this image
solution  after importing project to Android Studio in Project Structure field "Default Library Repository" was empty. When I have filled it with the same text as Android Plugin Repository field evrything have started working ;)
Enjoy ;)


text:
Q: How to mark view do not need layout_width and layout_height in Android XML layout Define some custom views with default layout_width and layout_height by override SetLayoutParams and Constructor method.  But Android Studio reports View need layout_width and layout_height.
TableRow do not need layout_width and layout_height as docs says.

A: When an Activity receives focus, it will be requested to draw its layout. The Android framework will handle the procedure for drawing.

When a View object's measure() method returns, its getMeasuredWidth() and getMeasuredHeight() values must be set, along with those for all of that View object's descendants.

So initially you have to set the layout_width and layout_height of a view and afterwards you can change it dimension and visibility according to your requirements.
You can read more about it here.


text:
Q: Find a key in a hash whose value is not the given value How can I find the first key in a hash that has a value which isn't equal to a given value? Given the following hash and the value 100,
h = { "a" => 100, "b" => 100, "c" => 800, "d" => 500 }

I want to find "c" => 800.

A: You can do this:
no_match_value = 100

h.find { |k,v| v != no_match_value }.first #=> "c"

It's unusual to look for a key or value that is in a particular location in a hash, but (since Ruby v1.9) you can do that. The ordering is determined by key-insertion order. Until v1.9 there was no concept of hash keys being ordered, just as elements of a set are not ordered. Some Rubiests consider key ordering to be heresy; others, myself included, have found good uses for it.

A: You can use select
Hash[*h.select {|_, v| v != 100}.first]
#=> {"c"=>800}

It returns an empty hash {} if there is no match.
Without the Hash[] part, it returns an array with key and value.

A: You can do:
h = { "a" => 100, "b" => 100, "c" => 800, "d" => 500 }
h.reject!{|k,v| v == 100}

# h = {"c"=>800, "d"=>500}

The resulting hash will have all key/value pairs where the value isn't 100.

A: Assuming you want to find the key, below code will work:
h = { "a" => 100, "b" => 100, "c" => 800, "d" => 500 }
result = h.detect{ |k,v| v != 100 }.first


text:
Q: Incrementing numbers
*

*I have a variable value which tracks whether the number is odd or even.

*I intialized a int value = 0;

*The variable "value" is now 0, After clicking 2 times, the system will print out "even" and after one second, the variable "value" will be incremented by 1;

*The variable "value" is now 1, it's odd number so it will print out, "odd" and after one second, the variable value will be incremented by 1;

*The variable "value" is now 2, it's even number so it will again allow the user to onClick on the JFrame 2 times. After clicking 2 times, the system will print out "even" and after one second, the
variable "value" will be incremented by 1;

*The variable "value" is now 3, it's odd number so it will print out, "odd" and after one second, the variable value will be incremented by 1;
and so on...
This goes on until I close the program.

I placed the "value" inside my timer and increment it but however the "value" is not incrementing after the countdown. why is it not incrementing? please help.
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
import javax.swing.Timer;

@SuppressWarnings("serial")
public class OnClickLesson extends JFrame   {

    private int value = 0, clicked = 0, countdown = 1;
    private Timer timer = new Timer(1000, null);
    public OnClickLesson() {
        timer = new Timer(1000, new countDownTimer());

        addMouseListener(new MouseAdapter() {
            @Override
            public void mousePressed(MouseEvent e) {
                if(value%2 == 0) {
                    clicked++;
                    if(clicked == 2) {
                        System.out.println("even");
                        timer.start();
                    }
                }
            }
        });

        if(value%2 == 1) {
            System.out.println("odd");
            timer.start();
        }

        setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        pack();
        setSize(400,600);
        setLocationRelativeTo(null);
        setVisible(true);
    }

    private class countDownTimer implements ActionListener {
        @Override
        public void actionPerformed(ActionEvent e) {

            if (countdown == 0) {
                timer.stop();
                countdown = 1;
                value++;
            }

            else {
                System.out.println("Countdown " + countdown--);
            }
        }
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                new OnClickLesson();
            }
        });
    }
}

A: I think you've made a small logical error in your code...
If you take a look at this section...
addMouseListener(new MouseAdapter() {
    @Override
    public void mousePressed(MouseEvent e) {
        if(value%2 == 0) {
            clicked++;
            if(clicked == 2) {
                System.out.println("even");
                timer.start();
            }
        }
    }
});

if(value%2 == 1) {
    System.out.println("odd");
    timer.start();
}

I believe the if(value%2 == 1) {... statement is suppose to be inside the mousePressed method...
addMouseListener(new MouseAdapter() {
    @Override
    public void mousePressed(MouseEvent e) {
        if(value%2 == 0) {
            clicked++;
            if(clicked == 2) {
                System.out.println("even");
                timer.start();
            }
        } else if(value%2 == 1) {
            System.out.println("odd");
            timer.start();
        }
    }
});

This way, when the mousePressed is called, it can equally evaluate both states.
Also, I think you should probably reset the clicked value
clicked++;
if(clicked == 2) {
    System.out.println("even");
    timer.start();
    clicked = 0;
}

Otherwise you will never be able to trigger the "even" section again...


text:
Q: Из БД не выводятся таблицы с id > 10 Вывожу данные из таблицы таким образом: (фаил Function.php)
function get_tests(){
    global $db;
    $query = "SELECT * FROM test WHERE enable = '1'";
    $res = mysqli_query($db, $query);
    if(!$res) return false;
    $data = array();
    while($row = mysqli_fetch_assoc($res)){
        $data[] = $row;
    }
    return $data;
}

/**
* получение данных теста
**/
function get_test_data($test_id){
    if( !$test_id ) return;
    global $db;
    $query = "SELECT q.question, q.parent_test, a.id, a.answer, a.parent_question, q.correct_answer
        FROM questions q
        LEFT JOIN  answers a
            ON q.id = a.parent_question
        LEFT JOIN test
            ON test.id = q.parent_test
                WHERE q.parent_test = $test_id AND test.enable = '1'
                ORDER BY rand()
";
    $res = mysqli_query($db, $query,);
    $data = null;
    while($row = mysqli_fetch_assoc($res)){
        if( !$row['parent_question'] ) return false;
        $data[$row['parent_question']][0] = $row['question'];
        $data[$row['parent_question']][1] = "0%";
        $data[$row['parent_question']][2] = "25%";
        $data[$row['parent_question']][3] = "50%";
        $data[$row['parent_question']][4] = "75%";
        $data[$row['parent_question']][5] = "100%";
        $data[$row['parent_question']]["correct_answer"] = $row[ 'correct_answer'];
    }
    return $data;
}

    function get_correct_answers($test) {
        if( !$test ) return false;
        global $db;
        $query = "SELECT q.id AS question_id, a.id AS answer_id, q.correct_answer
            FROM questions q
            LEFT JOIN answers a
                ON q.id = a.parent_question
            LEFT JOIN test
                ON test.id = q.parent_test
                    WHERE q.parent_test = $test AND a.correct_answer = '1' AND test.enable = '1'";
        $res = mysqli_query ($db, $query);
        $data = null;
        while($row = mysqli_fetch_assoc($res)){
            $data[$row['question_id']] = $row['correct_answer'];
        }
        return $data;
    }

Добавляю в БД записи (Через phpMyAdmin):
INSERT INTO `questions` (`id`, `question`, `parent_test`, `correct_answer`) VALUES
(1, 'Первая', 1, 1),
(2, 'Вторая', 1, 1),
(3, 'Третья', 1, 1),
(4, 'Четвертая', 1, 1),
(5, 'Пятая', 1, 1),
(6, 'Шестая', 1, 1),
(7, 'Седьмая', 1, 1),
(8, 'Восьмая', 1, 1),
(9, 'Девятая', 1, 1),
(10, 'Десятая', 1, 1),
(11, 'Одинадцатая', 1, 1);

Вывожу в индексном файле:
<?php print_arr($test_data) ?>

В ответ получаю пустоту, НО если убираю 11 пункт - получаю:
Array
(
    [2] => Array
        (
            [0] => Вторая
            [1] => 0%
            [2] => 25%
            [3] => 50%
            [4] => 75%
            [5] => 100%
            [correct_answer] => 1
        )

    [5] => Array
        (
            [0] => Пятая
            [1] => 0%
            [2] => 25%
            [3] => 50%
            [4] => 75%
            [5] => 100%
            [correct_answer] => 1
        )

    [3] => Array
        (
            [0] => Третья
            [1] => 0%
            [2] => 25%
            [3] => 50%
            [4] => 75%
            [5] => 100%
            [correct_answer] => 1
        )

    [6] => Array
        (
            [0] => Шестая
            [1] => 0%
            [2] => 25%
            [3] => 50%
            [4] => 75%
            [5] => 100%
            [correct_answer] => 1
        )

    [10] => Array
        (
            [0] => Десятая
            [1] => 0%
            [2] => 25%
            [3] => 50%
            [4] => 75%
            [5] => 100%
            [correct_answer] => 1
        )

    [1] => Array
        (
            [0] => Первая
            [1] => 0%
            [2] => 25%
            [3] => 50%
            [4] => 75%
            [5] => 100%
            [correct_answer] => 1
        )

    [9] => Array
        (
            [0] => Девятая
            [1] => 0%
            [2] => 25%
            [3] => 50%
            [4] => 75%
            [5] => 100%
            [correct_answer] => 1
        )

    [4] => Array
        (
            [0] => Четвертая
            [1] => 0%
            [2] => 25%
            [3] => 50%
            [4] => 75%
            [5] => 100%
            [correct_answer] => 1
        )

    [7] => Array
        (
            [0] => Седьмая
            [1] => 0%
            [2] => 25%
            [3] => 50%
            [4] => 75%
            [5] => 100%
            [correct_answer] => 1
        )

    [8] => Array
        (
            [0] => Восьмая
            [1] => 0%
            [2] => 25%
            [3] => 50%
            [4] => 75%
            [5] => 100%
            [correct_answer] => 1
        )

)

Если ID записи до 10 (включительно) - всё выводится, но если появляется 11 - var_damp ничего не возвращает.
То есть, если ID пишу любой выше 10 - ничего не возвращается.
Структура ID - int(10) UNSIGNED AI
P.S.
Гуглил уже всё, что можно. Такое ощущение сложилось, что подобной ошибки ни у кого не бывает.

A: Вот один из запросов из кода:
SELECT q.id AS question_id, a.id AS answer_id, q.correct_answer
FROM questions q
LEFT JOIN answers a ON q.id = a.parent_question
LEFT JOIN test ON test.id = q.parent_test
WHERE q.parent_test = $test AND a.correct_answer = '1' AND test.enable = '1'

Запрос - неверный. Он превращает LEFT JOIN в INNER JOIN - следует ли удивляться, что результат далёк от желаемого?
Должно быть
SELECT q.id AS question_id, a.id AS answer_id, q.correct_answer
FROM questions q
LEFT JOIN answers a ON q.id = a.parent_question AND a.correct_answer = '1'
LEFT JOIN test ON test.id = q.parent_test AND test.enable = '1'
WHERE q.parent_test = $test


text:
Q: Re-use of texture unit for different texture types breaks in chrome check out the following test:
http://binks.knobbits.org/webgl/texture3.html
It's a simple test of cube textures.  It also has a 2D texture in there for good measure.
I discovered that in some browsers (so far, chrome) The image is not displayed properly if I re-use the same texture unit for drawing the cube texture as for the 2D texture.
There is a checkbox at the bottom marked "Use separate texture units for the cube texture on the sphere and the 2D texture on the floor" that shows this.
Is this a bug in chrome or in my code?

A: I don't see anything wrong with your code but
1) You can't use the same texture for 2 different targets. In other words you can't do this
tex = gl.createTexture();
gl.bindTexture(gl.TEXTURE_2D, tex);
gl.bindTexture(gl.TEXTURE_CUBE_MAP, tex);

2) You can't use both a TEXTURE_2D and a CUBE_MAP on a texture unit AT THE SAME TIME.
You can assign both, but when you render you're only allowed to reference one of them in your shaders. In other words.
gl.activeTexture(gl.TEXTURE0);
tex1 = gl.createTexture();
tex2 = gl.createTexture();
gl.bindTexture(gl.TEXTURE_2D, tex1);
gl.bindTexture(gl.TEXTURE_CUBE_MAP, tex2);

Is okay but a shader that tried use both textures from texture unit 0 would fail.

A: I have ordered a bit the code of the drawing functions and now are working.
Square:
TexturedSquare.prototype.draw = function() {
    gl.bindBuffer(gl.ARRAY_BUFFER,this.v);
    gl.enableVertexAttribArray(gl.va_vertex);
    gl.enableVertexAttribArray(gl.va_normal);
    gl.enableVertexAttribArray(gl.va_tex1pos);
    gl.vertexAttribPointer(gl.va_vertex,4,gl.FLOAT,false,10*4,0);
    gl.vertexAttribPointer(gl.va_normal,4,gl.FLOAT,false,10*4,4*4);
    gl.vertexAttribPointer(gl.va_tex1pos,2,gl.FLOAT,false,10*4,4*8);

    gl.activeTexture(gl.TEXTURE0);
    gl.bindTexture(gl.TEXTURE_2D,this.texture);
    gl.bindTexture(gl.TEXTURE_CUBE_MAP,null);

    gl.uniform1i(shader.textures,1);
    gl.uniform1i(shader.texture1,0);
    gl.uniform1i(shader.cube_textures,0);
    gl.uniform1i(shader.cubeTexture0,1);

    gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER,this.e);
    gl.drawElements(gl.TRIANGLES,this.l,gl.UNSIGNED_SHORT,0);

    gl.disableVertexAttribArray(gl.va_tex1pos);
}

Sphere:
GLHTexturedSphere.prototype.draw = function() {
    gl.bindBuffer(gl.ARRAY_BUFFER,this.vbuf);
    gl.enableVertexAttribArray(gl.va_vertex);
    gl.enableVertexAttribArray(gl.va_normal);
    gl.enableVertexAttribArray(this.va_cubetex0pos);
    gl.vertexAttribPointer(gl.va_vertex,4,gl.FLOAT,false,8*4,0);
    gl.vertexAttribPointer(gl.va_normal,4,gl.FLOAT,false,8*4,4*4);
    gl.vertexAttribPointer(this.va_cubetex0pos,4,gl.FLOAT,false,8*4,4*4);

    gl.activeTexture(gl.TEXTURE0);
    gl.bindTexture(gl.TEXTURE_2D,null);
    gl.bindTexture(gl.TEXTURE_CUBE_MAP,this.texture);

    gl.uniform1i(shader.textures,0);
    gl.uniform1i(shader.texture1,1);
    gl.uniform1i(shader.cube_textures,1);
    gl.uniform1i(shader.cubeTexture0,0);

    gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER,this.ebuf);
    gl.drawElements(gl.TRIANGLES,this.l,gl.UNSIGNED_SHORT,0);

    gl.disableVertexAttribArray(gl.va_cubetex0pos);
}

Both of them are using now TEXTURE0. Please check WebGL states and uniform values.
Original code is a bit hard for me, sorry. But I think the problem is that texture1 and cubeTexture0 uniforms are been setted with the same value.


text:
Q: Dropwizard logging: add new appender for a particular logger I'm new to dropwizard and am trying to figure out ways to configure logging better.
I have registered a new logger in a bundle like so:
Logger log = LoggerFactory.getLogger("mylogger");
log.info("this is a log from mylogger");

Now I'm using this bundle in a bunch of services. By default any log that comes through this logger would be written to the application log file.
The problem I'm trying to solve is this: I want all logs written by mylogger(only) to go to a new file. It is fairly starightforward to add a new appender to the service yml file like:
logging:

  loggers:

  appenders:
  - type: file.
    currentLogFilename: ./logs/example.log
    archivedLogFilenamePattern: ./logs/example-%d.log.gz
    archivedFileCount: 5

But this would mean that all of application logs would now be written to example.log. I do not know of a way to specify a logger specifically for this appender which does not affect/alter already existing logging.
Can someone tell me if there's a way to do this in dropwizard? Thanks!

A: In Dropwizard 0.9.0 (released on Oct 28th 2015), they have added support for individual logger appenders and disabling logger additivity.
To achieve what you have described, you can specify the following in your yaml configuration file -
logging:
  level: INFO
  loggers:
    "mylogger":
      level: DEBUG
      additive: false
      appenders:
        - type: file
          currentLogFilename: /var/log/mylogger.log
          archivedLogFilenamePattern: /var/log/mylogger-%d.log.gz
          archivedFileCount: 5
  appenders:
    - type: console

Setting additive to false will prevent the logger (or anything under it) from writing to appenders which are hierarchically above it, including the root logger.
References -

*

*Dropwizard Logging Configuration

*Dropwizard 0.9.0 Release Notes

A: If you are wanting your custom logger to be the only logs in the log file, as well as going into the default appenders, you could create your own appender based on the Dropwizard logging spec.
Requirements:
Custom Appender factory
that extends io.dropwizard.logging.AbstractAppenderFactory (referred to as MyCustomFactory)
Custom configurations can be injected here from your .yml file by creating JsonProperties here, using Hibernate Annotations for any validations you need on the configuration file:
@NotNull
@JsonProperty
private String url;
@JsonProperty
private int maxBufferSize = 100;
@JsonProperty
private int sendDelayInSeconds = 10;

Give the class a @JsonTypeName("YourAppenderName"). This is how you reference the appender in your configuration.
This class needs access to any configuration you want to pass to your appender, since the function of this class is to create your appenders that Dropwizard will use.
Custom Appender
that extends ch.qos.logback.core.AppenderBase(Referred to as MyCustomAppender). You can write your own, or use an existing from from services like Loggly.
Inside the appender, check where the log is coming from and filter what you want to write to a file.
To tell Dropwizard about your new custom factory...
You need a file called io.dropwizard.logging.AppenderFactory placed into your src/main/resources/META-INF/services/ directory.
The contents of this file is the full name (include packages) for your custom Factory. (Example: com.myCompany.appender.MyCustomFactory)
Using the custom appender
In your yml file add the new appender by the name you specified:
appenders:
# Log warnings and errors to stderr
- type: console
  threshold: INFO
  target: stderr
# Custom Logger
- type: YourAppenderName
  threshold: INFO
  url: https://sendYourLogsHere/logs

A: You can refer to the code in dropwizard-logging library for samples.
Check the FileAppenderFactory. It is a good reference point.


text:
Q: String index out of range on space bar character For example the name Donald trump (12 character) brings up the error string index out of range 7 (where the space is found) even though the name Donald trump is longer.
package test;

import javax.swing.JOptionPane;

public class Usernamesubstring {

    public static void main(String[] args) {
        String fullname = JOptionPane.showInputDialog("What is your full name");
        int breakbetween = fullname.lastIndexOf(" ");
        String firstnamess = fullname.substring(breakbetween - 3, breakbetween);
        int length = fullname.length();
        String lastnamess = fullname.substring(length - 3, length);
        String firstnamec = firstnamess.substring(0, 0);
        String lastnamec = lastnamess.substring(breakbetween + 1, breakbetween + 1 );
        firstnamec = firstnamec.toUpperCase();
        lastnamec = lastnamec.toUpperCase();
        String firstname = firstnamess.substring(1,3);
        String lastname = firstnamess.substring(1,3);
        firstname = firstnamec + firstname;
        lastname = lastnamec + lastname;
        System.out.println(firstname + lastname);
}
}

Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 7
at java.lang.String.substring(String.java:1963)
at test.Usernamesubstring.main(Usernamesubstring.java:14)

A: You've made it more complicated than it needs to be. A simple solution can be made using String.split (which divides a string into an array of smaller strings based on a delimiter, e.g. "Donald Trump".split(" ") == {"Donald", "Trump"})
Full Code

class Usernamesubstring // change that since it no longer uses substrings
{
    public static void main (String[] args)
    {
        String fullName = "Donald Trump";
        String[] parts = fullName.split(" ");
        String firstName = parts[0];               // first item before the space
        String lastName = parts[parts.length - 1]; // last item in the array

        System.out.println(firstName + " " + lastName);
    }
}

A: sometimes independent of your indexes
String fullName = "Donald Trump";
String[] result = fullName.split (" ");

in result you will find now
result [0] ==> Donald
result [1] ==> Trump
isn't that a little easier for your project?

A: Your error shoul be in the line  String lastnamec = lastnamess.substring(breakbetween + 1, breakbetween + 1 ); as lastnamess is a string of lenght 3 from fullname.substring(length - 3, length); and breakbetween is greater then 3 for "Donald Trump", where space is character 6.
You should simpify your code a bit, it makes it easier to read and find the problems.

A: tl;dr: The exception occurs when you try to access a String at an index which exceeds it's length or is just not contained in the string (negative values).
Regarding your approach: It's usually not a good idea to prompt a name in full because people tend to input weird stuff or mix up the order. Better prompt for first and last name separately.
Assuming someone input his name with Firstname Lastname you wouldn't have to make such a substring mess, Java has some nice features:
    String name = "Mario Peach Bowser";
    name = name.trim();
    String[] parts = name.split(" ");
    String lastname = parts[parts.length-1];
    String firstname = name.replace(lastname, "").trim();
    System.out.println("Hello "+firstname+", your last name is: "+lastname);

In this case I am using the trim() function to remove whitespaces at the start and end and just split the string when a white space occurs. Since people can have some middle names and stuff, I just replace the last name out of the raw input string, call trim() on it again and you have everything extracted.
If you really want a substring approach, the following would work:
    String lastname = name.substring(name.lastIndexOf(" ")).trim();
    String firstname = name.substring(0,name.lastIndexOf(" ")).trim();

You usually don't store the index variables. But each variant would need some sort of error check, you can either use try{} and catch() or check the String before parsing.

A: Only these lines are required.
String[] nameArr = fullname.split(" ");
String lastN = nameArr[nameArr.length - 1];
int lastIndexOf = fullname.lastIndexOf(lastN);
String firstN = fullname.substring(0, lastIndexOf);
System.out.println(firstN + " " + lastN);


text:
Q: how to best structure application in symfony 2 I started using Symfony 2 after having experience with 5 php frameworks like Zend, CodeIgniter, Fuel, Yii and Cake. I am very confused on how to structure my project as better as I can. First of all I am confused in working with bundles. Bundles are some kind of modules used in other frameworks? Bascially I have my application and everything until now is stored in a bundles. If I want to make some helper functions and some libraries and abstract classes, I just make a new bundle for those?

A: See the Bundle Structure and Best Practices cookbook entry for basic ideas on the structure of a bundle.
I recommend having just one app specific bundle. I call it AppBundle.
Also, you don't have to have everything in bundles. Check this question for details.

A: Lots of other discussions on that matter:

*

*Should everything really be a bundle on Symfony 2?

*Confused with symfony2 bundles


text:
Q: git rebase using sourcetree I think I am confused on how to use SourceTree GUI to do git rebase. I have two branches "master" and "dev". As seen, the two branch diverged. I want to do a rebase on "dev" branch, using command line, this would be:
git checkout dev
git rebase master

I would have expected to right click "dev", and choose "Rebase current changes onto dev". I assume current changes means "new commits on master". But picking this option seems have no effect whatsoever. What would be the correct steps?

A:
But picking this option seems have no effect whatsoever.

Yes, because current changes are the one of the current branches, which is dev.
Rebasing dev on top of dev means an no-op.
git checkout dev
git rebase master

That means: current branch is dev: to be rebased on top of master.
So in SourceTree, you need to right-click on master (while dev is checked out), and select:
Rebase current changes onto master

Howe adds in the comments:

Current Naming of "rebase current changes onto [branch]" is misleading.   Check out this improvement discussion SRCTREE-1578.
After finding myself baffled attempting to bring a feature branch up to date with development and failing, I've come to realize that the left-pane context menu item labeled "rebase current changes onto $somebranch" actually does the opposite of what its name suggests:
  it rebases the current branch to the state of $somebranch;
  In other words it rebases $somebranch onto (or into) the current branch, not the other way around. (Right?)
The preposition "onto" in the current text is misleading; it implies that the object of the sentence ($somebranch in my example) will receive the changes.
  In fact, it is the opposite that will occur.
  The absence of the current branch's name adds to the confusion.
A re-wording that improves the sentence structure and includes the name of the affected branch would afford a huge win for clarity.
  For example:
rebase $currentbranch to head of $somebranch
rebase $somebranch onto $currentbranch


text:
Q: Replace large img src with thumbnail img woocommerce products loop I'm using woocommerce, and by default it use the large image in the product loop.
The goal is that I want to replace each large product image (1000x1000px) with the thumbnail image (300x300px) which is contained in the same folder as the large image.
Here is the html code:

  ...
  ...
  ...

With a total of 24 products per page.
And the jQuery :
I tried to put the jQuery code under the  tag in the child-theme/woocommerce/loop/loop-start.php file before the
, and in my custom.js file, both doesn't work.
jQuery(document).ready(function($) {

 $('.products_container img.wp-post-image').each(function() {
   var $this = $(this);

   $this.attr('src').replace('.jpg', '-300x300.jpg');
 });
});

If I put this code in the browser console, it replace the large image with the thumbnail as I want $('.products_container').find('img.wp-post-image').attr('src').replace('.jpg', '-300x300.jpg');
Any help would be appreciated

A: You can pass a function as the second parameter of .attr( attributeName, function )
The function is called for each element in the set and should return the new value of the attribute you've defined with the first parameter
jQuery(document).ready(function ($) {
    $('.products_container img.wp-post-image')
        .attr('src', function(idx, src) {
            return src.replace('.jpg', '-300x300.jpg');
        });
});


text:
Q: Approaches to Sand on a Conveyor Belt
Say we are given a conveyor belt with sand falling onto it at rate $\Omega$. I am trying to find the power it takes for the belt to operate if it goes forward with constant velocity $v$, but using two different approaches I get two different answers.

*

*The first way, I say that in one second, $\Omega$ amount of sand falls onto the belt, thus every second $\frac 1 2 \Omega v^2$ is required to continue moving the belt forward (simply by looking at kinetic energy difference) and $P=\frac 1 2 \Omega v^2$.

*The second way, I saw that $F=\frac {d(mv)} {dt}$, thus $F=\Omega v$. Finally, $P=Fv$ so $P=\Omega v^2$.
So which one is it: $P=\Omega v^2$ or $P=\frac {1} {2} \Omega v^2$, and where did I make an incorrect assumption in my two methods?

A: Your first answer gives you the rate at which the sand gains kinetic energy whereas your second answer gives you the rate at which work has to be done on the conveyor belt to keep it moving at constant speed.
When the sand falls on the belt in order to accelerate the sand to the same velocity as the belt there must be frictional forces between the sand and the belt.
There must also be relative movement between the belt and the sand during this acceleration phase as the sand cannot instantaneously to the velocity of the belt.
During the acceleration phase when there is slippage between the belt and the sand heat/thermal energy is generated and the rate of heat generation is the difference between your two answers.
So the motor which drives the belt increases the kinetic energy of the sand whilst heat is being generated due to the relative movement between the sand and the belt during the acceleration phase of the sand.

A: I think it is easier to accept that $P = \Omega v^2$, if one shows why the thermal energy generated happens to be excactly $\frac{1}{2}\Omega v^2$. Let an observer $O´$ be in a reference frame which is stationary with respect to the conveyor belt (i.e. $O´$ will be seen to have a velocity $+v$ in the lab - frame). To $O´$ a grain of sand with mass $dm$ will have a velocity $-v$ when falling onto the belt, and will start sliding backwards. Friction will oppose this, and the kinetic energy, $\frac{1}{2}dmv^2$, is converted to thermal energy. $O´$ will measure a temperature increase of the belt (and grain), consistent with this. Another observer $O$ in the lab - frame, will se the conveyor belt moving with velocity $v$, and the grain of sand starting out with zero velocity. Due to friction, it will start sliding along until it reaches velocity $v$, and its kinetic energy is $\frac{1}{2}dmv^2$. At the same time, thermal energy is generated. When $O$ measures the temperatrue increase of the belt, he will get the same readings as $O´$ (temperature being a scalar), and so this energy will be found to be $\frac{1}{2}dmv^2$. By conservation of energy, the energy that must be supplied to the conveyor belt to get a grain of sand up to speed, is $dmv^2$. To match the rate of sand falling onto the belt, the power that must be supplied is therefore $P = \Omega v^2$.

A: The answer by Farcher is right. I will comment further in hopes of increasing clarity and in order to clear up some mistakes introduced in other answers.
This kind of problem can be tackled by considering conservation of momentum. We also have conservation of energy, but that is more difficult to apply correctly because you have to take into account frictional heating.
Let's consider the sand falling during a time $t$ (you can make this a long time if you like). Before falling its momentum (in the direction of the conveyor) was zero. After falling and taking up the motion of the conveyor its momentum is $\Omega t v$. Now you might doubt that, and say that the last little bit of sand only just hit the conveyor so it is not yet moving at speed $v$. But that is a tiny correction which can be ignored in comparison to $\Omega t v$ (and we will argue in the end that it is correct to ignore it completely). The force is applied during the time $t$, so the required force is given by
$$
F t = \Omega t v
$$
so $F = \Omega v$ and $P =\Omega v^2$.
Now let's consider energy. The kinetic energy of the sand accounts for half the power; the other half has gone to heat. A further insight can be obtained by asking what would happen if there were no friction. In that case the sand would slip along the conveyor, it would not be accelerated. So instead let's have it fall into a sequence of containers like train trucks. Then as it falls into each truck, if there is no friction it will slip along the floor (we arrange for no vertical bounce). The end of the truck approaches and then hits the sand. Assuming an elastic collision the sand bounces off and moves off towards the other end. It continues bouncing to and fro inside the truck. This bouncing motion has more kinetic energy than the amount $(1/2) \Omega v^2 t$ where $v$ is the speed of the truck relative to the ground. How much more? The answer is: twice as much.
Now let's go back to the frictional case. The horizontal bouncing which I just described is then happening on a microscopic scale, generating sound waves in the sand and in the conveyor belt. These waves carry away the energy and the sand settles down until it is no longer in motion relative to the belt.

A: I believe the mistake arises from the expression $P = Fv$. Let's see how this equation was derived.
Consider a time interval $\mathrm{d}t$ in which the amount of mass falling is $\mathrm{d}m = \Omega \mathrm{d}t$.
$$F = \frac{\mathrm{d}p}{\mathrm{d}t} = \Omega v$$
Then consider the work done in this time $\mathrm{d}t$.
$$\mathrm{d}W = F \mathrm{d}s$$
Now here is where the mistake arises. If you take $\mathrm{d}s = v\mathrm{d}t$ then you get $P = Fv$.
However not all of the mass $\mathrm{d}m$ is travelling by a distance of $v\mathrm{d}t$. Suppose there are some number of particles falling in $\mathrm{d}t$ time. Then the first particle travels a distance of $v\mathrm{d}t$ however the last particle travels $0$ distance.
So the average distance travelled by the $\mathrm{d}m$ mass in this time interval is $\frac{1}{2}v\mathrm{d}t$. So we have
$$\mathrm{d}W = F \mathrm{d}s = \frac{1}{2}Fv\mathrm{d}t$$
$$P = \frac{1}{2}\Omega v^2$$

A: The work needed to accelerate a mass from rest to a constant speed $v$ is always twice the ultimate kinetic energy of the mass. So, work is $mv^2$ (not $\frac12mv^2$), or in your example $P=\Omega v^2$, since power is work per unit time, and $\Omega=m/t$.
Where did the extra energy go? If you think about it you realize that mass cannot be accelerated instantaneously because that would require an infinite force. There needs to be some stretching between the object that is moving at $v$ and the mass being accelerated. The interconnected objects act like a spring and are loaded with an energy equal to $\frac12mv^2$.
Why is this spring energy the same as the ultimate kinetic energy of the mass? Change your frame of reference from the mass (sand grain) to the object pulling the mass (the conveyor). In this frame the conveyor is stationary and the mass is moving backwards at $v$ and has $KE=\frac12mv^2$. When the mass stops moving relative to the conveyor, all this kinetic energy has been converted into spring energy. So back in the frame of reference of the sand, the total energy required is $mv^2$: half for the kinetic energy of the sand grain, and half for stretching the "spring" between the sand grain and the conveyor belt.

A: Your second approach F=Ωv; but the sand is gaining velocity from zero to v when it is falling onto belt, it is not a uniform velocity in this process. Therefore the power should be dP = Fdv, and hence the answer to your first approach $P=1/2  Ωv^2 $

A: In your second method don't forget f=ma so you still need a 1/2 term to get mass over time. All the sand isn't on the belt yet at t=0.


text:
Q: Swift: Sort Core Data array in a function I have an array of objects from Core Data that I would like to sort in a function in a child view. I know how to sort using .sorted(by:{}), but the problem is assigning the sorted array back to the ObservedObject variable so the UI updates with the sorted data.
In the code below, when I try to do habits = habits.sorted(by:{}), I get the following errors:

*

*Cannot assign to property: 'self' is immutable

*Mark method 'mutating' to make 'self' mutable

*Cannot assign value of type '[FetchedResults.Element]' (aka 'Array') to type 'FetchedResults'

Does anyone know a better way to do this or how to resolve the error?
struct ContentView: View {
    @Environment(\.managedObjectContext) var moc
    @FetchRequest(entity: Habit.entity(), sortDescriptors: [NSSortDescriptor(keyPath: \Habit.id, ascending: true)]) var habits: FetchedResults<Habit>
    var body: some View {
        NavigationView {
            VStack {
                List {
                    ForEach(habits, id: \.self) { habit in
                        VStack(alignment: .leading) {
                            Text(habit.title)
                            HStack {
                                ForEach(habit.dayArray.count-7..<habit.dayArray.count, id: \.self) { index in
                                    DayView(day: habit.dayArray[index], habits: self.habits)
                                }
                            }
                        }
                    }
                }
            }
        }
    }
    struct DayView: View {
        @Environment(\.managedObjectContext) var moc
        @ObservedObject var day: Day
        var habits: FetchedResults<Habit>
        var body: some View {
            Text("\(day.wrappedShort)").onTapGesture {
                self.sortHabits(day: self.day)
            }
        }
        func sortHabits() {
            self.habits = habits.sorted{ $0.title.uppercased() < $1.title.uppercased() }
        }
    }
}


text:
Q: Discrete Cumulative Probability Distribution Given F(x) = P(X <= x) for a discrete random variable
which of the following is generally true
$P(a <= X <= b) = F(b) - F(a),
P(a < X < b) = F(b) - F(a),
P(a <= X < b) = F(b) - F(a),
P(a < X <= b) = F(b) - F(a)$

A: Since the variable is discrete, it is generally correct the following:
$$P(a<x\leq b)=F(b)-F(a)$$


text:
Q: How can i set the 1st column data type as int and float for all the rest of columns? I want to set the 1st column 'ID' as index using numpy only.
import numpy as np
import io
from numpy import genfromtxt

data =io.StringIO("""
ID,1,2,3,4,5,6
5362,0.974,-0.404,-0.763,0.868,-0.5,0.16
485,-0.659,0.531,0.623,0.402,0.772,0.506
582,0.045,0.994,0.762,-0.036,0.117,-0.355
99,0.777,0.537,0.391,0.456,0.329,0.108
75,-0.44,0.522,0.856,-0.04,0.656,-0.935
474,0.357,0.81,0.135,0.389,0.055,0.224
594,-0.291,0.031,0.742,-0.332,0.815,0.983
597,0.968,-0.357,0.591,0.892,0.375,0.88
124,0.737,0.611,0.764,0.289,0.298,-0.705
635,0.883,0.96,-0.987,0.29,0.997,0.186
7894,-0.045,0.047,0.523,0.068,-0.9,0.356
1268,0.561,0.736,-0.375,0.465,0.908,0.2
38,0.465,0.623,0.734,0.145,0.489,0.759
88,0.029,0.166,0.098,0.285,0.18,0.829
887,0.464,0.652,-0.896,0.07,0.772,-0.268
994,-0.611,0.986,0.708,-0.195,0.938,0.166
478,0.109,0.664,0.977,0.2,-0.466,0.676
693,0.893,0.536,0.827,0,0.658,-0.31
455,0.745,0.851,0.025,0.667,0.094,0.127
874,0.036,-0.212,0.879,0.966,0.788,0.719
""")

I have used skip_header=1 but still I am geting the 1st row in my data.So  I have tried the foll.
data = genfromtxt(data, delimiter=',', skip_header=1, dtype=np.float64)
data = np.delete(data, 0, axis = 0)
#Suppose
N=7

Here I want to take the 1st N rows and find the determinant and show the corresponding indexes of the 7 rows as integers.
I
X = data[1:N+1, 1:]
det_X = np.linalg.det(X.T@X)

Expected : But as Integer values instead of float
[[5362.]
 [ 485.]
 [ 582.]
 [  99.]
 [  75.]
 [ 474.]
 [ 594.]]


text:
Q: Mongoose & Bluebird - typical callbacks within promises? Is there a better way to resolve the outer callback without explicitly invoking it from within the then()?  IE next(false) vs next(true).  My current implementation doesn't "feel" correct.  Or perhaps it is, and this is just the nature of writing it.
AccountSchema
  .path('email')
  .validate(function (value, next) {
    this.constructor.findOneAsync({email: value})
      .then(function (user) {
        if (user) {
          next(false);
        }

        next(true);
      });
  },
  'The specified email address is already in use.');


text:
Q: How to BREAK on with multiples tables For example there are three tables that are linked. I know you can use break on to get unique values for a column when using a select statement. My question is how can I use break on with multiple tables joined in a select statement. This is the code I have now.
CLEAR BREAKS
BREAK ON STR.STR_NUM SKIP 1 ON STR.STR_QTY SKIP 1

SELECT STR.STR_NUM, STR.STR_QTY, SUPP.SUPP_ID,SUPP.SUPP_COMP
FROM STR
INNER JOIN SUPPSTR
ON STR.STR_NUM = SUPPSTR.STR_NUM
INNER JOIN SUPP
ON SUPP.SUPP_ID = SUPPSTR.SUPP_ID
ORDER BY STR.STR_NUM,STR.STR_QTY,SUPP.SUPP_ID ASC;

This gives me multiple values of STR_NUM matched with each QTY and COMP of each. However I don't want duplicates of STR_NUM and STR_QTY(only SUPP_ID and SUPP_COMP), which I am trying to accomplish with BREAK on but it's not working.
I can only seem to use Break on with one table.
For example I will get an output like this:
STR_NUM   STR_QTY   SUPP_ID  SUPP_COMP
1001      120       101       AA
1001      120       102       AB
1001      120       103       AC
1002      300       101       AA
1002      300       102       AB
1002      300       103       AC
1002      300       104       AD
1003      100       101       AA
1003      100       102       AB
1003      100       103       AC
1004      50        101       AA
1004      50        102       AB

But what I want is something like this:
STR_NUM   STR_QTY   SUPP_ID  SUPP_COMP
1001      120       101       AA
                    102       AB
                    103       AC

1002      300       101       AA
                    102       AB
                    103       AC
                    104       AD

1003      100       101       AA
                    102       AB
                    103       AC

Thanks

A: 22:24:25 (21)HR@sandbox> select * from (select department_id, job_id, employee_id from employees order by 1,2,3) where rownum < 15;

DEPARTMENT_ID JOB_ID     EMPLOYEE_ID
------------- ---------- -----------
           10 AD_ASST            200
           20 MK_MAN             201
           20 MK_REP             202
           30 PU_CLERK           115
           30 PU_CLERK           116
           30 PU_CLERK           117
           30 PU_CLERK           118
           30 PU_CLERK           119
           30 PU_MAN             114
           40 HR_REP             203
           50 SH_CLERK           180
           50 SH_CLERK           181
           50 SH_CLERK           182
           50 SH_CLERK           183

14 rows selected.

Elapsed: 00:00:00.00
22:24:49 (21)HR@sandbox> break on department_id on job_id
22:24:55 (21)HR@sandbox> /

DEPARTMENT_ID JOB_ID     EMPLOYEE_ID
------------- ---------- -----------
           10 AD_ASST            200
           20 MK_MAN             201
              MK_REP             202
           30 PU_CLERK           115
                                 116
                                 117
                                 118
                                 119
              PU_MAN             114
           40 HR_REP             203
           50 SH_CLERK           180
                                 181
                                 182
                                 183

14 rows selected.

Elapsed: 00:00:00.04

And yeah, this has nothing to do with amount of tables in query. BREAK is not an sql but sqlplus operator which only processes query output and is not impacted by the query details.  Multi-table example:
22:31:07 (21)HR@sandbox> break
break on department_name nodup
          on job_id nodup

22:31:15 (21)HR@sandbox> l
  1  select * from (
  2  select d.department_name, e.job_id, e.employee_id
  3    from employees e join departments d using(department_id)
  4   order by 1,2,3
  5* ) where rownum < 15
22:31:15 (21)HR@sandbox> /

DEPARTMENT_NAME                JOB_ID     EMPLOYEE_ID
------------------------------ ---------- -----------
Accounting                     AC_ACCOUNT         206
                               AC_MGR             205
Administration                 AD_ASST            200
Executive                      AD_PRES            100
                               AD_VP              101
                                                  102
Finance                        FI_ACCOUNT         109
                                                  110
                                                  111
                                                  112
                                                  113
                               FI_MGR             108
Human Resources                HR_REP             203
IT                             IT_PROG            103

14 rows selected.

Elapsed: 00:00:00.10


text:
Q: javascript rickshaw graph auto scale I am plotting with rickshaw graph,  in the y-axis, I need to scale it properly.
I could do something like this:
var graph = new Rickshaw.Graph( {
  element: document.getElementById("chart"),
  renderer: 'multi',
  min:165000000,
  max:176000000,
  width: 1000,
  height: 500,
  ....

but I hope it can automatically scale in the y-axis,  instead of hard code "min" and "max" here.  anyone has a simple example for this?  Thanks

A: It seems that you need to go through all the data in your series, and detect the min and max.
There is an example on the Rickshaw website for scaled series: http://code.shutterstock.com/rickshaw/examples/scaled.html
If you look at the source code, you will see that they're manually going through the series data and finding the data extremums.

A: As ArtBIT suggested you have to go through your array and parse each element in order to find the min and max value.
Let's say that you have an array of prices that are going to be on the graph.
For example:
var y_ticks = new Rickshaw.Graph.Axis.Y( {
  graph: graph,
  orientation: 'left',
  tickFormat: function(y) {return parseInt(y);},
  tickValues: [minArray(prices), maxArray(prices)],
  element: document.getElementById('y_axis')
});

function minArray(a) {
  var min=a[0]; for(var i=0,j=a.length;i<j;i++){min=a[i]<min?a[i]:min;}
  return min;
}

function maxArray(a) {
  var max=a[0]; for(var i=0,j=a.length;i<j;i++){max=a[i]>max?a[i]:max;}
  return max;
}

minArray(a) and maxArray(a) finds the min and max of the input array a.


text:
Q: Import everything from a package I'm wondering if there is any way to import the full contents of a package so that I don't have to prefix calls to things in the package with a package name?
For example, is there a way to replace this:
import "fmt"
func main() {
    fmt.Println("Hello, world")
}

with this:
import "fmt"
func main() {
    Println("Hello, world")
}

A:
The Go Programming Language Specification
Import declarations
If an explicit period (.) appears instead of a name, all the package's
  exported identifiers declared in that package's package block will be
  declared in the importing source file's file block and must be
  accessed without a qualifier.

For example,
package main

import . "fmt"

func main() {
    Println("Hello, world")
}

Playground: https://play.golang.org/p/xl7DIxxMlU5
Output:
Hello, world


text:
Q: trying to enable a user to see the letsencrypt keys I do not know if this is the right place to ask, but I'l give it a try
I was trying to let user mysql read the letsencrypt keys.
Normally any user can see the live and the archive folders so the mysql user can also
debian:~# sudo -u mysql ls /etc/letsencrypt/archive/
example1.com example2.com example3.com

if I try to see the files in there
debian:~# sudo -u mysql ls /etc/letsencrypt/archive/example1.com
ls: Zugriff auf /etc/letsencrypt/archive/example1.com/ nicht möglich: Keine Berechtigung

(what means in german : you have no right to see the files.)
then I garbed setfacl and tried to gain mysql access to the files, so I went:
setfacl -R -m "u:mysql:r" /etc/letsencrypt/archive/

then I checked the acl
debian:~# getfacl /etc/letsencrypt/archive/example1.com
getfacl: Entferne führende '/' von absoluten Pfadnamen
# file: etc/letsencrypt/archive/example1.com
# owner: root
# group: root
user::rwx
user:mysql:r--
group::r-x
mask::r-x
other::r-x

then I became confident and praised myself, as I always do when I do smart things
For some reason I checked again :
debian:~# sudo -u mysql ls /etc/letsencrypt/archive/example1.com
ls: Zugriff auf /etc/letsencrypt/archive/example1.com/ nicht möglich: Keine Berechtigung

the user mysql still sees nothing. (setfacl --version 2.2.52)
Is there something I missed ?

A: You need to set the executable bit (x) on the folder as well for a user to be able to actually navigate into the directory. Try the following:
setfacl -m "u:mysql:rx" /etc/letsencrypt/archive/
setfacl -R -m "u:mysql:r" /etc/letsencrypt/archive/*


text:
Q: How reload src element How to force browser reload single element of the page ('src' in my case, or 'div', no matter)?
Using this code:
$("div#imgAppendHere").html("");

It changes page source, but not reload changed element. How to do it?
Thanks in advance.

A: Patrick Evans, you right, that hack is works.
So my code is:
var someRandQuery = "?" + (Math.random()*100000);
$("#imgAppendHere").html("");


text:
Q: Counting letters / characters in jQuery I searched online and looked at the API Docs on how to count characters, and I'm currently using this: $('.test').val().length;
However, it's not working at all.
My div looks like this:
Count These Letters

I expect $('.test').val().length; to return 19, but instead its returning 1... am I using the wrong function?

A: For text, you'll need .text(), like this:
 $('.test').text().length