If $ a=\frac{\sqrt{x+2} + \sqrt {x-2}}{\sqrt{x+2} -\sqrt{x-2}}$ then what is the value of $a^2-ax$ is equal to

Question:
If $$ a=\frac{\sqrt{x+2} + \sqrt {x-2}}{\sqrt{x+2} -\sqrt{x-2}}$$  then
  the value of $a^2-ax$ is equal to:
a)2 b)1 c)0 d)-1
Ans. (d)

My attempt:
Rationalizing $a$ we get,
$ x+ \sqrt {x^2-4}$
$a^2=(x+\sqrt{x^2-4)^2}=2x^2-4+2x\sqrt{x^2-4}$
Now,
$a^2-ax=2x^2-4+2x\sqrt{x^2-4}-x^2-x\sqrt{x^2-4}=x^2+x\sqrt{x^2-4}-4=xa-4$
Why am I not getting the intended value?
Comment: plug $x=2$ to find $a=1$, which leads to the answer $-1$.
Answer: $$\dfrac a1=\dfrac{\sqrt{x+2}+\sqrt{x-2}}{\sqrt{x+2}-\sqrt{x-2}}$$
calling for Componendo and Dividendo
$$\dfrac{a+1}{a-1}=\dfrac{\sqrt{x+2}}{\sqrt{x-2}}$$
Squaring we get  $$\dfrac{a^2+1+2a}{a^2+1-2a}=\dfrac{x+2}{x-2}$$
Again apply componendo and dividendo,  $$\dfrac{a^2+1}{2a}=\dfrac x2$$
Now simplify
Answer: Hint. Note after the rationalization you should get $a=\frac{x+ \sqrt {x^2-4}}{2}$ which is a solution of the quadratic equation $z^2-xz+1=0$.
Answer: You should check your rationalization of $a$ again. I believe you are missing a factor of $\frac{1}{2}$.
Additionally, you could find the answer by choosing some easily computable value of $x$, say $x = 2$, so $a = 1$ and $a^2 - ax = -1$.
Answer: Rationalizing $a$, you should get $$\frac{x+\sqrt{x^2-4}}{2}$$
Answer: HINT: write $a$ in the form $$a=\frac{\sqrt{x+2}+\sqrt{x-2}}{\sqrt{x+2}-\sqrt{x-2}}=\frac{(\sqrt{x+2}+\sqrt{x-2})^2}{4}$$
Answer: Doing rationalization you get:
$$a=\frac{x+\sqrt{x^2-4}}{2}\to a-x=\frac{\sqrt{x^2-4}-x}{2}$$
so,
$$a(a-x)=\frac{(\sqrt{x^2-4})^2-x^2}{4}=-1$$
Answer: $$a=\frac{\left(\sqrt{x+2}+\sqrt{x-2}\right)^2}{\left(\sqrt{x+2}+\sqrt{x-2}\right)\left(\sqrt{x+2}+\sqrt{x-2}\right)}=\frac{\left(\sqrt{x+2}+\sqrt{x-2}\right)^2}{4},$$ which gives $\sqrt{x+2}+\sqrt{x-2}=2\sqrt{a}$ and from here $\sqrt{x+2}-\sqrt{x-2}=\frac{2}{\sqrt{a}}.$
After summing of  last two equalities we obtain $\sqrt{x+2}=\sqrt{a}+\frac{1}{\sqrt{a}}$ or
$x=a+\frac{1}{a}$,
which gives the answer: $-1$ because
$$a^2-ax=a^2-a^2-1=-1$$


Lista para deleção lógica

Question: Tenho uma dúvida sobre de quem é a responsabilidade (back ou front) pela tratativa de deleção lógica e no meu caso, tenho uma lista no front que é enviada para o backend gravar ou inativar o registro:

[{ idTabela: 2, codKit: "kitCopleto", dataInicio: "2019-01-01", dataFim: "2019-01-01"}, { idTabela: null, codKit: "kitCopleto2", dataInicio: "2019-01-01", dataFim: ""}]

Atualmente quando o usuário exclui um item dessa lista, ao invés de setar o propriedade DataFim com a data de hoje, estamos excluindo fisicamente o item da lista e enviando para o backend.
Dessa forma o backend está sendo o responsável por realizar uma consulta no banco de dados, trazendo todos os itens e comparando com a lista que recebeu do front, se o item possui IdTabela logo ele já existe no banco de dados e deve ser alterado, caso contrario deve ser feito o insert.
Toda vez tenho que realizar um select na base trazendo todos os itens, isso não seria pouco performático?
Seria melhor trabalhar com 2 listas no front e enviar para o backend a lista já com a dataFim nos itens que foram excluídos pelo usuário?
Comment: Quando você excluir uma informação que é resgatada de um repositório qualquer o seu repositório precisa saber dessa exclusão ... após ele saber você envia para o  front que a lista não existe tal item ...
Comment: Ola Virgilio! Obrigado pela resposata, mas isso  só seria possivel se a cada item excluido fosse realizado um request...porém, por definição de UX foi determinado que só seria excluido de fato após o usuário clicar em "concluir"...dessa forma, sou obrigado a realizar um unico request enviando uma lista de itens.
Comment: Você só envia os itens excluídos, e após o retorno do backend remove do front !!!
Comment: Virgilio, o problema é um pouco maior. O usuário pode inserir novamente o mesmo item que excluiu ou inserir novos itens...logo, não posso encaminhar apenas os excluidos, devo encaminhar os novos registros tbm e estar sempre verificando se o item inserido já foi excluido, se o item ja estava cadastrado ou se trata-se de apenas um insert... Em algum lugar deve existir essa complexidade...minha dúvida é se o front seria o responsavel ou o backend.

OBS: Não preciso esperar o retorno do backend...conforme o usuario clica em excluir imediatamente o item some da lista.
Comment: Se o seu objetivo é quando grava pelo botão então se sabe resolver e já está fazendo assim, eu não faria assim eu faria cada um com sua responsabilidade, mas, pelo visto não pode... Então a regra é clara
Comment: @PauloBrunoSoaresSantos A resposta resolveu sua dúvida? Acha que pode aceitá-la? Veja o [tour] se não souber como faz. Isso ajudaria muito indicar que a solução foi útil para você. Também pode votar em qualquer pergunta ou resposta que achar útil no site todo (quando tiver 15 pontos).
Answer:
Toda vez tenho que realizar um select na base trazendo todos os itens, isso não seria pouco performático?

Sim, é menos performático.

Seria melhor trabalhar com 2 listas no front e enviar para o backend a lista já com a dataFim nos itens que foram excluídos pelo usuário?

Não sei, só você pode responder, só você conhece todos detalhes do sistema. Pode falar alguma coisa sobre isto.
Você confia em informação que vem do front? Se sim, então seu software tem sérios problemas de segurança e provavelmente nem sabe. Dados só devem ser validados lá no front se não fizer diferença se de fato o dado é inválido e for algo que apenas ajuda o usuário trabalhar melhor, se for algo importante para a integridade do sistema não tem opção, só pode ser feito no backend.
Se há concorrência, qualquer comparação deve ser feita no momento que precisa e de forma exclusiva, caso contrário você entra em condição de corrida.

Lista para deleção lógica


Going through file using iterators

Question: I have a binary file which containts 10 integers let's say in binary. Is there any way to go through that file using iterators? So far, I just tool those numbers from file and put them into array. But can I avoid using arrays or vectors? Something tells me I might need to overload ++ and —. Hope my question is clear enough.
Comment: Read it into a a buffer. Treat the buffer as an array. Are you sure they're in the right endian format? Why avoid arrays when they're the right tool for the job?
Comment: @tadman that's the task :(
Comment: If this is a coding challenge, **get coding**. Remember in C and C++ arrays and pointers are two sides of the same coin.
Answer: Using any std::istream to read the file, you can use std::istream_iterator and define a custom operator>> that uses std::istream.read() to read the integers.  For example:
struct binary_int
{
    int32_t value; // or whatever type you need
};

std::istream& operator>>(std::istream &in, binary_int &out)
{
    return in.read((char*)&out.value, sizeof(out.value));
}

{
    std::ifstream inFile(...);

    std::istream_iterator<binary_int> iter(inFile);
    std::istream_iterator<binary_int> end;

    while (iter != end)
    {
        // use iter->value as needed...
        ++iter;
    }
}

Going through file using iterators


how to use URL_ALIAS for search result of apachesolr module?

Question: I am using apachesolr in drupal 6.22 module to search. the links of the results look like http://mywebsite.com/node/NID , how can i manage it to show the url alias instead of displaying node/NID representation.
Thanks for your help
Answer: I am running the same configuration as you and this has the SEF urls by default.
Have you checked your URL Aliases? Does this problem occur for ALL nodes in SERPS? I would try rebuilding your aliases
Comment: it seems some of nodes don't have url alias... i think it is my mistake :)


reuse numerical value from a text entry in subsequent entries

Question: I'm trying to automate a procedure and to create the output file that I need. So far everything is going well, but I cannot figure out how to take the number at the end of one row and fill it in for rows after it.
I've tried solutions using awk, sed, etc, but so far, I can't seem to figure this out even with the helps of many googles.
POP-Test-01
10.10.10.10
User: User
Pass: Pass

POP-Test-02
10.10.10.11
User: User
Pass: Pass

POP-Test-03
10.10.10.12
User: User
Pass: Pass
But I want it to take the numerical values from the first line, and append it to the user and pass lines. But for the pass line, I'd like to add it twice.
POP-Test-01
10.10.10.10
User: User01
Pass: Pass0101

POP-Test-02
10.10.10.11
User: User02
Pass: Pass0202

POP-Test-03
10.10.10.12
User: User03
Pass: Pass0303
These are only examples, but the last two digits of the hostname(ex. POP-Test-03) will always be numerical digits.
Edit:
I've had some requests for more details. Sorry about that guys, so here is the skinny. Please note that all values are fake, these come from an input file. I just used the most generic values I could think of.
The input is a text file with only the values in the top example.
So I run a script that deploys instances and the only output I get from the deployment script is the Hostname and the IP address. I know it's not clean, but below is how I'm adding the user and password. But the user and pass are always the same between each batch of servers with only the number of the server being appended to the user and the password(twice). I'm doing this because an application we use requires the input of:
HOSTNAME
IP
User: (username)
Pass: (password)
(empty line)
Normally I have to enter these manually which is time consuming and I was hoping not necessary since I've started it with the commands below in a script I am trying to build to automate the process.
So I start with this:
POP-Test-01
10.10.10.10
And I'm trying to get to this:
POP-Test-01
10.10.10.10
User: User01
Pass: Pass0101

awk '/([0-9]{1,3}[\.]){3}[0-9]{1,3}/{print;print "User\:
Train";next}1' DeploymentDetails2.txt | tee DeploymentDetails2.txt

awk '/User/{print;print "Pass\: Training";next}1'
DeploymentDetails2.txt | tee DeploymentDetails2.txt

awk '/Pass/{print;print "\n";next}1' DeploymentDetails2.txt | tee
DeploymentDetails.txt

Comment: `A='POP-Test-03'; b=$(echo $A| cut -d'-' -f3); echo $b`
Comment: First tell us where you are getting, e.g. `POP-Test-03` and `10.10.10.12` from? Are these prior user inputs, filenames, file-contents, what? Are the `User: User` and `Pass: Pass` lines already present or are you adding them? If they are file-contents, the post the first 10 lines or so from the file they are coming from.
Answer: This appears to produce what you are looking for:
#!/bin/bash
HOST="POP-Test-"
IP=10
for i in {01..99} ; do
  echo ${HOST}${i}
  echo "10.0.10.${IP}"
  echo "User: User${i}"
  echo "Pass: Pass${i}${i}"
  echo
  let IP++
done

As you did not specify that there was an input file, I took the liberty of generating the ending number in the script, and reusing it in the user and pass lines.
Comment: Well, if it is generation question, that's the way to do it, (though I would use a `printf "%s\n%s\n%s\n%s\n\n" ...` for a single call and then `((IP++))` rather than `let`)
Comment: Sorry, this does come form an input file and those were just example IPs, they are actually random and my input file has the first section, and I just want to finish it off so that our other script can input the values properly.


What would be needed beat and synthesis wise in order to make something like this?

Question: I'm really concerned on how they did the piano and clarinet echo (if that's even what it is), because I've been looking for tutorials on YouTube for stuff like how to make a "boombape type beat" or "lofi beat" but nothing came close enough to show what I'm looking for. I'm not trying to duplicate this person's beat in anyway, just curious on how and what was used to make it educationally. Thank you

(Devaloop - Nightshift (Instrumental))
Answer: The most common way to put together a piece of music like this is to simply take samples / recordings of musicians playing appropriate beats and phrases, and loop and trigger portions of those samples to make a new beat with a new feel. These days there are probably many types of products that you could use to do this, and thousands of individual products that have these capabilities. Looking back into hip-hop history, one noteable series of machine that was often used to make this kind of beat was the Akai MPC series, starting with the MPC60 in 1988. The audio technology used was much better than what was possible using most home computers at the time, but was still basic by today's standards (12-bit sampling at 40KHz) - that, in combination with the scratchy audio quality obtained by sampling from old vinyl records, is the kind of thing gives lo-fi beats their characteristic sound. Another aspect of the 'lo-fi' feel comes from drum beats with one rhythmic feel being forced into a slightly different feel.
MPC machines are still available today, as are many similar devices. but so is the possibility of doing this kind of sample manipulation in a DAW (digital audio workstation), or even using an audio programming language.
Likewise with the delay effect there is no one particular piece of equipment you need. Tape delay effects are often associated with lo-fi style production, and of course there are now many virtual tape delays available.
Of course it would also be possible to synthesize a piece like this without using samples of musicians playing - but starting by following something like the original process of sampling sections of music and retriggering them will help you understand where much of the characteristic sound comes from.
Answer: you don't need a program to do this:
what you can hear is just the basic rhythm of a drum pattern (except of the fill ins at the breaks).
but the base drum is not on 1 and 3 as it is placed 1 and 3 +! that means there may be also played to eight notes on beat 3 but the first one is muted and the accent is on the second eight note.  that makes it more interesting to listen at.

to perform this you can use any sequencer program ... there are lots of free downloads here.
Comment: In electronic music genres, often the notes as such are not enough. You need very specific sounds, very specific effects, timbres, waveforms, to even get  categorized in the whole genre. There's no way to explain e.g. how to create a "lo-fi beat" using traditional musical notation, just as there's no way to describe how to do the autotune effect, using musical notation. I think the OP is asking for very specific effects and settings, plugin brands and models, sample libraries. "What products to buy, which buttons to press." That's how music is made nowadays. ;)
Comment: Hey,  I have the complete vst libraries  of dorico, halion, iconica
https://www.steinberg.net/de/products/vst/iconica/sections_and_players.html
and note performer. The trouble is I don't know where the bug is while the audio driver doesn't work: is it my laptop, is it windows 10 or is it the licence key of Halion SE and Cubase V. The Steinberg production had always problems with their software. I used already in 1988 their  twenty four sequencer and master score with Atari ST1024. It was a agony. But note performer by wallander instruments works with Finale.
https://www.noteperformer.com/
Comment: I don't know what this has to do with the question, but I highly recommend Steinberg's UR series of USB audio interfaces. I have UR44 and UR22mkII, and they are incredibly solid and well-working, works in Windows, Mac, Linux and iOS. *All* my audio interface related problems went away after switching from Echo to Steinberg. All of it, from analog Hi-Z input quality to software drivers, solid low latency, everything totally solved. DAW related frustration went away by switching from Cubase to Ableton Live over a decade ago. My first MIDI sequencer program was Cakewalk for DOS in 1989. :)


Atata. C#. How to open new tab?

Question: How to open a new tab in the Chrome browser?

I can open at the beginning of a test:
          AtataContext.Configure()
              .UseChrome()
              .WithArguments("new tab")

I tried to press the shortcuts "CTRL + T:

    [PressKeys("control" + "t", TriggerEvents.AfterClick)]

OR
.Press("^t");

Answer: Update for Atata v2.2+
New methods were added in Atata v2.2.0 to Go class:

Go.ToNewWindow<TPage>(...)
Go.ToNewWindowAsTab<TPage>(...)

Solution for older Atata version
Apparently CTRL+T combination doesn't work anymore for chromedriver. But we can use window.open() JavaScript which also opens new tab.
AtataContext.Current.Driver.ExecuteScript("window.open()");

// You also need to switch to newly opened tab.
Go.ToNextWindow<OrdinaryPage>(); // Set the type of your page object instead of OrdinaryPage.
Go.ToUrl("/someurl"); // Set URL.

You can also extract this code block to a method:
public static TPage CreateAndSwitchToNewTab<TPage>(string url)
    where TPage : Page<TPage>
{
    AtataContext.Current.Driver.ExecuteScript("window.open()");

    var page = Go.ToNextWindow<TPage>();
    Go.ToUrl(url);

    return page;
}

And use it in tests in a form of:
CreateAndSwitchToNewTab<ProductsPage>("/products")
    .PageTitle.Should.Contain("Products");

Comment: Super! Thanks a lot!
Comment: Hi Yevge I get Iwebdriver doesn't contain a definition for ExecuteScript
Comment: Right @RohitKumar. For Atata v2 the `AtataContext.Current.Driver.ExecuteScript("window.open()");` line should be replaced with `AtataContext.Current.Driver.AsScriptExecutor().ExecuteScript("window.open()");`.

Atata. C#. How to open new tab?


A proof of the Riesz-Markov for compact subsets of the complex numbers.

Question: I had the following idea of how to give a simple proof of the Riesz-Markov-Kakutani representation theorem for subsets of the complex numbers and I wanted to know whether someone sees some principle problem. Note that I am a Physicist, thus my knowledge of measure theory is very bad.
If I have given a compact subset $S$ of the complex numbers and a continuous positive linear functional $\phi: C(S) \rightarrow \mathbb{R}$, where $C(S)$ are the continuous function on S. I want to prove that there exist a measure $\nu$, such that $\phi(f) = \int_S f d\nu$. To start with, I want to make S to a measurable set. The measure induced by the lebesgue measure should give me a measure $\mu$ on S. Now continuous functions on that set are dense in $L^2(S,\mu)$. Thus I can extend $\phi$ to a continous positive linear functional on $L^2(S,\mu)$ by the B.L.T. theorem. By the Riesz-representation theorem in Hilbert spaces and $L^2(S,\mu)$ being a Hilbert space, there exist an $g \in L^2(S,\mu)$ such that $\phi(f) = \langle g,f \rangle = \int_S \bar g f d\mu$. Since $\phi$ is positive and continuous, $g$ has to be real and essentially bounded. Then I define $d\nu = g d\mu$ and think of having found my measure.
My question is, does the above logic work and is $d\nu = g d\mu$ really a measure?
Thanks!
Comment: I think you meant $p=2$ everywhere. What is the BLT theorem? Your proof doesn't work for all functionals, fir instance when you consider the evaluation at some point. On the other hand, it works for a large class of linear functionals – see the Radon-Nikodym theorem.
Comment: You are right, I only now realized that we only have for p = 2 a Hilbert space and otherwise only a banach space, thanks! BLT means that if you have a bounded linear transformation from a dense subspace of a complete space, you can extend it to the whole space, a special instant of https://en.wikipedia.org/wiki/Continuous_linear_extension. I guess then my statement about the extension via the BLT must somehow fail, because I would not think that the evaluation at a point is a well defined functional on L^2, because different representatives of the same equivalence class may differ at the point
Comment: I guess it fails exactly because by considering $C(S)$ as being dense in $L^2$, I implicitly only look at the equivalence classes of functions in $C(S)$, not at each function individually and by my comment above, then exclude the functionals such as the evaluation at a point.
Answer: It is not true that every continuous linear functional on $C(S)$ can be extended to a continuous linear functional on $L^2(S,\mu)$.
The problem is that the notions of continuity on the two spaces are different, since $C(S)$ and $L^2(S,\mu)$ have different topologies.
To be more precise, let $\|\cdot\|_0$ be the supremum norm on $C(S)$ and $\|\cdot\|_2$ be the $L^2$-norm on $L^2(S,\mu)$. Now, let $\phi$ be a $\|\cdot\|_0$-continuous linear functional on $C(S)$. Even if you regard $C(S)$ a subset of $L^2(S,\mu)$, there is no guarantee that $\phi$ is $\|\cdot\|_2$-continuous on $C(S)$.
A simple counterexample is as follows. Assume (with no loss of generality) that $0\in S$ is an interior point. The evaluation at $0$ is a $\|\cdot\|_0$-continuous linear functional (represented by the Dirac mass $\delta_0$).
This functional is however not $\|\cdot\|_2$-continuous. Indeed let $(f_n)_n$ be a sequence of continuous functions with the support of $f_n$ contained in a ball of radius $1/n$ around $0$ and satisfying $0\leq f_n \leq 1$ on $S$ and $f_n(0)=1$ for every $n$. It is readily seen that this sequence of functions is not a Cauchy sequence in $C(S)$, while it is a Cauchy sequence converging to the zero function $0\in L^2(S,\mu)$. If $\delta_0$ were $\|\cdot\|_2$-continuous, one would have the contradiction
$$0=\delta_0(0)=\delta_0\big(L^2(S,\mu)\text{-}\lim_n f_n\big)=\lim_n \delta_0(f_n)= \lim_n f_n(0)=1.$$


Qual a função e como usar os Controllers no Laravel

Question: Estou aprendendo Laravel por um canal, e me ficou a dúvida... Como devo criar meus Controllers? Até onde eu entendi, o view pede para ele, o controller vai validar e com sucesso chama o model.
Mas minha dúvida em geral é... Como devo estruturar meus controllers? Por exemplo:
Views são o que o usuário enxergam, assim fica fácil distinguir que serão páginas.
Models são estruturas de banco de dados (tabelas)
E Controllers entra como qual classificação? Preciso de um Controller para cada página que tenho? Minha única informação que tenho que eles utilizam funções.
Não sei se ficou claro ao ponto de entender a pergunta, qualquer coisa modifico, mas o resumo seria...
Como estruturar um Controller no Laravel?
PS: Deixando bem claro, sou novo em programação e gostei muito do framework Laravel, pelas coisas que ele faz junto com o PHP Artisan
Answer: Então creio que você não deve ter olhado a documentação mas tudo bem, vou tentar ajudar.
Controller como o nome sugere é a classe Controladora, que envolve sua lógica e talvez sua regra de negócio, afinal você não deveria deixar isso no arquivos de rotas, você precisa do Controller para controlar uma determinada informação para sua view.
Você pode usar um Controller para várias páginas mais isso dependendo de você.
Lei informações relativas ao MVC para entender mais. Leia também sobre o SOLID .Você certamente deve ter lido pouco sobre Arquitetura de projetos, e se tiver mais dúvidas você também pode dar uma olhadinha na documentação do Laravel. Lá tem mais informações sobre Controller ,exemplos e mais usabilidades do Controller
Documentação Laravel sobre o Controller
Aconselho também o que você veja o que é arquitetura de projeto MVC.
O que é MVC?
Comment: Valeu! Acabei de ver um vídeo sobre SOLID de um homem do MVC e me ajudou muito a entender como devo utilizar e etc... Só não entendi muito bem a parte do D... Fiquei bem confuso na hora.
Comment: DIP: seria o princípio de inversão , fala sobre o desacoplamento. Achei um link que tem ilustrações pode ajudar a entender.
http://ramonsilva.net/boas-praticas/solid/inversao-de-dependencias/


Dúvida Iniciante - Erro no Loop

Question: Galera, estou fazendo um exercício, porém algo está dando conflito neste pequeno trecho da repetição, da para colocar as primeiras informações do primeiro Loop, porém quando passa para o segundo em diante, ele pula a parte do Nome. Já inverti a ordem e não tenho ideias de como resolver.

/* Escrever um algoritmo para um programa que leia um conjunto de 50 fichas contendo cada uma, o nome,
altura e o sexo de uma pessoa. Calcule e imprima :
a) A maior e a menor altura da turma b) A media de altura das mulheres c) A média de altura da turma */
double somaT = 0, mediaM = 0, mediaT = 0, altura, somaM = 0;
double maiorH = 0, menorH = 999, maiorM = 0, menorM = 999;
char nome[30], sexo;
int i, mulher, turma;
turma = 0;
mulher = 0;

for (i = 0; i < 5; i++)
{
    printf ("Digite seu nome: ");
    gets (nome);
    printf ("Digite seu sexo: ");
    sexo = getche();
    printf ("\nDigite sua altura: ");
    scanf ("%lf", &altura);

    if (sexo = 'm') {
            if (altura > maiorH) {
                maiorH = altura;
            }
            if (altura < menorH) {
                menorH = altura;
            }
    }
    if (sexo = 'f') {
        mulher++;
        somaM = somaM + altura;
            if (altura > maiorM) {
                    maiorM = altura;
                }
                if (altura < menorM) {
                    menorM = altura;
                }
    }
    turma++;
    somaT = somaT + altura;
}
mediaM = somaM / mulher;
mediaT = somaT / turma;

if (maiorH > maiorM) {
    printf ("A maior altura da turma eh: %.2lf \n", maiorH);
}
else {
    printf ("A maior altura da turma eh: %.2lf \n", maiorM);
}
if (menorH < menorM) {
    printf ("A menor altura da turma eh: %.2lf \n", menorH);
}
else {
    printf ("A menor altura da turma eh: %.2lf \n", menorM);
}

printf ("A media de altura das mulheres eh: %.2lf \n", mediaM);
printf ("A media de altura da turma eh: %.2lf \n", mediaT);

system ("PAUSE");

Answer: Tente executar dessa forma, limpando o buffer do teclado
double somaT = 0, mediaM = 0, mediaT = 0, altura, somaM = 0;
double maiorH = 0, menorH = 999, maiorM = 0, menorM = 999;
char nome[30], sexo;
int i, mulher, turma;
turma = 0;
mulher = 0;

for (i = 0; i < 5; i++)
{
    printf ("Digite seu nome: ");
    fflush(stdin);
    gets (nome);
    printf ("Digite seu sexo: ");
    fflush(stdin);
    sexo = getche();
    printf ("\nDigite sua altura: ");
    fflush(stdin);
    scanf ("%lf", &altura);

    if (sexo = 'm') {
            if (altura > maiorH) {
                maiorH = altura;
            }
            if (altura < menorH) {
                menorH = altura;
            }
    }
    if (sexo = 'f') {
        mulher++;
        somaM = somaM + altura;
            if (altura > maiorM) {
                    maiorM = altura;
                }
                if (altura < menorM) {
                    menorM = altura;
                }
    }
    turma++;
    somaT = somaT + altura;
}
mediaM = somaM / mulher;
mediaT = somaT / turma;

if (maiorH > maiorM) {
    printf ("A maior altura da turma eh: %.2lf \n", maiorH);
}
else {
    printf ("A maior altura da turma eh: %.2lf \n", maiorM);
}
if (menorH < menorM) {
    printf ("A menor altura da turma eh: %.2lf \n", menorH);
}
else {
    printf ("A menor altura da turma eh: %.2lf \n", menorM);
}

printf ("A media de altura das mulheres eh: %.2lf \n", mediaM);
printf ("A media de altura da turma eh: %.2lf \n", mediaT);

system ("PAUSE");

Comment: Pronto, resolvido. Obrigado
Comment: opa blz , da um voto ai pra nois na questão resolvida pra ajuda, vlw

Dúvida Iniciante - Erro no Loop


how to replace the legends of Piechart using achartengine API?

Question: I am Using Achartengine Api for drawing pie chart. I am getting the legends displayed at the bottom of the Pie chart horizontally. but I want to display it on the right side of the Pie chart vertically. I heard that it can be done using setMargins() method . if I can use that please explain how to use that.
Thank you in advance.
Answer: The setMargins() API call is, as the name suggests, for setting the margins around the chart. You cannot move the legend using this and you actually cannot move the legend at all with AChartEngine. You can hide it.


How to Check device Dicovery and undiscovery of Bluetooth Le Device

Question: I am Working on Android application that List out the Bluetooth LE device which are discovered.
I am using following code to Scan BLE Devices.
    BluetoothManager mBta = ((BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE)).getAdapter();
    SNFBluetoothAdapter mSNFBluetoothAdapter=new SNFBluetoothAdapter(MainActivity.this);

    mBta.startLeScan(mSNFBluetoothAdapter);

Using This method I am able to Scan the Bluetooth Devices in Range in.
    onLeScan(final BluetoothDevice device, int rssi, byte[] scanRecord)

But Now My Issue is,
How can I check that Device Goes Out of bluetooth range and update my List of Devices?
Please Help.
Sorry for my Language.
Comment: You can see if something previously found does not get found again in some reasonable number of attempts. A decreasing rssi could also be a clue. Likely you will need to tune the decisioning to your application needs.
Answer: You could use several developers sdk. Check out for Radius Network beacon and Estimote beacon. Estimote descovers only estimote beacons. Beacons have proximity functions as your requirements and they can notify you when you enter / exit in the area.
Comment: The question is not specific to "beacons" and additionally SO prefers answers which provide a stand alone explanation and do not merely point to another place.
Answer: The method onLeScan(final BluetoothDevice device, int rssi, byte[] scanRecord) always run unless you stop this process.
So, if Device Goes Out of bluetooth range, it will automatically disappear.
No need worry.
Comment: @ Alex Tran.
I am managing ArrayList of Devices and Displaying it in ListView.
And onLeScan(final BluetoothDevice device, int rssi, byte[] scanRecord) Only Calls when Device come in the bluetooth range. So in onLeScan method I am adding Device to my List.
So If Device goes Out of range I have to remove the device from my List , So using this method it is not possible.
Try the code and If possible then Please Describe.
Answer: Finally I used the Timer to Refresh the List.
After Some Specific time Reset the List Data and ReFetch the DeviceList so it will fetch new List which are  In Range Devices.


Bison - Productions for longest matching expression

Question: I am using Bison, together with Flex, to try and parse a simple grammar that was provided to me. In this grammar (almost) everything is considered an expression and has some kind of value; there are no statements. What's more, the EBNF definition of the grammar comes with certain ambiguities:

expression OP expression where op may be '+', '-' '&' etc. This can easily be solved using bison's associativity operators and setting %left, %right and %nonassoc according to common language standards.
IF expression THEN expression [ELSE expression] as well as DO expression WHILE expression, for which ignoring the common case dangling else problem I want the following behavior:

In if-then-else as well as while expressions, the embedded expressions are taken to be as long as possible (allowed by the grammar). E.g 5 + if cond_expr then then_expr else 10 + 12 is equivalent to 5 + (if cond_expr then then_expr else (10 + 12)) and not 5 + (if cond_expr then then_expr else 10) + 12

Given that everything in the language is considered an expression, I cannot find a way to re-write the production rules in a form that does not cause conflicts. One thing I tried, drawing inspiration from the dangling else example in the bison manual was:
expression: long_expression
    | short_expression
    ;

long_expression: short_expression
    | IF long_expression THEN long_expression
    | IF long_expression long_expression ELSE long_expression
    | WHILE long_expression DO long_expression
    ;

short_expression: short_expression '+' short_expression
    | short_expression '-' short_expression
    ...
    ;

However this does not seem to work and I cannot figure out how I could tweak it into working. Note that I (assume I) have resolved the dangling ELSE problem using nonassoc for ELSE and THEN and the above construct as suggested in some book, but I am not sure this is even valid in the case where there are not statements but only expressions. Note as well as that associativity has been set for all other operators such as +, - etc. Any solutions or hints or examples that resolve this?
----------- EDIT: MINIMAL EXAMPLE ---------------
I tried to include all productions with tokens that have specific associativity, including some extra productions to show a bit of the grammar. Notice that I did not actually use my idea explained above. Notice as well that I have included a single binary and unary operator just to make the code a bit shorter, the rules for all operators are of the same form. Bison with -Wall flag finds no conflicts with these declarations (but I am pretty sure they are not 100% correct).
%token<int> INT32 LET IF WHILE INTEGER OBJECTID TYPEID NEW
%right <str> THEN ELSE STR
%right '^' UMINUS NOT ISNULL ASSIGN DO IN
%left '+' '-'
%left '*' '/'
%left <str> AND '.'
%nonassoc '<' '='
%nonassoc <str> LOWEREQ
%type<ast_expr> expression
%type ...

exprlist: expression { ; }
    | exprlist ';' expression { ; };

block: '{' exprlist '}' { ; };

args: %empty { ; }
    | expression { ; }
    | args ',' expression { ; };

expression: IF expression THEN expression { ; }
    | IF expression THEN expression ELSE expression { ; }
    | WHILE expression DO expression { ; }
    | LET OBJECTID ':' type IN expression { ; }
    | NOT expression { /* UNARY OPERATORS */ ; }
    | expression '=' expression { /* BINARY OPERATORS */ ; }
    | OBJECTID '(' args ')' { ; }
    | expression '.' OBJECTID '(' args ')'  { ; }
    | NEW TYPEID { ; }
    | STR  { ; }
    | INTEGER { ; }
    | '(' ')' { ; }
    | '(' expression ')' { ; }
    | block { ; }
    ;

Comment: Does your `if` expression use a `then` token or not? Your supposed extract includes both a production with `THEN` and one without. If that's real code, it will obviously cause problems. If it's not real code, you shouldn't claim that it is.
Comment: As part of an [mre], you would include the precise precedence declarations used. Details matter. Mentioning the fact that you have declarations doesn't show us what they are or allow us to see if they are hiding ir creating errors.
Comment: Please, when asking questions, provide a [mre]. In the case of an expression grammar, you can reduce the size of the code by removing actions and restricting the grammar to only a couple of operators. You only need to ensure that the reduced grammar has the same conflicts as the ones you want to solve.
Comment: @rici I will try to strip down what I have and include only the problem causing part
Comment: @rici I hope this is more clear
Comment: But you say "Bison with -Wall flag finds no conflicts with these declarations", so it's not exhibiting the problem you claim to have. :-) What evidence do you have that the rules are not correct?
Comment: @rici I will try to give an input file that fails, my output and the expected output. But I would like to know which precedence declarations are not necessary and, maybe, why? Although 'why is something **not** necessary" does not really make sense
Comment: Oops. My brain is not in gear today.
Answer: The following associativity declarations resolved all shift/reduce conflicts and produced the expected output (in all tests I could think of at least):
...
%right <str> THEN ELSE
%right DO IN

%right ASSIGN
%left <str> AND
%right NOT
%nonassoc '<' '='  LOWEREQ
%left '+' '-'
%left '*' '/'
%right UMINUS ISNULL
%right '^'
%left '.'
...
%%
...
expression: IF expression THEN expression
    | IF expression THEN expression ELSE expression
    | WHILE expression DO expression
    | LET OBJECTID ':' type IN expression
    | LET OBJECTID ':' type ASSIGN expression IN expression
    | OBJECTID ASSIGN expression
    ...
    | '-' expression %prec UMINUS
    | expression '=' expression
    ...
    | expression LOWEREQ expression
    | OBJECTID '(' args ')'
    ...
...

Notice that the order of declaration of associativity and precedence rules for all symbols matters! I have not included all the production rules but if-else-then, while-do, let in, unary and binary operands are the ones that produced conflicts or wrong results with different associativity declarations.
Comment: That's an eccentric precedence for `NOT`; in most languages `not a and b` means `(not a) and b` rather than `not (a and b)`. In fact, in most languages `not a < 3` would parse as `(not a) < 3`, even though `not (a < 3)` does seem to be more natural and some languages do treat it that way. If the grammar is written the way you write it, I don't think `ASSIGN` requires a precedence declaration; the precedence declaration would be required for `expression ASSIGN expression`. Of course, it doesn't hurt. Similarly for `.`, since its right-hand operand is probably also `OBJECTID`.


Converting a 3/4 melody to a 2/4 march, any tips?

Question: So, I'm writing a Theme and Variations piece using the Happy Birthday melody. And I am writing it for a string quartet. I know I will have or already have these variations:

Eighth note variation - Finished
Sixteenth note variation - Finished
Alla Marcia variation(3/4 melody turns into 2/4 march) - Working on right now
Alberti Bass variation(Cello plays Alberti bass while other instruments play a block harmonization of the melody) - Towards the middle of the variations
Cadenza variation(First violin plays a cadenza over the melody) - Towards the end of the variations
Canon variation - Penultimate or Ultimate variation of the set

And I'm thinking of possibly including these:

Syncopation, but in original 3/4 time signature(Kind of like Variation V of Mozart's 12 Variations on Twinkle Twinkle Little star in that the melody would probably be broken up between the instruments to keep interest up as well as make the syncopation more obvious) - Probably also towards the middle of the set
Minor key? - This is one am less sure about. I mean, it would change the feeling completely. Happy Birthday is, as the name suggests, a happy sounding song. Turning it emotionally on its head? I mean that might be interesting, but would it fit in with the rest of the piece which is in F major?
Chorale? - I mean, I could do it. I have written Bach Chorale-like sections within a larger piece for piano solo in a form such as Rondo. And that was with more than 4 notes, like up to 8 notes at a time. That's possible with the string quartet as well. Since Happy Birthday is at Andante, should I make the Chorale variation an Adagio at like 65 BPM and have it switch back to 80 BPM afterwards if I decide to include this variation?

The variation I am asking about is the Alla Marcia variation. How do I take a 3/4 melody like this melody:

and convert it into 2/4 in such a way that I don't end with a half bar? Or do I have to end with a half bar? This is just 1 example of me taking Happy Birthday and turning it into 2/4 on the piano.

But, how would I notate that? And are there any tips that will help me convert any melody in 3/4 into 2/4 in case I want to do a march variation on a different 3/4 melody?
Comment: Don't forget that a lot of marches are in 6/8 - that still gives the 'left, right' feel.
Answer: Your video is Happy Birthday in 2/4 but I think it would be more musical to take the written 3/4 version and add a 1/4 note duration to every downbeat so each bar becomes 4 beats, or two bars of 2/4. It would sound less rushed and would allow you to play it in a wide range of tempos.
Bar 1 becomes half, quarter quarter
Bar 2 becomes a half tied to quarter, dotted eighth, sixteenth, like this:

I think this has a better flow and more of a march feel.
Comment: @AlexanderWoo I'm sorry I don't agree. Marches are typically written with these types of rhythms. Also halving it would make the dotted 8th-sixteenth a dotted 16th-32nd, way too busy.
Comment: Except I would halve all your note values (and make 2 of your measures into one measure).
Answer: May I suggest this?

Losing the upbeat produces a pause between phrases during which the accompanying strings could do something fun!
Comment: Bit weird to have the accents "HAppy birthDAY to YOU", but still I like this version better than the current alternatives.
Answer: You played something like this.   That's fine.  What's your problem with notating it?

Or you could shift the accents and do something like this:

I don't think you need any 'tips'.   Your improvised version was fine, you got the march feel very well.
Answer: The most natural adaption to me would be in 4/4:
the syncopation should be on the word "birthday":
quarter -, half note,
"to you"
quarter- and half note.
And as you want it in 2/4 time the half note will be  2 quarter notes tied between bar 1 and 2. With other words like the original in 3/4 but the syllable "-day" counts 2 beats!
(I must tell you I' think I've played this march already!)
Answer: Or MAY-be . . .

?
Oops! Did it HAVE to be in 2/4?
Answer: I would do something like this as a foundation:

That quarter pause works fairly well as a hook.
Comment: I'm getting Broadway and tap dancing vibes from reading that melody.
Answer: To me all the previous suggestions feel unnatural. Regardless of whether a part is actually sung or played on an instrument – the listener will internally sing along, and you should avoid hiccupping this more than necessary.

Keep "Birth" and "You" on strong beats. In a march, strong beats are ever more dominating, and these are the words that need them.
Don't stretch words too long. It's not like this can't be done, also in a newly-written melody, but for an existing melody this feels extra weird, especially if combined with the staccato-like playing you have in a march.

The only way I can see how this can be achieved is by syncopating "day":
X:1
L:1/8
M:2/4
K:F
%%score T1
V:T1           clef=treble
% 1
[V:T1] c2 c2 | dc zf | e2 z2 | c2 c2 | dc zg | f2 z2

or
X:1
L:1/8
M:2/4
K:F
%%score T1
V:T1           clef=treble
% 1
[V:T1] c2 c2 | d3/2c/2 zf | e2 z2 | c2 c2 | d3/2c/2 zg | f2 z2

Syncopation may be not the first choice in a march, but I'd say on a weak beat it's fine.
You could add rest bars to make it four bars per line, but I would not.
What I would do, in full:
X:1
L:1/8
M:2/4
K:F
%%score T1 B
V:T1           clef=treble
V:B           clef=bass
% 1
[V:T1] c2  c2  | dc  z   f | e2 z2   | c2  c2  | dc  z g | f2  z2  |
[V:B]  F,2 E,2 | D,2 =B,,2 | C,2 D,2 | E,2 F,2 | G,2 C,2 | F,2 G,2 |
[V:T1] c2  c2  | (3:4:3c'2 a2 f2 | e2 d2   | z2  b3/2b/2 | (3:4:2a4(f2 | (3:4:2 f2) g4 | f4 ||
[V:B]  A,2 G,2 | F,2 C,2   | B,,3   (A,,| A,,2) B,,2  | C,4     | (3:4:2 z2 c,4 | F,4 ||

Answer: One way to approach the question is to preserve the metrical stress points. Use the basic concept that longer rhythm values denote accents. Put the accents on first beats. Fitting 2 into 3 requires a reduction as the most straight forward change. Reduced values should produce weaker stresses so put those smaller rhythms on weak beats. The melody's phrases start with anacrusis which should be preserved.

Using ' for strong stress and , for weak stress, and trying to approximate the first line of text with natural speaking, it seems like the pattern lines up with 6/8...

,hap,py | 'birth,day ,to | 'you


Unknown functions yield a given determinant

Question: I am trying to develop a nomogram which simultaneously shows the exact Fisher equation $(1+u) = (1+v)(1+w)$ and its linear approximation $u \approx v + w$.
This amounts to finding twelve smooth curves such that the following equations hold:
$$\det \begin{bmatrix}f_1(u) & f_2(u) & f_3(u) \\ g_1(v)& g_2(v) & g_3(v) \\ h_1(w) & h_2(w) & h_3(w)\end{bmatrix} = (1+v)(1+w) - (1+u)$$
$$\det \begin{bmatrix}f_4(u) & f_5(u) & f_6(u) \\ g_1(v)& g_2(v) & g_3(v) \\ h_1(w) & h_2(w) & h_3(w)\end{bmatrix} = v + w - u$$
My question is how to begin thinking about this problem --- how can you decide whether such curves exist, and how might you look for them?
Answer: For context for people trying to figure out what the question is about - we're discussing this thing: https://en.wikipedia.org/wiki/Fisher_equation
If you mean for them to be shown "all on the same scales" then I don't think this is possible, but if you either:
a) have both nomograms on the same axis-lines (same support lines but all with different scales for the exact and approximate forms, (so different tick marks and axis labels), or
b) allow at least one axis (support line) of the approximate equation to be different from the exact form,
-- then yes.

Note that the most obvious ways to tackle the first (i.e. exact) equation is on the log scale (I'll assume that all the variables exceed -1; interest rates above -100% seems uncontroversial; indeed normally they'd exceed 0)
That would produce three parallel scales in $log(1+u)$, $log(1+v)$, $log(1+w)$ (but with tick marks labelled in $u, v$ and $w$); on the other side of the same support lines you could place $u, v$ and $w$ as linear scales for the linear approximation, and set the scaling up so that the centres of the $v$ and $w$ scale represented the same value of $v$ and $w$ on both sides (so there'd be a single horizontal line that represented both equations at the same time and you could see the way that the scales diverged away from that)
That would look roughly like this:
  v v*    u u*    w w*
   |               |
   |       |       |
   |       |       |
   |       |       |
   |       |       |
   |       |       |
   |               |

where both the left and the right of each line would have its own tick marks and labels; the *-side of each axis-support line would show the scaling for the approximate equation. (It's suggestive to use slightly different colors for the two sides.)
Constructing this would require dealing with the determinant for the
*-variables separately from the non-* ones, but keeping them so that the column representing the abscissae of each axis support-line was the same for both determinants and choosing $w$&$w*$ and $v$&$v*$ scale pairs so they were the same at some convenient chosen point (presumably $0$).
You could set up an $N$ (or "Z") type nomogram for the product in the exact equation, (which has two linear scales on the parallel arms, for $1+u$ and one of the variables in the product, say $(1+w)$), where again it's labelled in $u$, $v$ and $w$, and then set up a third parallel axis (for $v$, say; noting that $(1+w) + (0+v) = (1+u)$ can also be labelled with w,v,u respectively)
That should look something roughly like this:
w    v* v   u
|
|10  | /
|    |/    |0
|    |0    |
|0  /|     |10
   / |20   |
           |20

Here the u and w scales do double-duty, but the v and v* scales are on different lines.
You can approach this second one by writing a pair of overlapping determinants:
Let W = 1+w and U = 1+u. Write V = 1+v for the exact equation and v*=v for the approximation.
So you want to simultaneously write W+v*=U and WV=U; if you write a 3x3 determinant for V W and U and another for W U and v*, but keep W and U the same
for both, you can write a 4-line array representing both determinants at the same time:
V      |  -V    1    0 |
U      ||  0   -W    1 ||
W      ||  U    0    1 ||
v*      |-v*/2 1/2   1  |

(assuming I didn't screw that up somewhere) and then manipulate rows and columns as you would a 3x3 determinant to produce something in standard form that's reasonably-scaled, keeping in mind that the tick marks and labels will all be in $u,v,w$ (and $v*$).


ERROR: py35: InterpreterNotFound: python3.5 even though python3.5 is installed

Question: I'm running my builds on my CI (bamboo) via tox on docker
my tox.ini look like this
[tox]
envlist = py27,py35
[testenv]
deps=-rrequirements.txt
commands=pytest

i'm running the tests like so
tox --recreate -vv -i $myindexserver
Testing the setup locally works (inside docker)

py27: commands succeeded
  py35: commands succeeded
  congratulations :)

But while running the same thing on the CI instance failes with

___________________________________ summary_________________________________
py27: commands succeeded
  ERROR:   py35: InterpreterNotFound: python3.5

inside the docker, running which python3 and which python3.5 succeeds
Has anyone faced similar issue?
Answer: Turns out that the docker container versions used by my local and the one used by the CI were different.
I'm keeping the answer here in the hopes that someone else finds this useful and possibly save the many hours of debugging that I had to waste.
do a docker images to find the tag that you're using locally, and check it against the version running inside your CI.


contour of circle is connected?

Question: I am having such a hard time trying to see whether the contour of the circle is connected: $A = \{ x^2 + y^2 = 1 \} $ I mean it is intuitively obvious, but I don't know how to prove it. Can someone help me please?
Comment: Typically one uses a basic result of point set topology that the continuous image of a connected set is connected, but you can prove this directly if you wish.
Comment: $f: [0,1] \to A$ defined as $f(t)=e^{2 \pi i t}$ is a continuous function, and $[0,1]$ is connected, so, its image, which is $A$, is connected.
Comment: How can you show circle is connected using this fact?
Answer: If you know the following "main" result, then you can apply the mapping that Twink describes to conclude the circle is connected:
Prop. If $\mathscr{S}$ is a connected topological space, and $f:\mathscr{S} \rightarrow \mathscr{T}$ is a continuous surjection, then $\mathscr{T}$ is also a connected topological space.
Specifically, we map $\mathbb{R}$ (which is connected) onto the circle by $f(\theta)=(\cos \theta,\sin \theta)$, and the continuity of this surjection establishes (by the above proposition) that the circle is connected.

contour of circle is connected?


Como enviar mutiplas imagens com este codigo!

Question: Apenas esta enviando uma imagen!
Meu Form
<form role="form" method="post" action="./?action=addmult" enctype="multipart/form-data">

           Imagen (480x480)
           <input type="file" name="image" multiple="">

           Pasta
           <input type="text" name="folder" class="form-control" placeholder="Pasta">

           <button type="submit" class="btn btn-primary">Enviar</button>

Estou usando a Class Upload!
Meu código.
if(isset($_FILES["image"])){
    $image=new Upload($_FILES["image"]);
    if($image->uploaded){
        $folder = 'teste';
        $new = mkdir($target_dir . $folder . "/");
        $image->Process("storage/images/".$folder);
        if($image->processed){
            $img = new ImageData();
            $p->title = $_POST["title"];
            $p->content = $_POST["content"];
            $img->src = $image->file_dst_name;
            $img->user_id=$_SESSION["user_id"];
            $imgx=$img->add();
        }
    }
}
Core::redir("./?view=galery");

Tentativa
        if(isset($_FILES["image"])){

    $handle=new Upload($_FILES["image"]);
    $files = array();
    foreach ($_FILES['image'] as $k => $l) {
    foreach ($l as $i => $v) {
    if (!array_key_exists($i, $files))
    $files[$i] = array();
    $files[$i][$k] = $v;
    }
    }
    foreach ($files as $file) {
    $handle = new Upload($file);
    if($handle->uploaded){

    $folder = $_POST["folder"];
    $new = mkdir($target_dir . $folder . "/");
    $handle->Process("storage/images/".$folder);

    if($handle->processed){

        $img = new ImageData();
        $p->title = $_POST["title"];
        $p->content = $_POST["content"];
        $img->src = $image->file_dst_name;
        $img->user_id=$_SESSION["user_id"];
        $imgx=$img->add();
        echo 'OK';
        } else {
        echo 'Error: ' . $handle->error;
        }
        } else {
        echo 'Error: ' . $handle->error;
        }
        unset($handle);
      }

    Core::redir("./?view=galery");

Comment: As classes Upload e ImageData não são nativas, logo **é impossível** responder a sua pergunta, pois nem sabemos se isso é um framework ou um código proprio e portanto desconhecemos o básico para poder fornecer qualquer ajuda.
Comment: você, não deve ter entendido a informação sobre ! Apenas esta enviando uma imagen! onde esta o wally ?
Comment: Sem conhecer o código não temos como afirmar como dizer com precisão qual o uso correto (ou mais adequado) para o upload, afinal de contas se é um código pessoal seu (me refiro as classes) só você saberia afirmar, se for um Framework popular então só se você informar qual é e qual a sua versão. PS: só pra avisar não fui eu quem deu o downvote.
Comment: tudo funciona imagedata e Upload o que acontece que nao esta enviando multiplas imagens e apenas uma imagen eh enviada !
criação de pasta , envio de imagen tudo ok!
como se trata de apenas uma classe como no link acima da mesma acredito , que não preciso mostrar que é um framework ou qualquer outra coisa ! pois a pergunta que eu fiz relacionada apenas ao upload inclusive encontrei este https://github.com/verot/class.upload.php/issues/1
Comment: Está chegando um array em `$_FILES["image"]`?
Comment: nao! nao chega nada.
Answer: Agradeço a todos pela ajuda !
com muito custo descobri o problema e estou passando a solução para todos
 Obrigado !
Codigo Reformulado!
<form role="form" method="post" action="./?action=addmult"
enctype="multipart/form-data">
 Selecione as imagens

                    Pasta
                <input type="text" name="folder" class="form-control" placeholder="Pasta">

        <input id="file-0c" class="file" type="file" name="image[]" multiple data-min-file-count="0">

Enviar

A solução encontrada foi de apenas um [] no name="image" para name ="image[]"


Is Mongo 3.4 using indexes for this query or not?

Question: I'm using a sharded replica set. Have one large collection with the following index:
{
    "shop" : 1,
    "email" : 1
}

I'm trying to find the best way of querying each element one by one:
db.user.explain('executionStats').find({shop:151, email:{$exists:true}}, {limit:1}))

and the results are the following.
My questions are:
Is the query using the index?
If yes, how can I read from this explain result?
Second:
is better to use this query, loop the cursor, then query again

.find({shop:151, email:{$exists:true}}, {limit:100}))

or

.findOne({shop:151, email:{$exists:true}}))

in a continuous loop?
{
"queryPlanner" : {
    "plannerVersion" : NumberInt(1),
    "namespace" : "vt4users.user",
    "indexFilterSet" : false,
    "parsedQuery" : {
        "$and" : [
            {
                "shop" : {
                    "$eq" : NumberInt(151)
                }
            },
            {
                "email" : {
                    "$exists" : true
                }
            }
        ]
    },
    "winningPlan" : {
        "stage" : "PROJECTION",
        "transformBy" : {
            "limit" : NumberInt(1)
        },
        "inputStage" : {
            "stage" : "FETCH",
            "filter" : {
                "email" : {
                    "$exists" : true
                }
            },
            "inputStage" : {
                "stage" : "IXSCAN",
                "keyPattern" : {
                    "shop" : NumberInt(1),
                    "email" : NumberInt(1)
                },
                "indexName" : "shop_1_email_1",
                "isMultiKey" : false,
                "isUnique" : false,
                "isSparse" : true,
                "isPartial" : false,
                "indexVersion" : NumberInt(1),
                "direction" : "forward",
                "indexBounds" : {
                    "shop" : [
                        "[151.0, 151.0]"
                    ],
                    "email" : [
                        "[MinKey, MaxKey]"
                    ]
                }
            }
        }
    },
    "rejectedPlans" : [

    ]
},
"executionStats" : {
    "executionSuccess" : true,
    "nReturned" : NumberInt(3),
    "executionTimeMillis" : NumberInt(0),
    "totalKeysExamined" : NumberInt(3),
    "totalDocsExamined" : NumberInt(3),
    "executionStages" : {
        "stage" : "PROJECTION",
        "nReturned" : NumberInt(3),
        "executionTimeMillisEstimate" : NumberInt(0),
        "works" : NumberInt(4),
        "advanced" : NumberInt(3),
        "needTime" : NumberInt(0),
        "needYield" : NumberInt(0),
        "saveState" : NumberInt(0),
        "restoreState" : NumberInt(0),
        "isEOF" : NumberInt(1),
        "invalidates" : NumberInt(0),
        "transformBy" : {
            "limit" : NumberInt(1)
        },
        "inputStage" : {
            "stage" : "FETCH",
            "filter" : {
                "email" : {
                    "$exists" : true
                }
            },
            "nReturned" : NumberInt(3),
            "executionTimeMillisEstimate" : NumberInt(0),
            "works" : NumberInt(4),
            "advanced" : NumberInt(3),
            "needTime" : NumberInt(0),
            "needYield" : NumberInt(0),
            "saveState" : NumberInt(0),
            "restoreState" : NumberInt(0),
            "isEOF" : NumberInt(1),
            "invalidates" : NumberInt(0),
            "docsExamined" : NumberInt(3),
            "alreadyHasObj" : NumberInt(0),
            "inputStage" : {
                "stage" : "IXSCAN",
                "nReturned" : NumberInt(3),
                "executionTimeMillisEstimate" : NumberInt(0),
                "works" : NumberInt(4),
                "advanced" : NumberInt(3),
                "needTime" : NumberInt(0),
                "needYield" : NumberInt(0),
                "saveState" : NumberInt(0),
                "restoreState" : NumberInt(0),
                "isEOF" : NumberInt(1),
                "invalidates" : NumberInt(0),
                "keyPattern" : {
                    "shop" : NumberInt(1),
                    "email" : NumberInt(1)
                },
                "indexName" : "shop_1_email_1",
                "isMultiKey" : false,
                "isUnique" : false,
                "isSparse" : true,
                "isPartial" : false,
                "indexVersion" : NumberInt(1),
                "direction" : "forward",
                "indexBounds" : {
                    "shop" : [
                        "[151.0, 151.0]"
                    ],
                    "email" : [
                        "[MinKey, MaxKey]"
                    ]
                },
                "keysExamined" : NumberInt(3),
                "dupsTested" : NumberInt(0),
                "dupsDropped" : NumberInt(0),
                "seenInvalidated" : NumberInt(0)
            }
        }
    }
},
"serverInfo" : {
    "host" : "host",
    "port" : NumberInt(27017),
    "version" : "3.2.11",
    "gitVersion" : "009580ad490190ba33d1c6253ebd8d91808923e4"
},
"ok" : NumberInt(1)

}
Comment: You are using 3.2, not 3.4 as in the question title. It doesn't matter though.
Answer: Your query is using the index. You can see that in the inputStage
"stage" : "IXSCAN"

You can check it in the docs to better understand its meaning.
Regarding your second question, if you want to fetch all results, looping with findOne is NOT better (performance wise) than doing the query normally.
Comment: indeed, I copied from local mongo. Doesn't matter anyway.
Comment: and indeed I ended up fetching with limit instead of find_one


Leon-Aubert Violin Year?

Question: How do I know when my Leon-Aubert violin was made? There is no name but there is a serial number. However, I cannot find any information about it anywhere.  I am sure I am not Googling it correctly but don't know how to look it up.
My parents bought it used in 1987, so it has some age on it.
Can somebody help me?
Comment: I meant it does not have a date in there.  It clearly says Leon-Aubert.
Answer: You probably won't find it already, but you can learn from the current violin makers. They can recognize it by the quality of what tree, for example, or painting it, and see a lot of details that we don't see. So the only way I can advise, because on the Internet you will not find!

Leon-Aubert Violin Year?


what's $\int \sin (e^x)\ dx$ ??

Question: I was working on a physics problem and I faced this integral:
$$\int \sin(e^x) \, dx =$$
I tried to solve it but I could not.
Comment: As an aside, $~\displaystyle\int_{-\infty}^\infty\sin\big(e^x\big)~dx~=~\dfrac\pi2~.$
Answer: $$ \int\sin{e^x}dx = \int{\frac{\sin{e^x}}{e^x}e^xdx} = \int{\frac{\sin t}{t}dt} = Si(t) + C = Si(e^x) + C$$
Where $Si(x)$ - sine integral and it can not be expressed in terms of elementary functions. See here.
Answer: According to Wolfram this integral is $Si(\exp(x))$ (The sine integral function)
Answer: Using taylor, $$\int \sin(e^x)dx=-\int\sum_{k=0}^\infty\frac{(-e^x)^{2k+1}}{(2k+1)!}dx=\sum_{k=0}^\infty\frac{(-e^x)^{2k+1}}{(2k+1)(2k+1)!}.$$
Converges for all $x$.
Comment: How do you get the last equality?
Comment: @YoTengoUnLCD, integrating term to term.
Comment: That's how I would have proceeded!  +1
Answer: It has no explicit solution, you can express the integral in terms of the SI function or compute it numerically if it appears as a definite integral.

what's $\int \sin (e^x)\ dx$ ??


How to catch default SMS app switching event?

Question: Is there any way to determine when user changes the default SMS app in settings? Is there any Intent action or something like this?
Answer: There is no system wide broadcast when the user switches the default SMS app, but what you can do is register a content observer on the SettingsProvider, by using Settings.System.getUriFor(String name). Pass the default SMS application constant to this method and register a content observer on the Uri. You'll only know that it has changed, but not to what app, but you can use the public API for that. Also, it's worth noting that this approach will only work when your app is running.
Edit: As of Nougat, there's now an intent broadcasted when the default SMS app changes.
Answer: maybe you should take a look at this: Android Devs Settings.System
Look out for getter Methods.
Comment: This will only help to detect the current default SMS app package name. But this is not enough.


check for noncorrelation of normal pseudo random numbers using scatterplot

Question: pseudo random number generators should give as output random sequences u1, u2, ... that are independent and identically distribuited (iid).
Since testing for independence is not easy, the first check is testing for noncorrelation. As a first visual test you could check the scatterplot of (Ui, Ui-1).
Let's do that for the R built in function runif (Mersenne Twister generator):
nsample <- 5000 #number of random uniform numbers that I'll generate
set.seed(111) #set the seed
U_mersennetwister <- runif(nsample) #generate nsample pseudo RN using the built-in R function (ie Mersenne Twister algorithm)
plot(U_mersennetwister[1:(nsample-1)],U_mersennetwister[2:nsample]) #scatterplot (Ui vs Ui-1)

The output, as expected span the unit square almost evenly, so we can conclude that Ui is incorrelated to Ui-1:

However, if I repeat the same procedure for the built-in function rnorm, I get that the following output, which not span evenly the two axis, so for example the probability that Zi-1 < 0 given that Zi = 3 is much smaller than the probability that Zi-1 < 0 given that Zi = 0:
N <- rnorm(100000)
plot(N[1:99999],N[2:100000])

This is the output:

Can someone explain me why (Zi, Zi-1) does not span evenly the two axis?
Comment: "So for example the probability that Zi-1 < 0 given that Zi = 3 is much smaller than the probability that Zi-1 < 0 given that Zi = 0" is not supported by your data (or by theory).  It looks like you might be misinterpreting the plots.  See https://stats.stackexchange.com/a/429367/919 for a detailed explanation.
Answer: Xi'an pointed out the original answer was wrong and I have corrected it (hopefully):
runif() generates samples from the uniform distribution while rnorm() generates samples from the normal distribution. So in the first plot you are essentially drawing from a multivariate uniform distribution while in the latter example you are not drawing from a multivariate uniform distribution. This is because the random number generators work as expected.
What you are doing in the first case is plotting a multivariate uniform distribution which has uniform coverage on a square and in the second case because both $U_i$ and $U_{i+1}$ are normally distributed you are making a multivariate normal distribution and plotting that. This is expected to look like a circle centered at (0,0) since rnorm() draws from a normal distribution with mean 0. You have effectively plotted the level sets of a 2D normal distribution: https://mathinsight.org/level_sets
Answer: The joint density of a pair of Normal rvs is
$$\frac{1}{2\pi}\exp\{-(x_1^2+x_2^2)\,/\,2\}$$
This means the level sets of the density are the circles of centre $(0,0)$. Since
$$X_1^2+X_2^2\sim\chi^2_2$$
it is further feasible to check the repartition of the simulated points inside/outside discs with known probability:

This plot contains 100 simulations of a bivariate Normal random vector, along with discs that correspond to the 75%, 50%, 25% and 10% quantiles of a $\chi^2_2$ distribution. It can be seen that approximately 75%, 50%, 25% and 10% of the simulated sample are inside the discs, respectively.
Here is my R code for plotting those graphs:
par(mfrow=c(2,2),mar=c(3,3,1,1))
for(pr in c(.75,.5,.25.1)){
plot(x,y, asp=1, xlim=c(-2,2),pch=19,col="navyblue")
draw.circle(0,0,sqrt(qchisq(pr,2)),nv=1000,bord=NULL,col="wheat",lwd=1)
points(x[x^2+y^2<qchisq(pr,2)],y[x^2+y^2<qchisq(pr, 2)],col="tomato",pch=19)}


Método de fechar uma Activity

Question: Boa noite, em minha aplicação fiz um DialogFragment coloquei uma função de fechar activity atual e voltar para anterior, a chamada coloquei no onBackPressed() e o código que faz essa função esta no onclick do "OK"... só que está me apresentando um erro no LogCat
Alguém poderia me ajudar?
DialogFragment:
    package com.gif.popupsair;

import android.app.Activity;
import android.app.Dialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.DialogFragment;
import android.support.v7.app.AlertDialog;

public class MyDialog extends DialogFragment {

    private Activity getActivity;

    @NonNull
    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        AlertDialog.Builder builderr = new AlertDialog.Builder(getActivity());

        builderr.setMessage("Isso e um dialogFragment").setPositiveButton("OK", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                getActivity.finish();
            }
        }).setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {

            }
        });

        builderr.setTitle("Hello Mundo");
        AlertDialog dialog = builderr.create();

        return dialog;
    }
}

Segunda Activity:
package com.gif.popupsair;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;

public class Main2Activity extends AppCompatActivity {

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

    public void AbrirDialog(View view){
       Toast.makeText(getApplicationContext(), "Aperte o botao para voltar", Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onBackPressed()
    {
        MyDialog di = new MyDialog();

        di.show(getSupportFragmentManager(), "my_dialog_tag");
    }
}

LogCat:
E/AndroidRuntime: FATAL EXCEPTION: main
                  Process: com.gif.popupsair, PID: 1370
                  java.lang.NullPointerException: Attempt to invoke virtual method 'void android.app.Activity.finish()' on a null object reference
                      at com.gif.popupsair.MyDialog$2.onClick(MyDialog.java:24)
                      at android.support.v7.app.AlertController$ButtonHandler.handleMessage(AlertController.java:157)
                      at android.os.Handler.dispatchMessage(Handler.java:102)
                      at android.os.Looper.loop(Looper.java:135)
                      at android.app.ActivityThread.main(ActivityThread.java:5254)
                      at java.lang.reflect.Method.invoke(Native Method)
                      at java.lang.reflect.Method.invoke(Method.java:372)
                      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
                      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)

Nome da primeira Activity: MainActivity
Obrigado...
Answer: Para fechar uma activity e "voltar" para a anterior, basta chamar o método finish();
Feito isso na segunda activity, ele fechará a mesma e voltará para anterior, no caso a sua activity "pai" que chamou ela.
Exemplo Activity Um
public class ActivityUm extends AppCompatActivity {

    @Override
    public void onCreate(Bundle bundle){
        super.onCreate(bundle);
        setContentView(R.layout.activity_um);

        Intent intent = new Intent(ActivityUm.this, ActivityDois.class);
        startActivity(intent); //Abre a segunda activity
    }
}

Activity Dois
public class ActivityDois extends AppCompatActivity {

    Button botao;

    @Override
    public void onCreate(Bundle bundle){
        super.onCreate(bundle);
        setContentView(R.layout.activity_dois);

        botao = (Button)findViewById(R.id.botao);
        botao.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View v){
                finish(); // Finaliza essa activity e volta para anterior
            }
        });
    }
}

Lembrando que ao pressionar o botão "voltar" do celular, já é chamado o método onDestroy() que tem por função "destruir" a activity, portanto ao entrar na segunda tela e pressionar o botão voltar do celular, ele fará a função do método finish() que associamos ao clique de um botão na tela.
Portanto neste caso, você pode remover o método onBackPressed(), que ele realizará a função nativa de voltar e destruir essa activity.
Comment: Então amigo.... criei um popup que aparce quando clicar no botão do voltar do celular e nisso me da a opção de  **ok** e **cancel**... na class no `setPostive` que seria o "OK" coloquei a função `onDestroy();` e não está indo, por que?
Comment: @Nathan, na classe *MyDialog* e no *onClick()* do botao OK chame o método `getActivity.finish();`.
Comment: @Luídne o meu funcionou dessa forma - `getActivity().finish();`... Obrigado pela ajuda.

Método de fechar uma Activity


Why must there be two points of a space filling curve $f: N \times N \rightarrow \{ 1,...,N^2 \}$ with distance $N+1$?

Question: Question
Why is the following statement true?
Given a $N \times N$ grid and any space-filling curve $f: N \times N \rightarrow \{ 1,...,N^2 \}$ that covers the entire grid, the cells on the grid which are assigned the numbers $1$ and $N^2$ (the "first" and "last" numbers) have $L_\infty$-distance of at most $N-1$, and therefore there must exist two cells which are direct neighbors on the grid but have a distance of at least $N+1$ on the curve.
Background
The previous statement is my slightly paraphrased version of a short assertion/statement made in a paper about space-filling curves I am studying.  The first part to me is clear:

The cells assigned numbers $1$ and $N^2$ are at a distance of at most $N-1$ on the grid.

(Using Chebyshev/chessboard distance this is the farthest away two cells can be on the grid).  But I do not see how it implies the second statement:

There always exist two directly neighboring cells whose numbers differ by at least $N+1$.

The statement is worded such that the conclusion is obvious, but I must admit it is not obvious to me.  The statement in question is in the very last paragraph of page labeled 8 in the full PDF available here. I will also note that for the first part of the statement the author uses the language "there is a path of length at most $N-1$" which seems strange to me and I cannot think of another way to interpret it besides the one I have stated.
Answer: Look at any simple path from the cell numbered $1$ to the cell numbered $N^2$, of length $\leq N$ (i.e., including $\leq N$ distinct cells), where the length of the path comes from the grid distance between the two points.You have at most $N-1$ "jumps" between adjacent cells on that path: if each jump has curve distance less than $N+1$, then the total curve distance $d$ is less than $(N-1)(N+1) = N^2-1$, so that you cannot go from $1$ to $N^2 > 1+ d$ (the curve value of the first and last point of the path).
I.e., at a very high-level, it can be seen as an averaging argument: if you have no more than $N-1$ jumps of length less than $N+1$, you cannot overall go from $1$ to $N^2$.
Comment: Well, it seems so simple when you put it like that.  Thanks.  :-)


Sharing Windows 7 NLB in home network

Question: I have read this question and have been googling trying to do what is in the title, with no luck. I´ve tried bridging connections, ICS, etc.
I have two separate internet connections from two different companies at my disposal. I have got the NLB in Windows 7 working using these two connections. The computer I am using for this task has two NICs and one wifi card. I´ve used the wifi card and a NIC for the NLB and works well, as well as using the two NICS for the NLB.
But now I need to share this NLB connection in my home network. Is this possible to do using only Windows 7 or what can the experts recommend?
Alternately, should I be looking at another OS?
Thank you all for your help
Answer: You should get an appliance like a router or L3 switch that can load-balance connections across multiple uplinks. Trying to do this on Windows 7 is not a great idea. It wasn't designed to act as a router, nevermind one that load balances multiple WAN uplinks.
Comment: You can probably do this with an OS that's more suited for work as a router, like one of the BSDs or Linux. Over the long-haul, the electricity required to run a full-blown desktop will more than overcome buying a dedicated piece of hardware, though.
Comment: Thanks for your thoughts MDMarra, however without getting into additional hardware, is there any 3rd party software that could help me achieve this?
Comment: Just want to make sure it can´t be done with Windows 7?, since the Desktop I have already has it installed. Then I will try Linux, any recommendations? And thanks again
Comment: This is a site for professionals. No professional is ever going to try and configure this in their environment using Windows 7. It's a desktop OS. It was never intended to do routing, the little functionality that is there was bolted on as an afterthought. If you want any kind of reliability (which is the cornerstone of being a professional) you'll use an OS that has this built-in, like one of the BSDs, or you'll buy a multi-uplink router than can aggregate or round-robin the connections.
Comment: @Andrew It can't be done with Win7 without 3rd party software. [pfSense](http://pfsense.org) can do this out of the box and it's pretty easy to configure (nice web interface).
Comment: Thank you for your input MDMarra, I understand that this shouldn´t be done on Windows 7, it was not designed for this, and so this is why I asked the community because I have not delved in this topic until now. @Chris S thank you, I will look into pfSense!

Sharing Windows 7 NLB in home network


Criptografia em Java com AES, como funciona?

Question: Já encontrei vários exemplos pelo Google, mas nenhum que explique direito como funciona uma criptografia em java com AES... Como funciona?
Em um exemplo da net, o cara cita que tem que usar uma chave, mas não explica o porque e nem para que serve;
ex:
public static final byte[] CHAVE = {85, 10, 0, -25, 68, 88, 46, 37, 107, 48, 10, -1, -37, -90, 70, -36};

Para que serve a chave?
Pode ser qualquer valor?
O que essa AES tem de diferente das outras?
Funciona no Android?
Edit:
Depois de uma conversa nos comentários, entendi que tenho que usar uma chave estática, pois a usarei num game, somente para guardar um valor usando shared pref. do Android. Este valor é o maior rank do player!
Mas ainda cabe minha pergunta, pode ser qualquer valor? Entendi nada desse exemplo (a chave que postei)...
Comment: Você nunca vai impedir um hacker desocupado de mexer no seu APK. Mas como se trata de um jogo e não de uma aplicação bancária ou militar, acho tranquilo deixar a chave no código. Espero que alguém possa lhe dar uma resposta adequada e com exemplos aqui (eu mesmo sou um zero a esquerda com Java...)
Comment: O AES funciona da mesma forma independente de plataforma, sistema operacional ou qualquer tipo de tecnologia que se utilize, já que se trata de um conjunto de operações matemáticas. É um algoritmo. Você pode encontrar [todo o blá-blá-blá científico na wiki](http://pt.wikipedia.org/wiki/Advanced_Encryption_Standard) (aviso: a menos que você tenha tesão por essas coisas, é muito *booooooooring*).
Comment: Outra coisa: a chave serve para garantir que somente alguém com a chave correta (a mesma da encriptação para algoritmos simétricos, ou a outra chave do par no caso de algoritmos assimétricos) possa decriptar a mensagem. Caso contrário não é criptografia, pois se não houver chave qualquer um pode decifrar suas mensagens. Se alguém quiser desenvolver essas ideias numa resposta mais completa, ganha meu +1.
Comment: A chave é um **conjunto de bytes** que é usado para encriptar a informação que você precisa esconder - por esse motivo, geralmente se trabalha com *Arrays* de bytes (é assim em .NET e Java, pelo menos). O resultado de uma encriptação é um conjunto de bytes que não faz o menor sentido para nada nem ninguém até que seja decriptado. No caso do AES, esse conjunto só pode ser decriptado com a mesma chave que foi usada na encriptação. A sua segurança depende dessa chave ser secreta. Pense em informação encriptada como ouro dentro de um cofre, e a chave como a combinação que abre o cofre ;)
Comment: vi que tem como gerar uma chave, tornando a aplicação mais segura, mas no meu caso, creio eu que isso é inviável, eu preciso gravar uma informação criptografada num arquivo gerado pelo shared pref do Android, creio então que a chave teria que ser estática! Mas como funciona esta chave? Pelo exemplo que citei... pode ser qualquer valor?
Comment: Vamos ver a coisa de outro ângulo: você encripta informação pra manter ela secreta. Se você deixar a chave junto do arquivo encriptado, você não está escondendo nada, ao menos não no aparelho Android onde a chave vai ficar. Talvez você queira fazer algo mais simples do que criptografia? Se você incluir seu objetivo final na pergunta, talvez alguém possa sugerir outros meios de alcançá-lo.
Comment: eu pensei muito e creio que a solução seja esta, pois é para um game que já fiz, mas ele tem uma pequena falha... O rank (somente o best) é gravado com shared pref. Uma pessoa com acesso root pode facilmente alterar este arquivo, aumentando seu rank, eu uso este arquivo somente para gravar o rank e retornar este dado ao iniciar a tela de gameover... No caso da criptografia eu geraria uma chave estática, mas ela não ficaria armazenada no arquivo, somente o valor do rank encriptado ficaria!
Comment: Também não adianta usar SQLite, daria no mesmo, eu somente armazeno um valor... O problema é alguém alterar este valor, eu sei que tem hackers que decompilam o APK e conseguem ler mesmo eu usando proguard, mas eu queria pelo menos impedir os noobs e leigos de alterar o rank
Answer: As chaves criptográficas são o que definem a saída do algoritmo de criptografia. Elas são definidas em bits. Como na maioria das linguagens de programação a menor unidade possível é o byte, elas são representadas por bytes. Um byte equivale a oito bits, então uma chave de 128 bits terá 16 bytes.
Você não deve escolher a chave, nem mesmo deve buscar uma chave na web. Você deve usar um gerador seguro de chaves criptográficas, que vai gerar um chave aleatória e vai garantir que chave tenha uma entropia alta.
Em Java, uma forma de gerar é essa:
KeyGenerator keyGen = KeyGenerator.getInstance("AES");
keyGen.init(256); // Tamanho da chave como exemplo.
SecretKey secretKey = keyGen.generateKey();

Sua outra questão, conforme levantada nos comentários, diz respeito à segurança de jogos em dispositivos móveis. Essa é uma questão complexa, que envolve diferentes fatores e depende da tecnologia utilizada. Leve em conta que é muito difícil criar um jogo completamente seguro. A maioria dos jogos mais populares nas lojas de aplicativos possui falhas de segurança.


Error indicator on role in cloud project

Question: I recently updated a client project to use Azure SDK 2.1 from 1.8. (Storage Client was updated a while ago). This was done on a feature branch.
During this process one of the roles in the cloud project started showing an error indicator.

Since this time, I have abandoned that feature branch. My project is back on the 1.8 SDK (October 2012 according to the Application tab). But the error indicator is still there. Other team members do not see this error. I do not see an error described anywhere.
How do I clear this error?
Answer: I did not notice that the web project associated with this role had been unloaded. After reloading, the error indicator goes away. doh!
This did not show up when switching branches since loaded/unloaded is an .suo setting that is excluded from source control


Differential equation inequality help

Question:
Let $x$ be the solution to the following differential equation :
  $$x'(t)=\sin(t^2x)\>,\>x(0)=0.1$$
  Show that
$(a)\quad \left|x(t)\right|\le0.1+t\quad\forall t>0$
$(b)\quad \left|x(t)\right|\le0.1e^\frac{t^3}{3}\quad\forall t>0$

$(a)$ I need help in verifying my solution. Using the formula :
$$\text{For the IVP}:x'(t)=f(t,x)\>,\>x(t_0)=x_0\\x(t)=x_0+\int_{t_0}^{t}f(s,x(s))\,ds$$
We have
\begin{align}
\left|x(t)\right|&=\left|0.1+\int_{0}^{t}\sin(s^2x(s))\,ds\right|\\\\
&\le 0.1+\int_{0}^{t}\left|\sin(s^2x(s))\right|\,ds\\\\
&\le 0.1+\int_{0}^{t}1\,ds\\\\
&=0.1+t\quad\forall t>0
\end{align}
Another doubt is that in the solution provided, there is this step :
$$\text{Note that }\left|\sin(t^2x_1)-\sin(t^2x_2)\right|\le t^2\left|x_1-x_2\right|\quad\forall t,x_1,x_2\in\mathbb{R}$$
How is it relevant in showing the inequality?
$(b)$
\begin{align}
\left|x(t)\right|&=\left|0.1+\int_{0}^{t}\sin(s^2x(s))\,ds\right|\\\\
&\le 0.1+\int_{0}^{t}\left|\sin(s^2x(s))\right|\,ds\\\\
&\le 0.1+\int_{0}^{t}\left|s^2x(s)\right|\,ds\\\\
\end{align}
Using Gronwall's inequality, we have
\begin{align}
\left|x(t)\right|&\le0.1+\int_{0}^{t}\left|s^2x(s)\right|\,ds\\\\
&\le 0.1+\int_{0}^{t}0.1s^2e^{\left|\int_{s}^{t}z^2\,dz\right|}\,ds\\\\
&\le 0.1+\int_{0}^{t}0.1s^2e^{\int_{s}^{t}z^2dz}\,ds\\\\
&\le 0.1e^{\int_{0}^{t}z^2\,dz}\\\\
&= 0.1e^\frac{t^3}{3}\quad\forall t>0
\end{align}
Answer: Using Gronwall inequality, since $\left|x(t)\right|\le0.1+\int_{0}^{t}\left|s^2x(s)\right|\,ds$, we have
$$
|x(t)|\le 0.1\exp\left(\int_0^ts^2\right)=0.1\exp\left(\frac{t^3}{3}\right)
$$

Differential equation inequality help


To compare two KL-divergence scores, does the prior model have to be the same for both?

Question: The KL-divergence compares a theoretical model $p$'s distribution with the empirical model $q$'s distribution, giving a score of $0$ if they, or their information contents, are identical.
Say we have two KL-divergences for two distinct models (that have the same units and context), therefore two pairs (4) distributions

If the first score $KLD_1=0.3$ tells us how far off model 1 ($p_1$) is in reality from theoretical model 1 ($q_1$),
and the second score $KLD_2=0.4$ quantifies how far off model 2 is in reality ($p_2$) from theoretical model 2 ($q_2$),

can I compare the values of $KLD_1$ and $KLD_2$ directly and conclude "model 1 outperformed model 2 because its score was lower, implying less divergence from its own theoretical prior" even though the scores were respectively measured based on two different models/priors? Or are two KLD scores only comparable if based on the same underlying theoretical model, i.e. $(p_1 || \mathbf{q_1})$ vs $(p_2 || \mathbf{q_1})$?
The question more abstractly,

KLD(red apples || green apples) vs KLD(red grapes ||  green grapes), or
KLD(red apples || mangos) vs KLD(red grapes || mangos)?
Answer: Yes, that is possible but chances are it is not the kind of performance you had in mind originally. Essentially, you are saying using model 1's predicted distribution to encode information about the "true" distribution 1 is more efficient than using model 2's predicted distribution to encode information about the "true" distribution 2.
This statement makes no claim about the predictive ability of either model. A model that predicts an ideal coin flip with odds of 50:50 will be right about as often as it is wrong and will have KLD = 0. Contrast this with a model that predicts that I will always eat a red apple that I bought. It will be right more often than it will be wrong (I do eat most of the apples that I buy), but sometimes I give the apple to my girlfriend instead, so the model doesn't match the "true" distribution and hence KLD > 0. Which of the two models makes better predictions?
Additionally, the models predict different things, so there is no reason to prefer one over the other; we can happily use both in tandem.


Question about the identity of $2^{2^n}$

Question: Is this identity true: $2^{2^n}= 4^n$?
I believe this is true as far as I know.
Sorry this is the only place to ask.
Is there another identity for $2^{2^n}$ which I can simplify to?
Comment: The ordinary meaning of $2^{2^n}$ is $2^{(2^n)}$, in which case the equality fails.
Comment: $2^{2^n}=2^{(2^n)}=4^{(2^{n-1})}=4^{2^{n-1}}$.
Comment: But isn't 2^(2^n) = (2^2)^n? Is there another identity for $2^{2^n}$?
Answer: No.  In standard usage, $2^{2^n}$ means $2^{(2^n)}$, not $(2^2)^n$.
Notice that $(a^b)^c$ is equal to $a^{bc}$, whereas $a^{(b^c)}$ cannot be similarly simplified.
Answer: Consider $n = 0$. The equation would not work.
Comment: but it seems to hold for n >0 though.
Comment: @tony1 $2^{2^3} = 256$, $4^3 = 64$
Comment: @tony1 This works for $n=1,2$ and nothing else.
Answer: Hint: What happens when $n = 0$?
Advice:
Also, before asking simple questions like these, it is a good idea to try out a few values.
Answer: A compiler — i.e., a computer program that translates a program written in a high-level language into a machine-level language — treats a^b^c as a^(b^c) rather than as (a^b)^c, (as the OP speculated).


Induced bilinear form on exterior powers - Towards a global Hodge Star Operator

Question: In all constructions of the hodge star operator I've seen so far there was a part where an inner product on the exterior power of the tangent space was defined by the ungodly local formula:
$$\langle v_1 \wedge \cdots \wedge v_k , w_1 \wedge \cdots \wedge w_k \rangle = det(\langle v_i,w_j \rangle)$$
Although i've been able to verify that it is in fact an inner product I have a terrible aversion to such ad hoc constructions. Therefore i was led to this:
Given a projective (hence locally free) $R$-module $M$ and a nondegenrate bilinear form $g: M \times M \to R$, i.e. one that gives an isomorphism:
$$\varphi: M \to M^* , \varphi: m \to g(-,m)$$
By the non degeneracy, $g$ extends naturally to $M^*$ by: $g(g(-,m_1),g(-,m_2))=g(m_1,m_2)$.
What's the canonical way to extend $g$ to the exterior powers $\bigwedge^k M^*$?
Comment: I don't think it's either local or ungodly. This is just what you get, I believe, when you declare that the wedge products of an orthonormal basis for $V$ will give an orthonormal basis for $\bigwedge^k V$.
Comment: @TedShifrin Wow! Why have i never seen this charactrization. That's great, thanks!
Answer: You need that $M$ is finitely presented in addition to projective in order for duality to work nicely. The problem reduces to describing a natural nondegenerate pairing
$$\wedge^k M \times \wedge^k M^{\ast} \to 1$$
where $1$ denotes the unit module $R$. Equipped with such a pairing, any isomorphism $M \cong M^{\ast}$ gives an isomorphism $\wedge^k M \cong \wedge^k M^{\ast}$, and we can apply the natural isomorphism $\wedge^k M^{\ast} \cong (\wedge^k M)^{\ast}$ coming from the above nondegenerate pairing.
In fact more generally there is a natural pairing
$$\wedge^n M \times \wedge^k M^{\ast} \to \wedge^{n-k} M$$
as follows: by the universal property of the exterior algebra, derivations $\wedge^{\bullet} M \to \wedge^{\bullet} M$ are freely determined by what they do to the generators $M$. In particular, elements of $M^{\ast}$ are naturally in bijection with derivations of degree $-1$, and again by the universal property of the exterior algebra, this induces an action of $\wedge^{\bullet} M^{\ast}$ on $\wedge^{\bullet} M$ where $\wedge^k M^{\ast}$ acts by "differential operators" of degree $-k$.
This description has the disadvantage that it doesn't treat $M$ and $M^{\ast}$ symmetrically. There are other things you can say but to my mind they're all a bit unsatisfying for other reasons. One attempt to write down this map ends up writing down $k!$ times this map for reasons I don't really understand. And in positive characteristic there isn't an analogous natural isomorphism $S^k M^{\ast} \cong (S^k M)^{\ast}$ for symmetric powers. There's something funny going on involving invariants vs. coinvariants for the action of $S_n$ on $M^{\otimes n}$ and I haven't sorted it out well in my head.
Comment: (Note that if we assume $P$ projective, it is enough to ask it be finitely generated for it to be finitely presented.)
Comment: Thanks for your answer. I've just asked an extended question about the same stuff http://mathoverflow.net/questions/223825/a-systemtatic-canonical-construction-of-the-hodge-star-operator


Get the alarm time which previously added to the AlarmManager

Question: I'm using the AlarmManager class to notify the user everyday in specific time  (user will choose the time from time picker)
every thing worked great al7mdllah ^^
But I want to get that time from the alarmManger and display it in the application to get a better UX
is there any way to get the alarm time?
Here's my code
public void witer_reminder(View view)
{
    am = (AlarmManager) getSystemService(Context.ALARM_SERVICE);

    Intent intent = new Intent(this, Witer_Notification.class);
    PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0,
        intent, PendingIntent.FLAG_CANCEL_CURRENT);

    Calendar cal = Calendar.getInstance();
    Calendar calSet = (Calendar) cal.clone();

    calSet.set(Calendar.HOUR_OF_DAY, picker.getCurrentHour());
    calSet.set(Calendar.MINUTE,picker.getCurrentMinute());
    calSet.set(Calendar.SECOND, 0);
    calSet.set(Calendar.MILLISECOND, 0);

     if(calSet.compareTo(cal) <= 0){
            //Today Set time passed, count to tomorrow
            calSet.add(Calendar.DATE, 1);
           }

      am.setRepeating(AlarmManager.RTC_WAKEUP, calSet.getTimeInMillis(),
              24*60*60*1000, pendingIntent);

}

Answer:
But I want to get that time from the alarmManger and display it in the application to get a better UX is there any way to get the alarm time?

Save it yourself somewhere persistent (file, database, SharedPreferences) when you set up the event. AlarmManager is write-only; you cannot retrieve information about scheduled events from it.


Find the Laurent series expansion in powers of z

Question: Find the Laurent series expansion in powers of $z$ of
$$f(z)=\frac{e^{2z}} {z}$$
valid in the region $|z|>$0.
Any help appriciated. Thanks
Comment: Did you mean $\lvert z\rvert > 1$? The function has only one singularity in $\mathbb{C}$, at $1$.
Comment: Sorry i mean z, not z-1 so The singularity is at 0
Answer: The Maclaurin series of $e^{2z}$ is
$$
1 + (2z) + \frac{(2z)^2}{2!} + \cdots = \sum_{k=0}^\infty \frac{2^k z^k}{k!}
$$
so the Laurent series you're looking for is simply $1/z$ times this, i.e.:
$$
\sum_{k=0}^\infty \frac{2^k z^{k-1}}{k!} =
\sum_{k=-1}^\infty \frac{2^{k+1} z^{k}}{(k+1)!}.
$$
The Maclaurin series of $e^{2z}$ converges on all of $\mathbb{C}$, since $e^{2z}$ is entire. Hence the Laurent series above converges for $z \neq 0$.


Problemas ao resgatar dados de um arquivo json

Question: Estou tentando carregar dados de um arquivo json em uma tabela html.
Estou tentando resgatar o json desta forma:
<code>function getJson(){
    $.getJSON('dados/livros.json', function(data){
        console.log(data);
    });
}
</code>
Exemplo do json que estou tentando resgatar:
<code>{
"livros": [
        {
            "id":1,
            "imagem":"images/JavaScriptEJquery.jpg",
            "nome":"Javascript e Jquery - Desenvolvimento de Interfaces Web Interativas",
            "autor":"JON DUCKETT",
            "genero":"Didatico",
            "anoEdicao":"2016",
            "editora":"AltaBooks",
            "estado":"Disponivel"
        },
        {
            "id":2,
            "imagem":"images/ScrumAArteDeFazerODobroNaMetadeDoTempo.jpg",
            "nome":"Scrum - A Arte de Fazer o Trabalho na Metade do Tempo",
            "autor":"JEFF SUTHERLAND",
            "genero":"Didatico",
            "anoEdicao":"2016",
            "editora":"LEYA",
            "estado":"Indisponivel"
        }
    ]
}
</code>
Localização do arquivo json:

Error:

jquery-3.3.1.js:9600 Access to XMLHttpRequest at
  'file:///D:/Catalogo%20de%20Livros/dados/livros.json' from origin
  'null' has been blocked by CORS policy: Cross origin requests are only
  supported for protocol schemes: http, data, chrome, chrome-extension,
  https.

Já estou a algum tempo pesquisando mas ainda não consegui solucionar este problema, nunca tinha me deparado com este erro antes. Qual é a causa este error ? como resolver ?
Comment: Levi, acho que o seu problema é o mesmo que esse, dá uma olhada: https://stackoverflow.com/questions/27742070/angularjs-error-cross-origin-requests-are-only-supported-for-protocol-schemes
Answer: Se você tiver usando o Chrome, esse é um bug conhecido do próprio Chrome:
Link: https://bugs.chromium.org/p/chromium/issues/detail?id=40787&q=ajax%20local&colspec=ID%20Stars%20Pri%20Area%20Feature%20Type%20Status%20Summary%20Modified%20Owner%20Mstone%20OS
Tente rodar no Firefox ou outro navegador, ou use um webserver, tipo http-server.
Link para um thread em inglês sobre isso: https://stackoverflow.com/questions/8533078/getjson-not-working-with-local-json-file
Answer: Testei a sua função e funcionou normalmente Levi, porém fiz uma chamada AJAX para que possa testar
<code>$.ajax({
            type: "GET",
            url: './dados/livros.json',
            dataType: 'json',
            success: function (jsonDadosRetorno) {
                console.log(jsonDadosRetorno);
            },
            error: function () {
            }
        });
</code>
Outra opção colocando o ./ no seu caminho relativo
<code>$.getJSON('./dados/livros.json', function(data){
console.log(data);
</code>


Problema com return false em JavaScript

Question: Preciso desenvolver um menu acordeon e estou tendo problemas com o evento de clique. Meu script:
$(document).ready(function(){
    $('.dropdown').click(
        function(){
            $(this).find("ul").slideToggle();
            return false;
        }
    );
});

O SlideToggle chama uma lista não ordenada que fica dentro de um elemento LI. Funciona perfeitamente, mas os links da lista param de redirecionar. Quando clico em algum deles, o slideToggle() simplesmente se desfaz, o menu retorna ao estado original e não sou redirecionado. Onde estou errando?
Comment: @PedroVinícius, ok, irei dar uma olhada
Comment: Poderia incluir um demo da estrutura do menu? Acredito que possa ser problema com relação a propagação do evento de `click`.
Comment: Insira isso como parte do HTML da sua pergunta
Comment: @PedroVinícius, poderia incluir também o elemento com classe `dropdown`? Acho que ajuda a descobrir o problema :)
Comment: @Wakim, o código do menu é gerado automaticamente pelo WP. Mas se você puder dar uma olhada no código-fonte no site, segue o link:

http://conscienciaestelar.filosofiaesoterica.com.br

É o menu da esquerda que está com esse problema :/
Answer: O erro ocorre justamente pelo return false;, que não deixa que o evento iniciado no link do submenu termine de executar.
Inclua o seguinte código logo após o registro do handler para o click no dropdown:
$('.sub-menu a').click(function(e) { e.stopPropagation(); });

Ao dar stopPropagation no clique do link, você irá previnir que o evento propague para cima, e ai não bloqueará o evento de navegação.
E ao clicar sobre o link, o usuário será redirecionado para a página.
Answer: Em jquery existe uma função chamada .preventDefault() que "nega" o evento original de uma tag HTML, desta forma você pode usa-lo para que seus links não tenham seu efeito original assim que forem clicados
$(document).ready(function(){
    $('.dropdown').click(
        function(event){
            event.preventDefault();
            $(this).find("ul").slideToggle();
        }
    );
});

Comment: Obrigado por responder amigo. Mas já tentei com essa função também. O efeito é o mesmo :-/
Answer: Vamos imaginar que seu HTML esteja assim:

        Abrir drop down A

Link A 1

Link A 2

        Abrir drop down B

Link B 1

Link B 2

E seu script esta aplicando o click ao elemento .dropdown quando o correto é aplicar o clique ao link filho direto do elemento .dropdown.
Então seu jQuery.click deve ficar assim:
$(document).ready(function(){
    $('.dropdown >a').click(function(){
       $(this).siblings("ul").slideToggle();
       return false;
    });
});

Problema com return false em JavaScript


Equations involving logarithms without calculator

Question: I am doing a course where we are not allowed to use a calculator and I find equations with logarithms rather tricky. Here's an example question:
Solve the following equation for $x \in \mathbb{R}$:
$\log_3(1 + 10x) = 4$
Apologies if I am not adhering to the community guidelines with this "no clue" type of question but I am unable to find any helpful sources for this.
Comment: Use the formula :
$$\log_3 (x) = y \Rightarrow x = 3^y$$
Comment: Hint : $g(x)=3^x$ is the inverse of $f(x)=\log_3(x)$
Answer: Let's solve a similar problem: $$\log_5(1+3x)=2.$$
In order to get rid of the $\log_5$ on the LHS, we apply $\exp_5$ on both sides:
$$\exp_5(\log_5(1+3x))=\exp_5(2).$$
Since $\exp_5$ and $\log_5$ are inverse functions of one another, they cancel each other out on the LHS. Further, on the right, we obtain $\exp_5(2)=5^2=25$. We're left with $$1+3x=25.$$ Solving for $x$ yields $x=8$.
Important: Logarithmic functions only allow for positive arguments. In this case, we must thus have that $1+3x>0$, that is, $x>\frac 13$. Our solution $x=8$ satisfies this condition. If it didn't, the equation would have been impossible, i.e., the set of solutions would have been empty.
Now it's your turn.