How to speak about creating non repeating combinations from lists of binary choices

Question: I have a pretty basic problem in which I need to combine each item of a with each of b and c where a,b, and c have boolean values.  For example:
a = [a is on, a is off]
b = [b is on, b is off]
c = [c is on, c is off]
I need to combine such that i get all combinations
a is on, b is on, c is on
a is on, b is on, c is off
a is on, b is off, c is on
a is on, b is off, c is off
a is off, b is on, c is on
and so on.
I thought this was called the quadratic product, but that doesn't show up in google searches.  I can't help but think this is a common mathematical operation, I just don't have the vocabulary for it.  What is it called and how might i go about learning how to generate these combinations?
Answer: This is the multiplication principle. You can think of this as all of the function $$f:\{a,b,c\}\longrightarrow \{0,1\}$$ This is denoted by $$\{0,1\}^{\{a,b,c\}}$$ and has cardinality $2^3.$ Notice that the sets match the numbers. If you are coding, which might be the scenario you are dealing with, i would recommend taking a look at binary expansions. This are all of the numbers from $0$ to $7$ written down in binary form. i.e., $000$ represents 0, $001$ represents $1$ and so on.


Kotlin: How can I invoke a lambda field which has a generic type of its class?

Question: How can I invoke a lambda field which has a generic type of its class? For some reason, a reference to such a generic class like Example<*> yields an accept that replaces the original type (like Example<Something>) with Nothing. How can I invoke such a lambda by only having reference to Example<*>?
Codebase I am having this problem with: https://github.com/Jire/Acelta/tree/master/src/main/kotlin/com/acelta/packet/incoming/packets
I am trying to this code, but as you can see on the 5th line I cannot invoke the lambda because the accept type is Nothing.
private val incoming = arrayOfNulls<Packet<*>>(256)

fun incoming(id: Int, packeteer: Packeteer) {
    val packet = incoming[id] ?: return
    packet.receive(packeteer, /* this is type Nothing! */)
}

Comment: Please try to create a minimal, self-contained example. How is `Packet` and `Packeteer` defined?
Comment: Please add specific code that you're having problem compiling/running in the question itself.
Comment: @miensol Usage added.
Comment: @KirillRakhman what you would expect the second argument to `receive` be?
Answer: This behavior is just how star projections (Foo<*>) work in Kotlin.
As said in the docs

For Foo<T>, where T is an invariant type parameter with the upper
  bound TUpper, Foo<*> is equivalent to Foo<out TUpper> for reading
  values and to Foo<in Nothing> for writing values.

If you use star projection Packet<*>, you know nothing about its generic type, thus you cannot safely pass any value to its method where a generic parameter is expected (that's why Nothing type is there).
You can use in-projection to specify a lower bound for the generic type, and for Packet<in SomeType> you will be able to pass instances of SomeType into the methods. This will require actual type parameter of Packet to be SomeType or some of its ancestors, similar to ? super T wildcard in Java:
private val incoming = arrayOfNulls<Packet<in SomeType>>(256)

fun incoming(id: Int, packeteer: Packeteer) {
    val packet = incoming[id] ?: return
    packet.receive(packeteer, someTypeInstance)
}

Otherwise, you can use unchecked cast to call the method, though it can result in ClassCastException thrown somewhere inside:
(packet as Packet<in SomeType>).receive(packeteer, someTypeInstance)

Comment: @Jire, you can perform unsafe cast: `(packet as Packet).receive(packeteer, someTypeInstance)`, though it might imply `ClassCastException` thrown somewhere.
Comment: Is there any unsafe way to bypass this restriction?


Calculate Triangle Ground using Height and Top Angle

Question: Is it possible to calculate the ground of a triangle only using the height and top angle.
Click here to see a poorly draw sketch of what I'm trying to calculate.
So is it possible and how, to calculate exactly that, only using either regular math or geometry, trigonometry or vector math functions.
Answer - Thanks to peterwhy
$angle:=\frac{(180^\circ-60^\circ)}{4}=30^\circ$
$base:=tan(angle)*10*2=11.547$
Where the $60^\circ$ is the top angle and the $10$ is the height of the triangle.
Comment: No, the _base_ is not fixed given the height and the opposite angle of base
Comment: What do I need more to be able calculate the desired result then?
Comment: One base angle, or two other side lengths (but with two side lengths you don't even need to know the height)
Answer: Not possible, and I can give you two example triangles with same height ($10$) and same "top angle" ($60^\circ$) but with different base length.
Consider the equilateral triangle with all angles $60^\circ$. By trigonometry you can find the base length to be $\frac{20}{\sqrt 3} = \frac{20 \sqrt 3}{3}$.
However, if the triangle is instead a right-angled one, then the base length would be $10\sqrt3 = \frac{30\sqrt3}{3}$, 1.5 times longer than the previous case.
In fact, the base length can be made as long as you want, by having a base angle close to $180^\circ - 60^\circ$.
Comment: Thanks, that was exactly what I wanted. I edited my post and added the final math expression that I got from what you answered.


Incluir vírgula em resultados vindos do banco de dados

Question: Tenho uma tabela onde a estrutura é a seguinte:

IDEstoques | IDProdutos | Tamanhos | Cores | Estoques

Nela armazendo os tamanhos, cores e estoques de cada produto. Porém estou precisando trazer do banco de dados as seguintes informações:
Tamanhos: P,M, G
Cores: Azul, Amarelo, Vermelho

Consegui trazer apenas os tamanhos da seguinte forma:
$sqlEstoques = mysqli_query($this->conexao,"SELECT * FROM loja_estoques WHERE IDProdutos = '".$jmBusca->IDProdutos."';");

if(mysqli_num_rows($sqlEstoques) > 0){
   $resultado = array();
   while($jmEstoques = mysqli_fetch_array($sqlEstoques)){
         $resultado[] = $jmEstoques["Tamanho"];
   }
    $visualizar .= "
Tamanhos:". implode(",",$resultado);
    $visualizar .= "
";
}

Saída: Tamanho: P,M,G

Como eu faria para trazer também as cores?
Cores: Azul, Amarelo, Vermelho

Comment: Da mesma forma que você fez com os tamanhos, salvando eles num array e depois com implode. Alguma dificuldade que você encontrou e não colocou na pergunta? Você pode [edit] pra ficar mais claro :)
Comment: Olá gmsantos. Desculpe, não consegui entender muito bem. Poderia me dar um exemplo?
Comment: troca `$jmEstoques["Tamanho"];` para Cores.
Comment: Certo. Já fiz isso, mas não consegui entender como posso salvar em um array e depois jogar para um implode para pegar o tamanho e as cores vindas do BD. Tenho que criar 02 querys e 02 laços?
Comment: itere uma fez, salve duas variáveis.
Comment: Desculpe gmsantos, realmente não consegui entender. Teria como me dar um exemplo baseado no meu código?
Answer: Enquanto você itera, salve em outra variável as cores:
$sqlEstoques = mysqli_query($this->conexao,"SELECT * FROM loja_estoques WHERE IDProdutos = '".$jmBusca->IDProdutos."';");

if(mysqli_num_rows($sqlEstoques) > 0){
   $tamanhos= array();
   $cores= array();
   while($jmEstoques = mysqli_fetch_array($sqlEstoques)){
       $tamanhos[] = $jmEstoques["Tamanho"];
       $cores[] = $jmEstoques["Cores"];
   }
   $visualizar .= "
Tamanhos:". implode(",",$tamanhos)."
";
   $visualizar .= "
Cores:". implode(",",$cores)."
";
}

Recomendo que estude um pouco a parte de lógica de programação, vejo que faltam alguns conceitos básicos. Leia um pouco também algumas perguntas sobre segurança, principalmente como evitar SQL Injection em PHP.
Comment: Perfeito gmsantos. Obrigado.


Nginx+Apache2+LetsEncrypt with IPhone cannot display page

Question: I have nginx+letsencrypt ssl cert and it's works fine for all but new iOS with Safari. It works fine with iPhone 4, but with iPhone 5 and newer it's not.
And I see multiple requests in nginx log:
IPADDRESS - - [03/Dec/2016:10:08:08 +0000] "GET / HTTP/2.0" 200 5999 "REFERER" "Mozilla/5.0 (iPhone; CPU iPhone OS 10_1_1 like Mac OS X) AppleWebKit/602.2.14 (KHTML, like Gecko) Version/10.0 Mobile/14B100 Safari/602.1"
IPADDRESS - - [03/Dec/2016:10:08:08 +0000] "GET / HTTP/2.0" 200 5999 "REFERER" "Mozilla/5.0 (iPhone; CPU iPhone OS 10_1_1 like Mac OS X) AppleWebKit/602.2.14 (KHTML, like Gecko) Version/10.0 Mobile/14B100 Safari/602.1"
IPADDRESS - - [03/Dec/2016:10:08:08 +0000] "GET / HTTP/2.0" 200 5998 "REFERER" "Mozilla/5.0 (iPhone; CPU iPhone OS 10_1_1 like Mac OS X) AppleWebKit/602.2.14 (KHTML, like Gecko) Version/10.0 Mobile/14B100 Safari/602.1"
IPADDRESS - - [03/Dec/2016:10:08:08 +0000] "GET / HTTP/2.0" 200 5999 "REFERER" "Mozilla/5.0 (iPhone; CPU iPhone OS 10_1_1 like Mac OS X) AppleWebKit/602.2.14 (KHTML, like Gecko) Version/10.0 Mobile/14B100 Safari/602.1"
IPADDRESS - - [03/Dec/2016:10:08:08 +0000] "GET / HTTP/2.0" 200 5998 "REFERER" "Mozilla/5.0 (iPhone; CPU iPhone OS 10_1_1 like Mac OS X) AppleWebKit/602.2.14 (KHTML, like Gecko) Version/10.0 Mobile/14B100 Safari/602.1"
IPADDRESS - - [03/Dec/2016:10:08:08 +0000] "GET / HTTP/2.0" 200 5998 "REFERER" "Mozilla/5.0 (iPhone; CPU iPhone OS 10_1_1 like Mac OS X) AppleWebKit/602.2.14 (KHTML, like Gecko) Version/10.0 Mobile/14B100 Safari/602.1"
IPADDRESS - - [03/Dec/2016:10:08:08 +0000] "GET / HTTP/2.0" 200 5998 "REFERER" "Mozilla/5.0 (iPhone; CPU iPhone OS 10_1_1 like Mac OS X) AppleWebKit/602.2.14 (KHTML, like Gecko) Version/10.0 Mobile/14B100 Safari/602.1"
...
and ends with 499 code
IPADDRESS - - [03/Dec/2016:10:08:08 +0000] "GET / HTTP/2.0" 499 5998 "-" "Mozilla/5.0 (iPhone; CPU iPhone OS 10_1_1 like Mac OS X) AppleWebKit/602.2.14 (KHTML, like Gecko) Version/10.0 Mobile/14B100 Safari/602.1"

and blank page in Safari browser.
HTTP section ngixn config:
##
# SSL Settings
##

ssl_stapling on;
ssl_stapling_verify on;
resolver 18.104.22.168 184.108.40.206;

ssl_protocols TLSv1 TLSv1.1 TLSv1.2; # Dropping SSLv3, ref: POODLE
ssl_prefer_server_ciphers on;
ssl_ciphers "ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-AES256-GCM-SHA384:DHE-RSA-AES128-GCM-SHA256:DHE-DSS-AES128-GCM-SHA256:kEDH+AESGCM:ECDHE-RSA-AES128-SHA256:ECDHE-ECDSA-AES128-SHA256:ECDHE-RSA-AES128-SHA:ECDHE-ECDSA-AES128-SHA:ECDHE-RSA-AES256-SHA384:ECDHE-ECDSA-AES256-SHA384:ECDHE-RSA-AES256-SHA:ECDHE-ECDSA-AES256-SHA:DHE-RSA-AES128-SHA256:DHE-RSA-AES128-SHA:DHE-DSS-AES128-SHA256:DHE-RSA-AES256-SHA256:DHE-DSS-AES256-SHA:DHE-RSA-AES256-SHA:AES128-GCM-SHA256:AES256-GCM-SHA384:AES128-SHA256:AES256-SHA256:AES128-SHA:AES256-SHA:AES:CAMELLIA:DES-CBC3-SHA:!aNULL:!eNULL:!EXPORT:!DES:!RC4:!MD5:!PSK:!aECDH:!EDH-DSS-DES-CBC3-SHA:!EDH-RSA-DES-CBC3-SHA:!KRB5-DES-CBC3-SHA";
ssl_dhparam /etc/nginx/ssl/dhparams.pem;

ssl_session_cache shared:SSL:5m;
ssl_session_timeout 1h;

SERVER section for domain:
listen 443 ssl http2;

ssl_certificate         /etc/letsencrypt/live/domain.com/fullchain.pem;
ssl_trusted_certificate /etc/letsencrypt/live/domain.com/chain.pem;
ssl_certificate_key     /etc/letsencrypt/live/domain.com/privkey.pem;

location / {
    proxy_pass          http://localhost:40011/;
    proxy_set_header    Host $http_host;
    proxy_set_header    X-Real-IP $remote_addr;
    proxy_set_header    X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header    X-Forwarded-Proto $scheme;
}

Nginx is used with Apache 2.4.23
<VirtualHost localhost:40011>
Protocols h2 http/1.1

AddDefaultCharset UTF-8

ServerName localhost

ServerAdmin email@example.com
DocumentRoot /var/www/domain.com/public
DirectoryIndex index.php

SetEnvIf X-Forwarded-Proto https HTTPS=on

<Directory /var/www/domain.com/public>
    Order Allow,Deny
    Allow From All
    AllowOverride None
    Options FollowSymLinks
</Directory>

</VirtualHost>

And Apache log contains same requests:
127.0.0.1 - - [05/Dec/2016:14:36:00 +0000] "GET / HTTP/1.0" 200 6122 "-" "Mozilla/5.0 (iPhone; CPU OS 10_1_1 like Mac OS X) AppleWebKit/602.2.14 (KHTML, like Gecko) Version/10.0 Mobile/14B100 Safari/602.1"
::1 - - [05/Dec/2016:14:36:00 +0000] "GET / HTTP/1.0" 200 6122 "-" "Mozilla/5.0 (iPhone; CPU OS 10_1_1 like Mac OS X) AppleWebKit/602.2.14 (KHTML, like Gecko) Version/10.0 Mobile/14B100 Safari/602.1"
127.0.0.1 - - [05/Dec/2016:14:36:00 +0000] "GET / HTTP/1.0" 200 6122 "-" "Mozilla/5.0 (iPhone; CPU OS 10_1_1 like Mac OS X) AppleWebKit/602.2.14 (KHTML, like Gecko) Version/10.0 Mobile/14B100 Safari/602.1"
::1 - - [05/Dec/2016:14:36:00 +0000] "GET / HTTP/1.0" 200 6121 "-" "Mozilla/5.0 (iPhone; CPU OS 10_1_1 like Mac OS X) AppleWebKit/602.2.14 (KHTML, like Gecko) Version/10.0 Mobile/14B100 Safari/602.1"

...and still blank page in Safari.
Comment: Run a couple of SSL tests and report back : https://www.ssllabs.com/ssltest/ and https://www.ssllabs.com/
Comment: What is nginx version? Make sure you are running the latest from mainline branch.
Comment: ssllabs says A+, nginx version is 1.11.6, ALPN support enabled
Answer: This doesn't seem to be a problem with SSL (or Let's encrypt). The fact, that the request shows up in your log file proves that the request came through fine (the SSL handshake is done before the actual request reaches the server).
A little googling for nginx http 499 shows that nginx uses this (unofficial) return code to indicate that the client closed the connection before nginx was able to send an answer.
The most probable reason for this would be that the script on the server takes so long to run, that the client thinks the connection timed out and closes the connection. This could be "solved" by reducing the time a script is allowed to run (if nginx supports this, I know it is possible with apache). Of course this doesn't solve the actual issue, it only changes the error code and reports it back to the client.
If the cause is a long running script, you would have to debug the script on the server side to determine what part of it takes so long.
Another possibility, with the client being a mobile device, could be that it is just a bad connection that results in the connection being dropped.
Comment: It doesn't explain multiple requests and a fact that only new iOS devices are affected.
Comment: No, it doesn't, it just points out that you are looking in the wrong place for the problem. Without knowing more about what's actually being served by nginx the question can't be answered.
Comment: It's a simple ngixn+apache2 server with `proxy_pass http://localhost:1234`. Apache log contains the same multiple requests. Can it be problem with Apache? I really confused that only iOS Safari is affected...
Comment: If the requests show up in apaches request log as well it confirms that this is not an SSL problem. It could be a problem with apache, with the connection between nginx and apache, the possibilities already mentiond above or something completely different. With the little information you provide the only thing that can be determined for certain is that it is not a problem with SSL. Everything else is just blind guessing.
Answer: Nginx cannot proxy to Apache by h2 protocol:
Protocols h2 http/1.1

removing this line solve the problem, but I still cannot understand why it's happing ONLY WITH devices iOS 10.
Answer: Now facing the same/similar issue on iOS 12 with nginx 1.16.0 proxying to apache enabled with http2. Workaround is to disable http2 on nginx, the right solution is described here https://trac.nginx.org/nginx/ticket/915 or https://trac.nginx.org/nginx/ticket/1150 - adding  proxy_hide_header Upgrade; will solve that. With Upgrade header (probably only) the iOS cannot handle "protocol upgrade request" together with that the request is already in http2.
The same proxy on apache 2.4 and mod_proxy works ok as this header is not forwarded to client as default.
Comment: Solved the issue for me ! Thanks ! ;)
Comment: This was the solution for me also, I did nothing with http/2
Answer: To be more specific, I did nothing with http/2, only the Upgrade header.
Inside this statement:
location / {
   proxy_pass http://127.0.0.1:8080;
   ...

}

Add this line:
   proxy_hide_header Upgrade;

FYI: iOS Safari had ERR_INVALID_RESPONSE; iOS Chrome had "cannot parse response".
Answer: The short answer is removing Protocols h2 http/1.1 in apache config
The problem is iOS cannot handle "protocol upgrade request" when the request is already in http2.
Your config enables http2 in both apache Protocols h2 http/1.1 and nginx.
When iOS connect to nginx, nginx has upgraded to http2 protocol.
Next, ngigx proxy request to apache in http protocol.
Apache will response with "protocol upgrade" in header, because apache get http request and send out "upgrade http2".
The "upgrade http2" makes iOS unhappy because the connection is already in http2.
Removing Protocols h2 http/1.1 in apache makes apache not response "protocol upgrade" in header when proxying with proxypass http://...


How can I create leave approval In sharepoint-2010

Question: I'm new to SharePoint and I'd like to Create a Leave approval Form Application which utilizes the Approval Workflow, Approver  as  userprofile  feild  in  sharepoint-2010?. Please guide me
Answer: http://workflowvalidation.codeplex.com/
you can using this solution, to create a custom validation process.
In your case, you create a Leave List (Creator, start date, final date...), you associate the workflow (Validation Workflow) to this list. And you create your custom process, the validator can defined in the column list or in the user profile service.
example: The Manager of the author.
if you have any problem contact me.


Melhor prática para criação de if

Question: Qual das duas opções de código tem uma performance melhor?
Vou exibir um exemplo bem simples, geralmente há mais código dentro do if.
A)
string mensagem = "OI";
if(exibirAdeus)
   mensagem = "Adeus";

B)
string mensagem = "";
if(exibirAdeus)
  mensagem = "Adeus";
else
  mensagem = "OI";

Answer: Não sei se vale a pena pensar em performance de um fragmento tão curto e de execução tão rápida. Porém podemos fazer a seguinte análise:
Em A) você inicializa a variável e ela só irá ser atualizada caso a expressão exibirAdeus seja verdadeira. Em B) você inicializa a variável com um valor que nunca será utilizado, desta forma terá o custo de atualizar a variável independente do valor de exibirAdeus.
Desta forma eu te digo que A) tem melhor performance que B). Mas não por ser C#, mas sim pelo algoritmo utilizado.
Comment: A) não necessariamente tem melhor performance que B). O correto seria performance igual ou melhor.
Comment: Fiquei curioso em saber porque houve um voto negativo aqui. Queria aprender onde está o problema da resposta.
Answer: A pergunta é pertinente sim caso o bloco de código no if contenha alta complexidade computacional, escritas no banco de dados ou em arquivos, etc..
O ideal, entre os dois, seria o (A).
Porque Performance(A) >= Performance(B)
Caso 1: a execução do programa tenha sempre exibirAdeus = true, Performance(A) = Performance(B). Tanto (A) como (B), acabarão sempre tendo o mesmo fluxo:
Algoritmo (A), Algoritmo (B):
1. Atribui "" ou "Oi" para `message`
2. Verifica `exibirAdeus == true`
3. Atribui "Adeus" para `message`

Caso 2: a execução do programa tenha 1 ou mais exibirAdeus = false, Performance(A) > Performance(B). Porque para esses casos (B) será mais custoso:
Algoritmo (A):
1. Atribui "Oi" para `message`
2. Verifica `exibirAdeus == true`: falso, não faz nada (message já é "Oi"). continua adiante.

Algoritmo (B):
1. Atribui "" para `message`
2. Verifica `exibirAdeus == true`: falso, precisa atribuir "Oi".
3. Atribui "Oi" para `message`

Mundo Real
No entanto, caso esse bloco seja pequeno e de baixa complexidade, isso se torna extremamante desnecessário.
O caminho que tu iria seguir é: O quão esse código está legível e fácil de dar manutenção (legibilidade & manutenabilidade). Digo isso porque há um consenso* que nesse caso apresentado, deverias se preocupar mais em colocar as chaves ({}) para demarcar os blocos do if-else.
string mensagem = "OI";     // padrão: caso mais provável...
if (exibirAdeus) {
   mensagem = "Adeus";
}

ou ainda, caso o código comece a ficar mais complicado como lembrado por C. E. Gesser:
private bool Teste(){
    [..]
    string mensagem = initMensagem(condicao);
    [..]
}

private string initMensagem(bool condicao){
    if (condicao) {
      return "Adeus";
    }
    return "OI";
}

Outro caso comum
string message = "";
if (condicao == 1){
   message = "blablbla";
}
else if (condicao == 2){
   message = "Lorem";
}
else if (condicao == 3){
   message = "Ipsum";
}
[..]
else {
   message = "Dolor";
}

Seria melhor escrito assim** por performance, legibilidade e manutenabilidade:
string message = "";
switch (condicao) {
    case 1:
       message = "blablbla";
       break;
    case 2:
       message = "Lorem";
       break;
    case 3:
       message = "Ipsum";
       break;
    [..]
    default:
       message = "Dolor";
}

*
https://softwareengineering.stackexchange.com/questions/16528
https://softwareengineering.stackexchange.com/questions/2715
https://stackoverflow.com/questions/15786949
**
https://stackoverflow.com/questions/445067
https://stackoverflow.com/questions/767821
https://stackoverflow.com/questions/395618
Comment: @felipe.avelar `switch` e' mais eficiente que `if/else` se houverem 5 ou mais casos. Se houverem >=5 casos, o `switch` e' implementado usando uma *hash table*/*lookup table* - e todos os casos terao acesso constante O(1). No caso demonstrado pelo @AndréFigueiredo, if/else teria melhor performance.
Comment: Para casos mais complicados, a organização do código fica melhor refatorando a lógica de inicialização para uma outra função:

    `string message = initMessage(condicao);`
Comment: @felipe.avelar, basicamente é o que @dcastro disse. A explicação detalhada está nos links** no SO em inglês.
Por isso, para identificar que os blocos `if/else` e `switch` são largos, coloquei um `[..]`.
Comment: Concordo! Melhor ainda!
Comment: @AndréFigueiredo porque e' que Porque Performance(A) >= Performance(B)?
Comment: "=" porque caso `exibirAdeus==true` em todos os casos durante a execução, o else nunca será executado; o fluxo será sempre o mesmo para ambos os casos: sempre ser criada a variável, inicializada, verificado `exibirAdeus==true`, e a variável atualizada para "Adeus".
">" para outros casos onde haverá algum `exibirAdeus==false` , onde (B) irá denegrir a performance pelo custo de atualizar a variável - a medida que ocorram mais `exibirAdeus==false`, (A) não irá atualizar.
Comment: O fluxo nao tem custo. O que custa e' a criaccao de objectos. E no caso A, se `exibirAdeus==false`, 2 objectos sao criados: "OI" e "Adeus" - e o objecto "OI" foi criado desnecessariamente. O caso ideal seria o caso C, como demonstrado na minha resposta.
Comment: Fique curioso do porquê usar `case` é menos custoso que vários laços `if\else`.
Comment: @dcastro atualizei a resposta com o porquê acredito que  Performance(A) >= Performance(B)
Comment: Na verdade, o passo **1. Cria string `message`** não exite em tempo de execução.
Comment: Bem lembrado @PauloMorgado, atualizei a resposta corretamente
Answer: Vale mencionar mais uma opção que escapou nos exemplos apresentados.  Aqui usando o operador ternário.
string mensagem = exibirAdeus ? "Adeus" : "OI";

Answer: O melhor caso não é A nem B. É C:
string mensagem;
if(exibirAdeus)
  mensagem = "Adeus";
else
  mensagem = "OI";

Em A:

se exibirAdeus == true, 2 objectos são criados ("OI" e "Adeus")
se exibirAdeus == false, 1 objecto foi criado ("Oi")

Em B:

se exibirAdeus == true, 2 objectos são criados ("" e "Adeus")
se exibirAdeus == false, 2 objecto são criados ("" e "Oi")

Em C:

se exibirAdeus == true, 1 objecto foi criado ("Adeus")
se exibirAdeus == false, 1 objecto foi criado ("Oi")
Answer: Levando em conta o seu algoritmo, para o processador a diferença é quase insignificante (como quase todo mundo disse) porem é obvio que se esse if estiver dentro de um loop para bilhoes essa diferença minina se torna mais sensivel. Creio que vale a pena você pensar sobre a semantica do que está escrevendo e ver se faz mais sentido o primeiro ou o segundo, melhorando assim a legibilidade e o entendimento.
Answer: Como o @Lizard corretamente mencionou, o desempenho depende da probabilidade da condição e também da otimização que o processador é capaz de fazer. Porém, eu acrescentaria aqui a frequência de uso dessa rotina.
Veja esta interessantíssima questão sobre velocidade de processamento em C. Os processadores modernos são capazes de processar várias instruções por ciclo, então se o resultado da expressão booleana for quase sempre o mesmo, o processador tem a capacidade de "prever" o resultado e otimizar o processamento como se o if não existisse.
Eu não sei quão é avançado é o compilador de C#, mas se até numa linguagem de altíssimo nível como Ruby houve ganho de desempenho por otimizações que dependem do processador, então C# não seria uma exceção.
Além disso, se uma rotina assim for usada frequentemente, a String inicial já estará carregada em cache e o custo de apontar uma variável para ela será bem pequeno. MNo segundo exemplo, você está apontando para uma String vazia, o que já exige o processamento de atribuição de variável.
Enfim, comparando com os gargalos comuns de desempenho, a diferença desses trechos é praticamente nula. E isso pode ser aplicado para a maioria das linguagens.
Por outro lado, é importante ressaltar que se, além da atribuição, houver qualquer tipo de processamento sobre o objeto o cenário pode mudar drasticamente. Após tantas afirmações de que "não faz diferença", alguém poderia optar pela alternativa A e acrescentar ali uma conversão para upper case, por exemplo.
Answer: Dentre A e B, o mais eficiente seria A. Mas o melhor mesmo seria um terceiro, um C:
string mensagem;
if(condicao)
  mensagem = "Adeus";
else
  mensagem = "OI";

Mas a eficiência do algoritmo gira em torno da condição que ele for usado, de probabilidade, então, consideramos o pior caso. Em A seria ter que mudar "OI" para "Adeus" depois de verificar a condição, e em B seria mudar o "" para "OI" ou "Adeus" depois de verificar a condição, tanto faz.
Agora deve vir a pergunta, por quê C se ela se parece tanto com B, que é pior que A? Porque a atribuição em B string mensagem = "" gera uma atribuição a mais independente do caso. Em A a chance de ocorrer uma mudança no valor é de 50%, e em C a chance de haver uma mudança não existe, sempre haverá uma atribuição apenas.
De fato o algoritmo é muito simples para considerar sua eficiência, mas dentro de um looping, ou dois, sendo executados milhares de vezes, com diversas possibilidades, a relevância de algo simples se torna importante, tornando o tempo de execução maior.
Consideração: O compilador sempre irá verificar se há um else, não é um processo a mais, é algo inerente ao condicional if.
Answer: A alternativa "A", vale muito a pena se houver uma chance maior de a mensagem ser "OI". Por exemplo, se sabe que existem mais homens que mulheres num determinado estado.
Ao fazer o cadastro, vale a pena fazer:
char sexo = 'M';
if (mulher)
    sexo = 'F';

Porém, não se preocupe com esse tipo de coisa. O processador tem uma capacidade muito grande e a diferença no tempo de execução é de milésimos. Por exemplo, um professor meu disse que:
int A = 10;

é 0,000014 mais rápido que
int A = 2 * 5;

Mas me diga, será que 0,000014 vai fazer diferença na sua aplicação? Claro que não, mas se mesmo assim você está curioso a respeito da diferença de tempo, faça o seguinte.
Declare um stopwatch, execute o método A, e então pare e exibe o tempo que decorreu.
Depois, declare outro stopwatch, execute o método B, e então exiba o tempo e ainda veja a diferença entre os dois. O Stopwatch marca o tempo passado até sua parada (como um cronômetro). Pode testar (:
EDIT
EXEMPLO DE USO:
Stopwatch sw = new Stopwatch();
sw.Start();
//seu código aqui
sw.Stop();
Console.WriteLine(sw.ElapsedMilliseconds.ToString());

Comment: Que meus professores me desculpem mas o Stack Overflow é o melhor professor de programação que eu tive em minha vida!
Comment: Na verdade a maioria dos compiladores irá resolver 2 * 5 em tempo de compilação e apenas armazenar 10 em tempo de execução.
Comment: Pode ser que eu tenha me enganado então. Meu professor me ensinou assim.
Comment: Quem sabe inglês deveria ler a série de posts sobre benchmark que o [Eric Lippert](http://stackoverflow.com/users/88656/eric-lippert) escreveu em http://tech.pro/blog/1293/c-performance-benchmark-mistakes-part-one
Answer: Isso vai depender de caso a caso. Se exibirAdeus for false na maioria dos casos, a alternativa A é mais eficiente, principalmente se a inicialização da variável for custosa.
Senão, vai fazer muito pouca diferença, é mais questão de estilo mesmo.

Melhor prática para criação de if


Taxonomy bulk edit in Drupal 7

Question: I have been trying to find a good, working method to do some bulk taxonomy operations in Drupal 7.
The Administration Views module doesn't appear to work - I just get page not found errors when trying to access any of the views.
So, I have been trying to follow this guide here: http://learnbythedrop.com/drop/166 . However, this is for Drupal 6 and I can't find the corresponding options in Drupal 7. There is no Style option in the view dialog, and Format contains:
Grid
 HTML list
 Jump menu
 Quicktabs
 Table
 Unformatted list, But nothing for VBO.
Can someone help here? This is where drupal really falls down IMO - total lack of up to date documentation and lots of time spent trying to find modules to do simple things which should be in core.
Comment: I've now watched the video here: http://nodeone.se/blogg/views-bulk-operations . I've found the bulk operations field to add, but there doesn't seem to be any taxonomy related actions. Is there really no decent way of doing this in d7?
Answer: I don't believe there is a really easy way to do this with d7 yet. Views bulk operations will probably be your best bet for the future, as there is work going on to provide this functionality (see: http://drupal.org/node/1142062).
In the meantime, vbo does work with the rules module, so it looks like it might be possible to use rules and vbo together to accomplish bulk taxonomy updates, although I don't think this is trivial. This screencast: http://vimeo.com/26884701 and this comment: http://drupal.org/node/1057158#comment-4792118 might help to get you started.
Comment: It seems like http://drupal.org/node/1142062#comment-4896268 might just work. I'll give it a try! Thanks a lot for the help, have been doing serious damage to my forehead trying to figure out how to do this one!
Answer: VBO now has a Modify Field Value option which you need to enable through Views.  The options are in the Bulk Operations FIELD.  Although at the moment there's an issue where updating taxonomy term fields for multiple nodes at the same time results in duplicate taxonomy terms with different TIDs added to your vocabulary.

Taxonomy bulk edit in Drupal 7


How can I prove that $a^{2}\leq(\frac{2ab}{a+b})^{2}\leq ab\leq(\frac{a+b}{2})^{2}\leq b^{2}$

Question: How can I prove that?
$$0<a\leq b$$
$$a^{2}\leq(\frac{2ab}{a+b})^{2}\leq ab\leq(\frac{a+b}{2})^{2}\leq b^{2}$$
Comment: What are $a$ and $b$? What is the relationship between $a$ and $b$?
Comment: sorry! $$0<a\leq b$$
Comment: It appears this is true precisely when $a \leq b$.
Comment: Of course, it is not true that $ab < 0$.
Answer: for the first :

$$a\leq b$$

\begin{eqnarray}
a+b&\leq& 2b\\
(a+b)^2&\leq& (2b)^2\\
a^2(a+b)^2 &\leq& (2ab)^2\\
a^2&\leq& \left(\frac{2ab}{a+b}\right)^2
\end{eqnarray}
for the second we know that

$$
0\leq (a-b)^2
$$

so
\begin{eqnarray}
2ab&\leq& a^2+b^2\\
2ab+2ab&\leq& a^2+b^2+2ab\\
4ab&\leq& (a+b)^2\\
4ab\times ab &\leq &ab(a+b)^2 \\
(2ab)^2 &\leq & ab(a+b)^2 \\
 \left(\frac{2ab}{a+b}\right)^2 &\leq & ab
\end{eqnarray}
for the third inequality we have :

$$0\leq (a-b)^2$$

\begin{eqnarray}
2ab\leq& a^2+b^2\\
4ab\leq& (a+b)^2\\
ab\leq& \left(\frac{a+b}{2}\right)^2
\end{eqnarray}
the last one we have we can deduce it directly from the mean inequality :
$$
a\leq b \; \implies \; a\leq \frac{a+b}{2} \leq b
$$
so

$$a \leq b $$

\begin{eqnarray}
a+b \leq& 2b \\
\frac{a+b}{2} \leq& b \\
\left(\frac{a+b}{2}\right)^2 \leq& b^2
\end{eqnarray}
Answer: Last one $$b^{2}-(\frac{a+b}{2})^{2}= (b+ \frac{a+b}{2})(b-\frac{a+b}{2}) = (\frac{a+2b}{2})(\frac{b-a}{2}) \geq 0 $$ since $b\geq a, a,b>0$ then
$$ b^{2} - (\frac{a+b}{2})^{2}\geq 0\Leftrightarrow (\frac{a+b}{2})^{2}\leq b^{2}$$
Answer: Second one: $$ 0\leq (a-b)^2 \Leftrightarrow 4ab \leq a^2 + 2ab +b^2 \Leftrightarrow \frac{4ab}{(a+b)^2} \leq 1 \Leftrightarrow (\frac{2ab}{a+b})^{2}\leq ab$$


Unable to create a new remote session. Please check the server log for more details

Question: I'm getting issue while running Testcase in Appium server "Unable to create a new remote session. Please check the server log for more details. Original error: An unknown server-side error occurred while processing the command.

Original error: 'app Package' option is required "
Comment: What does the server log say?
Answer: As per appium below 4 capabilities is utter required :

platformName
platformVersion
deviceName
app

Below is the JSON Object:
<code> {
        "platformName": "iOS",
        "platformVersion": "11.0",
        "deviceName": "iPhone 7",
        "automationName": "XCUITest",
        "app": "/path/to/my.app"
    }
</code>
Source:
http://appium.io/docs/en/writing-running-appium/caps/
By seen your error it seems your app key either missing in caps or they are worng


Proof to motivate the need for measure theoretic probability

Question: Im using Billingsley's Probability and Measure.  In lecture the instructor motivated the need for measure theory in probability by providing a solution to the following problem:

Show that a discrete probability space cannot contain an infinite sequence $A_1, A_2,...$ of independent events, each of probability $\frac{1}{2}$.  This is exercise 1.1a in the text.

My thought is that such a sequence may be interpreted as a dyadic expansion of some real number in the unit interval, thus the probability space must be unaccountably infinite.  Of course this is not rigorous and it differs from the approach suggested by the author.  The problem notes give the following hint:

"Each point lies in one of the four sets $A_1 \cap A_2$, $A_1^c \cap A_2$, $A_1 \cap A_2^c$, $A_1^c \cap A_2^c$ and hence would have probability at most $2^{-2}$; continue."

I'm not sure I see where he is going with this.  Of course as the sequence goes infinite, the probability of any set goes to zero, but how does this prove the space cannot be discrete?
Answer: Let $x$ be an element of the probability space $X$.  Let $p$ be the probability of the event $\{x\}$.  Consider the $2^n$ pairwise disjoint sets of the form
$A_1^{\varepsilon_1}\cap\dots\cap A_n^{\varepsilon_n}$ where for each $i\in\{1,\dots,n\}$, $\varepsilon_i\in\{0,1\}$, $A_i^0=A$ and $A^1_i=X\setminus A$.
Each of these sets has probability $2^{-n}$ and $x$ is an element of one of them.
It follows that $p\leq 2^{-n}$.  Since this holds for every $n$, $p=0$.
So every singleton in your space has probability $0$ and hence the space is not discrete.
Answer: Depends on what is meant by a discrete space but I presume its one for which there there has to be some event with positive probability, and there cannot be a continnuum of event. There are generally at most countably many atomic events with positive probability, if the space is uncountable; as normalization would fail.
In this case, it would fail regardless, every sequence has the same probability; they all must have probability zero if any one of them does. If countable addivity is not to violate normalization , all of the events must have PR=0 have probability zero (as any given sequence of prob 1/2 have the same probability, if one has Pr=0, they all do, they all do) . Lest independence or equiprobability Pr(A)=1/2) fails; if this fact alone does not constitute the impossibility of the space being discrete; as no positive valued events, then the fact that one could add them up nonetheless,as there are only countably many such events; then PR(sample space)=0, normalization would be violated. If they all had positive probability Pr(sample)=infinite (which they dont), and it still would be violated. If some of them had positive probability and other sequences did not (it may be possible) but then the sequences would not be equi-probable, or independent.
(1)One cannot have a countably infinite number of equi-probable events, if countable addivitity is to hold, without all of said events either having zero probability or positive probability in which Pr(sigma)=infinite, or Pr(sigma)=0; thus even if this is avoided by assigning such events zero probability;
(2)if discrete spaces allow for all events to have zero probability, Pr(sigma)=0. So it would not matter, even if a discrete space allowed for every sequence to have zero probability, normalization would still fail, as every sequence would have pr=0. And as there countably many of them, would use countable addivitity.
1.Either they must all have zero probability but there must be un-countably such events, so that one cannot derive a contradiction via normalization, via countable addivity,

Or they must have positive probability, and normalization will fail as there are only countably many events in the space. And they will add to more than one. Or they will not be independent, to begin with, as their probability must limit to zero, and if one sequence does, they all do (being equi-probable) and so Pr(sigma)=0, as every  sequence has the same probability value.

Otherwise, the events will not be independent. Not that some approach such as frequentists try to avoid this issue, by postulating certain convergence. I am wondering if this can be avoiding by dropping countable addivitity; or using non-standard analysis.
(as there is no axiom of uncountable addivity); or if said events had positive probability (not only would this violate the laws of the probability calculus),
. And each sequence of independent and identical distributed events, is equally probable. One can in other cases,
By discrete; Do you mean that at there are at most countable infinitely, many events in F, the sigma algebra. Or that every event has positive probability. Every event is an atom. It is well known that every sequence with probability 1/2 has the same probability as each other, and if one has a probability of zero, every sequence will. I am wondering if this generalizes; it known that events when not equi-probable, can have positive probability, if there are only countable infinitely many of them (but in this case even if there are only countably infinitely many such sequences, they are all equally probable, and so that route of escape is not viable
Moreover,if these events are independent, then there will be un-countably many such  sequences if there is one, in the sigma algebra. Otherwise certain sequences will be ruled and will not be independent; In particular probability half events converge much more slowly then other events (the probability of attaining any given sequence with probability close to the relative frequency) is lower then for other probability values.
The strong law of large numbers holds for such events, because there are simply much more of them.  It is, also well known that almost all (uncountably many sequences, and most such sequences) by a theorem of Borel (normality theorem) consisting of binary trials, from amongst the uncountably infinite totality) have relative frequency 1/2.
Then this follows. Every infinite sequence of of probability 1/2 has probability of limiting to zero; Countable addivity would either fail, fail as P(sigma)=0 and likewise the law of large numbers which follow from it.
(2)To ensure that that one does get a violation of normalization there cannot be only countably infinitely many such events.
Lest one could add them up, vis a vis countable additivity; derive the failure of normalization.
To get around this issue;  countable addivitity cannot apply directly and to ensure this, one needs an uncountable number of such sequences
Once cannot have a countable infinite many equiprobable events (infinite sequences of probability 1/2) much less an un-countably many, unless there probability is zero.
(3) or otherwise the events could not be independent.
.
And in this case, the case, the measure and the proportion must line up (by the strong law of large numbers); but almost all the measure is not on said sequence (they add to zero) in a discrete space; almost all such sequences do not limit to relative frequency half, and as each sequence is as likely as another; it is not the case that almost surely, relative frequency convergence to the probability value will occur. I once posed this question to my maths professorm in relation to whether there are uncountably many countably infinite sequences with an irrational value relative frequency value.
There are.
Otherwise it would be a counter-example to the strong law of large number, failing for such values as well, even, in a non discrete space. For the same reason. One could add their probability values, and attain that the probability that such a sequence would converge would be close to zero
Answer: If we have 2 events $\mathcal{A}_1, \mathcal{A}_2$, the events will lies in $\mathcal{A}_1 \bigcap \mathcal{A}_2, \mathcal{A}_1^c \bigcap \mathcal{A}_2, \mathcal{A}_1 \bigcap \mathcal{A}_2^c, \mathcal{A}_1^c \bigcap \mathcal{A}_2^c$, and each event would have probability at most $2^{-2}$.
Similarly, if there are n events, they should be lies in sets $\mathcal{A}_1^{\epsilon_i} \bigcap \cdots\bigcap \mathcal{A}_n^{\epsilon_i}, i = 1,2,\cdots, \epsilon_i \in \{0,1\}, \mathcal{A}^0 = \mathcal{A}, \mathcal{A}^1 = \mathcal{A}^c$. Each events with probability at most $2^{-n}$.
$\lim_{n \to \infty} 2^{-n} = 0$, discrete probability space cant not have $\Pr(\omega) = 0$ everywhere since the we must have $\sum_{i=1}^n \Pr(\omega_i) =1$.
Thus, a discrete probability space cannot contain an infinite sequecne $\mathcal{A}_1, \mathcal{A}_2,\cdots$ of independent events each of probability $\frac{1}{2}$


PDI (Kettle) looped job step parellelization

Question: Preface
I have automated and scripted the creation of individual .ktr files to handle the extraction and syncing of data between Source (MySQL) and Target (InfoBright) databases. One .ktr file is created for each table.
I have a set of 2 Jobs and 2 Transformations which make up a "run" to find the data sync .ktr files and queue them for execution.
Job 1 (entry point)

Run Transformation to search target directory for files matching wildcard passed from command line
For every row, run Job 2 (file looper)
After the run is done, do some error checking, mailing, close out

Job 2 (file looper)

Run Transformation to take the result and populate a variable with the filename
Run ${filename} Transformation to perform syncing between MySQL and Infobright
Perform some error checking, populate an error log, etc. Standard graceful failures and error logging

This all works perfectly. I can queue up 250+ .ktr files in my target directory, and kitchen gets through them in about 9-15 minutes, depending on the volume of data to sync
Problem
Pentaho doesn't appear to support the parallelization of this abstract looped execution of transformations. Jobs don't support output distribution like Transformations do. I've checked the Pentaho support forums, and posted on there with no response.
I'm looking to get 4 or 5 parallel threads going, each executing one of the queued results (gathered filenames). I'm hoping somebody here can provide some sort of insight into how I can achieve this, aside from manually globbing files with filename tags, and running the kitchen job 5 times, passing in the filename tags as a parameter.
(This doesn't really address the output result distribution issue, as it just runs 5 separate sequential jobs, and doesn't distribute the workload)
EDIT: Here's the post on the Pentaho forums with images, that might help to illustrate what I'm talking about: http://forums.pentaho.com/showthread.php?162115-Parallelizing-looped-job-step
Cheers
Answer: After a lot of trial-and-error and a LOT of research, I've discovered the following:

Kettle doesn't support load-based distribution, only round-robin (It's typically used to distribute rows of data to different steps, so load / execution time is almost never a factor)
Round-robin-only distribution means my each Job in the distribution will handle the same number of results (in my case, each Job Executor step handles 9 transformations, regardless of how long each one could take.)
The workaround (round-robin distribution rather than true parallelization) was simpler than I thought, once I fully grasped the manner in which Kettle processed and passed results, and I only needed to move my job execution step from my parent job to the first Transformation, using the Job Executor step.
Because of this distribution method, it would be beneficial to have long-running results picking up next to each other in the results, so they are distributed evenly across the jobs

I did add a reply to my thread on the Pentaho Forums, providing a picture of my solution.
Unfortunately, per #1, it appears as though there's no support for my original goal.
Answer: Cant this be done with a transaformation with input rowset -> Job executor step ?
Job executor step
 - Filename can be parameterized in Parameters tab
 - No of rows to send = 1 in Row grouping tab
 - No.of copies changed from 1 to whatever you need


Como continuar incrementando o valor de uma variável mesmo depois que uma página é recarregada?

Question: Queria colocar para acrescentar +1 na variável $a toda vez que a página for carregada.
Já usei o código:
  $a = ++$a;
  echo $a

e também o:
  $a = $a++;
  echo $a

Mas só adiciona uma vez e, quando atualizo a página, ela não adiciona mais nada. Alguém pode me dar uma sugestão?
Comment: cara ta totalmente desorganizada sua pergunta, mas vou te dar uma dica: use `for`: http://php.net/manual/pt_BR/control-structures.for.php
Comment: Tenta ser mais claro na pergunta, especifica melhor o que você procura.
Comment: Nenhuma das resposta foram aceitas, nenhuma te ajudou?
Answer: $txt="";
$arquivo="";
$visitas="";

    $txt        = "contador.txt";
    $arquivo    = fopen($txt,"a+");
    $visitas    = fgets($arquivo,1024);
    fclose($arquivo);

    $arquivo    = fopen($txt,"r+");
    $visitas    = $visitas + 1;
    fwrite($arquivo,$visitas);
    fclose($arquivo);

    echo "Esta página foi visitada $visitas vezes";

A função fopen abre o arquivo especificado na variável $txt.
O modo  r+ abre para leitura e escrita; coloca o ponteiro do arquivo no começo do arquivo.
A função   fgets  retorna uma linha de um arquivo aberto com o comprimento especificado (opcional - especifica o número de bytes para ler). O padrão é de 1024 bytes.
A função fwrite permite a escrita em arquivos,
Essa resposta atende o comentário do autor na resposta do David Santos.

voce poderia me dar um exemplo de como fazer isso para guardar em um arquivo txt – romulo henrique 9/07 às 2:44
Comment: Graças ao seu comentário!!!!
Comment: Eu não sei se a edição foi por conta da minha crítica, mas na verdade eu imagino que talvez o AP possa não saber o que faz as funções `fopen` e `fclose`... por isso falei que faltou explicação...
Comment: @WallaceMaxters foi por conta do downvote, mas sua observação foi boa. Vou editar e colocar alguma explicação
Comment: Fui eu que negativei. Mas já que se propôs explicar, vou remover. A ideia era só estimular explicar melhor. Algumas pessoas podem pensar que ajuda o AP, mas outros usuários virão por conta desse problema e ficarão com dúvidas sobre o que foi feito na resposta.
Comment: @WallaceMaxters Por esse motivo que acho que todo voto negativo deveria ter um comentário para que o autor da resposta possa adequá-la a exemplo do sugerido no seu comentário!
Comment: sensacional, cara. Ficou show de bola a edição. +1
Answer: O script guarda os valores das variáveis apenas em tempo de execução, depois disso o espaço na memória ocupado por elas é liberado. Toda vez que você atualizar a página o script volta ao seu estado original.
Caso queira guardar o valor de uma variável mesmo após atualizar a pagina, será necessário guardar o valor da mesma em um lugar externo ao arquivo, como por exemplo : xml, banco de dados, txt, entre outros...
Comment: ou até mesmo cookies, e sessões.
Comment: voce poderia me dar um exemplo de como fazer isso para guardar em um arquivo txt
Answer: Como foi dito pelo David Santos, ao recarregar a página os valores não são guardados. Eles são registrados ali apenas em tempo de execução, depois disso são removidos da memória.
Em PHP, existe várias maneiras para se manter valores. Um dois mais comuns para o seu caso seria o uso de Sessão ou Cookies.
Eu optaria pelo uso da sessão. As sessões mantém uma ponte entre o cliente e o servidor, permitindo guardar valores específicos para cada cliente (navegador) que carrega sua página.
No seu caso, poderia ser utilizado a variável $_SESSION (como foi citado em uma das respostas, porém sem nenhuma explicação sobre o que seria isso).
Veja:
// inicia a sessão. Deve ser colocado antes de todo o código de saída para o
//navegador e antes de usar a variável super global `$_SESSION

session_start();

// Se existir o índice 'a', incrementa. Se não, define 0
if (isset($_SESSION['a'])) {

  $_SESSION['a']++;

} else {

  $_SESSION['a'] = 0;

}

// imprime o valor
var_dump($_SESSION['a']);

O código acima funcionará da seguinte forma: $_SESSION será guardado no servidor, com uma identificação única para o cliente (navegador, que é registrada num Cookie). No if temos o isset que define se o índice 'a' existe no array de $_SESSION. Se existir, ele incrementa os valores. Porém se não existir, nós definimos que ele será 0.
Assim, toda vez que a página for recarregada, o valor também será modificado e ficará salvo na sessão.
Veja Mais:

Trabalhar com session sem cookies para prevenir roubo de sessão

Aqui há uma explicação sobre o fato de toda Sessão usar Cookies

Como funciona a sessão em navegadores web?

Sessões são usadas muito para efetuar login de usuários:

Qual a melhor maneira de criar um sistema de login com PHP
O que guardar em uma sessão de login?

Contador de usuários
Na minha humilde opinião, se você quiser fazer um contador de usuários, como foi assinalado em alguns comentários, creio que a melhor maneira é usando um banco de dados.

Como gravar valores no banco de dados MYSQL usando PHP?
Answer: É fácil, tenta usar o código abaixo:
<?php

if(isset($_SESSION['a'])) {
    $_SESSION['a'] += 1;
} else {
    session_start();

    $_SESSION['a'] = 1;
}

echo $_SESSION['a'];

Comment: É verdade @GuilhermeAlves, cookies também resolve o caso, mas depende do objetivo, se ele quiser que o contador funcione para diferentes usuários, o jeito é armazenar mesmo o contador em algum lugar.
Comment: Bom eu pensei nisso, eu sugeri o `for` pra ele, mas depois que vi que ele quer guardar valores mesmo atualizando a página. Acho que `Cookies` também serve.
Comment: @FabianoLothor vc poderia me explicar se possiveu como faço para armazenar em um arquivo txt e como faço para ele pegar aquele numero que esta no arquivo txt e adicione +1
Comment: @romulohenrique porque estás a ir pelo caminho mais longo?
Comment: @GuilhermeAlves, tem um jeito mas facil como
Comment: @GuilhermeAlves, eu to querendo que quando uma pessoa entre ele some mas 1 igual aqueles contator de visitas
Comment: @romulohenrique, tem plugins para isto. mas se você quer faze-lo, Fabiano já deu a mão. é só tentar
Comment: Eu acho que é um grande problema você ensinar como fazer, mas não explicar nada em sua resposta @FabianoLothor. Você deve ter percebido que, se o Autor da Pergunta não soube que uma variável não seria incrementada por conta do tempo de excecução, é sinal que ele precisa de uma breve explicação sobre o uso de sessões e afins.
Comment: Isso resolve o problema do AP, mas seria interessante explicar por que isso resolve também.


angular $http gracefully handling errors

Question: Can someone give background on how $http works with respect to JSON, is it detecting the format of output and converting it to JSON automatically on success or do I've to handle this manually?
If that's the default behavior what happens if it can't convert the output to JSON?
Context: In this case where my web service failed because of sql connection error but success still got called
My $http related code sequence:
    this.$http.defaults.headers.common["Accept"] = "application/json";

    this.$http.get(common.Config.getEndPoint() + "/sync", {params:params})
        .success(function(data, status, headers, config) {
            self.onResult(data);
        })
        .error(function(data, status, headers, config){
            console.log(data)
        });

Error - (because my mySQL server wasn't running, this can be fixed but my objective is to gracefully handle this error on the frontend if this happens, looking for a good strategy both on the backend as well as frontend)
SQLSTATE[HY000] [2002] Connection refused

Fatal error:  Call to a member function prepare() on a non-object in

PHP line that generated the error
$statement = $this->connection->prepare("SELECT id, username, password FROM `user` WHERE username = :username AND suspended = 0 AND deleted = 0");

Learning:
success gets run for any 2xx status codes, while error runs for any 1xx, 3xx, 4xx & 5xx
Comment: I asked because the api is returning something like a 200OK even though the DB is down. IMO, you should return a 50x code instead so that your error callback is executed instead of the success callback. You can handle this on the frontend by checking the status code is actually successful in your success callback. But that's not fixing the actual issue which is that your api is returning a success when it should actually return an error.
Comment: Is the server setting the `Content-Type` header when it responds to the request? If not, then you have to tell `$http` what to expect.
Comment: What status code is returned from the web service?
Comment: @NeilSmith I've edited the code to address your question, the point is to how to gracefully handle this situation?
Comment: @user2727195 please change question subject. It doesn't refer to your problem
Comment: @Brett can we do something like `if ($this->connection)` but that just spits out the error output without letting me to specify a status code like 500
Comment: Why can't you set the status inside of an else for said if condition?
Comment: What the server responds with content-wise is irrelevant as long as you correctly set the status header. With a status header of 500, angular will run the error handler.
Comment: so let me recap - if server response is success (200) with content-type is JSON, the angular $http will automatically handle the parsing part, and call the success, but if some other status code, it will run the error handler? correct?
Comment: It will execute the success callback for any of the successful status codes and error for the others. It determines if the response was successful or not by the response's status code. See here http://httpstatus.es/
Comment: ok so in general `success` will run for any 2xx and `error` will run for any 5xx?
Comment: I believe `error` will run for 4xx also.
Comment: Ok, I just checked, error runs for 1xx, 3xx, 4xx, 5xx, while success only runs for 2xx
Answer: The problem is that a success status code is returned without valid JSON data. This is due to your API returning an incorrect status code. You should fix this in your API if you want to actually fix the problem:
if db is down
    return 503 or something.

Otherwise, you can check the status code in your success callback:
this.$http.get(common.Config.getEndPoint() + "/sync", {params:params})
    .success(function(data, status, headers, config) {
        if (status starts with 2)
            self.onResult(data);
    })
    .error(function(data, status, headers, config){
        console.log(data)
    });

But this isn't the proper fix imo. Your title is asking for a graceful way to handle errors and the 2nd approach isn't graceful.
Also note the pseudo code in there (I forget if status is a string or number).
Comment: can you please help me with caching, it's still stuck to old output, added cache param but no use, if I change params itself I get latest output. `this.$http.get(common.Config.getEndPoint() + "/sync", {params: params, cache: false})`
Comment: A second question really belongs in its own question to help future readers out. Link me to the question if you decide to make one and I'll check it out.
Comment: I'd but I'm afraid some idiots here are too eager to down vote before I actually get a chance to enhance a question after discussion, sometimes in certain domains I'm not clear what needed to be asked, any advice?


Faceted search show tid instead of taxonomy name

Question: I need to create a facet search using taxonomies, I have as a index the taxonomy term name but when I go to search, in the facet I see the tid and not the taxonomy term name. I follow a tutorial but I can't found the solution.
Search Index

Facet

Search

There is one issue in drupal.org talking about a TranslateTaxonomyProcessor callback processor but I don't know how to use it. Another issue talkin about the same processor: https://www.drupal.org/node/2673888
This is the list of my Processors:
Answer: You need to check "Translate entity label" option to see the name.
By editing Tag facet block you can see that option.

If you have still same issue.
You need to install Core Views Facets module.
Then select Facet source.
<code>View Search content, display Page
</code>
Added One example o/p screenshot.
Comment: I did it but then there is nothing to show, the faucet is empty
Comment: Made some changes on answer hopes that will work.
Comment: ok let me know if you are getting any problem.
Comment: this solution works in your enviroment?
Comment: yes added o/p screenshot.
Comment: Let us [continue this discussion in chat](http://chat.stackexchange.com/rooms/46348/discussion-between-adrian-cid-almaguer-and-smalution).


How can I save checkbox in devexpress gridview?

Question: Does anyone know how to save checkmarks inside the devexpress gridview?
I set
OptionSelection.MultiSelectMode
to
CheckBoxRowSelect
and
OptionsLayout.StoreAllOptions
to
True.
Whenever I close and reopen the form, the checkbox I just checked keeps getting unchecked. So is there a way to save checkmarks?
Answer: Rows selected is not part of the grid layout. GridView has the built-in capability to save selected rows in the grid data source. To enable this capability, specify the GridView.OptionsSelection.CheckBoxSelectorField property as described at Sync Selection with Data Source.
If you need to save selected rows somewhere else, implement a custom solution. This is illustrated at Data Grid for Windows Forms - How to preserve a View's state.


What regression formula would best fit this curve?

Question: I am using Matlab to try and find a good fit for this curve:

None of the built-in formulas seem to work well.
Any suggestions?
Comment: This appears really to be a question about fitting a distribution, not a regression question: see http://stats.stackexchange.com/questions/10594/converting-arbitrary-distribution-to-uniform-one .
Comment: Well, I need to be able to get F(x) given x through a direct formula (without summation or anything fancy)  so isn't that regression?
Comment: Yes, but this is an extremely specialized application: the curve has to go from 0 to 1 monotonically; the original data are extremely highly correlated; and the meaning of "good" depends on how you are going to use the fit.  (E.g., you might be better off fitting the derivative of this curve rather than the fit itself, or you might need to get a much better fit near $F(x)= 1$ than elsewhere: have you read Taleb's Black Swan tirade?)  If you don't disclose all those things, even the best experts could unknowingly give you formulas that perform poorly.
Comment: @whuber: I did tell Mike @ m.SE that he needed to have *some* idea about how things are distributed in his application, and that assuming things are "normal" doesn't always work... oh well.
Answer: Looking at the charts in your first question, this looks slightly like the absolute value of a standard normal distribution, what Wikipedia calls a half-normal distribution, and your curve here looks like the top half of the cdf of a normal distribution.
One way to check is to look at various quantiles of your distribution, compared with those of the absolute value of a standard normal.  In R, using your data, this might look like
<code>> mydat <- read.csv("http://furlender.com/data.csv", header=FALSE)
> mean(mydat$V1)   # compare with sqrt(2/pi) = 0.7978846 for half normal
[1] 1.014772
> median(mydat$V1) #              compare with 0.6744898 for half-normal
[1] 0.9162514
> percents <- c(0.01, (1:19)/20, 0.99, 0.999, 0.9999, 0.99999, 0.999999)
> quantile(mydat$V1, percents) / qnorm(percents/2 + 0.5)
      1%       5%      10%      15%      20%      25%      30%      35%
1.479777 1.455286 1.443074 1.435248 1.429568 1.421616 1.409148 1.400204
     40%      45%      50%      55%      60%      65%      70%      75%
1.386696 1.372990 1.358436 1.341848 1.323763 1.306209 1.287204 1.266550
     80%      85%      90%      95%      99%    99.9%   99.99%  99.999%
1.245071 1.223053 1.198247 1.172505 1.148309 1.141927 1.220474 1.412236
99.9999%
1.371697
</code>
and this suggests that your distribution is slightly more dispersed than the absolute value of a standard normal, perhaps somewhere between 1.15 and 1.4 times. Even the tails fit this description.  Drawing the ecdf confirms this compared with scaled normals.
<code>> plot.ecdf(mydat$V1, lwd=3)
> curve(2*pnorm(x/1.4 )-1, 0, 7, col="red"  , add=TRUE)
> curve(2*pnorm(x/1.15)-1, 0, 7, col="green", add=TRUE)
</code>

If you wish, you could stop there, and choose some intermediate value (perhaps 1.2718 to give a similar mean).  Or you could look for some normal-like symmetric distribution which has even moments about 0 similar to your data, and then take the absolute value.  These moments are easily calculated: for example the second and fourth are:
<code>> mean(mydat$V1^2)
[1] 1.516602
> mean(mydat$V1^4)
[1] 5.972706
</code>
suggesting that (before taking the absolute value) the symmetric distribution would be slightly platykurtic even though the extreme tail is normal-like.
Comment: +1 for the really nice idea of checking against quantiles.  A good way to fit tails is to fit the 1/4, 1/8, 1/16, ... quantiles.  Note that this is not really half-normal: the mode is slightly positive.  Also, it's short tailed compared to the normal.  You can correct that with a Box-Cox transformation or something similar and get a much closer fit overall.
Answer: Check out Eureqa for a neat evolutionary approach to finding the mathematical form of an otherwise ambiguous function. It's native to Windows but works fine on Linux & Mac via Wine (in which case I'd suggest you use winebottler).
Comment: This is one case where Eureqa will likely fail unless some clever pre-processing is done.  The problem is that CDFs like this typically have some error function-like tails and Eureqa has no function sufficiently like Erf.  If you first smooth this "curve" (it's really the EDF of 400K+ points) and ask Eureqa to fit its *derivative* in an appropriate manner it might do a good job.  (I suggest a Box-Cox transformed normal pdf for starters.)  That presumes the OP needs a good fit to the PDF itself, of course.


Como validar origem do formulario?

Question: Eu tenho uma aplicação web no qual existe um  formulário de login e registro, e pelo que percebi eu posso baixa o HTML do meu site e manda requisição pelo meu PC apontando para o site, então como eu verifico a origem do formulário?
Comment: Com id/token de uma sessão ou um captcha.
Answer: Existem diferentes maneiras de fazer, a primeira e talvez a mais usar é o "anti-CRSF" (se é que pode-se chamar assim):
autenticar.php:
<?php
session_start();

if (isset($_POST['token'], $_POST['login'], $_POST['senha'])) {
    $token = empty($_SESSION['token']) ? NULL : $_SESSION['token'];

    //Compara o token com o post
    if ($_POST['token'] === $token) {
         /*Valida $_POST['login'] e $_POST['senha']*/
    } else {
         echo 'Requisição invalida';
    }
} else {
    echo 'Faltam dados no Form';
}

login.php
<?php
session_start();

//Cria um token
$_SESSION['token'] = md5(uniqid(rand(), true));
?>

<form method="POST" action="autenticar.php">
<input type="hidden" name="token" value="<? php echo $_SESSION['token']?>" />
<input type="text" name="login" placeholder="login">

<input type="password" name="senha" placeholder="senha">

<button type="submit">Logar</button>
</form>

Desta maneira você cria um token e salva ele na sessão, na próxima página você verifica o POST e a sessão, se ambos tiverem valores iguais significa que o veio da mesma origem, isso é um exemplo bem básico, existe ainda um exemplo que tenta fazer dificultar mais ainda isto, nele todos os campos tem chaves randomicas, segue exemplo:

https://pt.stackoverflow.com/a/116437/3635

A outra maneira é verificar o referer, por exemplo:

http://exemplo/paginaA.php
<form method="POST" action="paginaB.php">
<input type="text" name="login" placeholder="login">

<input type="password" name="senha" placeholder="senha">

<button type="submit">Logar</button>
</form>

http://exemplo/paginaB.php
<?php
if (empty($_SERVER['HTTP_REFERER']) || $_SERVER['HTTP_REFERER'] !== 'http://exemplo/paginaA.php') {
    echo 'Acesso bloqueado';
    exit;
}

//Resto do script

Note bem que o uso do HTTP_REFERER pode muitas vezes falhar e pode facilmente ser trapaceado usando plugin ou requisições por ferramentas como CURL, wget, etc e até mesmo plugins pra navegadores podem controlar os headers das requisições.
O anti-CRSF é considerado bem mais seguro, mas também pode ser trapaceado, no entanto é bem mais difícil fazer isto.
Resumindo não existe nada 100% seguro, mas os exemplos ajudam a prevenir.
Comment: Muito obrigado!
Comment: Obrigado pela resposta super explicativa, com a primeira solução o usuário pode baixa formulário com key e enviar varias vezes com tentativa de fazer um login, certo?
Comment: @Cleideson ele pode baixar o form com a key, mas ela é regenerada a todo momento, a key que ele baixar já será invalida quando tentar enviar uma requisição via form baixado ;)

Como validar origem do formulario?


RSA in practice

Question: I know how decryption and encryption in RSA works when I have a plaintext $m$ represented as an integer. But how will (in practice, not in theory) a text be converted into an integer? I guess there has to be a method that is used universally, or otherwise decryption would yield an integer and the receiver would not know the corresponding text?
Comment: There's ASCII, Unicode, etc. Anything you can store on a computer is stored as a series of bits, which just make it a large number written in binary.
Comment: http://crypto.stackexchange.com
Comment: The short answer is: you don't convert a "message" to an integer. You send a key instead.
Comment: It is defined in the standards [rfc2313 PKCS #1: RSA Encryption Version 1.5](https://tools.ietf.org/html/rfc2313) and [rfc8017: PKCS #1: RSA Cryptography Specifications Version 2.2](https://tools.ietf.org/html/rfc8017)
Answer: In fact, in practice we do not encrypt arbitary messages using RSA. This is a misconception that's propagated in a lot of text books.
What usually happens is that we use AES or some other symmetric cipher (I'll call it) $E(K,m)$ to encrypt a message $m$ with a (long enough and random etc.) key $K$. We then actually send $E_{\text{RSA}}(K)$ together with $E(K,m)$. So the receiver than RSA-decrypts the key and then decrypts the message with that key $K$. This has several advantages:

RSA is slow and this way we only do one encryption and one decryption per "session".
We can re-use that key for a period to keep sending messages (as is done in online https sessions, or ssh-sessions etc.)
Symmetric ciphers systems have support for long/short messages (so independent of the size of the modulus we use in RSA) and we can add authentication tags etc.

In short, more efficient and more secure. A lot of standards are based on this "hybrid" idea: RSA (or Diffie-Hellman) to get a key across safely, and symmetric encryption for actual data.
This reduces your question to "how do we send keys" in RSA? Well, typically RSA-moduli are about 2048 bits (256 bytes) and keys 32 bytes or 256 bits. So easily within range. It's a bit like the modulus is around 1000 and we only want to send numbers smaller than 40, say. So typically we randomise the 32 bytes key which is a 256 bit number (we're working with computers, so decimal representations aren't used, again a text book idea to get small numbers; don't be misled by this!) to a number of the size of the RSA modulus in a uniquely reconstructible way and then work in RSA with that encoded number from which the key of 32 bytes can be uniquely found back again.
Answer: So there is not a singular solution. You can implemente this on many ways. You can use ASCII, UNICODE, or maybe some other code that makes sense only to you (and reciver must use it, of cource), it doesn't metter. It is on you how to implement it! If you make some untrivial code, it can be more difficult to do decription and to intercept your data.  You only need to transform letters to numbers (you can easy pair, for an example: (A - 1), (B - 2)... or do some method as I mentioned before). Then you need a formaula to do encryption.

The process by which this is done is that a message, for example "Hello World" is encoded as numbers (This could be encoding as ASCII or as a subset of characters {a=01,b=02,...,z=26}). This yields a string of numbers, generally referred to as "numerical plaintext". For example, "Hello World" encoded with a=1,...,z=26 by hundreds would yield  08051212152315181204.

More of this you can find in this article. Hope it helps!

RSA in practice


Configuration of SSL on Jetty 9 : oeji.SelectorManager:qtp1706748598-22-selector-0: java.lang.NullPointerException

Question: I'm trying to configure SSL on Jetty 9.0.4. I'm using Jetty with WebSockets, and Autobahn Android for the Client.
I tried several configurations, following this:
http://www.eclipse.org/jetty/documentation/current/configuring-ssl.html
And this:
Configure SSL on Jetty
At the end I always have this exception
2013-07-07 13:36:11.742:WARN:oeji.SelectorManager:qtp1384613607-13-selector-0:
java.lang.NullPointerException
    at org.eclipse.jetty.server.HttpConnection.<init>(HttpConnection.java:96)
    at org.eclipse.jetty.server.HttpConnectionFactory.newConnection(HttpConnectionFactory.java:61)
    at org.eclipse.jetty.server.SslConnectionFactory.newConnection(SslConnectionFactory.java:86)
    at org.eclipse.jetty.server.ServerConnector$ServerConnectorManager.newConnection(ServerConnector.java:401)
    at org.eclipse.jetty.io.SelectorManager$ManagedSelector.createEndPoint(SelectorManager.java:575)
    at org.eclipse.jetty.io.SelectorManager$ManagedSelector.access$500(SelectorManager.java:318)
    at org.eclipse.jetty.io.SelectorManager$ManagedSelector$Accept.run(SelectorManager.java:699)
    at org.eclipse.jetty.io.SelectorManager$ManagedSelector.runChange(SelectorManager.java:407)
    at org.eclipse.jetty.io.SelectorManager$ManagedSelector.runChanges(SelectorManager.java:396)
    at org.eclipse.jetty.io.SelectorManager$ManagedSelector.processChanges(SelectorManager.java:479)
    at org.eclipse.jetty.io.SelectorManager$ManagedSelector.select(SelectorManager.java:440)
    at org.eclipse.jetty.io.SelectorManager$ManagedSelector.run(SelectorManager.java:420)
    at org.eclipse.jetty.util.thread.QueuedThreadPool.runJob(QueuedThreadPool.java:596)
    at org.eclipse.jetty.util.thread.QueuedThreadPool$3.run(QueuedThreadPool.java:527)
    at java.lang.Thread.run(Thread.java:722)

I put everything in jetty.xml. Here is my configuration.
<New id="sslContextFactory" class="org.eclipse.jetty.util.ssl.SslContextFactory">
    <Set name="KeyStorePath">
        <Property name="jetty.home" default="." />/<Property name="jetty.keystore" default="etc/keystore"/>
    </Set>
    <Set name="KeyStorePassword">
        <Property name="jetty.keystore.password" default="OBF:password"/>
    </Set>
    <Set name="KeyManagerPassword">
        <Property name="jetty.keymanager.password" default="OBF:password"/>
    </Set>
    <Set name="TrustStorePath">
        <Property name="jetty.home" default="." />/<Property name="jetty.truststore" default="etc/keystore"/>
    </Set>
    <Set name="TrustStorePassword">
        <Property name="jetty.truststore.password" default="OBF:password"/>
    </Set>
    <Set name="EndpointIdentificationAlgorithm"/>
    <Set name="ExcludeCipherSuites">
        <Array type="String">
            <Item>SSL_RSA_WITH_DES_CBC_SHA</Item>
            <Item>SSL_DHE_RSA_WITH_DES_CBC_SHA</Item>
            <Item>SSL_DHE_DSS_WITH_DES_CBC_SHA</Item>
            <Item>SSL_RSA_EXPORT_WITH_RC4_40_MD5</Item>
            <Item>SSL_RSA_EXPORT_WITH_DES40_CBC_SHA</Item>
            <Item>SSL_DHE_RSA_EXPORT_WITH_DES40_CBC_SHA</Item>
            <Item>SSL_DHE_DSS_EXPORT_WITH_DES40_CBC_SHA</Item>
        </Array>
    </Set>
</New>
<Call id="sslConnector" name="addConnector">
    <Arg>
        <New class="org.eclipse.jetty.server.ServerConnector">
            <Arg name="server">
                <Ref refid="Server" />
            </Arg>
            <Arg name="factories">
                <Array type="org.eclipse.jetty.server.ConnectionFactory">
                    <Item>
                        <New class="org.eclipse.jetty.server.SslConnectionFactory">
                            <Arg name="next">http/1.1</Arg>
                            <Arg name="sslContextFactory">
                                <Ref refid="sslContextFactory"/>
                            </Arg>
                        </New>
                    </Item>
                    <Item>
                        <New class="org.eclipse.jetty.server.HttpConnectionFactory">
                            <Arg name="config">
                                <Ref refid="tlsHttpConfig"/>
                            </Arg>
                        </New>
                    </Item>
                </Array>
            </Arg>
            <Set name="host">
                <Property name="jetty.host" />
            </Set>
            <Set name="port">
                <Property name="jetty.tls.port" default="8443" />
            </Set>
            <Set name="idleTimeout">30000</Set>
        </New>
    </Arg>
</Call>

Then all what I did without SSL should work on jetty ? My servlet and socket ?
Thanks everybody
Answer: Actually, I was on Jetty 9.0.3 using the librairies of version 9.0.4. I upgraded the server to 9.0.4 and it now works!
Answer: I had the same problem (on jetty 9.0.4). With all libs of the 9.0.4 versions, and the error presumed.
After some digging in examples; I encountered this jetty configuration example. When you look at the jetty-ssl.xml file you encounter following code:

  <New id="sslHttpConfig" class="org.eclipse.jetty.server.HttpConfiguration">
    <Arg><Ref refid="httpConfig"/></Arg>
    <Call name="addCustomizer">
      <Arg><New class="org.eclipse.jetty.server.SecureRequestCustomizer"/></Arg>
    </Call>
  </New>

When you add this to you xml file all should be working.


Use Razor in Jquery

Question: I am writing AJAX call which looks as follow:

            }

i want to call _ModulePatial action in Home controller in default Area using Url.Action

                    }

/Home/_ModulePartial works fine but i want to achive this using @Url.Action because we have 2 different URl http:/TestUrl.com/Test/User/Login and http://TestUrl.com/User/Login so the above Url will not work under one of the server. as 1st Url contains "Test" it is not able to find Home controller.
So can we use Url.Action in Jquery?
Firebug gives this error
SyntaxError: missing } after property list
[Break On This Error]

url: /Home/_ModulePartial,

when trying to call using @Url.Action in 1st script
Answer: You need to include the area name in your ajax call and you have to do it like this:
'@Url.Action("_ModulePartial", "Home", new { area = "Test" })'

Here's the complete ajax call:

Also, ensure that the extra "}" after the script tag is just a copy-paste error.
Answer: Got it... :)
Just use single quotes. and it works

            }

Comment: To expand on this, remember that ASP.NET calls such as Razor are performed at the server level, before the page is sent to the client. What you are doing is setting a placeholder for text to be injected by the server. Once the page is sent to the client, the placeholder text will already have been changed. jQuery is a client-side language, and is interpretted by the browser. All of the server-side code will have been replaced, and the browser will only see the result of the ASP.NET calls. I hope that makes sense.

Use Razor in Jquery


Doing Cox univariate analyses followed by multivariable analysis on significant variables?

Question: I have collected a dataset on a group of patients with a rare disease where not much is known. These patients can have an outcome, X, which has been seen in 50 of the 300 patients. I want to find out the risk factors associated with getting X in this rare disease. Since barely anything is known about this disease I barely have any hypotheses about which risk factors might have an influence except for the common stuff like smoking. I have over 30 variables collected (possible risk factors).  I understand that you can only analyze one risk factor for every 10 events but I really only want to find possible risk factors so I can help these patients, just a clue for possible risk factors would help.
To minimize the amount of variables I input into the multivariable analysis I was thinking of doing something I've seen in several other studies where they do a univariable analysis for each risk factor, then they grab those with a p value of below 0.20 (where does that number come from?) and enter those into the multivariable analysis. In the table the results from both analyses are shown. I've seen this in reputable journals such as NEJM. What are some caveats of doing it this way? Or could I do it in another way? Any help is greatly appreciated.
Answer: This type of approach is often used,* but it has some dangers. First are the problems inherent in any attempt at automated model selection like that. Second is the inherent omitted-variable bias in Cox models. As with logistic regression, omitting any predictor associated with outcome from a Cox model will tend to bias the magnitudes of coefficients of included predictors down toward zero. Unlike with linear regression, this is the case even if the omitted predictor is uncorrelated with the included predictors. So with the single-predictor analyses there is a risk of missing an important contributor on this account.
An approach based on knowledge of the subject matter is generally best. It might be possible to use such knowledge to combine multiple related risk factors into single combined predictors (without looking first at their relationships with outcome). Or you could take advantage of the penalization provided by ridge regression to allow a higher ratio of included predictors to events. The penalization might be omitted from predictors like smoking that you expect to be strongly associated with outcome.
These types of issues are explained in Frank Harrell's course notes and book, with illustrative examples.

*The single-predictor p-value cutoff for inclusion in that approach to Cox multiple regression is a rule of thumb to get the number of predictors down to a reasonable value. A value of 0.20 is not always the choice.


BEM syntax in SASS

Question: I have a simple HTML and CSS with BEM. I want style for class .block__item-header-mark inside class .block__item-header--has-round.
I use CSS .block__item-header--has-round .block__item-header-mark { /styling here/ }. But I don't think this is good syntax.
My question is:

How to call .block__item-header-mark inside .block__item-header--has-round with better syntax in my SCSS code ?
My BEM syntax is good ?

Code

.block {
  &__item {
    &-header {
      &--has-round {
        /* How to call .block__item-header-mark with better syntax ??? */
        .block__item-header-mark {
          /*overide style*/
        }
      }
      &-mark {
        /*normal style*/
      }
    }
  }
}

Comment: That's a perfectly fine approach.
Comment: BEM classes on your HTML is perfect. On CSS, I don't think you need to use all the hierarchy as if you need some selector to override your style, the math will be hard. Limit the specificity of your CSS selector as possible
Answer: You can create a variable to refer to the scope you want

.block {
  &__item {
    &-header {
      $header: &;
      &--has-round {
        #{ header }-mark {
          /* override style */
        }
      }
      &-mark {
        /*normal style*/
      }
    }
  }
}
Comment: `&--has-round &-mark` <- wouldn't this violate BEM?
Comment: @zerkms I don't think it violates, but then again, I haven't used BEM in a while and I could be wrong
Comment: https://en.bem.info/methodology/quick-start/ "this block structure is always represented as a flat list of elements in the BEM methodology:" BEM implies you don't use cascade.
Comment: @zerkms `has-round` is a modifier, so the actual mistake I see is it should be `&_has-round &-mark`
Comment: Yep, but `&--has-round &-mark` is cascade and is not "flat" anymore.
Comment: In my head modifiers weren't flat. Cascade has a very different meaning than the opposite of flat, so that got me confused a bit in your second comment.

I'll edit my answer

BEM syntax in SASS


Haskell: Perform function for each element in function list parameter

Question: There is probably a simple answer to this, but I am new to Haskell. I am trying to iterate through a function parameter and use each list element to call another function. I have a function that performs a move given the game board, the move, and the player number and returns the new game board. Its function header looks like this:
play :: [[Char]] -> Char -> Char -> [[Char]]
play gameBoard moveDirection playerSymbol = ...

I am trying to call it from a driver function that has the parameters of the initial game board and a list of moves to be performed on the game board. Is there a way to call the play function for each element in the move list such that the gameExample function below return the game board after every move has been made?
moveDirections = "udlrudlr"
gameExample :: [[Char]] -> [Char] -> [[Char]]
gameExample gameBoard (moveDirection : moveDirections) =
    play gameBoard moveDirection 'p'

Please let me know if you require any clarifications.
Comment: Calling a function for each element of the list, feeding each call's output to the input of the next, is known as a *fold*.  See [foldl and foldr](https://hackage.haskell.org/package/base-184.108.40.206/docs/GHC-List.html#v:foldl)
Answer: You can do it with explicit recursion:
gameExample gameBoard [] = gameBoard
gameExample gameBoard (moveDirection : moveDirections) =
    gameExample (play gameBoard moveDirection 'p') moveDirections

Or you can use the foldl function to do that for you:
gameExample = foldl (\gameBoard moveDirection -> play gameBoard moveDirection 'p')

There's also Data.Foldable.foldl', which is usually better for performance than foldl is, but you don't need to worry about that for a toy program like this one.
Comment: Also, consider changing the order of the arguments to `play` so that you can simplify the definition to `gameExample = foldl (play 'p')`.


If $G$ is a group with, then the subgroup of $S_n$ constructed in the proof of Cayley's theorem is a transitive subgroup of $S_G$

Question: I'm new to group theory and have some struggles to show the the question. Here, a subgroup $H\subset S_n$ is called transitive if for every $\{i,j\}\subset\{1,2,\dots,n\}$ there is a $\tau\in H$ with $\tau(i) = j$ and Cayley's theorem says that every group $G$ is isomorphic to a subgroup of $S_G$.
We can define a homomorphism $\varphi : G\to S_G$ and know the fact that $G$ is isomorphic to $\varphi(G)$. So I think that we need to show that $\varphi(G)$ is a transitive subgroup of $S_G$ (if I'm correct so far) and I cannot progress anymore. Can you help me to show this or if my approach is wrong, correct it please.
Comment: What is the homomorphism $\phi : G \rightarrow S_G?$ If I had to guess, probably $\phi(g) = L_g$, where $L_g : G \rightarrow G$ is defined by $L_g(x) = gx$ or something like that (I might have messed up something, you need to be careful here so that it's actually a homomorphism).
Answer: You have to chase the proof of Cayley's theorem.  If your group $G$ is
$$
\{e=g_1, g_2, \ldots, g_n\}
$$
then we have the permutation $\sigma_k$ induced by $g_k$ which respects the permutation on the subscripts obtained by left-multipying by $g_k$.  So, if $g_kg_i = g_j$ then $\sigma_k(i)=j$.  Then $g_k \mapsto \sigma_k$ is an isomorphism from $G$ to the subgroup $\{\sigma_k \mid k = 1, 2, \ldots, n\}\subseteq S_n$.
Now the result is clear:  if you want to know which permutation maps $i$ to $j$, you just use the subscript $k$ corresponding to $g_jg_i^{-1}$.  This is some element $g_k \in G$, and by definition $\sigma_k(i)=j$.
Edit:  I see that I did this in $S_n$ and not $S_G$, but it's the same idea:  the equation $xi=j$ can always be solved for $x \in G$.
Answer: I think it's a good idea to keep well-separated in the argument the symmetric groups $S_G$ and $S_n$. Said $\varphi$ Cayley's embedding of $G$ into $S_G$, the subgroup $\varphi(G)\le S_G$ is transitive because, for every $g,h\in G$, we get $\varphi_{hg^{-1}}(g)=h$: so, for every $g,h\in G$, there's an element of $
\varphi(G)$ (namely $\varphi_{hg^{-1}}$), which carries $g$ to $h$.
Now, to plug this all into $S_n$, you have to take a bijection $f\colon G\to\{1,\dots,n\}$ and define the isomorphism (prove it) $\psi_f\colon S_G\to S_n$ via $\sigma\mapsto f\sigma f^{-1}$. Then $\psi_f(\varphi(G))$ is a transitive subgroup of $S_n$ (isomorphic to $G$), because, for every $i,j\in\{1,\dots,n\}$:
\begin{alignat}{1}
&(\psi_f(\varphi_{f^{-1}(j)(f^{-1}(i))^{-1}}))(i)=j \\
\end{alignat}

If $G$ is a group with, then the subgroup of $S_n$ constructed in the proof of Cayley’s theorem is a transitive subgroup of $S_G$


Show that bias term involving an indicator function convergences to zero

Question: Assume that we have $N$ observations of i.i.d. data $(Y_i,X_i)_{i=1}^{N}$. We want to learn the model given by $Y=f(X)+\epsilon$. We use the data to estimate $\hat{f}$ using any machine learning algorithm, e.g. random forests or neural nets. We assume that our method is consistent, i.e. $\hat{f}\xrightarrow{p}f$, but we do not assume anything about the convergence rate. In particular, we do not assume that $\hat{f}$ is root-N consistent.
We consider a bias term that arises from a particular estimator (I don't want to bore you with the details). The bias term reads
$bias=\sqrt{N}\mathbb{E}\left[Y_i\left(1_{\left\{ f\left(X_{i}\right)<c\right\} }-1_{\left\{ \hat{f}\left(X_{i}\right)<c\right\} }\right)\right],$
where $c$ is a known constant.
I want to prove that $bias=o_p(1)$, i.e. as $N\xrightarrow{}\infty$, we have $bias\xrightarrow{p}0$. We can assume that $X$ has a density. If we didn't have the indicator functions, it would be impossible to show without assume root-N consistency, but I wonder whether we can show this due to the indicator function. For instance, we may assume that $\text{Pr}\left(f\left(X\right)=c\right)=0$.
Question: How would you prove $bias=o_p(1)$ (if it is at all)?
Answer: Maybe something like the following treatment:
Define the random variable
$$Z_i(N) \equiv \left(1_{\left\{ f\left(X_{i}\right)<c\right\} }-1_{\left\{ \hat{f}\left(X_{i}\right)<c\right\} }\right) \implies Z_i(N) \in \{-1,0,1\}$$
Since the estimator is consistent, we also have that
$$Z_i(N) \to_p 0 \implies Z_i(N) \to_d 0$$
Then
$$ \text{bias} = -\mathbb{E}\left[Y_i\mid \{Z_i(N) =-1\}\right]\cdot \sqrt{N} \cdot P_N(Z_i=-1) + \mathbb{E}\left[Y_i\mid\{ Z_i(N) =1\}\right]\cdot \sqrt{N}\cdot  P_N(Z_i=1)$$
So one needs for zero bias at the limit, that
$$\sqrt{N} \cdot P_N(Z_i=-1) \to 0,\qquad \sqrt{N}\cdot  P_N(Z_i=1) \to 0$$
or,
$$ \exists\, N^*, \,\delta >0 : N> N^*\implies P_N(Z_i=-1) \leq \frac{1}{\sqrt{N}\cdot N^\delta}$$
and the same for the other probability. But this requirement will eventually hold for some finite $N^*$, since these probabilities will not "jump down" to zero from some strictly positive value.
PS: Evidently, we need also to assume that the conditional expected values remain finite.


Problemas com shortcodes aninhadas

Question: Olá! Estou tentando utilizar algumas shortcodes aninhadas, porém não estou tendo êxito.
As shortcodes são estas, em ordem de declaração na functions.php:
function p_generico_shortcode( $atts , $content = null )
{
    return '
' . do_shortcode($content) . '
';
}
add_shortcode( 'pov-generico', 'p_generico_shortcode' );

Segunda:
function f_moca_shortcode( $atts , $content = null )
{
    return '
' . do_shortcode($content) . '
';
}
add_shortcode( 'fala-moca', 'f_moca_shortcode' );

Ao tentar utilizar:
[fala-moca]TEXT[pov-generico]OTHER TEXT[/pov-generico][/fala-moca]

estou obtendo:

TEXT

OTHER TEXT

Em vez de:

TEXT
OTHER TEXT

Percebi que, ao aninhar shortcodes que retornam HTML com elementos diferentes (ex. p e span) ele processa corretamente.
Answer: RESOLVIDO!
O problema simplesmente era pelo fato do wordpress não aceitar (assim como os padrões w3c), duas tags p aninhadas. Alterando para span a tag filha resolveu tudo.

Problemas com shortcodes aninhadas


Generate every permutation of list elements pairs without repeating or inverted pairs

Question: I know this is similar to previous questions but there are enough differences in my request to merit a new question. I have a list of string elements.
>>> mainlist
['one', 'two', 'three', 'four', 'five']

I want to create a looped program that takes the first element and then pairs it with the remaining elements like so:
['one two', 'one three', 'one four', 'one five']

Notice it did not create the pair 'one one'
The next cycle should be:
['two three', 'two, four', 'two five']

Notice, again, it did not create 'two two' or even 'two one' as, for my purposes, this is equal to 'one two'.
and so on...
The nearest I've got is:
for primary in mainlist:
    for secondary in mainlist:
        if primary == secondary: print("skipping...")
        else: print(primary + " " + secondary)

>> skipping...
one two
one three
one four
one five
two one
skipping...
two three
two four
two five
three one
three two
skipping...
three four
three five
four one
four two
four three
skipping...
four five
five one
five two
five three
five four
skipping...

Based on the above you can see that this doesn't quite match what I'm after. Any help would be really appreciated - I'm sure there's an elegant solution out there somewhere.
Answer: You want to use itertools.combinations:
In [1]: import itertools as it

In [2]:  mainlist = ['one', 'two', 'three', 'four', 'five']

In [3]: for a,b in it.combinations(mainlist, 2):
   ...:     print(a, b)
   ...:
one two
one three
one four
one five
two three
two four
two five
three four
three five
four five

In the same way you could also create all possible triplets from the same by specifying 3 as second argument:
In [4]: for a,b,c in it.combinations(mainlist, 3):
   ...:     print(a, b,c)
   ...:
one two three
one two four
one two five
one three four
one three five
one four five
two three four
two three five
two four five
three four five

If you want to produce also the pairs one one, two two etc. you should use combinations_with_replacement instead.

If you want to group together the pairs with the same first element you can use itertools.groupby:
In [1]: import itertools as it
   ...: mainlist = ['one', 'two', 'three', 'four', 'five']
   ...:

In [2]: for key, group in it.groupby(it.combinations(mainlist, 2), key=lambda x:x[0]):
   ...:     print('key is', key)
   ...:     print('grouped elements', list(group))
key is one
grouped elements [('one', 'two'), ('one', 'three'), ('one', 'four'), ('one', 'five')]
key is two
grouped elements [('two', 'three'), ('two', 'four'), ('two', 'five')]
key is three
grouped elements [('three', 'four'), ('three', 'five')]
key is four
grouped elements [('four', 'five')]

Finally, if you want to write the loops explicitly you can use enumerate to keep track of your current index:
In [3]: for i, el in enumerate(mainlist):
   ...:     for el2 in mainlist[i+1:]:
   ...:         print(el, el2)
   ...:
one two
one three
one four
one five
two three
two four
two five
three four
three five
four five

This is basically what combinations does, except that it works with arbitrary sizes (pairs, triplets etc)
Answer: Simply use nested for loops:
>>> mainlist = ['one', 'two', 'three', 'four', 'five']
>>> for e in mainlist:
    for i in mainlist:
        if e == i:
            print "Skipping"
        else:
            print e, i

Skipping
one two
one three
one four
one five
two one
Skipping
two three
two four
two five
three one
three two
Skipping
three four
three five
four one
four two
four three
Skipping
four five
five one
five two
five three
five four
Skipping
>>>

Comment: This unfortunately produces inverted pairs eg. 'one two' and 'two one' so no good.
Answer: One solution:
l = ['one', 'two', 'three', 'four', 'five']

for i in range(len(l)):
    print ["{} {}".format(l[i], l[j]) for j in range(i + 1, len(l))]

Or you can explore the endless possibilities of itertools as suggested by @Bakuriu.
output
['one two', 'one three', 'one four', 'one five']
['two three', 'two four', 'two five']
['three four', 'three five']
['four five']
[]

Comment: Thanks, list indices is what I needed!
Comment: @Beeman You're welcome. Feel free to mark my answer as helpful or accepted if you want to reward me :-)
Comment: Hi, I had to mark the answer that I went with as the accepted one - despite yours and others being equally useful, sorry. Also I don't have enough rep to mark yours as helpful but when I do I shall
Answer: Nested for loops using the indices should do the trick:
for i in range(len(mainlist)):
    for j in range(i,len(mainlist)):
        if mainlist[j] == mainlist[i]:
            print 'Skipping'
        else:
            print mainlist[i] + ' ' + mainlist[j]

Comment: Thanks - I'll use this as it's the easiest to implement in my existing code


Dúvidas sobre o uso do tipo GUID no lugar de int

Question: Vejo muitos modelos de sistemas na net onde campos Id são definidos com tipo GUID em vez de INT, como no exemplo abaixo:

public class Product
{
    public Guid Id { get; protected set; }
    public string Name { get; protected set; }
    public int Quantity { get; protected set; }
    public DateTime Created { get; protected set; }
    public DateTime Modified { get; protected set; }
    public bool Active { get; protected set; }
}

Qual a vantagem de usar GUID em vez de INT?
Isso pode prejudicar a performance da Aplicação e/ou banco de dados?
Tenho um sistema comercial que está sendo projetado ainda... Se eu usar GUIDS em vez de INTS em minhas tabelas, isso seria recomendado?

Um abraço a todos!
Comment: Possível duplicada de: [Devo utilizar GUID ou int como chave primária?](https://pt.stackoverflow.com/questions/21907/devo-utilizar-guid-ou-int-como-chave-primária)
Answer: Guid de uma forma simples é uma estrutura que representa um inteiro de 128 bits (16 bytes), permitindo representar 3.4028237*10^38 valores.
Um int dependendo do sistema é representado por 32 bits (4 bytes).
Na minha opinião depende do tamanho da sua base de dados.
Neste link, é melhor explicado:
https://pt.stackoverflow.com/a/22574/104651