Distributed filesystem - confused

Question: I am new to this concept. :)
Can I use a distributed filesystem in as a way to have redundancy for web applications?
Server A and Server B would have Apache/mySql installed on the distributed filesystem and server C manages the connections (if sA is down, go to sB - or a round-robin DNS). Would something like this work?
If so, that would be awesome, since I would not have to worry about db syncing and file syncing.
Thank you!
Edit: Thank you very much all for the informative answers! Lots of things for me to digest. I (almost) randomly nominated an answer.
Comment: Can you?  Yes.  Should you?  Hell no.
Answer: Since you aren't clear about what technology you're actually talking about, I assume by "distributed filesystem" you mean DFS.
DFS-R doesn't work with databases. You'll still need to provide redundancy at the database levels, however this will work for web content. You only need to update a single server and the changes will be replicated to the other servers in the DFS-R pool.
Answer:
Can I use a distributed filesystem in as a way to have redundancy for
  web applications?

Sure, you can.

Server A and Server B would have Apache/mySql installed on the
  distributed filesystem and server C manages the connections (if sA is
  down, go to sB - or a round-robin DNS). Would something like this
  work?

You can use MySQL replication or take a look at: http://dev.mysql.com/doc/refman/5.0/en/ha-overview.html
And Apache, you can setup A and B with DRBD in dual-primary mode and a cluster filesystem like GFS or OCFS2. About the C, you can use HAProxy or Pacemaker.
Answer: MySQL cannot run from a shared or synced filesystem. You will need to look into other solutions for that, for example using MySQL Cluster.
Apache and other web servers should be fine running on shared or synced storage. Make sure you share the session storage for your scripting language as well (e.g., PHP), otherwise the user will lose the session when changing server.
DNS round-robin is not a good solution for HA (high availability), and arguably not even for loadbalancing. Consider using some other technique. There are for example multiple solutions for loadbalancing which also achieves HA. From the top of my head: Linux Virtual Server (LVS), Varnish and possibly Nginx.
Comment: "MySQL cannot run from a shared or synced filesystem" -- I'd *love* to know where you got that idea.
Comment: womble, from this page: http://dev.mysql.com/doc/refman/4.1/en/multiple-servers.html I see now that they have removed the warning from newer versions of the manual, but that doesn't mean that the problems mentioned in the old manual shouldn't be considered. MySQL Cluster or similar solutions is still the preferred way.
Comment: I see no mention of the word "synced" on that page, and the only mentions of "shared" are related to shared memory.  The only restriction I can see is on having two MySQL servers using a common data directory, which isn't specific to a shared filesystem.
Answer: As for the MySQL bit, you can either setup a MultiMaster configuration ( http://dev.mysql.com/doc/refman/5.1/en/mysql-cluster-replication-multi-master.html ), or you can have a Master/Slave server, kept in sync via DRBD ( http://www.mysql.com/why-mysql/drbd/ ), with a heartbeat sensor to handle failover -- or you can just have a Master/Slave kept in sync via MySQL's internal replication; it's brain-dead simple to get up and running. There are about a million ways to handle failover between the two servers.
Other people have provided good answers to the Apache issue.

Distributed filesystem - confused


Lidando com arquivos compactados em PHP

Question: Preciso resolver o seguinte problema com PHP: o usuário irá fazer upload de um arquivo zip contendo centenas (possivelmente milhares) de arquivos. Eu devo descompactar esses arquivos em um certo diretório e, após isso, devo iterar sobre o nome (preciso do nome!) de cada arquivo arquivo descompactado para realizar um conjunto de operacoes sobre esse arquivo. Alguém conhece alguma ferramenta em PHP para lidar com esse tipo de problema?
Answer: Extrair arquivos em PHP: http://php.net/manual/en/ziparchive.extractto.php
Obter conteúdo de um diretório: http://php.net/manual/pt_BR/function.scandir.php
Você também pode usar comandos do teu sistema, se preferir: http://php.net/manual/pt_BR/function.shell-exec.php

Lidando com arquivos compactados em PHP


How to use 32-bit native libraries on 64-bit Android device

Question: I use a native library in my application that is only compiled for armeabi, armeabi-v7a and x86.
When this library is loaded on a 64-bit device like the Samsung S6, the application crashes with an UnsatisfiedLinkError
java.lang.UnsatisfiedLinkError: dalvik.system.PathClassLoader[DexPathList[[zip file "/data/app/com.myapp-2/base.apk"],nativeLibraryDirectories=[/data/app/com.myapp-2/lib/arm64, /vendor/lib64, /system/lib64]]] couldn't find "libfoo.so"
    at java.lang.Runtime.loadLibrary(Runtime.java:366)
    at java.lang.System.loadLibrary(System.java:989)

The library is closed source unfortunately. Is there any way to fix this without recompiling the library with 64-bit targets?
Comment: Have you looked at https://stackoverflow.com/q/27712921/603270 and https://stackoverflow.com/a/29329413/603270 ?
Comment: I did. One applies to AOSP, the other one for dynamic classloading. My case is actually much more simple. But I just discovered that another native library that I include does indeed supply 64-bit .so files, therefore there is a arm64-86 folder in my /lib folder in the final apk. Probably this is why the system assumes, that I provide 64-bit .so files in all cases. I'll try to recompile this librariy with 32-bit support only and see if it works.
Comment: Good thinking. Let us know (answer you own question if needed).
Comment: http://tools.android.com/tech-docs/new-build-system/user-guide/apk-splits#TOC-ABIs-Splits
Answer: When you install an APK on Android, the system will look for native libraries directories (armeabi, armeabi-v7a, arm64-v8a, x86, x86_64, mips64, mips) inside the lib folder of the APK, in the order determined by Build.SUPPORTED_ABIS.
If your app happen to have an arm64-v8a directory with missing libs, the missing libs will not be installed from another directory, the libs aren't mixed. That means you have to provide the full set of your libraries for each architecture.
So, to solve your issue, you can remove your 64-bit libs from your build, or set abiFilters to package only 32-bit architectures:
android {
    ....
    defaultConfig {
        ....
        ndk {
            abiFilters "armeabi", "armeabi-v7a", "x86", "mips"
        }
    }
}

Comment: add `android.useDeprecatedNdk=true` to a file named gradle.properties at the root of your project. btw don't feel bad about using a deprecated integration, as using abiFilters is still the cleanest way atm to filter out 64-bit libs from an APK.
Comment: As of today (August 1st, 2019), you cannot submit APKs to the Google Play Store without 64-bit architecture.
Comment: Looks good, the 64-bit folders are gone with this snippet. I will mark the answer as accepted once I can find a 64 bit phone to reproduce
Comment: http://tools.android.com/tech-docs/new-build-system/user-guide/apk-splits#TOC-ABIs-Splits
Comment: Getting error NDK integration is deprecated in the current plugin.  Consider trying the new experimental plugin.
Comment: Thanks @ph0b, this solves a totally different issue I've been struggling with for days :)
Comment: @ph0b You should make a separate answer. It is bearly visible and this solved my problem too :)
Comment: @ph0b i have issue with two different so file that i have used if i set ndk api filter to `abiFilters "arm64-v8a","armeabi", "armeabi-v7a", "x86","x86_64", "mips"` then first so file working fine but second so file not loaded and if i set `abiFilters "armeabi", "armeabi-v7a", "x86", "mips"` then first so file store loading but second file working fine can you please provide any solution
Comment: Adding this to my app's `build.gradle` file did it for me :)
Comment: Unfortunately, this solution did not work for me. I have also updated the gradle.properties file with deperecatedNDK property but that also do not behave as per expectation.
Answer: The above answer will help to generate a build with 32- bit only not a 64-bit. If you are using  [ abiFilters "armeabi", "armeabi-v7a", "x86", "mips"  ]. generate signed apk means, that is not for 64 bit. It will raise an error when we upload into Google Play store. It is not an 64 bit build.


ciclo de repetiçao For encadeado, em C # sharp, iniciaçao

Question: Olá, boa tarde alguém me consegue corrigir o programa para estar certo? O objetivo é o programa em c sharp escreve está pronto para receber a reforma, caso tenha mais de 60 anos e mais de 30 anos de trabalho. Estou a falhar em algo e nao consigo descobrir, obrigado.
class Program
    {
        static void Main(string[] args)
        {
            bool val;
            int codigo, idade, trab, anonascim, anoingres;
            int anoatual=2020;

        do // ler e validar o codigo do empregado
        {
            Console.Write("\n\t Insira o codigo do empregado");
            val = int.Parse(Console.ReadLine(), out codigo);

        }
        while (!val);

        for (int i = 0; i <codigo ; i++)
        {
            do
            {
                Console.Write("\n\t Insira o ano de nascimento do empregado");
                val = int.Parse(Console.ReadLine(), out anonascim);
                Console.Write("\n\t Insira o ano de ingresso na empresa");
                val = int.Parse(Console.ReadLine(), out anoingres);

             }
            while (!val);
        }

        if (idade > 64 || trab > 29)
        {
            for (int idade = 0; idade > 64; idade++)
            {
                idade = (anoatual - anonascim);

                Console.Write($"\t com {idade} ");

                for (int trab = 0; trab > 29; trab++)
                {

                    trab = (anoatual - anoingres);
                    Console.Write($"\t com {trab} ");
                }

            }
        }

                    Console.WriteLine($"\n\t Esta em condicoes de requerer a reforma :{i}, codigo");

            else
            {
                Console.WriteLine($"\n\t Nao esta em condicoes de requerer a reforma ");

            }
        }

    }
}

Comment: Qual o erro específico que está acontecendo?
Answer: Olá, tudo bem? De acordo com a sua descrição, caso a pessoa tenha 64 anos ou mais e tenha trabalhado por 29 anos ou mais ela pode requerer a reforma. Com base nisso, refiz o seu código.
class Program
{
    static void Main(string[] args)
    {
        bool val;
        int codigo, idade, trab, anonascim, anoingres;
        int anoatual=2020;

    do // ler e validar o codigo do empregado
    {
        Console.Write("\n\t Insira o codigo do empregado");
        val = int.Parse(Console.ReadLine(), out codigo);

    }
    while (!val);

        do
        {
            Console.Write("\n\t Insira o ano de nascimento do empregado");
            val = int.Parse(Console.ReadLine(), out anonascim);
            Console.Write("\n\t Insira o ano de ingresso na empresa");
            val = int.Parse(Console.ReadLine(), out anoingres);

         }
        while (!val);

           idade = (anoatual - anonascim);
           trab = (anoatual - anoingres);

            Console.Write($"\t com {idade} ");
            Console.Write($"\t com {trab} ");

            if(idade >= 64 && trab >= 29){
            Console.WriteLine($"\n\t Esta em condicoes de requerer a reforma :{i}, codigo");}

        else
        {
            Console.WriteLine($"\n\t Nao esta em condicoes de requerer a reforma ");}}

Answer:   bool val,val1;

[...]
do
   {
        Console.Write("\n\t Insira o ano de nascimento do empregado");
        val = int.TryParse(Console.ReadLine(), out anonascim);
        Console.Write("\n\t Insira o ano de ingresso na empresa");
        val1 = int.TryParse(Console.ReadLine(), out anoingres);

     }
    while (!val && !va1);


$E(\|x\|^p_2)$ of a $n$ dimensional vector given by a gaussian distribution

Question: Suppose that vector $x \in \mathcal{R}^n$, and $x$ conforms to the standard gaussian distribution $\mathcal{N}(0, I_n)$. Can we calculate $E(\|x\|^2_2)$? Can we further extend to the case of  $E(\|x\|^p_2)$, when $p\in \mathcal{N}, p\geq 1$?
Note that there is already a link for the $p=1$ case, i.e., Average norm of a N-dimensional vector given by a normal distribution
Comment: Is this supposed to be the $p$-th power of the $2$-norm or just the $p$-norm? Of maybe the $p$-th power of the $p$-norm?  Your formula and the title are conflicting on this.
Comment: Actually p-th power euclidean norm.
Answer: If $X$ is a standard $n$-dimensional Gaussian random variable, then $\|X\|_2^2 \sim \chi_n^2$. The chi-squared distribution has density
$$2^{-n/2} \Gamma(n/2)^{-1} x^{n/2 - 1} e^{-x/2}I\{x > 0\} \, dx.$$
With this we can find an explicit formula for the expectation of $\|X\|_2^p$
$$E[\|X\|_2^p] = E[(\|X\|_2^2)^{p/2}] = \int_0^\infty 2^{-n/2} \Gamma(n/2)^{-1} x^{(p + n)/2 - 1} e^{-x/2} \, dx = 2^{-n/2} \Gamma(n/2)^{-1} 2^{(p + n)/2} \Gamma((p + n)/2) = 2^{p/2} \frac{\Gamma\Big(\frac{p + n}{2}\Big)}{\Gamma\Big(\frac{n}{2}\Big)}.$$
To get approximations and inequalities, you just need to apply some approximations for the gamma-function. A standard reference for this would be Abramowitz and Stegun.


Self-adjoint bounded operator with finite spectrum implies diagonalisable?

Question: Let $T$ be a self-adjoint bounded operator on a not-necessarily finite dimensional Hilbert space.
Suppose $T$ has finite spectrum. Does it follow that the elements of the spectrum are eigenvalues, and the operator diagonlisable?
Answer: Yes, you can calculate the spectral projection for each eigenvalue $\lambda$ by integrating the resolvent in a small contour around $\lambda$ that avoids all of the other eigenvalues
$$P_\lambda = \frac{1}{2\pi i} \int_C (T-z I)^{-1} \, dz.$$
The Hilbert space will then be the direct sum of the spectral subspaces corresponding to the spectral projections. Isolated elements of the spectrum are always eigenvalues.
Comment: I think so. A self-adjoint operator with a finite spectrum is a special case of self-adjoint operators with compact resolvent. You might want to look up the spectral theorem for self-adjoint operators with compact resolvent.
Comment: Thank you Brian
Comment: Does this speak to discrete spectrum?
Answer: Since this is also tagged "C$^*$-algebras", I'll answer in that setting. If $\sigma(T)=\{\lambda_1,\ldots,\lambda_n\}$, we can construct continuous functions (polynomials, even) $f_1,\ldots,f_n$ with $f_k(\lambda_j)=\delta_{kj}$. Then $\sum_k\lambda_kf_k(t)=t$, and functional calculus gives us
$$
T=\sum_k\lambda_kf_k(T),
$$
where $f_1(T),\ldots,f_n(T)$ are pairwise orthogonal projections.
Comment: Glad I could help!
Comment: Thank you Martin. You're a maestro with this stuff.


Por que em documentação a vírgula fica do lado de dentro?

Question: Lendo documentação muitas vezes já vi isso mas não entendo porque é assim:
JSON.parse(text[, reviver])

Por que a vírgula não fica para o lado de fora? Por exemplo, assim:
JSON.parse(text,[ reviver])

Tem alguma explicação?
Answer: Os colchetes indicam que o parâmetro é opcional. A vírgula fica dentro dos colchetes porque ela própria faz parte de todo o conteúdo que é opcional.
Ou seja, se fosse assim:
JSON.parse(text,[ reviver])

Isso daria a entender que eu poderia chamar a função assim: JSON.parse(text,) (até pode em JS, mas em outras linguagens com sintaxe mais rígida, daria erro).
Porém, se tivéssemos, por exemplo, uma função com vários parâmetros opcionais e a vírgula fosse documentada fora dos colchetes:
JSON.stringify(value, [replacer], [space])

Aí daria a entender que eu poderia fazer JSON.stringify(value,,) (e isso nem o JS aceita).

Claro que tem um certo preciosismo e "todo mundo entenderia sem problemas" que não é para deixar essas vírgulas no final. Mas ao colocar a vírgula dentro dos colchetes, estou indicando que todo o bloco "vírgula + parâmetro" é opcional (ou coloca ambos, ou nenhum).
Sei que para alguns parece pedante, mas acho importante ter uma documentação clara, sem ambiguidades e nem margem para intepretações erradas. Sem contar que demonstra mais cuidado com os detalhes. Provavelmente é por isso que muitos colocam a vírgula dentro dos colchetes.

Origem incerta
Embora a outra resposta (antes de ser editada e apagada) tenha citado a notação EBNF (que de fato usa colchetes para indicar que algo é opcional), as origens desta notação parecem ser mais antigas.
Primeiro, vale lembrar que não existe um padrão oficial definido para esse tipo de documentação. Não no sentido de ter uma norma ISO, RFC, especificação, ou seja lá o que for.
Não encontrei fontes que cravam com certeza a origem exata, mas a referência mais antiga que encontrei foi o UNIX PROGRAMMER'S MANUAL (escrito em 1971, mais de 20 anos antes do EBNF). Na introdução é dito que:

Square brackets ([]) around an argument indicate that the argument is optional

Esta é portanto uma forte candidata à "origem" (pelo menos até alguém encontrar uma referência mais antiga).
Eu acho que faz sentido imaginar que este manual tenha influenciado a notação das documentações modernas. Afinal, o contexto é muito similar (documentação/manual).
E também faz sentido que essa mesma notação tenha sido usado em outros contextos, como o EBNF (que é uma notação para definir gramáticas e descrever linguagens formais, o que não tem a ver com documentação em si). Afinal, muita coisa em computação é assim, a sintaxe e terminologia de alguns contextos acabam sendo aplicados ou adaptados para outros, e o uso de colchetes para indicar algo opcional seria apenas mais um caso.
Mas creio que dá para afirmar com certo grau de certeza que a origem desta notação não é o EBNF.

Ver também:

How to interpret function parameters in software and language documentation?
Linux/Unix 'man' page syntax conventions


A counter-example for continues functions on Metric spaces

Question: Give a function $f : X \to Y$ such that $(X,d)$ and $(Y,p)$ are metric spaces, and $f$ is continues and one-to-one function and onto $Y$ but $f^{-1}$ is not continues ?
I know that compactness of $X$ must play a role here, because if $X$ is compact then there is no such counter-example, so $X$ must be no compact, but other than this i don't have a direction for the solution, please help.
Comment: Related: https://math.stackexchange.com/questions/68800/functions-which-are-continuous-but-not-bicontinuous
Answer: If $X:=(\mathbb{R},d)$ where $d(x,y)=1$ for all $x,\ y$ and $Y:=(\mathbb{R},|\ |)$ where $|\ |$ is a canonical metric, then $f=id: X\rightarrow Y$ is continuous. But $f^{-1}(1/n) = 1/n$ does not converge to $0$
Answer: Take the identity function from $\mathbb R$ into itself, with the discrete metric on the lect and the usual one on the right.


Check if the entered value is in the range

Question: I'm trying to change the background color of the typed row if the entered number is not in the range. The problem I'm facing is currently it is checking only the textbox which is entering due to the on change event attached to the textbox. What I'm looking for is I need to check if any of the textbox value in the row is not in the range.
For example: The first row range is 1 to 4, I want to check if any of the textbox entered values in the first row is not in the range(1 to 4).

$(document).on("change", "input", function() {
  var enteredValue = parseFloat($(this).val());
  var parentTr = $(this).closest('tr')
  var specFrom = parseFloat(parentTr.attr('data-from'));
  var specTo = parseFloat(parentTr.attr('data-to'));
  if (specFrom > enteredValue || specTo < enteredValue) {
    parentTr.css('background-color', 'red');
  } else if (specFrom === enteredValue || specTo === enteredValue) {
    parentTr.css('background-color', 'yellow');
  } else {
    parentTr.css('background-color', 'white');
  }
});

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />

    OD
    1 to 4
    <input type="number" name="h_no1[0]" value="">
    <input type="number" name="h_no2[0]" value="">
    <input type="number" name="h_no3[0]" value="">

    OD
    5 to 10
    <input type="number" name="h_no1[1]" value="">
    <input type="number" name="h_no2[1]" value="">
    <input type="number" name="h_no3[1]" value="">

    OD
    10 to 15
    <input type="number" name="h_no1[2]" value="">
    <input type="number" name="h_no2[2]" value="">
    <input type="number" name="h_no3[2]" value="">

Comment: It should accept the numbers not in the range. Color change is just to notify the user
Comment: You should [edit] your question to include any further thoughts you have; no need to use comments. I would change the code to use classes, then just check whether the row already has an out-of-range class (via `hasClass()`) before adding an in-range class (via `addClass`).
Answer: You can use .each loop to iterate through your inputs and check then your if-conditions there . Also , you can keep a flag to see if any of the cases meet then you can exit loop without looping further and then assign bg-color to your tr.
Demo Code :

$(document).on("change", "input", function() {
  var cases = ""
  var parentTr = $(this).closest('tr')
  var specFrom = parseFloat(parentTr.attr('data-from'));
  var specTo = parseFloat(parentTr.attr('data-to'));
  parentTr.css('background-color', "white"); //default color
  //loop through inputs
  parentTr.find("input").each(function() {
    var value = parseFloat($(this).val())
    if (specFrom > value || specTo < value) {
      cases = "red";
    } else if (specFrom === value || specTo === value) {
      cases = "yellow";
    }
    //if not empty
    if (cases != "") {
      return false; //exit loop
    }
  })
  //change color
  parentTr.css('background-color',
    cases == "" ? "white" : cases);
});

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />

    OD
    1 to 4
    <input type="text" name="h_no1[0]" value="">
    <input type="text" name="h_no2[0]" value="">
    <input type="text" name="h_no3[0]" value="">

    OD
    5 to 10
    <input type="text" name="h_no1[1]" value="">
    <input type="text" name="h_no2[1]" value="">
    <input type="text" name="h_no3[1]" value="">

    OD
    10 to 15
    <input type="text" name="h_no1[2]" value="">
    <input type="text" name="h_no2[2]" value="">
    <input type="text" name="h_no3[2]" value="">

Comment: change `if (cases != "") {` to `if (cases != "" && cases != "yellow") {`
Comment: Thanks for the answer. How to give first priority to red color condition?
Comment: In the first row I tried 4 in the first textbox then the color is yellow which is correct. Then in the next textbox in the same row I entered 5 but it's still in yellow color
Answer: Here I created a set of function to determine initial values in "setup"
I then set the td background and row background for each 'td' as values change.  I then I fire a trigger to check the row for values and then set the row (tr) to the "lowest" level of warning depending upon the td values it contains on the observed td's
Note I used green as a "neutral" color instead of white to clearly show the td and row color.

const mything = {
  indicator: {
    warn: "#FFDDDD",
    equal: "#FFFF55",
    neutral: "#DDFFDD"
  }
};

$('#watchme').on("change input", "input[type='number']", function() {
  let v = this.value;
  let enteredValue = parseFloat(v);
  let isNotNumber = Number.isNaN(enteredValue);
  let parentTr = $(this).closest('tr');
  let parentTd = $(this).closest('td');
  let specFrom = parseFloat(parentTr.data('from'));
  let specTo = parseFloat(parentTr.data('to'));

  //  console.log(v, typeof isNotNumber,isNotNumber, specFrom, specTo, enteredValue);
  parentTd.data("level", (isNotNumber || enteredValue > specTo || enteredValue < specFrom) ? "warn" :
    (specFrom === enteredValue || specTo === enteredValue) ? "equal" :
    "neutral");
  parentTr.trigger('checkrow');
  let indicatorValue = mything.indicator[parentTd.data("level")];
  parentTd.css('background-color', indicatorValue);
}).on('setup', function() {
  $(this).find("input[type='number']").trigger('change');
}).on('checkrow', 'tr', function() {
  let ov = $(this).find("td.observed_values");
  let r = ov.filter(function() {
      return $(this).data('level') == "warn";
    }).length > 0 ? "warn" :
    ov.filter(function() {
      return $(this).data('level') == "equal";
    }).length > 0 ? "equal" :
    "neutral";
  $(this).css('background-color', mything.indicator[r]);
}).trigger('setup').trigger('setup');

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />

    OD
    1 to 4
    <input type="number" name="h_no1[0]" value="">
    <input type="number" name="h_no2[0]" value="">
    <input type="number" name="h_no3[0]" value="">

    OD
    5 to 10
    <input type="number" name="h_no1[1]" value="">
    <input type="number" name="h_no2[1]" value="">
    <input type="number" name="h_no3[1]" value="">

    OD
    10 to 15
    <input type="number" name="h_no1[2]" value="">
    <input type="number" name="h_no2[2]" value="">
    <input type="number" name="h_no3[2]" value="">


Em qual realidade Kony Framework é a melhor escolha?

Question: Hoje o mercado está buscando cada vez mais frameworks para um desenvolvimento hibrido de aplicativos mobile. Um framework que já havia ouvido falar era o Kony, pois foi escolhido pelo Itau (Recentemente Trocado).
Gostaria de entender um pouco mais sobre este framework:

Em qual realidade de projeto o Kony é a melhor escolha?
Quais as vantagens do Kony como Framework?
Qual o motivo dos frameworks híbridos trabalharem, em sua maioria, com javascript e derivados?

Conferi no site do framework e eles possuem outros grandes players em seus clientes (Localiza, FarmaTodo, etc.)
Comment: Não conhecia, e fiquei impressionado, seria Kony um app inventor que presta? kk
Comment: Olá Luiz, eu sugiro você dividir sua dúvida em mais perguntas. Existem três asssuntos na sua *bullet list*... O primeiro pode ser facilmente considerado como principalmente baseado em opiniões. Os outros dois são boas perguntas e cada um merece uma resposta diferente.
Comment: Acredito que não, pelas minhas pesquisas ele é bem ruim de utilizar e dar manutenção, por isso queria entender o que leva alguem a escolhe-lo.
Answer: Em qual realidade de projeto o Kony é a melhor escolha?
Quando você tem serviços legados que tem saída em SOAP, pois ele possui uma ferramenta integrada chamada Mobile Fabric que permite a fácil conversão para JSON para você realizar suas chamadas RESTful.
Quais as vantagens do Kony como Framework?
Ele possui uma rápida curva de aprendizado pois utiliza javascript para sua implementação, possui uma equipe por trás para oferecer suporte e gera código nativo.
Qual o motivo dos frameworks híbridos trabalharem, em sua maioria, com javascript e derivados?
Creio que pela simplicidade e familiaridade, por ser uma linguagem que é comum em várias linguagens, por exemplo, programadores que tem familiaridade com asp.net, php, entre outras linguagens web geralmente tem javascript como linguagem em comum, além disso javascript é ponto de interseção entre os dois sistemas operacionais mais utilizados para celular.
Comment: Pelo que vi o kony tão péssimo feedbak, você acha que ele é uma escolha acertada?


open graph with angular 2

Question: I'm struggling a little with a SPA built with Angular 2.
I have a list of items. When I click over some item, the app shows the details, with title, description and picture.
In my details.component.ts, at ngOnInit method I get the details (async) from api. After details loaded I add/update open graph meta tags manipulating the DOM.
And here is the problem: if someone copy the URL and paste at Facebook, the details (by json through API) will load after html, and facebook won't get the updated open graph tags.
Did someone have this kind of problem? Any ideia about how to fix it?
Answer: Some (many?) consumers aren't going to bother rendering your javascript in order to get your opengraph tags.  The only two fixes I'm aware of for this are either to

statically render your contents (using Angular-Universal, or something like that) and redirect bots and crawlers to the pre-rendered content
failing that, it is prudent to have backup opengraph tags in your index.html, so that at least your pages have something on the page, even if it's not the open graph data for the current article.

open graph with angular 2


Using one neural network for each image type

Question: I have been reading about Convolutional neural networks and its use in image recognition. Most of the examples I have seen so far train one single network to classify an image into one label or class.
What I have understood so far is that the power of CNN resides in their ability to understand important shapes for each class through the convolution filter. However, my intuition is that if we feed to the network images from different classes the filters will have to adapt its weights to fit them all. (e.g. a filter that is able to recognise dog, cars and humans characteristic shapes)
Wouldn't it be more efficient to have a NN for each label or class as the convolutional filters learned will be more specific and accurate? In this way I can make sure that convolutional filters of the dog model will have their weights optimised to recognise the different parts of the dog.
Comment: Unfortunately this argument is flawed. A model having seen only dog images will be *worse* at recognising dogs, because it has never seen any examples that are *not* dogs. If the model simply says: "dog" for any image fed to it, it will score perfectly on the dog data and learn nothing about dogs.
Comment: I understand. What if you feed the model dogs and not dogs images?
Answer: Yes, you could fit a binary classification network for each class, and the resulting models would have much higher combined capacity. However neural networks aren't really limited by model capacity, but rather by the amount of data and need for regularization.

Wouldn't it be more efficient to have a NN for each label or class as
  the convolutional filters learned will be more specific and accurate?

The popular Imagenet classification test consisted of 1000 classes. Surely, a 1000 models with a combined 1000 times more filters wouldn't be more efficient by any sense of the word (it would also be prohibitively difficult to train). Since dogs, humans, and many other classes of objects all share at least some common patterns, lines, and shapes within them, it makes more sense to fit just one model.

In other words, CNNs are already too good at learning specific features. The challenge we now face is to prevent them from overfitting.
Comment: Yes. I understand that in terms of computation this is probably unrealistic. But assuming that we have infinite resources I was wondering if it would make more sense having 1000 binary models where you feed all the image dataset to each one. I imagine you will end up with 1000 models with their weights fine tuned to recognise the different features of each image type instead of a single model where weights could be less accurate since they have to fit several types of images.


Recording setup for live performances with various sound engineers in various venues

Question: My band plays in a variety of venues with a variety of sound engineers with varying levels of competence. The venues supply the mics and DIs.
So we would like to record live the raw feeds from the mics and DIs on separate channels before they go to the sound board so that we can edit and mix them later.
What kinds of equipment should we be looking for to do this with a minimal amount of fuss onstage?  There's just the band members, no budget for a separate recording engineer.
Comment: Sorry, equipment searches are off-topic here. If you want to record each instrument directly and then send a copy to the engineer, you're going to spend a lot of money and have a very long setup time. A better option is to get a portable stereo recorder with built in microphones and just record what the audience hears. That will also help you assess how good the engineers you work with are.
Comment: @ToddWilcox our close reason states "Questions seeking recommendations for specific equipment are off-topic, because they are primarily opinion based. Instead, **describe the required function and setting in which the equipment will be used, and ask what you should look for to achieve that.**" Surely that's *exactly* what the poster has done here - described what's wanted, and then asked what kind of thing would be appropriate?
Comment: @topomorto You raise an excellent point. I read the question as asking for the names of specific products but now I see how the actual intention is more general and on topic. I might even answer it.
Answer: I have done live recording like what you are describing. We use a "splitter Snake" which sends two outputs for each input, one going to house sound, one going to recording setup.
You could achieve the same thing with mic splitter boxes on each mic, since the house sound will likely already be set up.  You will also need dual output DI boxes for your DI's. Extra mic and instrument cables for each also.
You will need a recording setup that has enough inputs for your DIs and mics. A Digital Interface and a Laptop should be enough to get the basic tracks down. There will be some extra setup time as you plug in the connections and check the levels on your system, but if the band practices before hand and everyone has their job set, it shouldn't add too much more time to your regular stage setup.


Easy way to play a "B" chord on guitar

Question: I learned to play guitar a couple years ago, but I can't for the life of me play a "B" chord.  Is there any version that isn't a bar chord?  Or do I have to suck it up and learn to play a bar chord?
Comment: If you need that chord while you're in key E, then B7 is the answer. X21202. Otherwise, there is only the 'A' shape barre on fret 2, or the 'E' shape barre on fret 7. Since you want to play guitar, learning barre chords has to be the way to go. Like it, lump it, do it !
Comment: Thank you!  That really helps.  I probably will learn the B chord at some point.
Comment: Trying to play the B with a barre on the 2nd fret and fingers 2,3 and 4 on the 4th fret is tough for a beginner. Try playing the low B on fret 2 string 5 with your index finger and using your pinky as a barre on the 4 high strings. You can support it with your ring finger. Just avoid picking or plucking the high E string since that note is not part of a regular B chord.
Comment: If you mute you don't have to barre the E shape. You can play it X9987X
Comment: @JohnBelzaguy I disapprove of these fingerings, especially for beginners, because they only really work in a "thumb around the neck" position – not a good habit to get into. (Not to say it can't sometimes be a useful tool to _also_ have available, just it shouldn't be the _default_.) However, the same chord fingered as 1234 without any bar _does_ make sense as a beginner option.
Comment: @leftaroundabout Thumb around the neck? How? A pinky barre on the 4th fret covering the A shape with the index finger on the second fret A string can be easily played with the thumb where it should be, in the middle of the neck. Not only that but it encourages doing a barre with the 1st finger because it is natural to do so. Your fingering is also sound, of course. Honestly, I can't even play the chord I described with the thumb over the neck, something i never encourage BTW.
Answer: Yes, in a nutshell. But no, not a nice open chord like E (022100), if you're in standard tuning.
B7 has its own non-bar opportunities (see Tim's comment). But I'm going to just stick to B major chords with standard tuning, since that is the original question.
Here are four possibilities; some are easier than others:

Use 1, 2, 3 fingers or 2, 3, 4

If you are willing to bar a little, there are more too, like xx9877.
These aren't the only ones out there, but hopefully are a good start. Feel free to comment if you'd like more.
Comment: I'd add a B power chord to the mix: x244xxx - easy to play, and easily replaces B major in a lot of situations

Easy way to play a "B" chord on guitar


How to center verticaly blocks in two bootstrap columns?

Question: I have this html:

Some big header

            <select class="form-control">
                <option>TMP</option>
            </select>

some more text

and I am getting this result:

There is margin property on tag h1 so there are some blank space above h1. There are no such space above select, so this elements are not centered.
"What you've tried?"
I've tried bad and monstrouse method. I know it can be used to center divs. But not in this case... I have added line-height and height properties to the select:
.select {
  height: 80px;
  line-height: 80px;
}

.form-control {
    display: table-cell;
}

Yes, it worked, but it is not relative at all. What if on left column there will be h2 text, not h1?
jsFiddle example of "what you tried?"
Also, "what you've tried?" 2: I tried to use form-horizontal class. Look this:

And the code:

Some big header

            <select class="form-control">
                <option>TMP</option>
            </select>

Also, text in the left column is right aligned (as form label, obvious). I don't want this.
jsFiddle example of "what you tried?" 2
So the question is: how I can center both elements vertically? Highly prefer using bootstrap classes and approaches. Don't suggest methods, where you specifying height of div, margins or paddings: it is not relative at all.
Answer: To be able to use vertical alignment, I think you need to override the floating used by bootstrap classes, and use inline-block for the columns. It's not exactly a bootstrap approach, but I think it works and is responsive. There is one disadvantage that can be a bit annoying, is that you need to make sure there is no space between the divs...

Some big header

            <select class="form-control">
                <option>TMP</option>
            </select>

.vcenter-col {
    display: inline-block;
    vertical-align: middle;
    float: none;
}

Jsfiddle
Did I understand correctly your question?
Answer: Try this CSS :
h2 {
    margin: 0;
}

BootStrap does a lot off things in CSS, so be careful to correcty set your CSS selector to not override all BootStrap CSS.
But, does your HTML can't change ? Is seems to me that the H2 element should have been a LABEL.
Comment: Exactly. Your solution will override all headers.


Várias cidades em um projeto

Question: Boa Tarde!
Queria umas dicas.
Estou desenvolvendo um projeto de um site de classificados, quero utiliza-lo com várias cidades aqui da região, como eu posso fazer para que no mesmo site o usuário selecione sua cidade?
Por exemplo, o usuário seleciona São Paulo o site direciona para os classificados de São Paulo. Rio de Janeiro a mesma coisa, etc...
O que me indicam?
Obrigado!
Comment: Alguma dúvida em específico?
Comment: Como separar isso num banco de dados?
Comment: Basicamente uma tabela com os municípios e um campo `id_municipio` (exemplo) na tabela de anúncios
Answer: Existem diversas maneiras de fazer isso, você pode fazer com url's amigaveis passando o parâmetro da cidade direto na url, exemplo:
www.meusite.com.br/saopaulo
www.meusite.com.br/riodejaneiro
você pode fazer via o evento onchange do javascript, ao selecionar a cidade em uma lista (select html) ele redireciona para a cidade escolhida.
via AJAX e dai nem precisaria recarregar a página, apenas selecionava a cidade e já atualizaria o conteúdo no container que você especificar.
Comment: Mas e como separar isso no BD?
Comment: Crie uma tabela cidades, e na tabela de classificados relacione o ID da cidade com o anúncio.

Várias cidades em um projeto


Does $h \circ f = I = f \circ g \implies h = g$?

Question: Suppose that the identity function $I$ is defined as $I:X \to X$ such that $\forall x \in X$, $I(x) = x$.
I was hoping that $f(g(x)) = h(f(x)) = x \implies g(x) = h(x)$ for a proof I am constructing. I am stuck as to where to begin. Any help would be greatly appreciated. Cheers.
Comment: $f \circ g = \operatorname{id}_X$ shows that $f$ is surjective, and $h \circ f = \operatorname{id}_X$ shows that $f$ is injective. Altogether we have that $f$ is bijective. Then by composing with $f^{-1}$, we have $g = f^{-1} = h$.
Comment: @SangchulLee Thanks for your reply. I appreciate it. :)
Answer: $$
h = h\circ\operatorname{id}_X = h\circ (f\circ g) = (h\circ f)\circ g = \operatorname{id}_X\circ g = g
$$
Comment: Absolutely right and succinct. Thanks for your answer, this helps a lot!
Answer: If $h(f(x))=x$ then it is also true that $f(h(x))=x$ now if $f$ is inyective we are done. If not there is no such inverse of $f$ for all the reals because then if $a$ and $b$ has the same image in $f$, $h$ will have to give different values for those images, which by definition is not a function.
Comment: $h(f(x)) = x$ does not imply that $f(h(x)) = x$. Consider for example $f(x) = e^x$, $h(x) = \log(x)$ if $x> 0$, $h(x) = 0$ if $x\leq 0$.
Comment: well but it's true $e^{ln(x)}=ln(e^x)=x$
Comment: Only if $x >0$. $f (h (0))=e^{0}=1\neq0$ in my example.
Comment: Well the limit of $h(x)$ when $x\rightarrow 0$ is $-\infty$ and the limit of $f(x)$ when $x\rightarrow -\infty$ is $0$.
Comment: Limits are completely irrelevant here.


How do I install this module?

Question: I tried to install the Wysiwyg module, but it doesn't work. I copied the folder to /sites/all/, but how do I enable it?
The instructions say:

You need to install and configure an editor library also. Please see this link for instructions.
Comment: Please be more specific about what you are confused about.  The instructions page seems pretty clear to me.  If you're having trouble with a specific step, please write what you are trying to do and what kind of error message you are getting or what kind of problem you are having.
Comment: "it doesn't work" is extremely vague. What doesn't work? What errors do you get? Have you actually tried to follow the very detailed instructions on the link you posted? If not, please follow those before asking here. If you have, what step of the instructions are you failing to understand?
Answer: The module files are searched in specific directories, as evident in the drupal_system_listing() code. The directories where Drupal looks for modules are the following:

profiles/$profile/modules, where $profile is the name of the currently enabled profile
sites/all/modules
$config/modules, where $config is the name of the directory containing the settings.php file currently used

If you copied the files in sites/all, then the module is not found because it is not in a directory where the modules are looked for; that would explain why you cannot enable the module.
The first step reported in the instructions is clearly the following one:

Download, extract, and place Wysiwyg module in the modules folder like any other Drupal module.

(The emphasis is mine.)
The part you are quoting is not about the module, but the editor library that module should use.
Once you installed and enabled the module, you will be able to visit its configuration page (admin/config/content/wysiwyg), which will give you a list of libraries that module supports. Once you verify which one is compatible with your server, and you choose the one you want to use, you download the installation file following the link given in that page, and extract its content in sites/all/libraries/. Keep in mind the following notes give in the documentation page you linked.

If the editor comes in a wrapper folder that equals its short-name, then you can put the entire wrapper folder straight into Wysiwyg's folder:
/sites/all/libraries/[editorname]. Make sure that the resulting structure is NOT like /sites/all/libraries/[editorname]/[editorname] unless the settings page indicates otherwise.
If the editor comes in a wrapper folder with additional characters (e.g. version number), then you can put the entire wrapper folder into the sites/all/libraries folder, but need to rename it to its short-name:
/sites/all/libraries/[editorname]. Make sure that the resulting structure is NOT like /sites/all/libraries/[editorname]/[editorname-version].
If the editor comes without a wrapper folder, then you need to create the editor's short-name folder yourself and copy the editor library files into that folder: /sites/all/libraries/[editorname].

If you correctly followed the instructions given from the module and its documentation, on admin/config/content/wysiwyg you will see that the editor library you copied will be reported as installed. If you don't see that, it means you copied the editor files in the wrong directory, or there are other errors (e.g. the version you installed is not compatible with the module).
Answer: Move the module to sites/all/modules/. Then you can activate it under index.php?q=admin/build/modules (Drupal 6) or index.php?q=admin/modules (Drupal 7).

How do I install this module?


Can Socket.io be used on node.js if node.js was compiled without openssl?

Question: I am working on a node.js project using Express and Socket.io on an embedded sheeva board (node.js 0.10.12 running on busybox Linux). Since this is embedded, everything is built with sparse options and there is no crypto stuff installed (node.js was compiled --without-openssl). This server will be used on a LAN and no sensitive information will be transmitted or received, so encryption isn't required.
When I run this script with node:
var app = require('express')();
var server = require('http').Server(app);
var io = require('socket.io')(server);

server.listen(3000);

node fails with the following output:
tls.js:67
    throw new Error('node.js not compiled with openssl crypto support.');
Error: node.js not compiled with openssl crypto support.
    at tls.js:67:9
    at NativeModule.compile (node.js:892:5)
    at NativeModule.require (node.js:861:18)
    at https.js:22:11
    at NativeModule.compile (node.js:892:5)
    at Function.NativeModule.require (node.js:861:18)
    at Function.Module._load (module.js:297:25)
    at Module.require (module.js:364:17)
    at require (module.js:380:17)
    at Object.<anonymous> (/usr/share/nodeserver/node_modules/socket.io/node_modules/engine.io/node_modules/ws/lib/WebSocket.js:10:13)

This is expected since node was compiled without openssl support. Tracking down the error in /usr/share/nodeserver/node_modules/socket.io/node_modules/engine.io/node_modules/ws/lib/WebSocket.js, this is the line that is causing the issue:
https = require('https')

I know I can't simply comment that out. Is there some way to tell Socket.io to not use any https and crypto features?
I've searched around and found tons of information on how to use Socket.io with openssl, but nothing about how to use it without...
Comment: I think its due to the CommonJS standard and that conditional requir-ing is not considered good. Besides author would have thought it is best to bundle both. Providing only one seperately may not have been a good idea.
Comment: Did you try and comment out the https line? I think you should try that once. Socket.io is built such that it can support connections with both TLS or otherwise, so if you remove all the crypto stuff from Socket.io lib, then I think it should still work.
Comment: I did try that, and it just fails at the point in WebSocket.js where that object is used.
Comment: I might be missing something but... why just not use http instead of https? It doesnt work?
Comment: @Jarema IT doesn't work. Those first three lines of code that I mention will trigger the error. When I do `require('socket.io')(server)` (where `server = require('http').Server()`) it throws the error `node.js not compiled with openssl crypto support.`. The `ws` module which is required by `engine.io` which is required by `socket.io` always calls `require('https')` and `require('crypto')`.
Comment: @user568109 That makes sense. It looks like I will just have to build node.js with ssl support even if I'm not using it.
Answer: If you change
https://github.com/websockets/ws/blob/master/lib/WebSocketServer.js#L10
from
  , crypto = require('crypto')

to
  , crypto = null

Since this object is only used for secure connections - not a nice solution as you are modifying an included module but it should work.
I don't think modifications are actually needed here (but on testing you might find you need to):
https://github.com/websockets/ws/blob/master/lib/WebSocket.js#L13
https://github.com/websockets/ws/blob/master/lib/WebSocket.js#L572


WYSIWYG CKEditor config.js not being used?

Question: I've installed and configured the WYSIWYG module (latest dev) to use CKEditor, and I have downloaded the latest version of CKEditor (latest full release) to sites/all/libraries.  I'm able to use the editor.
I need to customize a few additional things, so I'm applying configuration changes to config.js in sites/all/libraries/ckeditor/config.js.  However, it seems like this file is not even being used or read at all.  I tested this hypothesis by adjusting the stock config.js as so:
CKEDITOR.editorConfig = function( config ) {
    // Define changes to default configuration here. For example:
    config.allowedContent = true;
    alert('Hello!');
};

alert('World!');

Whenever I load the editor, I would expect to get either one or two alerts, one saying either Hello! or World! or both.  However, no alert windows are launched.
How does one customize the configuration of CKEditor when using the WYSIWYG module?
Answer: This took some research, but I found this article which describes how to do it.
The meat of the article is the following hook, which defines a custom config file:
<?php
/**
 * Implements hook_wysiwyg_editor_settings_alter()
 */
function MODULENAME_wysiwyg_editor_settings_alter(&$settings, $context)
{
    // The $context variable contains information about the wysiwyg profile we're using
    // In this case we just need to check that the editor being used is ckeditor
    if ($context['profile']->editor == 'ckeditor')
    {

        // The $settings variable contains all the config options ckeditor uses.
        // The array keys correspond directly with any setting that can be applied
        // to CKEditor - as outlined in the CKEditor docs:
        // http://docs.cksource.com/ckeditor_api/symbols/CKEDITOR.config.html
        // Another way to override configuration is to use your own configuration javascript
        // file. In this case, we're going to add our own configuration file that will
        // Hold our stylesSet customizations...
        $settings['customConfig'] = base_path() . drupal_get_path('module', 'MODULENAME') . '/ckeditor_custom_config.js';
    }
}

Comment: This worked perfectly for me. The problem is that you require an additional custom module to actually config CKEditor. Once you do this, it works just fine and you have full control over CKEditor.
Comment: This works partly for me. Not all settings in the ckeditor_custom_config.js are honoured, but some are. Others work if you put them straight into the modules function `$settings` variable. Confusing.
Answer: I had a similar problem, and it turns out that CKEditor was caching the config.js file. Not even pressing control-F5 would solve that: I had to delete the cache manually from the browser's setting.
Hope this helps someone =)
Comment: It shouldn't have been cached if you disabled aggregation of JS files in `/admin/config/development/performance` and cleared your cache there as well. Hope this helps stop someone from making 100 different files for 100 different commits.
Answer: All you need to do is to edit /sites/all/modules/ckeditor/ckeditor.config.js instead of ckeditor/config.js file.
Comment: You shouldn't be hacking contrib modules. Especially without information around providing a patch (if it is a bug fix, which this is not.) https://www.drupal.org/node/1054616
Comment: WYSIWYG version doesn't live there anyway.


Como mostrar o número que mais aparece em um vetor na linguagem C?

Question: Dada uma sequência de N números entre 0 e 100. Determine qual o valor de maior frequência.
Segue o que fiz até o momento:
<code>#include <stdio.h>
#define max 100

int main()
{
    int vetor[max],i,j,frequencia=0,maior=0,tamanho_vetor,cont=0;

    scanf("%d",&tamanho_vetor);

    if(tamanho_vetor>=1 && tamanho_vetor<=1000000)
    {
        for(i=0; i<tamanho_vetor; i++)
        {
            scanf("%d",&vetor[i]);

           /* Como vou fazer a comparação, para achar o numero que mais aparece e quantas vezes ele aparece? */

                 if(vetor[i]==)
                {
                    cont++;
                    frequencia ;
                }
        }
        printf("%d %d\n",frequencia,cont);
    }

    else
        return 0;
}
</code>
Comment: Jovem, jogar somente o enunciado não ajuda muito a entender sua dificuldade, clique em EDITAR, adicione o que já tentou fazer e explique  onde você está tendo dificuldade.
Comment: OK VOU EDITAR A PERGUNTA
Comment: Só não precisa escrever em caixa alta, não necessidade.
Comment: ok, valeu pela dica!
Answer: vou mandar um código que retorna a maior frequência de números, mas que é utilizado para uma faixa pequena de números, eu sei que você quer retornar a frequência com uma faixa maior de números, para isso você vai ter que primeiro ordenar os números por seleção e depois tirar a moda, que é o maior numero que se repete.
<code># include <stdio.h>
# include <stdlib.h>

int main() {

int vetor[10];
int j=0;
int tamanho;
int c = 0;
int i = 0;

for (i = 0; i <= 11; i++)
 vetor[i] = 0;

printf("Digite quantidades de numeros que deseja procurar:\n");
 scanf("%d >>", &tamanho);

for (j = 0; j < tamanho; ++j){
 scanf("%d", &c);
 vetor[c]++;
}

int moda = 0;

for (c = 1; c <= tamanho; c++) {
 if (vetor[c] > vetor[moda])
     moda = c;
}

printf("A moda dos valores e': %d", moda);

return 0;
}
</code>
Answer: Tente desta forma:
<code>#include <stdio.h>
#include <stdlib.h>

int main(int argc, char* argv[])
{
    int balde[100];
    //int* amostra;
    int x;
    int n;
    int i;
    int maiorBalde;

    // Esvazia os baldes.
    for (i = 0; i < 100; ++i)
    {
        balde[i] = 0;
    }

    printf("Digite o tamanho da amostra (0 para sair): ");
    scanf("%d", &n);

    if (n)
    {
        //amostra = (int*)malloc(n * sizeof(int));

        fflush(stdin);
        printf("Digite os %d numeros (entre 0 e 100) separados por espacos: ", n);
        for (i = 0; i < n; ++i)
        {
            scanf("%d", &x);
            //amostra[i] = x;
            ++balde[x - 1];
        }

        // Escolhendo o x que tem o maior balde.
        maiorBalde = 0x80000000;
        for (i = 0; i < 100; ++i)
        {
            if (maiorBalde < balde[i])
            {
                maiorBalde = balde[i];
                x = i + 1;
            }
        }

        // Imprime x.
        printf("O valor com maior frequencia e %d, com %d de frequencia\n",
            x, maiorBalde);

        //free(amostra);
    }
}
</code>


Laravel unique validation with where and join

Question: I'm trying to add aditional where clause in the unique validation rule. But before that, i need a join with other table. But I'm not being successful.
I have 2 Tables:
teams
with id, and name field
role_user_team
with role_id, user_id, and team_id being this three the key.
So i need to check if the teams.name field is unique for one specific user.
I did try this:
<code>'name' => Rule::unique('teams')->where(function ($query){
    //return $query->where('account_id', 1);
    return $query->join('role_user', 'role_user.team_id', '=', 'teams.id')->where('role_user', Auth::user()->id);
          });
</code>
I know the problem is with the join but i don´t know how to solve it.
Thank you!
Comment: I think join is not allowed in the where clause...so i need a new validation rule to check what i want. ¿Any idea of this?
Comment: Indeed, seems like joining is not functioning, although this is not documented anywhere. The closure gets a standard query builder object so you would expect joining to just work. But the querybuilder object seems to get edited afterwards, breaking joins.
Comment: Use `Auth::id()` instead of `Auth::user()->id`. Object `Auth::user()` can not exists.
Answer: This seems to be a bug in how Laravel handles the QueryBuilder object just before the actual query to DB is done. Printing the query log shows that no actual join is performed. It could also be an inadequacy in the documentation (under "additional where clauses"), because that doesn't mention a limitation on using the QueryBuilder.
The quickest solution is to extend the Validator on the fly, like this:
<code>public function rules()
{
    Validator::extend('custom_rule', function ($attribute, $value) {
        // The user that's being edited, if any.
        $currentUser = $this->route('user');

        $query = User::join('addresses', function ($join) {
            $join->on('addresses.user_id', 'users.id')
                ->where('addresses.address_type', 'home');
        })->where($attribute, $value)->where('users.id', '!=', $currentUser->id ?? 0);

        // True means pass, false means fail validation.
        // If count is 0, that means the unique constraint passes.
        return !$query->count();
    });

    return [
        'name' => 'required|custom_rule',
    ];
}
</code>
Answer: I know this is an old question. Face the same problem and fix it like this:
<code>'name' => Rule::unique('teams')->where(function ($query){
    //return $query->where('account_id', 1);
    $query->join('role_user', function ($join) {
        return $join->on('role_user.team_id', '=', 'teams.id')->where('role_user', Auth::user()->id);
       });
     })
</code>
Hope it helps.
Comment: Works like charm! thanks... and it's not about the return statement either
Comment: @EmekeAjeh bkm Which version are you using ? Am using 5.5 doesn't work for me.
Comment: @DaniyalNasir I was using v8. V5.5 is a lot older so might be missing some method or have different syntax. If you could verify the source code from ./vendor directory and see what's missing or different, that might help.
Comment: Yep, I resort to using [Rule Object](https://laravel.com/docs/5.5/validation#using-rule-objects)
Answer: Laravel 5.8 - problem is still exists.
See \Illuminate\Validation\DatabasePresenceVerifier class, method addConditions().
It can be clearly seen that if a validation rule condition is a closure, then it is performed inside the nested where section, which excludes the possibility of using joins:
<code>/**
 * Add the given conditions to the query.
 *
 * @param  \Illuminate\Database\Query\Builder  $query
 * @param  array  $conditions
 * @return \Illuminate\Database\Query\Builder
 */
protected function addConditions($query, $conditions)
{
    foreach ($conditions as $key => $value) {
        if ($value instanceof Closure) {
            $query->where(function ($query) use ($value) {
                $value($query);
            });
        } else {
            $this->addWhere($query, $key, $value);
        }
    }

    return $query;
}
</code>
And yes, the only one way to use join in validation rule - is make your own rule, like aross sayd.
Answer: Look at the documentation in Advanced Join Clauses
<code>$query->join('role_user', function ($join) {
    return $join->on('role_user.team_id', '=', 'teams.id')->on('role_user', '=', Auth::id());
});
</code>


Zipping a folder in linux gives different size with different user

Question: I have a folder which i want to create tgz file and compute its sha256:
The folder is converted to tgz using following command
 "tar -c -C #{Shellwords.escape dir} #{Shellwords.escape basename} " \
        "--owner=0 --group=0 --mtime='2000-01-01 00:00:00' | gzip -n > #{Shellwords.escape file}"

Now i ran the above process using 2 separate users and it gave me 2 files: 1 and 2
Both tgz files differ in sizes:
-rw-r--r--@ 1 myuser  \Domain Users  9024 Jul 31 14:28 1.tgz
-rw-r--r--@ 1 myuser  \Domain Users  9037 Jul 31 14:29 2.tgz

If i try to compute diff between files i dont see any diff.Diff was obtained using following command.
diff  <(tar -tvf 1.tgz | sort) <(tar -tvf 2.tgz | sort)

If i compute sha256 using ruby of these 2 files , then it differs.
The question is : Why do i get difference in tgz files when running from different users.
Comment: Stack Overflow is a site for programming and development questions. This question appears to be off-topic because it is not about programming or development. See [What topics can I ask about here](http://stackoverflow.com/help/on-topic) in the Help Center. Perhaps [Raspberry Pi Stack Exchange](https://raspberrypi.stackexchange.com/), [Internet of Things Stack Exchange](https://iot.stackexchange.com/) or [Unix & Linux Stack Exchange](http://unix.stackexchange.com/) would be a better place to ask.
Comment: This is a programming question only.
Answer: the differences are in the headers, the header of each file in a tar contains the user and group id. see https://en.wikipedia.org/wiki/Tar_(computing)#Header .
Also modern tar adds additional data called Ustar to the header:  https://en.wikipedia.org/wiki/Tar_(computing)#UStar_format
which contains also the owner username.
try:
diff  <(gunzip -c 1.tgz | xxd) <(gunzip -c 1.tgz | xxd)

and you'll see the difference


Given a distance, two different speeds and time how to determine how far was traveled on each speed.

Question: Given a distance, two different speeds and time how to determine how far was traveled on each speed.
For example, if 100m has been traveled in 5 seconds and there was the option to travel the distance by bike and on foot. Speed on bike is 40m/s and speed on foot is 10m/s, how far did the person travel by bike and how much on foot? (Yes values are not actual representation of the real world)
Answer: traveled distance=D=100
time taken=t=10
t=time on foot+time on bike=tf+tb
D=10*time on foot+40*time on bike=10tf+40tb
100=10tf+40tb => tf=10-4tb
edit: time taken was actually 5, not 10, but the idea is the same
Comment: I got this far as well, but the problem is tf nor tb is known
Comment: Well tf+tb=5, tf=10-4tb. substituting: 10-4tb+tb=5 -> -3tb=-5 ->tb=5/3 -> tf=10-4*(5/3)=1/3
Comment: Totally forgot about the substitution, let's just say it was still early
Answer: Let $t_1$ denote the time travelled on foot and $t_2$ the time travelled by bike. Then we have on one side
$$ t_1 + t_2 = 5$$
on the other hand, if we consider the travelled distance
$$ 10t_1 + 40t_2 = 100. $$
Can you do it from here?
Comment: I got this far as well, but the problem is t1 nor t2 is known
Answer: You say that you've gotten to the point where you have two equations and two variables - so what's the problem? Do you need help with the algebra? Solve for t1 in one equation in terms of t2, then substitute that in the second equation to solve for t2.
Comment: Totally forgot about the substitution, let's just say it was still early


$x+ay=4, ax+9y=b$, Find the values of $a$ and $b$ for which the system has more than one set of solutions

Question: I've tried $2$ different methods that my teacher taught me to get it, but I keep getting the wrong answer. Can someone please show me the steps as to how to get the correct answer?
Comment: Do you know the concept of determinants?
Comment: We are given two straight lines that have multiple intersection points, so they must be the same line (and in fact have infinitely many intersection points). Thus, .
Answer: $x+ay=4\Rightarrow x = 4-ay\Rightarrow a(4-ay)+9y=b\Rightarrow 4a-a^2y+9y=b\Rightarrow (9-a^2)y=b-4a$. From this you can see that in order to have more than $1$ set of solution, it must be true that: $9-a^2=0=b-4a$. This yields: $(a,b) = (\pm 3,\pm 12)$
Answer: The system has more than one solution exactly when the two given equations are non-zero scalar multiples of each other. So we know that:
$$
\frac{a}{1} = \frac{9}{a} = \frac{b}{4}
$$
The first equation tells us that $a^2 = 9$ so that $a = \pm 3$. The second equation tells us that $b = 4a$. So our solutions are $(a, b) = (-3, -12)$ and $(a, b) = (3, 12)$.


R shiny sliderInput with restricted range

Question: In my R shiny sliderInput I want to restrict the range of the input of a given slider with larger maximum value.
For example assume the input has to be in the interval [1:10].
Of course I could now define min=1, max= 10 in sliderInput options, but then I will get only a slider with values in this interval.
My goal is to see a slider with values (for example) in [1:50], but the user can move this slider only in the interval [1:10]. This would make my app even better.
Is this possible?
Answer: Building up from your previous question you can use the min values, here slider 1 is restricted to 80 max and slider 2 restricted to 50
#rm(list = ls())
library(shiny)

slider1limit <- 80
slider2limit <- 50

ui <-pageWithSidebar(

  # Application title
  headerPanel("Sliders should sum to 100!"),
  # Sidebar with sliders whos sum should be constrained to be 100
  sidebarPanel(
    sliderInput("slider1", "Slider 1: ", min = 0, max = 100, value = 0, step=1),
    uiOutput("slider")),

  # Create table output
  mainPanel(tableOutput("restable"))
)

server <- function(input, output,session) {

  observeEvent(input$slider2,{
    values <- min((100 - input$slider2),slider1limit)
    updateSliderInput(session, "slider1", min =0,max=100, value = values)
  })
  output$slider <- renderUI({
    values <- min((100 - input$slider1),slider2limit)
    sliderInput("slider2", "Slider 2: ", min=0,max=100, value = values)
  })

  output$restable <- renderTable({
    myvals<- c(input$slider1, input$slider2, 100-input$slider1-input$slider2)
    data.frame(Names=c("Slider 1", "Slider 2", "Slider 3"),Values=myvals)
  })
}
runApp(list(ui = ui, server = server))

Comment: Thank you again. Now I have all I need to build it as I want. You helped me a lot today
Answer: You can use the from-min and from-max data attributes. This requires to modify the sliderInput function.
sliderInput2 <- function(inputId, label, min, max, value, step=NULL, from_min, from_max){
  x <- sliderInput(inputId, label, min, max, value, step)
  x$children[[2]]$attribs <- c(x$children[[2]]$attribs,
                               "data-from-min" = from_min,
                               "data-from-max" = from_max,
                               "data-from-shadow" = TRUE)
  x
}

ui <- fluidPage(
  sliderInput2("slider", "Slide:",
              min = 0, max = 100, value = 50, step = 5, from_min = 20, from_max = 80
  )
)

server <- function(input, output) {}

shinyApp(ui, server)

And thanks to the from-shadow data attribute, there is a segment showing the available range.
Comment: Do you need to define a new `updateSliderInput` function to update the `from-min` and `from-max` arguments ?


Compiling nginx with nginx-gridfs, getting mongo-c-driver errors during make

Question: I'm attempting to compile nginx (version 1.0.11) with gridfs support (nginx-gridfs version 0.8) on Ubuntu 11.10 (gcc version 4.6) using the nginx module here:
https://github.com/mdirolf/nginx-gridfs

The installation instructions described there are simple:
* Clone the nginx-gridfs repository (`git clone https://github.com/mdirolf/nginx-gridfs`)
* Check out the mongo-c-driver submodule (`git submodule init` then `git submodule update`)
* Download and unpack the nginx source (from `http://nginx.org/download/nginx-1.0.11.tar.gz`)
* Run `./configure` with `--add-module=/path/to/nginx-gridfs/repository`
* `make` and `sudo make install`

These steps worked fine for me last time I set up nginx-gridfs on a machine (about four months ago on Ubuntu 10.04, with gcc 4.5 and nginx version 1.0.5), but now (on a fresh Ubuntu install) I'm getting an error. The ./configure is working fine, but make fails with:
/path/to/nginx-gridfs/mongo-c-driver/src/mongo.c: In function 'mongo_count':
/path/to/nginx-gridfs/mongo-c-driver/src/mongo.c:939:5: error: missing initializer [-Werror=missing-field-initializers]
/path/to/nginx-gridfs/mongo-c-driver/src/mongo.c:939:5: error: (near initialization for 'out.dataSize') [-Werror=missing-field-initializers]
/path/to/nginx-gridfs/mongo-c-driver/src/mongo.c: In function 'mongo_simple_int_command':
/path/to/nginx-gridfs/mongo-c-driver/src/mongo.c:981:5: error: missing initializer [-Werror=missing-field-initializers]
/path/to/nginx-gridfs/mongo-c-driver/src/mongo.c:981:5: error: (near initialization for 'out.dataSize') [-Werror=missing-field-initializers]
/path/to/nginx-gridfs/mongo-c-driver/src/mongo.c: In function 'mongo_simple_str_command':
/path/to/nginx-gridfs/mongo-c-driver/src/mongo.c:1013:5: error: missing initializer [-Werror=missing-field-initializers]
/path/to/nginx-gridfs/mongo-c-driver/src/mongo.c:1013:5: error: (near initialization for 'out.dataSize') [-Werror=missing-field-initializers]
/path/to/nginx-gridfs/mongo-c-driver/src/mongo.c: In function 'mongo_cmd_get_error_helper':
/path/to/nginx-gridfs/mongo-c-driver/src/mongo.c:1055:5: error: missing initializer [-Werror=missing-field-initializers]
/path/to/nginx-gridfs/mongo-c-driver/src/mongo.c:1055:5: error: (near initialization for 'out.dataSize') [-Werror=missing-field-initializers]
/path/to/nginx-gridfs/mongo-c-driver/src/mongo.c: In function 'mongo_cmd_ismaster':
/path/to/nginx-gridfs/mongo-c-driver/src/mongo.c:1098:5: error: missing initializer [-Werror=missing-field-initializers]
/path/to/nginx-gridfs/mongo-c-driver/src/mongo.c:1098:5: error: (near initialization for 'out.dataSize') [-Werror=missing-field-initializers]
cc1: all warnings being treated as errors
make[1]: *** [objs/addon/src/mongo.o] Error 1

Any idea why this would fail?
The cc1: all warnings being treated as errors leads me to believe that I may be able to add -Wno-error to CFLAGS to tell it not treat warnings as errors to avoid this issue. But I'm worried that treat-warnings-as-errors is enabled here for a reason, and that turning it off would only make the compilation successful on the surface, but not actually work.
Anyone know what's going on here?
Comment: So far, no problems using the solution in my comment.
Comment: Adding `--with-cc-opt=-Wno-error` did allow the make to complete successfully. I will report back if this results in any problems.
Comment: Having this same issue. Please do report!
Comment: `--with-cc-opt=-Wno-missing-field-initializers` is a bit more specific.
Answer: Using your ignore warnings methods made the compilation work but I would actually get failure to connect to the database with user/password errors in use. What worked for me was a combination of building mongo from scratch to supply nginx build with newer libs: http://pastebin.com/tMsL2eC9
But this wasnt actually enough. I also had to specifically check out mongo c driver v0.3.1 in the submodule of nginx-gridfs. So that is, v0.8 of nginx gridfs. V0.3.1 mongo c driver, and the fresh mongo build being references from the env specified in that link. Then I built nginx 1.0.11 with no errors and it worked.


Codeigniter ou PHP Queue (fila)

Question: Estou fazendo um envio massivo de arquivos para um servidor de fotos.
Ocorre que até enviar todas as fotos, o usuário acaba esperando um tempão. Aí me deram a dica de pesquisar sobre fila de espera ou queue.  Desta forma, o usuário poderia deixar a página de uploads e fazer outras coisas no sistema, enquanto por trás o PHP faria o envio.
No Codeigniter, não encontrei nada a respeito. Alguém sabe como fazer via PHP ou Codeigniter uma fila de espera de tarefas?
Comment: Eu sei trabalhar esse _upload_ sem incomodar o usuário nem dar _refresh_ na página. Mas se vc quer trocar de página enquanto faz o _upload_ (é o que parece), então eu acho que eu e você teremos que pesquisar mais. O problema é que, mesmo em requisições assíncronas, vc vai precisar do `JavaScript` e do _form_ carregado na memória (_browser_), e mudar de página não me parece ser uma boa ideia pq o negócio recarrega todo. Já vi coisas como _server side upload in php_, e creio ser possível, por causa do `CGI`, mas nunca me aventurei. Como disse, depende de (muita) pesquisa.
Answer: Pessoal no Laravel existe uma função cron que fica trabalhando no backstage, como se fosse o cronjob do linux.
Ocorre que não encontrei isto no CodeIgniter, o que fiz foi bem simples:
1- Criei uma tabela de cronjobs;
2- Ao upar as fotos para o sistema, o mesmo salva no cronjobs uma tarefa que é lançar para o outro servidor aos poucos;
3- Setei um cronjob que bate de tempos em tempos neste script, que analisa os cronjobs pendentes e faz o envio.
O negócio ficou tão bacana que estou usando para diversas outras funções, na qual o usuário não precisa aguardar (exemplo disparo de e-mails simples através do sistema, geração de relatórios mais pesados, etc).

Codeigniter ou PHP Queue (fila)


Why is my bash script terminating?

Question: I have a node app running on my Linux hosting server.
Sometimes the app crashes and I need to restart it, so I log in and type these commands:
pkill node
cd public_html/n49900_dpndev
node server.js &

And the app runs again.
Now I would like to put this into a script so I simply need to start the script (or can execute it from a PHP script, for instance).
I created a file called "startnode":
#!/bin/bash
pkill node
cd public_html/n49900_dpndev
node server.js &

I changed the permissions with chmod 755 startnode.
But when I execute it with ./startnode it responds with:

Terminated

What do I need to do so that the commands I type in manually also work in the bash script?
Comment: Why don't you just make a systemd unit?
Comment: add a `-x` to your first line:
`#!/bin/bash -x`
That will show your verbose/debug node and you can see where the terminated appears.
Does node or server.js _require_ an interactive shell?
Answer: Your script name has "node" in the name and pkill node is probably killing it.
Using pkill -x node to kill only processes whose name is exactly "node" might be more to your liking. Or even pkill -f -x "node server.js" to kill the process with the exact full command line.
Answer: pkill is killing every process launched with a program with a name containing the word node even you script
Rename you script to whatever name not containing the word node

Why is my bash script terminating?


Como implementar reCAPTCHA do google no meu site?

Question: Estou tentando implementar o reCAPTCHA da Google no meu site, e não consigo fazer a integração Server-Side (Utilizo a linguagem PHP). Como posso fazer para que o reCAPTCHA funcione, e realize a validação antes enviar os dados do meu formulário?
Fonte e Documentação do Google reCAPTCHA
Comment: Achei sua pergunta interessante porque parece que não existe a página do reCAPTCHA em português. Sei que muitos acham que todo programador tem que saber inglês, mas acho que não faz mal ter algo como um "guia" do reCAPTCHA por aqui... (ou é fora de escopo?) Acho que ajudaria se você melhorasse um pouco mais a pergunta, incluindo o erro específico que não está conseguindo resolver, e colocasse ao menos algum código que já esteja utilizando.
Comment: seu server side é o que ? java, php, .net ou assembly ? Edite sua pergunta e adicione a tag da linguagem :o)
Comment: Campos editados. Meu serv-side é php
Answer: Introdução ao reCAPTCHA
O reCAPTCHA é uma nova ferramenta do Google para proteger seu site contra spammers e bots. Ele vem de uma ideia novadora, pois até então os captchas eram vistos mais como um obstáculo do que um auxiliar pelos usuários. Com o reCAPTCHA isso é diferente, pois tudo que o usuário precisa fazer é clicar em um checkbox, confirmando que não é um robô. Dessa forma todos ganham, o usuário tem acesso mais rápido às informações desejadas, e você mantém visitantes indesejáveis de seu site.
Incrível! Quero ter um desses, como faço?
O primeiro passo é você conseguir uma chave para o seu site. Vá até o site abaixo e clique no botão azul localizado na posição superior-direita do site, escrito "Get reCAPTCHA": https://www.google.com/recaptcha/intro/index.html
Após ter cadastrado seu site, você terá em mãos duas informações importantes: a chave do site, e a secret (chamarei de chave secreta). O primeiro passo para implementar o reCAPTCHA em seu site é inserir a API em seu site. Insira o código dentro da tag head de seu site:

Tudo pronto para o próximo passo.
Criando o formulário
Crie um formulário comum, eu fiz com dois campos: um para o usuário colocar o nome, e outro para uma mensagem qualquer. A marcação ficou assim:

Exemplo de formulário com o reCaptcha

<form action="formulario.php" method="post">
  Digite seu nome: <input type="text" name="nome">

  Deixe sua mensagem:

  <textarea name="mensagem" rows="7" cols="35"></textarea>

  <input type="submit" value="Submit" name="formulario">
</form>

Inserir o reCAPTCHA no formulário é extremamente simples, você só precisa adicionar o seguinte elemento na posição que deseja que ele apareça:

Não esqueça de substituir SUA-CHAVE pela chave que você recebeu no site, lembrando que é a chave do site, não a chave secreta!
Substitua a propriedade action na tag form para o nome do arquivo PHP que irá validar o formulário. Você pode validar na mesma página, mas eu preferi deixar em uma separada para o código ficar mais simples.
Mas não posso validar usando JavaScript na hora?
Não :) Você já irá entender o motivo.
Criando o código PHP para validar o formulário
Vamos obter o valor do campo de nome e da mensagem que o usuário enviou:
if (isset($_POST['nome'])) {
    $nome = $_POST['nome'];
}

if (isset($_POST['mensagem'])) {
    $mensagem = $_POST['mensagem'];
}

A partir daqui que a validação do captcha realmente acontece. É nos enviada via POST um valor fornecido pelo reCAPTCHA, é possível recuperar esse valor pela variável $_POST['g-recaptcha-response']. Logo:
if (isset($_POST['g-recaptcha-response'])) {
    $captcha_data = $_POST['g-recaptcha-response'];
}

// Se nenhum valor foi recebido, o usuário não realizou o captcha
if (!$captcha_data) {
    echo "Por favor, confirme o captcha.";
    exit;
}

Parece que acabou, né? Não! Agora que vem a parte divertida, lembra quando eu disse que era necessário que o captcha tinha que passar por uma validação PHP? Isso é necessário pois o reCAPTCHA usa informações no banco de dados do Google, que contém diversas informações sobre o usuário que "efetuou" o captcha. Dessa forma é possível distinguir um usuário comum de um bot. Para validarmos o usuário, precisamos fazer uma requisição para a API do reCAPTCHA, utilizando o file_get_contents. Observe:
$resposta = file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=SUA-CHAVE-SECRETA&response=".$captcha_data."&remoteip=".$_SERVER['REMOTE_ADDR']);

Procure no meio da URL por SUA-CHAVE-SECRETA e substitua pela sua. O que esse comando faz é recuperar dados na API do reCAPTCHA por informações sobre os valores que foram fornecidos pelo captcha, além de enviar o IP do usuário para futuras avaliações.
Com a requisição enviada, só nos falta tratar a resposta:
if ($resposta.success) {
    echo "Obrigado por deixar sua mensagem!";
} else {
    echo "Usuário mal intencionado detectado. A mensagem não foi enviada.";
    exit;
}

Espero que tenha entendido como o sistema funciona. Qualquer dúvida já sabe, estamos aqui para ajudar. ;)
Comment: Cara , depois de quase arrancar meus cabelos por 2 dias, eis que aqui consegui resolver o problema de um ReCaptcha não estava funcionado em um cliente novo. Por algum motivo nao tinha jeito de funcionar e com suas orientações DEU CERTO! :) Obrigada
Answer: RESPOSTA TOTALMENTE REFORMULADA. Motivo: eu coloquei as informações conforme fui descobrindo e ficou muito ruim. Agradeço ao Rafael Almeida, pela primeira resposta, que me ajudou muito e me levou a descobrir mais coisas. E aos administradores, que fizeram alterações que me orientaram a melhorar a resposta. A minha resposta existe só para acrescentar informações ao excelente trabalho já feito por Rafael Almeida.
Código no lado do cliente (HTML e JavaScript)
Uma questão levantada: mas não posso validar usando JavaScript na hora?
Até daria para fazer, na verdade, usando AJAX: mandar a informação para o PHP e obter a resposta antes de submeter o formulário inteiro, com o restante dos campos. No entanto, não parece um esforço necessário, pois, ao clicar no reCAPTCHA, ele não libera enquanto o usuário não der a resposta certa. Pelo menos, não vi acontecer outra coisa senão com ou sem a marca "check" para indicar que está tudo OK (por exemplo, não vi um X vermelho no lugar). Em outras palavras, o reCAPTCHA é tudo ou nada: ou o usuário não respondeu ou respondeu e respondeu certo.
O que parece ser útil aqui fazer a verificação no JS antes de enviar para o PHP para saber se o usuário ao menos usou o reCAPTCHA, para evitar o envio do formulário inteiro. Isso é muito fácil, pois a API já tem a função, é só colocar alguma coisa assim na função que executa no onsubmit do formulário:
 if (grecaptcha.getResponse() == "")
 {
      alert("Você não clicou no reCAPTCHA, por favor, faça!")
      return false;
 }

Código no lado do servidor (PHP)
O que me levou a obter mais informações é que o código com file_get_contents não deu certo para mim. Inicialmente, achei que o problema fosse o método de envio da função (GET, enquanto o site do reCAPTCHA diz que precisa ser POST). Depois, descobri que funciona perfeitamente na cópia do site hospedada no meu PC. Ou seja, é o servidor da hospedagem (eu uso Hostmídia) que bloqueia. Eu ainda tentei, mas sem sucesso:
ini_set('allow_url_fopen', 1)

A resposta alternativa, baseada em cURL, pode ser útil para quem tem o site na mesma hospedagem ou em outra que também bloqueie. De qualquer forma, pode ser interessante para evitar que, em caso de warning, no fique registrado no log a URL incluindo a chave secreta. Segue o código:
# Os parâmetros podem ficar em um array
$vetParametros = array (
    "secret" => "SUA-CHAVE-SECRETA",
    "response" => $_POST["g-recaptcha-response"],
    "remoteip" => $_SERVER["REMOTE_ADDR"]
);
# Abre a conexão e informa os parâmetros: URL, método POST, parâmetros e retorno numa string
$curlReCaptcha = curl_init();
curl_setopt($curlReCaptcha, CURLOPT_URL,"https://www.google.com/recaptcha/api/siteverify");
curl_setopt($curlReCaptcha, CURLOPT_POST, true);
curl_setopt($curlReCaptcha, CURLOPT_POSTFIELDS, http_build_query($vetParametros));
curl_setopt($curlReCaptcha, CURLOPT_RETURNTRANSFER, true);
# A resposta é um objeto json em uma string, então só decodificar em um array (true no 2º parâmetro)
$vetResposta = json_decode(curl_exec($curlReCaptcha), true);
# Fecha a conexão
curl_close($curlReCaptcha);
# Analisa o resultado (no caso de erro, pode informar os códigos)
if ($vetResposta["success"]) echo "
Captcha OK!
\n";
else
{
    echo "$
Problemas:
\n";
    foreach ($vetResposta["error-codes"] as $strErro) echo "$strTab
Erro: $strErro
\n";
}

Um pouco mais, ainda no lado do servidor...
Se olhar as instruções do site do reCAPTCHA, há a indicação de uma biblioteca que está no github, em /google/recaptcha. Também funciona bem: bastou colocar a pasta src do ZIP baixado em algum lugar do site e usar o código parecido com o exemplo deles. O único problema é que estava dando o seguinte erro:

invalid-json

Então encontrei dica em outro artigo Stackoverflow (indicação do método CurlPost):
$recaptcha = new \ReCaptcha\ReCaptcha($secret, new \ReCaptcha\RequestMethod\CurlPost());
$resp = $recaptcha->verify($gRecaptchaResponse, $remoteIp);
if ($resp->isSuccess()) {
    // verified!
} else {
    $errors = $resp->getErrorCodes();
}

Para isso, não testei se o problema era na hospedagem ou na própria classe da biblioteca.
Comment: E como instalar o `ReCaptcha\ReCaptcha`? Via composer?
Answer: Segue uma implementação completa do reCaptcha que estou usando em um site que estou desenvolvendo, a única coisa que falta pra funcionar 100% é criar os objetos, mas deixei bem descrito como criá-los, sou apenas estudante então fiz o melhor que pude.
<?php ini_set('display_errors',1); ini_set('display_startup_erros',1); error_reporting(E_ALL); ?>
    <?php
    function __autoload($class_name){
        require_once '../_lib/'.$class_name.'.php';//-->lê minhas classes de forma automática
    }
    ?>
    <!DOCTYPE html>

        <link rel="stylesheet" type="text/css" href="_css/login.css"/>

    <?php
    $helper = new Helpers();//-->objeto com vários métodos importantes
    if (isset($_POST['attempt'])){//verifica se tem tentativa restante
        $attempt = intval($helper->validation($_POST['attempt']));//validation=método que verifica e escapa minha sring (trim(), stripcslashes() e htmlspecialchars())
    }else{
        $attempt = 3;//se não for definido número de tentativas, aqui é definido como 3
    }

    if (isset($_POST['g-recaptcha-response']) and isset($_POST['username']) and isset($_POST['password'])) {//garante que todos os campos foram preenchidos
        $captcha_data = $_POST['g-recaptcha-response'];
        if ($captcha_data) {//Verificação do reCaptcha
            $resposta = file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=DIGITE-SUA-CHAVE-SECRETA-GERADA-PELO-GOOGLE-AQUI=" . $captcha_data . "&remoteip=" . $_SERVER['REMOTE_ADDR']);
            if ($resposta) {//validação do reCaptcha
                $username = strtolower($helper->validation($_POST['username']));
                $password = $helper->validation($_POST['password']);
                $user = new User();//--->meu objeto que acessa o banco de dados usando PDO
                $userValidated = $user->checkPasswordHash($username);//--->método do meu objeto que procura o usuario no bacno de dados (SELECT * FROM tbl_Users WHERE username = $username)
                if ($userValidated){//verifica se o email existe, se existir...
                    if ($userValidated->status == 1){//verifica se a conta está bloqueada ou não
                        echo 'Essa conta está bloqueada, criar botão para reenviar o email de recuperação...';
                    }else{
                    $hash = $userValidated->password;//retorna o hash do password
                    if (password_verify($password, $hash)) {//compara a senha e o hash que foi criado usando password_hash() e salvo no banco de dados
                        echo 'Password é válido, inserir código que inicia as sessões e chama a próxima página';//-->insira seu código
                    } else {//caso o password estjeja errado, perde uma tentativa
                        if ($attempt != 1){//se a tentativa restante for igual a 1, a proxima vez será direcionado para a página de recuperação de senha
                            $attempt--;
                            echo 'Usuário e senha não combinam, você tem mais '.$attempt.' tentativas';//mostra o número de tentativas restante
                        }else{//bloqueia a conta e chama a página de recuperação de senha
                            echo 'inserir código que bloqueia a conta e abre pagina de recuperaçao de senha';//-->insira seu código de bloqueio
                        }
                    }
                    }
                }else{//se o email não existir, perde uma tentativa mas não avisa se o erro foi no email ou na senha
                    if ($attempt != 0){
                        $attempt--;
                        echo 'Usuário e senha não combinam, você tem mais '.$attempt.' tentativas';//mostra o número de tentativas restante
                    }else{//bloqueia a conta e chama a página de recuperação de senha
                        echo 'inserir código que bloqueia a conta e abre pagina de recuperaçao de senha';//-->insira seu código de bloqueio
                    }
                }
            } else {
                echo "Validação não concluída, tente novamente.";
                exit;
            }
        } else {
            echo "Validação não concluída, tente novamente.";
            exit;
        }
    }
    ?>

        <form class="login" action="login.php" method="post">
            <fieldset>
                <legend>Login</legend>
                Email:
                <input id="inputEmail" class="inputText" type="email" maxlength="30" name="username" required>
                Password:
                <input id="inputPassword" class="inputPassword" type="password" maxlength="20" name="password" required>

                <input type="hidden" name="attempt" value=<?php echo $attempt ?> />
                <input type="submit" value="Confirmar" id="send" class="send">
            </fieldset>
        </form>


What chord would this most logically be thought as?

Question:
(from http://www.sheetmusic1.com/winston/Road.pdf)
I have figured that the first chord he plays is a Cm11 but what is the chord in the fifth bar? I know it could be a million things such as Em7#5/C or a Cmaj9 with the 7th omitted, but what would it most logically be thought of given the idea of chord progressions?
Comment: Please include any information required for answering in the question. SE posts should always be self-contained so as to be robust against [link rot](https://en.wikipedia.org/wiki/Link_rot).
Answer: I think it's pretty clearly a C(add9).   There's not much functional going on here.  He's just exploring various colours of C chord.   It's not until bar 29 that he decides the C7 is going to be the dominant of F.  And that's really the only bit of functional harmony in the whole piece!
This is George Winston in his pastoral, 'New Age' style.  He meanders rather than progresses.  That's OK, but there's maybe not much point in labelling the chords 'logically'.
Answer: Whenever you're confronted with a difficult analytic decision like this, try to explain it in a way that not only helps you hear this section, but that also might help inform a later section. Another way to frame this suggestion is to use later material to help determine what's happening earlier.
When we get to the Moderato section in m. 8, I immediately see a switch after two measures from C minor to C major. As such, I think it would be best to understand m. 5 as a type of C major, since hearing it that way will create a Cm-to-CM progression similar to the one that we'll hear starting in m. 8.
As such, my read would be that m. 5 is a Cadd9 chord.
But there's another reason, too: since the bass C G doesn't change in m. 5, it's going to be easier for the listener to understand m. 5 as a modification of the chord that came before it, not a chord with a completely different root.

Having listened to the entire piece, one could understand these C chords as just suggesting dominant in various (if slightly unorthodox) ways. The F chord halfway through page 2 really sounds like tonic at first hearing, although the F at the end really sounds like IV. Ultimately, I think that's the point of the piece: harmonic ambiguity.


Should I let my violin bridge tilt forwards?

Question: I just got myself a violin, being a beginner who has never played any bowed instruments before and intending to teach myself how to play. I came across an instruction video that stated that the bridge should be standing absolutely perpendicular to the body, but that it can be acceptable that it tilts slightly backwards. I looked at my violin and concluded that my bridge tilts ever so slightly forward. At the base, the edge closest to the neck is the contact point with the violin body, and the edge closest to the tailpiece is less than a millimeter above the body.
Is this acceptable until I change the strings, or should I loosen the strings and reposition the bridge right away? I don't have any sense of how delicate the instrument is yet, and I don't want to find out the hard way.
Comment: Since you are new to the instrument, and because the bridge is maladjusted, you really should have a luthier inspect it to make sure the soundpost is properly placed.  If the soundpost is missing, string tension could break the violin; if mis-adjusted, the sound will be very poor.
Answer: The bridge has feet which need to be properly in contact with the violin body. If it tilts, then chances are that it's not completely so. It can be moved, slowly ('untilting') so that it's perpendicular to the body - upright - without slackening the strings, although you may be more comfortable sliding the bridge if they are loosened slightly.
The other problem may well be that at some time that bridge was removed. Maybe it fell off when all the strings were changed - not a good thing to do all at the same time. So, at the same time, it's worth checking that the bridge is indeed in the correct place. The decision as to where that should be was made when the violin was made. On the side of the f-holes are tiny vs. An imaginary line between them will be the line that bridge sits on. That way, the fingering patterns will be correct for that violin.
Comment: @Jacob Be very careful correcting the bridge! Lie it on something soft, put a rag underneath the tailpiece, and with your arms resting on the body and slowly tilt it upright with your thumbs on one side and your fingers on the other. Use a piece of card with a 90 degree angle to check if it is correct. If the bridge falls over, take it to a luthier for proper setting. (Its position is important)


Finding expectation and variance

Question: I know what are the generic formulas for numbers, but I'm not so sure about the actual formula if you're given probability density functions. Let $X$ have the pdf $f(x)=0.5(x+1)$ with $-1<x<1$. What would be the Expected $Y$ ($EY$) and Variance of $Y$ or $VY$?
I think $EY = \int \limits _{-1} ^1 0.5(x+1) x^2 \ \Bbb d x = \frac 1 3$, right. To calculate variance, we do $E(Y-EY)^2$, right? But then, would the next integral we have to calculate for variance be $\int \limits _{-1} ^1 (x^2-\frac 1 3)^2 0.5(x+1) \ \Bbb d x$?
Comment: Consider TeXifying your question so as to attract more answers.  =)
Comment: okay, done textifying.
Comment: Your really should clean up the question. More TeX, Confusion between random variables called X and Y, which seem to be the same. Apparent error in method of finding the mean. Apparent error in formula for finding the variance. I hope I have given you enough help in my Answer so you can find your way. Errors seem to be more due to haste than fundamental misunderstanding.
Answer: First, you must have mean that the density function (PDF) is $f(x) = .5(x + 1)$ for $x \in (-1,1).$
Just as there are 'generic formulas' for means and variances of
data, there are formulas for the mean $\mu$ and variance $\sigma^2$
of a continuous random variable $X$ with density function $f(x).$
You should check to make sure your function $f(x)$ really is
a density function: (a) verify that $f(x) \ge 0,$ for such $x,$ and (b) that
$$\int_\infty^\infty f(x)\,dx = \int_{-1}^1 .5(x  + 1)\,dx = 1.$$
Then you need to find
$$\mu = E(X) = \int_{-1}^1 x[.5(x + 1)]\,dx.$$ Try sketching the
density curve from -1 to 1. Does your answer $\mu = 1/3$ seem to be the 'balance'
point of the density curve? The answer may be correct, but your
formula looks wrong.
Then for $\sigma^2 = V(X)$ you can find
$$\sigma^2 = \int_{-1}^1 (x - \mu)^2[.5(x + 1)]\,dx.$$
An alternative method is to use the equality $V(X) = E(X^2) - \mu^2.$
So you could find
$$E(X^2) = \int_{-1}^1 x^2[.5(x + 1)]\,dx$$
and subtract $\mu^2.$
Below is a brief R program that simulates a million realizations
of your random variable and finds some approximations you can
use to check your work. (It happens that your random variable
is related to a beta random variable: $X = 2Y - 1,$ where
$Y \sim Beta(2, 1);$ see your text or the Wikipedia article
on 'beta distribution'.)
<code>m = 10^6;  x = 2*rbeta(m, 2, 1) - 1
mean(x);  var(x)
## 0.333737   # approx E(X)
## 0.2219013  # approx V(X)
mean(x^2);  mean(x^2)-mean(x)^2
## 0.3332815  # approx E(X^2)
## 0.2219011  # 2nd approx of V(X)
</code>
The picture shows a histogram of the million simulated values
and your PDF. The dotted red line is at $\mu = 1/3.$
Comment: Why do you multiply by x when finding the E(X) in the integral and what is the difference between using EY and EX along with Var(Y) and Var(X)?
Comment: Look at definition of E(X), the x factor is part of the formula. I only see random variable X defined, but I see E(Y) and Var(Y). Is Y a different random variable?

Finding expectation and variance


How to create an 'Upload a file' field?

Question: I have a content entity type, and I would like to have an 'Upload file' field. I have declared the field in my Entity class
<code>$fields['file'] = BaseFieldDefinition::create('file')
    ->setLabel(t('Upload a file'))
    ->setDescription(t('Choose file from your computer'));
</code>
And in EntityForm I am trying to set some settings, because I need to make this dependable later with the '#states'
<code>$form['file'] = [
    '#title' => $this->t('File'),
    '#description' => $this->t('Upload a file from your computer'),
    '#type' => 'file',
    '#default_value' => $entity->file->value,
];
</code>
But at the moment the field is displayed, but I have problems on saving the form. The file is attached, but not getting uploaded and the error says:

Fatal error: Call to a member function getValue() on a non-object in
  C:\A
  plus\drupalsite\core\modules\file\src\Plugin\Validation\Constraint\FileValidationConstraintValidator.php
  on line 18
Comment: In field definition add  ```->setDisplayConfigurable('form', TRUE)``` and then in hook update for exmaple load the default form display and configure it. This is for texfield but have a look at upload widget what settings it has: ```$form_display->setComponent('myfield', ['type' => 'text_textarea', 'weight' => -10, 'settings' => ['rows' => 3]]);``` or just do it manually.
Comment: [Set image as permanent in custom block plugin, temporary URI](http://drupal.stackexchange.com/questions/222015/set-image-as-permanent-in-custom-block-plugin-temporary-uri). Check this link for uploading an image in Drupal 8
Answer: <code> $form['File'] = array(
        '#type' => 'managed_file',
        '#title' => t('Choose  File'),
        '#upload_location' => 'public://MyFilesFolder/',
        '#default_value' => $entity->get('File')->value,
        '#description' => t('upload file'),
        '#states' => array(
          'visible' => array(
            ':input[name="File_type"]' => array('value' => t('Upload Your File')),
          ),
        ),
      );
</code>
Comment: The file is uploaded, but not saved, unfortunately :(
Comment: follow this link on how to save @badm[link]http://drupal.stackexchange.com/questions/198135/how-do-i-save-uploaded-file-permanently-in-file-manged-table/198185#198185
do inform me if u need me to add that part here (save permanent part)
Comment: the problem is in this line '#default_value' => $entity->get('File')->value, if i set  '#default_value' => array(10) for exmple it uploads some file with this fid, but how can i get this file__target_id $entity->file__target_id->value doesn't work

How to create an 'Upload a file' field?