Variance of total sales $Z_n$

Question: At a gas station, the number of customers arriving during a certain hour is a random variable $N$ with distribution
$$P(N = n) = \frac{e^{-30}30^n}{n!}, n=0,1,...$$
Compute the expected value and variance of the total sales $Z_n$ during that hour if the expected value and variance of a single sale are 3.67 and 2.24 respectively.
I found the expected value to be the expected value of $N$ times the expected value of a single sale. $E(N)$ is
$$\sum_{n=0}^{\infty}\frac{ne^{-30}30^n}{n!} = e^{-30}30\sum_{n=1}^{\infty}\frac{30^{n-1}}{(n-1)!} = 30$$
So the expected value of the total sales $Z_n$ is 30(3.67) = 110.1.  This is correct.
My trouble is with the variance. It is stated that the variance of $Z_n$ is $nb^2$, where $b$ is the variance of $Y$. I thought that $n=30$ and $b=2.24$, but this would yield $150.5$. The correct answer should be $470.5$.
I know how to go about finding the variance of the number of customers (I got 30), but I don't know if that's needed here.
EDIT:
I found $Var(N)$ (for number of customers) by using a trick from the book where you first find $E(N(N-1))$ then add $E(N)$ to get $E(N^2)$:
$$E(N(N-1)) = \sum_{n=0}^\infty \frac{n(n-1)e^{-30}30^n}{n!} = 30^2e^{-30}\sum_{n=2}^\infty \frac{30^{n-2}}{(n-2)!} = 900$$
Then $E(N^2) = 900 + 30 = 930$.
Finally $Var(N) = 930 - 30^2 = 30$.
Answer: If the single sales are each $X_i$, then the total sales are $Z=\sum_{i=1}^N X_i$.
Note $E[N] = \operatorname{Var}[N] = 30$ (show this!).
The expected value of total sales is $$E[Z]=E[N]E[X] = (30)(3.67)=110.1$$ and the variance of total sales is
$$\operatorname{Var}[Z]=E[N]\operatorname{Var}[X] + \operatorname{Var}[N](E[X])^2$$
$$=(30)(2.24) + (30)(3.67)^2=471.267$$

The variable $Z$ is a random sum of random variables. That is, the number $N$ of terms is random, and each of the terms $X_i$ is identically distributed. Presumably, the number of terms and each of the terms all are independent.
Comment: How did you obtain the formula for Var(Z)?
Comment: It's not too hard to derive. See [this link](http://www.math.unl.edu/~sdunbar1/ProbabilityTheory/Lessons/Conditionals/RandomSums/randsum.shtml) for an easy-to-understand explanation. I'm too lazy to write it up in MathJax ;)

Variance of total sales $Z_n$


TortoiseSVN and local source code term

Question: I'm learning to use TortoiseSVN. When I get code from an existing source repository, it is placed in a directory on my local machine. That directory is then tied to SVN somehow. My question is, what is this link called? Is it called a link, or a mapping, or something else entirely. I'm trying to learn the terminology so I can find answers effectively.
Currently, I'm trying to communicate that a local folder needs to stop being connected to SVN via TortoiseSVN. I know that saying "Removing a folder from SVN" is incorrect, because that would imply deleting the folder in the source repository itself. Should I communicate to remove the mapping? Or what?
Thank you!
Answer:
a local folder needs to stop being connected to SVN via TortoiseSVN

Unversion Working Copy
Answer: There is not any hard and fast rule.Remove/Deleted is good.
This will help you: http://tortoisesvn.net/docs/nightly/TortoiseSVN_en/tsvn-glossary.html

TortoiseSVN and local source code term


How to add an element in a menu vertical

Question: In fact, I use Bootstrap 5 for the create of a menu vertical.

My problem is that I would like to add a black background to the top of the left menu.

I don't understand where I should create the block in Bootstrap or CSS, please

<!DOCTYPE html>

      <title>HTML CSS JS</title>
      <link href="https://firstname.lastname@example.com/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">

            <svg class="bi me-2" width="40" height="32"> </svg>
            BBBootstrap

                Home

                Dashboard

                My Orders

                Settings

                Bookmarks

Answer: You can add parent div to both the menus and add class d-flex to parent
class
please check this :

.navbar {
  height: 60px;
  width: 100%;
  background: #000;
}
<!DOCTYPE html>

  <title>HTML CSS JS</title>
  <link href="https://firstname.lastname@example.com/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">

        <svg class="bi me-2" width="40" height="32"> </svg>
        BBBootstrap

           Home

           Dashboard

           My Orders

           Settings

           Bookmarks

      Navbar


Retornar uma função

Question: Criei uma função teste() que deve ser preenchida com o While e retornar os dados. Por que quando chamo minha função teste() dentro da função PageLoad_Arquivo() a mesma não carrega?
function teste(){

    $resultadowhile = "

Cod.	<Data	Última Atualização	Unidade	Departamento	Arquivo	Status
";
    while($row = mysql_fetch_array($result)){
        $resultadowhile .= "
" .
            's' . $row['id_arquivo'] . '	' .
            '' . formatarDataBRASIL($row['txt_data']) . '	' .
            '' . $row['txt_unidade'] . '	' .
            '' . $row['txt_departamento'] . '	' .
            '' . $row['txt_arquivo'] . '	' .
            '' . $row['flag_status'] . '	' .
        "
";
    }
    $resultadowhile .= "
";

}

function PageLoad_Arquivo(){

    $result = mysql_query("
    select a.id_arquivo, a.txt_arquivo, a.txt_data, a.txt_caminho, d.id_departamento, d.txt_departamento, u.id_unidade, u.txt_unidade, a.flag_status from tb_arquivo a
    left join tb_departamento d on a.id_departamento = d.id_departamento
    left join tb_unidade u on a.id_unidade = u.id_unidade
    ORDER BY a.txt_data DESC
    ") or die(mysql_error());

    $relacao = "style='display:block'";
    $cadastro = "style='display:none'";
    $resultadowhile = "";

    if(mysql_num_rows($result) > 0){
        teste();
        renderForm('', '', '', '', '', '', '', '', $relacao, $cadastro, $resultadowhile);
    }else{
        $resultadowhile = "
Sem resultados.
";
        renderForm('', '', '', '', '', '', '', '', $relacao, $cadastro, $resultadowhile);
    }

}

Answer: O problema não é que sua função não rode. Ela apenas não faz nada a não ser montar a string da tabela e fim da história. Você precisa retornar a string para poder receber o valor.
function teste() {
    // ...
    return $resultadowhile;
}

// ...
if(mysql_num_rows($result) > 0) {
    $resultadowhile = teste();

EDIT
COmplementando, o mesmo vale para a sua variável $result que é utilizada na função teste. Esta variável não existe. Você precisa passá-la como parâmetro.
function teste($result) {
    // ...
}

// ...
if(mysql_num_rows($result) > 0) {
    $resultadowhile = teste($result);

Comment: Tks... Estava tentando fazer como vc indicou e estava dando erro... na verdade eu estava fazendo diferente da sua recomendação, agora funfou.
Answer: Ela carrega sim, mas você está achando que uma função entra dentro de outra como um include, e não é assim. Uma variável não comunica de uma função para outra. Você tem tem que passar o valor dela para a variável ou retornar o valor para quem chamou. Assim:
function teste($resultadowhile) {
    $resultadowhile .= "

Cod.	<Data	Última Atualização	Unidade	Departamento	Arquivo	Status
";
    while($row = mysql_fetch_array($result)){
        $resultadowhile .= "
" .
            's' . $row['id_arquivo'] . '	' .
            '' . formatarDataBRASIL($row['txt_data']) . '	' .
            '' . $row['txt_unidade'] . '	' .
            '' . $row['txt_departamento'] . '	' .
            '' . $row['txt_arquivo'] . '	' .
            '' . $row['flag_status'] . '	' .
        "
";
    }
    $resultadowhile .= "
";
    return $resultadowhile;
}

function PageLoad_Arquivo() {
    $result = mysql_query("
    select a.id_arquivo, a.txt_arquivo, a.txt_data, a.txt_caminho, d.id_departamento, d.txt_departamento, u.id_unidade, u.txt_unidade, a.flag_status from tb_arquivo a
    left join tb_departamento d on a.id_departamento = d.id_departamento
    left join tb_unidade u on a.id_unidade = u.id_unidade
    ORDER BY a.txt_data DESC
    ") or die(mysql_error());
    $relacao = "style='display:block'";
    $cadastro = "style='display:none'";
    $resultadowhile = "";
    if(mysql_num_rows($result) > 0){
        $resultadowhile = teste($resultadowhile);
        renderForm('', '', '', '', '', '', '', '', $relacao, $cadastro, $resultadowhile);
    }else{
        $resultadowhile = "
Sem resultados.
";
        renderForm('', '', '', '', '', '', '', '', $relacao, $cadastro, $resultadowhile);
    }
}

Coloquei no GitHub para referência futura.
Note que apesar de nas duas funções existir uma variável com nome $resultadowhile elas são variáveis completamente diferentes e que por acaso tem o mesmo valor. Só porque o valor da variável existente na função PageLoad_Arquivo() foi passada para a variável na função teste(). Você pode passar qualquer valor de qualquer variável como nome que for como parâmetro. Pode passar um literal. Claro que idealmente neste caso deve ser algo do tipo string, caso contrário poderá não ter o resultado desejado.
Chamando teste($resultadowhile) você está passando o valor desta variável como argumento.
Declarando a função como function teste($resultadowhile) você está recendo uma parâmetro chamado $resultadowhile. Este parâmetro é uma variável local da função teste(), ela só existe dentro desta função.
Então para que você possa passar o valor manipulado da variável para a função que a chamou você precisa retorná-la através do comando return conforme visto na última linha da função modificada que eu postei.
Este retorno precisa ser guardado em uma variável e pode ser a mesma $resultadowhile que foi passada como argumento.
Claro que é possível não passar argumento algum se for do seu desejo mas a função ficaria menos flexível e complicaria usar em outras situações que você já tivesse um texto HTML inicial. E o uso da função é justamente poder reusar em diversas situações diferentes. Então você poderia retirar o parâmetro e apenas retornar o valor da variável se não quiser esta flexibilidade conforme mostrado da resposta do Oeslei.
Existe uma outra forma de passar o valor da variável através de referências mas neste caso não é necessário e é um tópico um pouco avançado.

Retornar uma função


Football - Two injured players from the same team

Question: Watching the premier league game of Liverpool vs Chelsea today, there was a point during the game that Chelsea had two players injured at the same time.
The commentator mentioned that if there was two players from the same team injured they didn't need to leave the pitch before returning. But then the referee made them do so. What is the rule that governs this instance? Seems unfair that the game would restart with one team down to 9, albeit briefly.
Comment: If at all possible, supplementing your post with a clip where this occurred might help. I was watching this game as well, the players were [André Schürrle](http://en.wikipedia.org/wiki/Andr%C3%A9_Sch%C3%BCrrle) and [John Obi Mikel](http://en.wikipedia.org/wiki/John_Obi_Mikel). I do remember the commentator, [Lee Dixon](http://en.wikipedia.org/wiki/Lee_Dixon), touching on the fact that two people were down (*may I add, continuing to waste time as Chelsea had done all game*), but I don't remember him specifying that they didn't have to leave the field?
Answer: The referee will not require two players from the same team to leave the field if they collide and they need immediate attention (ie. are seriously injured).
p. 73 - 74 of the 2013/14 FIFA Laws of the Game (abridged for clarity):

The referee must adhere to the following procedure when dealing with injured
  players:
...

play is allowed to continue until the ball is out of play if a player is, in the
  opinion of the referee, only slightly injured
play is stopped if, in the opinion of the referee, a player is seriously injured

...

as soon as the referee has authorised the doctors to enter the field of play,
  the player must leave the field of play, either on a stretcher or on foot. If a
  player does not comply, he must be cautioned for unsporting behaviour
an injured player may only return to the field of play after the match has
  restarted

...
Exceptions to this ruling are to be made only when:

a goalkeeper is injured
a goalkeeper and an outfield player have collided and need immediate
  attention
players from the same team have collided and need immediate attention
a severe injury has occurred, e.g. swallowed tongue, concussion, broken leg
Answer: As far as I am aware they were made to leave the field because they were not injured in the same incident. For instance if the two players collided into each other then they would not be required to leave the field.


Binomial series

Question: I am stuck in a problem about binomial series and would be very happy if someone could help me how to move on with it...
I have to prove that $\sum_{v=k}^{\infty }\binom{v}{k}z^{v-k}=\frac{1}{(1-z)^{k+1}}$ for $k\geq 0$ and $z\in \mathbb{C}$ and  $\left | z \right |<1$.
Is this like the special case of binomial series $\frac{1}{(1-z)^{\beta +1}}=\sum_{k=0}^{\infty }\binom{k+\beta}{k}z^{k}$ (according to Wikipedia), where i need to substitute $x=-z$ in the usual formula $(1+x)^{\alpha }=\sum_{k=0}^{\infty }\binom{\alpha }{k}x^{k}$ ?
Thank you in advance!
Comment: $\sum_{v=k}^{\infty }{\binom{v}{k}z^{v-k}}=\sum_{u=0}^{\infty }{\binom{u+k}{k}z^u}$ where $u=v-k$. Do you see how to continue from here?
Comment: Your last expression is $\sum_{k=0}^\alpha$
Answer: Yes, replace $(z,\beta,k)$ in WP formula by $(z,k,v-k)$ in the formula you want to prove and use the identity ${v\choose v-k}={v\choose k}$.
Answer: If $f(z)=\sum_{n=1}^\infty a_kz^k$ for all $|z|<1$ then $f'(z)=\sum_{n=1}^\infty a_k(z^k)' \ \forall \ |z|<1$; see this.
Show that $\dfrac{1}{(k+1)(v-k-1)}\binom{v}{k}=\binom{v}{k+1}$ and use induction.

Binomial series


Does differentiability on an open set imply differentiability on a compact set?

Question: If I have a function $f(x) \in C^\infty$ for $x \in (-\epsilon,+\epsilon)$. Can I find a compact set in $(-\epsilon,+\epsilon)$ where $f(x)$ is also $\in C^\infty$? I need this information to imply that $f(x)$ is bounded in that compact set, so it takes it´s maximum/minimum.
Comment: You just need continuity. You don't need differentiability. Take the compact set $[-\varepsilon/2,\varepsilon/2]$.
Comment: @CameronWilliams So I can imply that $f(x)$ is continuous on $[-\epsilon/2,\epsilon/2]$ and therefore bounded?
Comment: Yep that's exactly right!
Comment: @CameronWilliams Thank you very much.
Comment: Feel free to answer your own question if you'd like :) That way it will not get bumped later for not having an answer. You can accept it two days later.
Comment: @CameronWilliams I tried:) Would you please take a look if it's correct/clear? And I just explained it, did not prove it.
Comment: Looks good! Great work.
Answer: So if a function $f(x)$ is continuous differentiable on an open set $(-\epsilon, \epsilon)$ then there exists an compact set such as $[-\epsilon/2,\epsilon/2]$ in which $f(x)$ is continuously bounded and takes its maximum.


Get width and height during animation state

Question: I'm just wondering if it is possible to get the width and height of an element during animation state where height and width are animated? I'm using CSS3 to accomplish the animation. and I want to get it every 10 millisecond?
<code>#animElement{
    -webkit-transition: width 1s, height 1s;
}
</code>
My javascript code is little bit wrong, could you take a look at it to? I'm testing to write the number i every 10 millisecond. I'm just testing this code for using it to get the width and height later.
<code>for(var i=0;i<1000;i++){
    (function(num){
        window.setTimeout(function(){$('#flyingSquare').html(num);}, 10);
    })(i);
}
</code>
It wirtes the number 1000 directly which is wrong. It should count to 100 instead.
Comment: You can't get realtime information on the element while it's being animated, only the end state. If you tell us more about your use case we might be able to find a workaround.
Answer: If you use JavaScript to do the animation you can more easily.
Comment: Do you know how to get the smooth animation then? It slows down when nearing end of animation state? 3:rd degree polynom?
Comment: Use Jquery for smooth animations with ease-in and ease-out.


Prove that the set of all numbers formed by finite sums of elements of $S$, is countable.

Question: $S$ = {$\sqrt[n]{a}$ : $n\in\mathbb{N}$ and $a\in \mathbb{Q}$}
Prove that the set of all numbers formed by finite
sums of elements of $S$, is countable. We know that $S$ is countable.
I am not sure how to approach this one and have been stuck for awhile now. I would appreciate any assistance. Thank you!
Answer: You could "cheat" and write the sums formally, i.e. do not consider $\sqrt{2}+\sqrt{3}$ to be the same number as $\sqrt{3}+\sqrt{2}$. That way what you are asking is "Is the collection of finite strings from an alphabet of countably infinite size also countably infinite?", which should follow from some basic theorems like, the union of countably many sets of countable size is countable.
Answer: For each $n,m\in\mathbb{N}$, we can see the sum $\sqrt[n]{a_1}+\dots+\sqrt[n]{a_m}$ (where $a_1,\dots,a_m\in\mathbb{Q}$) as a formal sum and it can be represented by the $m$-ary tuple $(a_{n1},...,a_{nm})$ (here $a_{ni}:=a_i$ for $0\leq i\leq m$). So, define the set $A_{nm}:=\{(a_{n1},\dots,a_{nm}):a_i\in\mathbb{Q},1\leq i\leq m\}$. Now is easy to see that each $A_{nm}$ is countable, the the set
$$
A_n=\bigcup_{m\in\mathbb{N}}A_{nm}
$$
Is countable for each $n\in\mathbb{N}$. In the same form, the set
$$
A=\bigcup_{n\in\mathbb{N}}A_n
$$
Is countable.
With this, define the bijection $F:A\rightarrow S$ as $F((a_{n1},\dots a_{nm}))= \sqrt[n]{a_1}+\dots+\sqrt[n]{a_m}$. So $|S|=|A|=\aleph_0$.


slide infinito com css e html

Question: Meu slide nao quer ficar transitando infinitamente:
<!DOCTYPE html>

<meta charset="utf-8" />

depois do 4 quero que volte pro 1 e continue...
Answer: Seu erro é apenas que vc escreveu essa propriedade errada
animation-interation-count: infinite;

Não é interation deveria ser iteration
Dessa forma: animation-iteration-count: infinite;
Importante: Como vc pode ver na documentação da Mozilla o valor inicial para o iteration-count é de 1, por isso a animação só acontece 1x, depois como o CSS não reconhece a propriedade que está escrito errado ela para depois de uma repetição. https://developer.mozilla.org/en-US/docs/Web/CSS/animation-iteration-count
Veja seu código funcionando com esse erro corrigido.

body {
 background: #000000;
}

* {
 margin: 0px;
 padding: 0px;
}

.galeria {
 margin: 200px auto;
 width: 480px;
 height: 270px;
 position: relative;
 overflow: hidden;
}

.foto {
 position: absolute;
 opacity: 0;
 animation-name: animacao;
 animation-duration: 20s;
 animation-iteration-count: infinite;
}

@keyframes animacao {

 25% {
  opacity: 1;
  transform: scale(1.1, 1.1);
 }

 50% {
  opacity: 0;
 }
}

.foto:nth-child(1) {}

.foto:nth-child(2) {
 animation-delay: 5s;
}

.foto:nth-child(3) {
 animation-delay: 10s;

}

.foto:nth-child(4) {
 animation-delay: 15s;

}

slide infinito com css e html


How to make a rule return all details of a fact using Prolog

Question: Using Prolog, I first created two facts called grade and food: The first fact is grade(X,Y) where X is the student (rob or matt) and Y is the grade level (freshman or sophomore). The second fact is food(X,Y) where X is the student (rob or matt) and Y is the food (pizza, burger, pasta, wrap).
I created a rule called preference(X,Y), where X is the student (rob or matt) and Y is the students' preference.
I want to enter preference(rob,X). in the GNU Prolog and have it return:
sophomore, pizza, burger.
However, it keeps returning: sophomore, pizza, pizza.
How do I fix this problem? I've spent hours looking into this. Thanks
This is the code I have:
grade(rob, sophomore).
grade(matt, freshman).
food(rob, pizza).
food(rob, burger).
food(matt, pasta).
food(matt, wrap).

preference(X,Y):-
   grade(X,A),
   food(X,B),
   food(X,C),
   Y = (A, B, C).

Comment: Just making sure I understand the question, why do you want `Y` to have both food and a grade in `preference`?
Comment: I would like to first return the grade level and then both of the foods because rob likes pizza and burger. I can't have it only return pizza.
Answer: The way you have defined your facts is nice. The way you query it is not conventional. Here is how I would do it. The "preference" rule is simpler:
grade(rob, sophomore).
grade(matt, freshman).

food(rob, pizza).
food(rob, burger).
food(matt, pasta).
food(matt, wrap).

preference(X, A, Y):-
   grade(X, A),
   food(X, Y).

You conventionally query the database and get all solutions with backtracking:
?- preference(rob, Grade, Food).
Grade = sophomore,
Food = pizza ;
Grade = sophomore,
Food = burger.

If you want to collect the foods, you can use bagof/setof, like this:
?- bagof(Food, preference(rob, Grade, Food), Foods).
Grade = sophomore,
Foods = [pizza, burger].

What if you want to query all freshmen?
?- bagof(Food, preference(Person, freshman, Food), Foods).
Person = matt,
Foods = [pasta, wrap].

Answer: You need to state that the value of B and C are different; there are multiple ways to do that, for the simplicity I go with \==/2 (documentation):
preference(X,Y):-
   grade(X,A),
   food(X,B),
   food(X,C),
   B\==C,
   Y = (A, B, C).

Gives the output
| ?- preference(X,Y).

X = rob
Y = (sophomore,pizza,burger) ? ;

X = rob
Y = (sophomore,burger,pizza) ? ;

X = matt
Y = (freshman,pasta,wrap) ? ;

X = matt
Y = (freshman,wrap,pasta) ? ;

no

If you don't want to have the basically doubled entries you can go with the (in this case lexical) "less than" @</2:
preference(X,Y):-
   grade(X,A),
   food(X,B),
   food(X,C),
   B @< C,
   Y = (A, B, C).

| ?- preference(X,Y).

X = rob
Y = (sophomore,burger,pizza) ? ;

X = matt
Y = (freshman,pasta,wrap) ? ;

no

Answer: I may be wrong, but I suspect this may be a misunderstanding of prolog in general in addition to a non-intuitive REPL. Prolog doesn't really "return" a value, it just tries to match the variables to values that make your predicates true, and I would be willing to bet you're hitting enter after you see the first result.
The way preference is currently written B and C will match any two foods that rob is associated with. This could be pizza, pizza or pizza, burger or burger, pizza, or so on. It does not check whether B and C are equal. When I run preference(rob,X). prolog does not only give me the first result UNLESS I hit enter.
| ?- preference(rob,X).

X = (sophomore,pizza,pizza) ? ?
Action (; for next solution, a for all solutions, RET to stop) ?

If you hit a (or spam ; a few times) prolog will give you the rest of the results.
| ?- preference(rob,X).

X = (sophomore,pizza,pizza) ? a

X = (sophomore,pizza,burger)

X = (sophomore,burger,pizza)

X = (sophomore,burger,burger)

yes
| ?-

I think that all you really need to get all of a person's preferences is just food unless you specifically need them in a tuple or list which will take some slightly more complicated logic (let me know in a comment if that's what you're looking for)
| ?- food(rob, X).

X = pizza ? a

X = burger

yes
| ?-


What are the main concepts that aid singing in key?

Question: In my previous question I asked about how many notes are needed to establish what key you are in. That kind of dodges around the purpose of me asking so here's a more direct question.
With an instrument or with a duet what are the main concepts that aid a lead vocalist in staying in key.
Is it really as simple as singing around a TONIC and being careful as you add more tones? Also, I know one way could be using your brain and ears (having good taste).
Is the only theoretical information for this concept the idea of the drone(s). Example books: The Harmonic Experience by W A Mathieu, Music and the power of sound by Alain Danielou.
Comment: Don't think tonic has much bearing on the situation. Listening, both to the accompaniment and one's own voice are more important. A key is only really a concept, and whilst playing an instrument 'in key' will involve using particular notes, singing, with its continuum of notes available, is a far more complicated (imo) situation, which ironically is far easier for the majority than playing an instrument, with pre-determined note-producing places.
Comment: Note, the phrase "in key" (or "*on* key" or "in tune") is usually taken to mean "using accurate intonation," producing the exact pitch that one means to. If this is an outgrowth of your previous question, that's not really about identifying tonal center. The singer whose pitch "drifts" until they're in fact singing in a different key doesn't realize they've modulated. Being able to avoid this is an important foundational step for any successful singer. If the question is how you can write in such a way as to minimize this danger for beginning singers, maybe edit to make that clearer.
Comment: One way of framing the question might be: There are definitely things you can do to make it *harder*, even for trained singers (destabilizing a tonal center, asking for unprepared dissonances, giving little accompanimental support especially at an entrance, etc.), so... do the opposites of those things!
Comment: Btw, I use a drone as a practice aid to perfect intonation. If I play an arpeggio, it's harder to evaluate the distance from my C to my E, as they happen sequentially in time, than to evaluate both of them against a drone C simultaneously, letting me hear interference patterns. I'm not sure it's the key to your intent, though, because if you have to sing a m2 or M7 against the drone it can take skill. Instead, a nice blunt chordal accompaniment that can keep things steady: Ask someone to sing "Happy Birthday," give them a big dominant 7th chord, and they'll take your key.
Comment: @AndyBonner I guess a better way to describe it  could be, what are different techniques to best present and sustain the tonal atmosphere/key for singers to stay in tune. I'm very stuck on the concept of the drone or tonic now that I've come across the book Music and the power of sound by Alain Danielou. Indian classical music, Ancient Greek, and modern Byzantine all have the idea of using the drone/tonic as a tool to help singers stay in key. Although, I'm not quite sure one note is the best way to do it, but in theory it makes sense. There always seems to be one particular note
Comment: @AndyBonner (don't.) that can be a drone/tonic/pedal tone for the entire piece unless you change keys.
Comment: @AndyBonner Actually, I'm not sure why I didn't come across it before or rationalize it, but the idea I'm speaking on is the idea of the tanpura. But of course, the tanpura just happens to be another variation of guitar and other string instruments. But anyway, the idea to tune the strings and continuously play those as a drone to create a harmonic foundation is exactly what I'm speaking of. While I can see within every composition there is a tonic, Its clear that the tanpura is tuned to chords. Its just a matter of which chords establish a key, that's what I'm still looking to conceptualize.
Comment: Let us [continue this discussion in chat](https://chat.stackexchange.com/rooms/149030/discussion-between-lecifer-and-andy-bonner).
Answer:
With an instrument or with a choir what are the main concepts that aid a lead vocalist in staying in key

The most important thing is probably to be able to listen to what's going on around you while you are also singing.  If you are singing with an unaccompanied chorus and they start going flat, you don't want to stay in key; you want to adjust to them.
Knowing how to adjust your pitch slightly higher or lower depending on the melody and   the harmony, or for an expressive reason, is important.
Having a good vocal technique so your voice is actually producing the pitch your ear wants it to produce is another important factor.  Many amateur singers simply lack the control needed to sing the pitches they want to sing; caricatures of amateur "off key" singers typically capitalize on that.
As Tim says, key and tonality are actually secondary here.  What matters most is whether the pitch you're singing at any given time matches with the pitches others are singing or playing at that time.  If a piece opens with C and E flat, it doesn't matter whether the key is C minor or A flat major or anything else.  What matters is that everyone with C matches each other and everyone with E flat matches each other and that the distance between C and E flat is the correct distance (whatever is "correct" for that piece, depending on the tuning system or temperament chosen by the performers or the music director).
Comment: `(whatever is "correct" for that piece, depending on the tuning system or temperament chosen by the performers or the music director).` Thank you for mentioning this.


How do I let users view, edit or delete their own contents?

Question: I am working on a website where there will be users publishing contents.
How can I restrict users from accessing other users' contents and only able to view, edit or delete their own contents?
Comment: "users publishing contents" and "only able to view their own contents" is contradictory, since publishing typically means "let everyone see". What exactly do you mean?
Answer: You can set these permissions at People > Permissions. Take a look at the 'Node' section. Also, a very practical module for specific cases is Field Permissions.

The Field Permissions module allows site administrators to set field-level permissions to edit, view and create fields on any entity.
Answer: You can use Node Access Rules module.This module control the access to a certain node or node group by Rules. It allows you to control the access to a node (create/view/edit/delete) by Rules.
Answer: What you're talking about is Drupal node access control.
The core's built-in support for node access control is rather course, in particular when it comes to viewing content.  If your specific requirement is that user shall only be able only be able to view, edit or delete his/her own contents, the simplest solution is to not publish the content.
You do this by setting the the default state  for a new node to unpublished.  Navigate to Administration » Structure » Content types, and then pick the content type.  Under Publishing options you untick the option Published.  Then, to allow user to see his/her own content, navigate to Administration » People » Permissions and tick the permission View own unpublished content for the authenticated user. To allow the user to edit and delete his/her own contect rick the persmissions Create new content, Editit own content, Delete own content for all the content types you want your users to be able to use.
The above solution is for Drupal 7 and can be realized with the functionality in core alone.
If you for some reason can not use the solution outlined above, you must use some sort of node access control module to control the access to view the node (create new, and edit/delete own can still be controlled by means of core user permissions).  There is a page at Drupal.org listing all node access modules, with a capsule review of each.  I suggest you take a look at that page to see if you can find a suitable module.
Comment: Thank you very much for the help it is working.

I was wondering  if there is any way I can show list of their own content with option to delete or edit.

Thank you very much for the help.
Answer: After few days of research I finally find an easy way to manage users control over their own content.

Step 1:
Visit http://drupal.org/project/workspace to download the latest version of "Workspace".

Step 2:

Extract the files into a folders on your desktop. The folder will be called "workspace".

Step 3:

Login to your site's files via FTP and navigate to /sites/all/. If there isn't a folder called /modules/ here, create one.

Step 4:

Upload the "workspace" folder to /sites/all/modules/

Step 5:

Go to Administer >> Site building >> Modules and enable Workspace. You'll need to check only one box.

Step 6:

When your users login they'll see a link in the admin menu called "My Workspace". When they click on it they'll see a screen like this:


Linux qos: tc DRR qdisc does not work

Question: There is tc queue discipline DRR(Dificite Round Robin) .
It has same capabilities, as HTB, but instead of using buckets, filled with tokens, it just assignes every queue some Dificit Counter. On packet sending DC is decreased by packet size. If DC is less than packet size, DC is increased by queue's quantum and next queue is processed. So, it can divide outgoing traffec in some ratio, without knowing channel width(which is required for HTB). See http://www.unix.com/man-page/linux/8/tc-drr/
Setup: two hosts, 172.16.1.1 и 172.16.1.2.
On first host we are listening to traffic:
nc -l 8111
nc -l 8112

On second host we check speed:
pv /dev/zero | nc 172.16.1.1 8111
pv /dev/zero | nc 172.16.1.1 8112

Now speed is equal(pv is utility allowing to measure speed of data tranfering via pipeline). Add  DRR on second host(HTB at top is used to emulate real channel speed limits):
tc qdisc add dev eth0 root handle 1: htb
tc class add dev eth0 parent 1: classid 1:1 htb rate 100mbit ceil 100mbit
tc qdisc add dev eth0 parent 1:1 handle 2: drr
tc class add dev eth0 parent 2: classid 2:1 drr quantum 600
tc class add dev eth0 parent 2: classid 2:2 drr quantum 1400
tc filter add dev eth0 parent 1: protocol ip prio 1 u32 match ip dport 8111 0xffff classid 2:1
tc filter add dev eth0 parent 1: protocol ip prio 1 u32 match ip dport 8112 0xffff classid 2:2

Speed remains equal :( What am I doing wrong?
Comment: Obvious question but is the client on a different host to the server?
Comment: Yes, it's 2 virtual machines
Comment: Is the speed equal at ~50mbits? Or is it not hitting the htb contraints?
Answer: Answer: DRR does not drop packets itself. To get the desired behavior, add child qdiscs to the DRR child classes like pfifo limit 50 to cause the child qdisc to drop packets instead of queueing them effectively indefinitely. The solution was found here: linux.org.ru thread
Reference: man tc-drr

NOTES This  implementation  does  not  drop packets from the longest queue on overrun, as limits are handled by the individual child qdiscs.
Answer: drr is a scheduler, you still have to allocate different bandwidth to classes with htb.
I guess you though specifying quantum as 600 and 1400 will give close to 1:2 ratio. In fact it will not. You may get close to that ratio on your config only in case of congestion, e.g. create multiple UDP streams, and then measure two in question, but it's still not the thing you are expecting.
Comment: Why? If I understand algorithm correctly, in case of congestion(new packets appear faster than they can be sent out) for 2 classes with quamtums 600 and 1400 DRR will send packets from second class more often: for example, if all packets have size 1500(default Ethernet MTU) for every 6 packets in first class 14 packets of second class will be sent. Where is my mistake?
Comment: Did you try at least three UDP streams? It's important to have UDP streams in order to create congestion, third stream should not match either filter. No congestion -> no QoS kicks in at all. If no explicit bandwidth specified, quantum should play role, but again only if congestion happens. Whole idea behind qos that it kicks in only if congestion in particular class in hierarchy happens.

Linux qos: tc DRR qdisc does not work


Creating 1D arrays of mpfr_t types in C

Question: I am working with the GNU MPFR library, I write some simple C code.
I am trying to create a one-elemental array of mpfr_t objects:
mpfr_t result;
// (some code that assigned values to the variable 'result')
mpfr_t temparr[1];
temparr[0] = result;
mpfr_clear(result);

And I get the following error:

./library/file.hpp:663:20: error: array type 'mpfr_t' (aka '__mpfr_struct [1]') is not assignable
1 error generated.
Error: Process completed with exit code 1.

What should I modify here? Also - I guess I have to additionally clear the temparr[0] variable too, right?

Since I am here, I might as well ask about dynamical arrays. Later in the code, in another function, I have:
mpfr_t* temparr = new mpfr_t[var];
// some code
for (unsigned int i=0; i < var; i++) mpfr_clear(temparr[i]);
delete[] temparr;

I guess this is alright, no? It is not raising any errors during compilation now, at least...
Comment: [Section 5.2](https://www.mpfr.org/mpfr-current/mpfr.html#Assignment-Functions) is where you can find the assignment functions. You'll also want to see the initialization functions.
Answer: As described in the MPFR manual:

The C data type for such objects is 'mpfr_t', internally defined as a one-element array of a structure

This explains that you cannot do assignments of mpfr_t directly.
Moreover, the mpfr_t array does not contain all the data that define the MPFR number (this is something more or less missing in the manual; this is described in the Internals section, but I suppose that users should not have to read this section to warn them against doing incorrect things). This means that, in general, you are not allowed to just copy the mpfr_t array (e.g. by memcpy). The only safe way to copy MPFR numbers is via the MPFR interface, e.g. mpfr_set.
Your C++ code seems correct (at least the part you wrote). You may define arrays of mpfr_t.

Creating 1D arrays of mpfr_t types in C


Backup & Restore OpenLDAP 2.4 with multi-master replication enabled

Question: We have an openLDAP cluster running with two Master(producers) and one consumer. I read the below guides and got a good enough idea about using slapcat/ldapsearch with slapadd/ldapadd to backup & restore the data.
How to Clone an OpenLDAP Database
LDAP backup with slapcat vs. ldapsearch
For me using ldapsearch with ldapadd worked on taking a backup and restoring it. However, I ended up changing the entryUUID, contextCSN, create & modifyTimestamp of the entries.
ldapsearch -x -H ldaps://ldap.server.net -D "dc=mycompany,dc=net" -W -b "dc=admin,dc=mycompany,dc=net" -LLL > ldapd-"`date +%Y%m%d`".ldif

ldapadd -x -c -H ldapi:/// -D "dc=admin,dc=mycompany,dc=net" -y "${PASSWORD_FILE}" -f "ldapd-"`date +%Y%m%d`".ldif

I wanted to check if this is a preferred way of doing a backup & restore operations or is there any better practices ?
Answer: Part of the reason to use multimaster is that you only need to restore in the event of total system failure, not the failure of any individual node. You can lose all but the last master and syncrepl should restore everything as you add in replacements.
If your meta-data is important to you then you'll want to use slapcat/slapadd rather than ldapsearch/ldapadd. (You can use ldapsearch and slapadd if you also search of operational attributes. E.g. ldapsearch -b dc=example,dc=com "*" +.)


Javascript Closure and Data Visibility

Question: I am trying to wrap my head around the idea of classes, data visibility and closures (specifically in Javascript) and I am On the jQuery docs page for types, it mentions that closures are used to hide data:

The pattern allows you to create objects with methods that operate on data that isn't visible to the outside—the very basis of object-oriented programming.

The example:
function create() {
  var counter = 0;
  return {
    increment: function() {
      counter++;
    },
    print: function() {
      console.log(counter);
    }
  }
}
var c = create();
c.increment();
c.print(); // 1

By declaring the variable counter with the keyword var, it is already locally scoped inside the function/class definition. As far as I know and can tell, it isn't accessible from the outside to begin with. Am I missing something from a data visibility perspective.
Second, is there an advantage to writing the class like above versus like below:
function create() {
  var counter = 0;
  this.increment = function() {
      counter++;
  }
  this.print = function() {
      console.log(counter);
  }
  return this;
}
var c = create();
c.increment();
c.print(); // 1

As I understand it, these are more or less semantically the same thing - the first is just more "jQuery style". I am just wondering if there is an advantage or other nuance I don't fully appreciate from the first example. If I am correct, both examples create closures in that they are accessing data declared outside their own scope.
http://docs.jquery.com/Types#Closures
Answer: First of all, you are correct that both versions use closures.
The first version is cleaner (in my opinion) and more popular in modern javascript. The major potential drawback of the first style is that you cannot effectively assign objects to the constructor's prototype, which is useful (and more efficient) if you are creating a lot of the same objects.
The second style, I've actually never seen in production Javascript. Normally, you would instantiate create with new, instead of returning this in the create() function, like so:
function create() {
  var counter = 0;
  this.increment = function() {
      counter++;
  }
  this.print = function() {
      console.log(counter);
  }
}
var c = new create();
c.increment();
c.print(); // 1

Comment: Minor nit: returning "this" is equivalent to not explicitly returning anything at all, when using the new operator. Without the new operator, "this" is the current context (often times global), and such you end up clobbering global variables.
Comment: And personally, this is the way I prefer to create objects, after having tried innumerable techniques. I think this is just so much cleaner and easier to understand. But that's me. :)
Answer:
By declaring the variable counter with
  the keyword var, it is already locally
  scoped inside the function/class
  definition. As far as I know and can
  tell, it isn't accessible from the
  outside to begin with. Am I missing
  something from a data visibility
  perspective.

It's not that the counter variable isn't accessible from outside the function to begin with, it's that it is accessible to the increment and print functions after create function has exited that makes closures so useful.
Comment: +1 for answering the part of the question everybody else is avoiding for some reason
Answer: Well, I don't care to get into a religious war over how to create objects in JavaScript, since some people feel strongly that there is a right and wrong way to do it.
However, I want to point out something in your second set of code that isn't too savory - namely, the fact that you are assigning things new properties on the object contained in the this keyword - do you realize what that object is? It isn't an empty object unless you use instantiation syntax like this:
var c = new create();

When you do that, the this keyword inside the body of the constructor function is assigned a brand new object, as though the first line in the body were something like:
this = {};

But when you call create() as a function, as you do in that example, you are altering the scope outside of the function's definition (as alluded-to by @seanmonster in the comments).
Comment: Unless assigning the function to a prototype or other object, "this" is actually the global object (window).
Comment: Hee hee, my bad - your comment's grammar is so subtle and I took it to say something opposite of what it said. Sorry about that. I gotta get off of these weird meds...
Comment: I appreciate your answer - although typically true, to be more precise, as I have reflected in my now-edited answer, the this keyword could be something other than the global object, depending on where the function definition is found. If his "create" function were nested inside a constructor function, which is entirely valid, the this keyword would be different than the global scope. So, again - I appreciate your bringing this up because it can be tricky business...
Comment: its even trickier. if you do have a function inside a constructor, it's not necessarily bound to the new object.  example: var Toy = function() { this.type = 'ball'; var create = function() { this.prop = 'i just accessed window'; } create(); } Any time you set up var something = function() { }, "this" is the global object by default.  It's only different if it's a property of an object (var obj = { create: function() { //this == obj} }), or Toy.prototype.create = function() { //this == new Toy }).  Can be scary if not paying attention.
Answer: You should compare the example against this snippet
function create() {
  this.counter = 0;
  this.increment = function() {
      this.counter++;
  };
  this.print = function() {
      console.log(counter);
  }
}

var c = new create();
c.increment();
c.print(); // 1

So when new create() is called it initializes the new object with two methods and one instance variable (namely: counter). Javascript does not have encapsulation per-se so you could access c.counter, as follows:
var c = new create();
c.increment();
c.counter = 0;
c.print(); // 0

By using closures (as shown in your examples) counter is now longer an instance field but rather a local variable. On the one hand, you cannot access from outside the create() function. On the other hand, increment() and print() can access because they close over the enclosing scope. So we end up with a pretty good emulation of object-wise encapsulation.
Answer: Your 2nd example does still use closures, because the increment and print functions still act on a variable otherwise is out of scope — by the time you call c.increment() the create function has already exited.
I like the first example because it avoids the "this" keyword, and in javascript "this" can be tricky — it doesn't always refer to what it seems like it should.
Comment: I'm pretty sure the act of using the variable in the anonymous function means that it will persist, even though the function has exited and normally that variable would be discarded.
Answer: Christian Heilmann has a fairly decent article on the module pattern that you describe that might help you wrap your head around it and why it's useful.
Answer: This syntax makes more sense to me coming from an OOP background:
Create = function {
  // Constructor info.

  // Instance variables
  this.count = 10;
}

Create.prototype = {

     // Class Methods
     sayHello : function() {
          return "Hello!";
     },

     incrementAndPrint : function() {
          this.count++;

          // Inner method call.
          this.print();
     },

     print : function() {
         return this.count;
     }

}

var c = new Create();
alert(c.incrementAndPrint());

Answer: MYAPP = (function(){
   var v1,v2;
   return {
    method1:function(){},
    method2:function(){}
   };
})();

I always use closures like this in my application, as do this, all my own defined methods are in MYAPP namespace ,the v1 and v2 are only accessible by methods in MYAPP.In my application, I often only write a "app.js" file,all my js codes inside. I guess you can define a method called "registy" to define private variable in MYAPP, then you can use it in your methods. All extra variables and methods should be defined by registy method when you wanna add extra codes in html file, just like JQuery.extend method. I've heard if use too many closures in IE browser, you are easy to get stack overflow. (In my opinion)
Answer: In your second example, when you call create(), within the scope of the function, this is the global object (which is always the case when you call a "bare" function, without using it as a constructor or accessing it as a property (e.g. a "method" call)).  In browsers, the global object is window.  So when you call create subsequent times, it creates new closures, but you then assign them to the same global object as before, overwriting the old functions, which is not what you want:
var c = create(); // c === window
c.increment();
c.print(); // 1
var c2 = create(); // c2 === c === window
c.print(); // 0
c2.print(); // 0
increment(); // called on the global object
c.print(); // 1
c2.print(); // 1

The solutions, as others have pointed out, is to use new create().

Javascript Closure and Data Visibility


Differentiability of $(x,y)\mapsto|x|\cdot y$

Question:
Check the differentiability of the function $f:\mathbb{R}^2\rightarrow \mathbb{R}$ of two variables given by the formula $$f(x)=|x_1|\cdot x_2$$

I still have problems with this. I started by trying to count partial derivatives:
$\displaystyle\frac{\partial f}{\partial x_1}(x)=\lim_{h\to 0}\frac{f(x_1+h,x_2)-f(x_1,x_2)}{h}=\lim_{h\to 0}\frac{|x_1+h|x_2-|x_1|x_2}{h}$, so I think the problems can be at the points: $(0,x_2)$, where $x_2\neq 0$, because then we have that this limit is equal to $\displaystyle\lim_{h\to 0}\frac{|h|x_2}{h}$ which doesn't exist (left and right limits are not equal).
$\displaystyle\frac{\partial f}{\partial x_2}(x)=\lim_{h\to 0}\frac{f(x_1,x_2+h)-f(x_1,x_2)}{h}=\lim_{h \to 0}\frac{|x_1|(x_2+h)-|x_1|x_2}{h}=|x_1|$, so I think we haven't any problems here, this partial derivative always exists.
But what exactly can we deduce from these speculations about partial derivatives?
I've also tried to proudly find the differential of this function. I was taught that the function is differentiable at the point $x$ iff there exists (if there exists, there is only one) a linear mapping $L$ such that  $(*)\displaystyle\lim_{h\to 0}\frac{f(x+h)-f(x)-L(h)}{\|h\|}=0$. Then we say that $Df(x)=L$ is a differential of function $f$ at the point $x$. For example consider function $g:\mathbb{R}^2\rightarrow \mathbb{R}, \ g(x)=x_1\cdot x_2$. We can find differential of this function by looking at the increment of this function: $g(x+h)-g(x)=(x_1+h_1)(x_2+h_2)-x_1x_2=x_1h_2+x_2h_1+h_1h_2$ . Then the candidate for $Df(x)$ is linear part of this increment: $L(h)=x_1h_2+x_2h_1$. When we check $(*)$ it appears that indeed it is a desired differential.
But in my example: $f(x+h)-f(x)=|x_1+h_1|(x_2+h_2)-|x_1|x_2$ I'm confused, it seems hard. Do I have to consider a few cases depending on a sign of $x_1,  \ x_2$ ?
Can anybody make it clear for me? It is really important to me to finally understand this topic.
Answer: A necessary condition for a function $f\colon \mathbb{R}^2 \to \mathbb{R}$ to be differentiable at $x_0$ is that both partial derivatives at $x_0$ exist. In this case, $$Df(x_0) \colon (h_1,h_2) \mapsto \frac{\partial f}{\partial x_1}(x_0)h_1 +\frac{\partial f}{\partial x_2}(x_0)h_2.$$
In other words, if the differential exists, then it must have this precise form.
If one partial derivative does not exist at $x_0$, then you can stop. Otherwise, you need to check that the linear mapping $$(h_1,h_2) \mapsto \frac{\partial f}{\partial x_1}(x_0)h_1 +\frac{\partial f}{\partial x_2}(x_0)h_2$$ satisfies the definition of derivative. A sufficient condition for differentiability is that both partial derivatives exist and are continuous around $x_0$.
Comment: so in my example $\frac{\partial f}{\partial x_1}(x)$ does not exist at the points $(0;x_2)$ for $x_2\neq 0$ and here I can stop and say that the function $f$ is not differentiable?
Comment: Of course! Listen: if a differential $L$ did exist at $(0,0)$, then we should conclude that $$L(h_1,0) = \frac{\partial f}{\partial x_1}(0,0)h_1,$$ but the right-hand side is not defined.
Comment: I see now. Thank you very much! This observation with formula for $Df(x_0)$ seems to be very useful, I didn't realise it before. Thank you for your answer.
Comment: You're welcome. Anyway, it follows immediately from the definition of differential.
Answer: Let $g(x_1,x_2)=x_1x_2$, then $g$ is differentiable everywhere with $\partial_1g(x_1,x_2)=x_2$ and $\partial_2g(x_1,x_2)=x_1$.
(1.) Since $f=g$ on the open set $U^+=\{x_1\gt0\}$, $f$ is differentiable on $U^+$ with differential $Dg$.
(2.) Since $f=-g$ on the open set $U^-=\{x_1\lt0\}$, $f$ is differentiable on $U^-$ with differential $-Dg$.
(3.) The last case is $V=\{x_1=0\}$.
(3.i) At any point $x_0=(0,y)$ in $V$, $\frac{f(0+h,y)-f(0,y)}h=\text{sgn}(h)y$ hence $\partial_1f(x_0)$ does not exist if $y\ne0$.
(3.ii) At point $(0,0)$, $|f(h,k)|=|hk|=o(\|(h,k)\|)$ hence $Df(0,0)$ exists and is $Df(0,0)=0$.
To sum up, $f$ is differentiable at $(x_1,x_2)$ if and only if $x_1\ne0$ or $(x_1,x_2)=(0,0)$, and then,
$$
Df(x_1,x_2):(h,k)\mapsto \text{sgn}(x_1)\cdot x_2\cdot h+|x_1|\cdot k.
$$


Fading Android Title Bar

Question: So I am following the steps to create WebView-based Applications for Android. And I have successfully removed the Notification and Title bar from the app. Though whenever I open the app the title bar for it is visible for a split second. How could I remove this? Below is the code I have to remove it from the App:
protected void onCreate(Bundle savedInstanceState) {
    this.requestWindowFeature(Window.FEATURE_NO_TITLE);
    this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

PS. I am no Android developer, so I will try to understand your input as best as possible.
EDIT: This app I am building needs to support 2.2 and up, and when I run this on a phone with 2.3 the title bar is still visible. What else do I need to add?
Answer: Change the theme in the Android Manifest file to something with no title bar or full screen.
Answer: In your activity theme use <item name="android:windowNoTitle">true</item>
Answer: If you are Using this
android:theme="@android:style/Theme.NoTitleBar.Fullscreen"

in Application Tag of your Menifest file.
Then You have to remove from your Code:
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
    this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);

Comment: By adding this, the app doesn't open.
Comment: Even after removing that code the app still won't start.
Comment: Then you have to post your erorr logcat

Fading Android Title Bar


cannot create second cassandra keyspace with NetworkReplication with spring data

Question: i have two keyspaces. one of them is created perfectly but the other one is only created with with SimpleReplication. When i create it with network replication it is created but when i do
describe keyspace in cqlsh it returns:
'NoneType' object has no attribute 'export_for_schema'
But the keyspace with network replication can be created from cqlsh.
In spring logs everything looks ok
<code> [CREATE KEYSPACE IF NOT EXISTS a_events_local WITH replication = { 'class' : 'NetworkTopologyStrategy', 'dс1' : 3, 'dс2' : 3 }
</code>
My Cassandra Config
<code>public abstract class CassandraConfig extends AbstractCassandraConfiguration {

    @Value("${cassandra.host}")
    private String host;

    @Value("${cassandra.port}")
    private int port;

    @Value("${cassandra.user}")
    private String usr;

    @Value("${cassandra.psswd}")
    private String psswd;

    @Value("${cassandra.keyspace.a}")
    private String keyspaceA;

    @Value("${cassandra.keyspace.b}")
    private String keyspaceB;

    @Override
    @Bean
    public CassandraClusterFactoryBean cluster() {
        CassandraClusterFactoryBean cluster =
                new CassandraClusterFactoryBean();
        cluster.setContactPoints(host);
        cluster.setPort(port);
        cluster.setUsername(usr);
        cluster.setPassword(psswd);
        cluster.setKeyspaceCreations(getKeyspaceCreations());
        cluster.setJmxReportingEnabled(false);

        return cluster;
    }

    @Override
    protected String getContactPoints() {
        return host;
    }

    @Override
    protected int getPort() {
        return port;
    }

    @Override
    public SchemaAction getSchemaAction() {
        return SchemaAction.NONE;
    }

    @Override
    protected List<CreateKeyspaceSpecification> getKeyspaceCreations() {
        return Arrays.asList(getAKeySpaceSpecification(), getBKeySpaceSpecification());
    }

    private CreateKeyspaceSpecification getAKeySpaceSpecification() {
        return CreateKeyspaceSpecification.createKeyspace(keyspaceA)
                .ifNotExists(true)
                //.withSimpleReplication(3);
                .withNetworkReplication(DataCenterReplication.of("dс1", 3) , DataCenterReplication.of("dс2", 3));
    }

    private CreateKeyspaceSpecification getBKeySpaceSpecification() {
        return CreateKeyspaceSpecification.createKeyspace(keyspaceB)
                .ifNotExists(true)
                .withNetworkReplication(DataCenterReplication.of("dc1", 3), DataCenterReplication.of("dc2", 3));
    }
</code>
Keyspace A config
<code>@Configuration
@EnableCassandraRepositories(
        cassandraTemplateRef = "keyspaceACassandraTemplate")
public class CassandraDDConfig extends CassandraConfig {

    @Value("${cassandra.keyspace.a}")
    private String keyspace;

    @Value("${cassandra.a-entities-package}")
    private String aEntityPackage;

    @Override
    @Bean("keyspaceDDSession")
    public CassandraSessionFactoryBean session() {
        CassandraSessionFactoryBean session = new CassandraSessionFactoryBean();

        session.setCluster(cluster().getObject());
        session.setConverter(cassandraConverter());
        session.setKeyspaceName(getKeyspaceName());
        session.setSchemaAction(getSchemaAction());
        session.setStartupScripts(getStartupScripts());
        session.setShutdownScripts(getShutdownScripts());

        return session;
    }

    @Override
    @Bean("keyspaceACassandraTemplate")
    public CassandraAdminTemplate cassandraTemplate() throws Exception {
        return new CassandraAdminTemplate(this.session().getObject(), cassandraConverter());
    }

    @Override
    protected String getKeyspaceName() {
        return keyspace;
    }

    @Override
    public String[] getEntityBasePackages() {
        return new String[] {aEntityPackage};
    }
}
</code>
Keyspace B config
<code>@Configuration
@EnableCassandraRepositories(
        cassandraTemplateRef = "keyspaceBCassandraTemplate")
public class CassandraSparkConfig extends CassandraConfig {

    @Value("${cassandra.keyspace.b}")
    private String keyspace;

    @Value("${cassandra.b-entities-package}")
    private String dcEntityPackage;

    @Override
    @Bean("keyspaceBSession")
    public CassandraSessionFactoryBean session() {
        CassandraSessionFactoryBean session = new CassandraSessionFactoryBean();

        session.setCluster(cluster().getObject());
        session.setConverter(cassandraConverter());
        session.setKeyspaceName(getKeyspaceName());
        session.setSchemaAction(getSchemaAction());
        session.setStartupScripts(getStartupScripts());
        session.setShutdownScripts(getShutdownScripts());

        return session;
    }

    @Override
    @Bean("keyspaceSparkCassandraTemplate")
    public CassandraAdminTemplate cassandraTemplate() throws Exception {
        return new CassandraAdminTemplate(this.session().getObject(), cassandraConverter());
    }

    @Override
    protected String getKeyspaceName() {
        return keyspace;
    }

    @Override
    public String[] getEntityBasePackages() {
        String[] entities = new String[1];
        if(saveAll){
            entities[0] = bEntityPackage;
        }
        return entities;
    }
}
</code>
Comment: what `nodetool describecluster` shows?
Comment: Cluster Information:
        Name: cassandra
        Snitch: org.apache.cassandra.locator.GossipingPropertyFileSnitch
        DynamicEndPointSnitch: enabled
        Partitioner: org.apache.cassandra.dht.Murmur3Partitioner
        Schema versions:
                8ff4a796-ce40-33e6-b19d-07f9d91d2j9b: [10.244.13.140, 10.244.11.141, 10.244.9.142, 10.244.7.40, 10.244.12.43, 10.244.8.44]
Comment: ok. I thought that you've got schema disagreement...
Answer: in the end i used getStartupScripts to create keyspaces. and it works, data is written to and read from corresponding tables.
<code>@Override
    @Bean
    public CassandraClusterFactoryBean cluster() {
        CassandraClusterFactoryBean cluster =
                new CassandraClusterFactoryBean();
        cluster.setContactPoints(host);
        cluster.setPort(port);
        cluster.setUsername(usr);
        cluster.setPassword(psswd);
        cluster.setStartupScripts(getStartupScripts());
        cluster.setJmxReportingEnabled(false);
        cluster.setMetricsEnabled(false);

@Override
    protected List<String> getStartupScripts() {
        final String scriptCreateAkeyspace =
                "CREATE KEYSPACE IF NOT EXISTS "
                        + keyspaceA
                        + " WITH durable_writes = true"
                        + " AND replication = {'class' : 'NetworkTopologyStrategy', 'dc1' : 3, 'dc2' : 1 };";

        final String scriptCreateSparkKeyspace = "CREATE KEYSPACE IF NOT EXISTS "
                + keyspaceB
                + " WITH durable_writes = true"
                + " AND replication = {'class' : 'NetworkTopologyStrategy', 'dc1' : 1, 'dc2' : 3 };";

        return Arrays.asList(scriptCreateAkeyspace, scriptCreateBKeyspace);
    }
</code>


Find extremums for u(x,y)

Question: I am not able to calculate extremums for the given function:
$u = 3x^2 - 3xy + 3x +y^2 + 5y$
I am able to calculate
$
u_x = 6x - 3y+ 3
$
$
u_{xx} = 6
$
$
u_{xy} = -3 = u_{yx}
$
$
u_y = -3x + 2y + 5
$
$
u_{yy} = 2
$
But what is next? Where are extremum points?
Comment: You may want to start with finding all *stationary points*, i.e. solutions to the system of equations: $u'_x = 0$, $u'_y = 0$.
Answer: Since $u$ is differentiable, any local min/max point $(x,y)$ must satisfy $Du(x,y)=0$. You've already done the calculations, so just solve \begin{align}
6x-3y+3&=0 \\
-3x+2y+5&=0
\end{align} to get a single point $(x_0,y_0)$. The matrix representing $D^2u(x_0,y_0)$ (i.e. the "Hessian matrix") is $$H=\begin{bmatrix}6 & -3 \\ -3 & 2\end{bmatrix},$$ as you've calculated. Clearly $\det(H)>0$, so $D^2u(x_0,y_0)$ is positive definite. Then apply the higher derivative test to deduce that $u$ has a local minimum at $(x,y)$.
(In fact, this is a global minimum, since the fact that $D^2u$ is positive definite everywhere implies that $u$ is convex.)
Answer: You're almost there.
$$u_x=6x-3y+3=0 \to y= 2x+1$$
$$u_y=-3x+2y+5=0$$
Substitution leads to
$$-3x+2(2x+1)+5=0 \to x=-7, y=-13$$
Which is the global minimum since both $u_{xx},u_{yy}>0$
Comment: btw, it is y = -13
Comment: Apparently the hardest step, fixed.

Find extremums for u(x,y)


FQL Multiquery Returned Info

Question: I'm trying to use an FQL Multiquery to obtain my most recent Facebook question and options with one query using an http request.
So far the query I tried to use is:
<code>SELECT name, votes FROM question_option WHERE question_id IN
   (SELECT id, question FROM question WHERE owner = me()
   ORDER BY created_time DESC LIMIT 1)
</code>
Unfortunately this only returns the name and votes from the outer query and not the question text from the inner one. Is there a way to retrieve all 3 without making 2 queries?
Answer: What you posted isn't a multiquery. A proper multiquery should get you what you want:
<code>{
'question_detail':
  'SELECT id, question FROM question WHERE owner = me()
     ORDER BY created_time DESC LIMIT 1',
'question_answers':
   'SELECT name, votes FROM question_option WHERE question_id IN
      (SELECT id FROM #question_detail)'
 }
</code>
You'll need to get rid of the whitespace for this to properly execute.
Comment: I'm making an HTTP request using just a URL, how would a multiquery like this translate to a valid URL?
Comment: It's pretty well explained in the facebook developer guides [here](https://developers.facebook.com/docs/technical-guides/fql/#multi). Your query URL is like: `https://graph.facebook.com/fql?q={"question_detail":"SELECT+id,+question+FROM+question+WHERE+owner=me()+ORDER+BY+created_time+DESC+LIMIT+1","question_answers":"SELECT+name,+votes+FROM+question_option+WHERE+question_id+IN+(SELECT+id+FROM+#question_detail)"}`
Comment: Yes I tried something very similar to that when I first tried a multiquery, unfortunately with the same result as your example.
`Parser error: unexpected '{' at position 0.`
Comment: Yet strangely if I rewrite the #question_detail as the original query it works fine, so thank you.
Comment: You've got to really watch the syntax here. The Facebook JSON parser is not forgiving at all. One small mistake and you'll get the `Unexpected {` error.

FQL Multiquery Returned Info


multiple keyword match with db_like

Question: I am using db_select for database query, following code works fine when $keyword is any string
<code> $result = db_select('my_table', 'mt')
        ->fields('mt')
        ->condition('my_column', '%' . db_like($keyword) . '%', 'LIKE')
        ->execute()
        ->fetchAllKeyed();
</code>
How can I make the same query working when $keyword is suppose to be an array of strings like ("del","mum") ,if my_column is location column so query will return me places like Delhi, Mumbai.
Comment: refer to http://drupal.stackexchange.com/questions/51089/creating-module-with-autocomplete-and-accepting-multiple-values-in-textfield for a similar example.
Answer: You can build your query while looping through each keyword and adding this as an OR condition.
<code>$db_or = db_or();
$query = db_select('my_table', 'mt');
$query->fields('mt');

foreach ($keywords as $keyword) {
    $db_or->condition('my_column', '%' . db_like($keyword) . '%', 'LIKE');
}

$query->condition($db_or);
$results = $query->execute()->fetchAllKeyed();
</code>
Comment: Thanks!
syntax error at
$db_or->condition('my_column', '%' . db_like($keyword) . '%', 'LIKE'));
extra ')' at the end.

multiple keyword match with db_like


Uso de jquery para puxar registros, mas não aparece

Question: Vi num tutorial do celke, dar select no BD usando php e listar os registros utilizando jquery. Consigo ver que puxou os dados, mas na hora de mostrar dentro do span não mostra. Gostaria de saber onde errei, e como puxo outros registros, pois tem varios checkbox pra filtrar e ao clicar neles quero que dê um select no banco e me traga essa informação la e que eu possa estilizar ela.
(A home.php está dentro de uma pasta, e a index em outra(pasta raiz), não sei se é por isso que não ler, e não sei como entrar dentro da outra pasta, uso netbeans)
HTML

JQUERY

PHP
$consulta_bd = "SELECT * FROM uniao";
  $result=pg_query($conexao, $consulta_bd);
  if  (($result)){
      while($linha_usuario = pg_fetch_assoc($result)){
          echo $linha_usuario['cd_regua'] . "
";
}
    }   else
{
      echo "Nenhum resultado encontrado";
}

Answer:   $.ajax({
            url: "/home.php",  // coloque aqui o endereço que vai buscar os dados no banco
            success: function (data) {
                $('#conteudo').html(data);
                $('#conteudo').show(); // Mostrar o retorno em texto no html

            },
            error: function (request, status, erro) {

                $('#conteudo').html('Ocorreu um erro, entre em contato com T.I!', erro);
                $('#conteudo').show();

            },
            complete: function (jqXHR, textStatus) {

            }
        });

Comment: Eu fiz a primeira etapa, usei jquery para monitorar o evento do checkbox, "Ao clicar no checkbox 'regua', consultar o banco de dados e trazer o registro 'regua' que está lá". Logo após monitorar se for "checked", faça a consulta no BD e me retorne dentro de um flexbox. Sempre que marcar o chexbox me traga aquele dado. Sabe me dizer como coloco dentro do jquery pra me trazer essa consulta logo após a marcação no checkbox?


Extending the 80/20 rule

Question: I have seen comments on the web that because the 80/20 rule is fractal, it applies to the sub groups. In other words, if the top 20% of causes drive 80% of outcomes, then the top 4% of causes must drive 64% of outcomes, etc.
Can that be extended both ways? If the top 20% of causes drive 80% of outcomes, then the bottom 80% of causes drive 20% of outcomes. Extending that, you'll get the top 36% of causes driving 96% of outcomes.
This wikipedia discussion describes it; but the resulting plot (red line here) doesn't look smooth.
I have to admit I don't understand the mathematics, so I would appreciate an intuitive explanation for why it does/doesn't make sense to extend the 80/20 rule this way.
Answer: The red line to which you link (like all descriptions of datasets) is only approximate and so maybe you should be more tolerant of imperfect estimation.
That said, I think the claimed 'fractal nature' of the 80/20 rule may be based more on a hypothetical probability model than on reality, especially if you're trying to use it for the 'top 4%'. 'Fractal nature' may be a concept worth contemplating casually, but not necessarily embracing seriously.
A large and reliable dataset for the top 4% of any strongly right-skewed population must be pretty hard to find.

I have often had to caution clients and students that "exponential trends do not continue." Put another way, for practical purposes, the far right tail of
supposedly exponential data may not be worth detailed scrutiny.

I'd say this caution applies even more appropriately to far right tails of supposedly Pareto data.
Comment: Thank you Bruce. From what you said, it sounds like we shouldn't try applying the Pareto heuristic recursively i.e. 80 / 20 --> 64 / 4 --> 51.2 / 0.8 because it's probably not meaningful. I'm trying to get a sense for the principle behind why it isn't meaningful. Does it have to do with the non-random nature of the sub-samples, so the Pareto distribution based on an assumption of random sampling wouldn't hold? Or does it have to do with insufficient N, where at a 4% sub-group, there's too much variability around the 64% to make it mean anything?
Comment: It has to do with the approximate modeling of real-life data, useful for some purposes, not necessarily for all. // For example, in many applications it is OK to model test scores, people's heights, etc. as normal--even though all normal distributions put _some_ probability below $0.$ Even with a sample size of several billion you won't find anyone with a negative height. // Use the model when it works, but beware that it might not always apply.
Answer: The 80/20 rule is a catchy slogan, commonly repeated in many places, but do not take it literally. There are examples where it holds, there are also many counterexamples where the numbers are not exactly this. In Wikipedia, and other sources, you can easily find multiple examples where the numbers are not exactly 80/20, e.g. the 1% rule. The TL;DR about the rule is that for many phenomena, the majority of outcomes is generated by the minority of events, but the actual numbers would vary on case-by-case basis.
Comment: Thanks Tim, I follow that the specific 80 / 20 figures aren't definitive i.e. it could be 90 / 20, or 80 / 10. I'm just curious, for a given heuristic (taking 80 / 20 as an example), is there a general principle that would/wouldn't support extending the heuristic backwards and forwards i.e. 80 / 20 becomes 64 / 4 and 51.2 / 0.8 in one direction, and 96 / 36 and 99.2 / 48.8 in the other direction?

Extending the 80/20 rule


How to pragmatically control acces to Wi-Fi network

Question: Considering this scenario,
At coffee bar you order the drink and get bill for that,
On bill there is key for Wi-Fi network which is going to be valid for next X hours.
I want to try realize something like that.
Where to start looking,
Does PfSense have that in box ?
Should I left wireless network open and do authorization on internal site for allowing go users to go out ?
I am confused How I can pull or generate KEY pragmatically by C# (.NET) (that is language I know).
Answer: What you're interested in is WPA2-Enterprise:

There are two versions of WPA2 - WPA2-Personal, and WPA2-Enterprise:
  - WPA2-Personal protects unauthorized network access by utilizing a set-up password.
  - WPA2-Enterprise verifies network users through a server.

You need to have the WIFI router with appropriate WPA-Enterprise support, a server which will host the user database, and software that will iteract with that database.
Comment: Thanks a lot, My router have WPA-Enterprise support, Any recommendation for Server that can interact with WPA-Enterprise keys
Answer: I've built a hotspot for the site here which is used in a similar way, user gets ticket, ticket has username and password which is valid for a few hours.
Here I've used RADIUS as the authentication backend, so usernames are programmatically added to and removed from the RADIUS user database (which can be LDAP, an RDB, flat file).
As you suggest, I've used PfSense as it has a built in captive portal which can authenticate against RADIUS as a standard feature. Using the captive portal means the wireless can be open so it's easy to connect to, but you can still control access.
Edit: Process here is:

Staff generate ticket via webpage (PHP)
Webserver inserts users into LDAP (PHP+OpenLDAP)
User logs into captive portal (PfSense+FreeRADIUS)
RADIUS authenticates the user against LDAP (OpenLDAP+FreeRADIUS)


Wordpress w3 total cache and load balancing concerns

Question: The website we are working on right now will be hosted on two load-balanced IIS servers. The database will be common, on a third server.
The plugin (w3 total cache) saves all the files on the disk, inside a wp-content/cache folder.
Right now we are using only one server so everything works fine, but we have to attach the second one soon to the load balancer.
My question is:
- Is it safe to attach the second server as is, without any modification in the plugin ? Do we encounter a risk of the html inserting a cached css file for example, that is present only on one server and not the other ?
- If it is not safe, would a shared wp-content/cache folder solve the issue (symbolic link or so) ?
Regards
Comment: what did you find out?
Comment: We moved the wp-uploads in a shared folder between both servers, but left the wp-content/cache folder as is (so one per server).
It's been a year almost now but so far it raised no issue. We sometime needs to clear the cache on each servers but it never raised any issue that I know of.
Comment: only wp-uploads? what if you do a plugin update?
Comment: We push all changes we do on both servers
Answer: You can move the entire wp-content folder to a shared directory on a file server. Ensure that the directory permissions allow IIS modify rights just like your current wp-content folder. Then create a virtual directory within your IIS website and point it to the shared path.
This way both web servers can share the same uploads, plugins etc. and you don't have to worry about trying to mirror both web servers. Make the following entry in the wp-config.php on each web server:
define('WP_CONTENT_DIR','//server/sharedpath'.'/wp-content');
define('WP_CONTENT_URL', 'https://url-to-virtual-directory/wp-content');

Do this before the entry in wp-config.php:
require_once(ABSPATH.'wp-settings.php');


Get List Sheet Names Filter by Tab Color Hex

Question: I can generate a list of all Sheets names by using the following script:
function SHEETNAMES(option = 0) {

  var sheetNames = new Array()
  var sheets = SpreadsheetApp.getActiveSpreadsheet().getSheets();
  var currSheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet().getName();

  if (option === 0) {
    for (var i = 0; i < sheets.length; i++) sheetNames.push([sheets[i].getName()]);
  } else if (option === -1) {
    for (var i = 0; i < sheets.length; i++) if (currSheet != sheets[i].getName()) { sheetNames.push([sheets[i].getName()]) };
  } else if (option === 1) {
    sheetNames.push(currSheet);
  } else {
    throw "Option argument must be -1, 0, or 1";
  }
  return sheetNames
}

Each tab sheet I have has 2 colors, red (#ff0000) or green (#00ff00). How if I want to do a color filter, if I only want to show a list of sheet tab names that are only green (#00ff00) for example.
Answer: I believe your goal is as follows.

You want to retrieve the sheet names by checking the tab color using Google Apps Script.
You want to give the color as the HEX value.

In this case, how about the following sample script?
Sample script:
function SHEETNAMES(tabColor) {
  const sheets = SpreadsheetApp.getActiveSpreadsheet().getSheets();
  const sheetNames = sheets.reduce((ar, s) => {
    const colorObj = s.getTabColorObject();
    if ((tabColor && colorObj.getColorType() == SpreadsheetApp.ColorType.RGB && colorObj.asRgbColor().asHexString() == tabColor) || (!tabColor && colorObj.getColorType() == SpreadsheetApp.ColorType.UNSUPPORTED)) {
      ar.push(s.getSheetName());
    }
    return ar;
  }, []);
  return sheetNames.length > 0 ? sheetNames : [""];
}

In this case, when SHEETNAMES("#ff0000") is used, the sheet names with the tab color of #ff0000 are returned.
When SHEETNAMES() is used, the sheet names with no tab color are returned.

Note:

It seems that getTabColor() can be used. But, it seems that this has already been deprecated. Please be careful about this. Ref

Reference:

getTabColorObject()
Answer: Get Tabnames by color
function gettabnamesbycolor(hexcolor="#ffffff") {
  const ss = SpreadsheetApp.getActive();
  const tcs = ss.getSheets().map(sh => {
    let cobj = sh.getTabColorObject();
    let type = cobj.getColorType().name();
    if(type == "RGB" && cobj.asRgbColor().asHexString() == hexcolor) {
      return sh.getName();
    } else if (type === "UNSUPPORTED" && hexcolor == "#ffffff") {
      return sh.getName();
    }
  }).filter(e => e);
  //Logger.log(JSON.stringify(tcs));
  return tcs.join(',');
}


Replacing exe icon with WiX

Question: So we are OEM'ing our app, and we have multiple WiX projects referencing our app.
Now it's easy enough to switch out the ico used to create the shortcuts, control panel add/remove icon, etc... But is there a way to change the icon that is inside my applications exe?
Comment: What EXE are you referring to? Are you using WiX 3.6 with Burn to generate a setup.exe or are you talking about your own application's EXE that you are packaging with WiX?
Comment: My own applications, exe
Answer: This isn't really a WiX question, IMO.   Windows Program Executables ( PE ) files have embedded resources.  You would need to use a resource editor  to take your compiled EXE and replace icon.   Otherwise you'd have to recompile your EXE from source with a new icon.
Another possibility is your EXE is a very thin veneer that launches a DLL(s) where your real code is.  This way people can create different implementations of the EXE for branding purposes yet share common functionality.
I do something like that in the Fireworks and IsWiX projects found on CodePlex.
Comment: yuck, I've got the app itself loading a different icon at runtime for the window/taskbar and all the shortcuts use the new icon.  I guess I'll just live with the exe having it's current icon (or strip it out entirely).

Replacing exe icon with WiX


Como unir diversas variáveis em uma só em php e passar para JQuery em um link

Question: Consultei sobre o assunto e até consegui encontrar algumas formas mas nada que conseguisse solucionar o meu caso, vou tentar ser direto para facilitar.
Tenho uma tabela onde listo algumas visitas de algumas empresas, tenho as visitas dos tipos RTV e ATV e estou somando as visitas e colocando nessa tabela nos respectivos campos nas datas, cada soma representa as visitas feitas, no exemplo abaixo o dia 18/09 teve 3 visitas ATV.

Cada visita dessa tem um ID, ou seja, 3 IDs e o que estou tentando fazer é unir esses ID´s em uma mesma variável, fiz os selects necessários e criei essa estrutura para armazena-los, mas não de forma dinâmica, estou fazendo esse select dentro de um loop e ele está assim, no caso da visita ATV:
     $sqlMontaLinkATV = "SELECT supVisitaRtv.IdVisita FROM supVisitaRtv WHERE Tipo = 'ATV' AND supVisitaRtv.Data = ? AND IdEmpresa = ? ";
     $arrayParamLinkATV = array($DataInc, $IdEmpresa);
     $ResultadoLinkATV  = $crud->getSQLGeneric($sqlMontaLinkATV, $arrayParamLinkATV, TRUE);

O resultado dessa pesquisa estou vendo assim com um print_r($ResultadoLinkATV):
Array ( [0] => stdClass Object ( [IdVisita] => 33 ) [1] => stdClass Object ( [IdVisita] => 34 ) [2] => stdClass Object ( [IdVisita] => 37 ) )

Onde tenho os ID´s das visitas que preciso, tentei fazer a inserção delas em uma variável dessa forma:
 $IdVisita = array();
 array_push($IdVisita, $ResultadoLinkATV[0]->IdVisita);

Espero ter conseguido explicar de forma satisfatória.
Comment: No seu banco o '3' é um valor real ou você chega no '3' somando registros de visitas na hora da consulta?
Answer: Com base nos dados da pergunta, o resultado da sua consulta SQL é da seguinte forma:
$ResultadoLinkATV = [
    (object) ["idVisita" => 33],
    (object) ["idVisita" => 34],
    (object) ["idVisita" => 37]
];

Você pode obter a lista de ids através da função array_column do PHP:
$ids = array_column($ResultadoLinkATV, "idVisita"); // [33, 34, 37]

Assim, $ids será um array da forma [33, 34, 37]. Se precisar os valores como string, pode converter para JSON:
$ids_string = json_encode($ids); // "[33,34,37]"

Ou utilizar o implode.

Veja funcionando no Ideone.
Comment: Olá @Anderson Carlos Woss, estou usando o PHP versão 5.6.22 e não consegui ver o resultado como exemplificado, preciso de alguma permissão especial?
Obrigado pela dica.
Comment: Tanto `json_encode` quanto `array_column` estão presentes nesta versão, então não veio motivos para não funcionar. Como tentou fazer, de fato?
Comment: Fiz dessa forma:

$IdVisita = array_column($ResultadoLinkATV, "IdVisita");
print_r($IdVisita);
O resultado é esse: Array ( )
Comment: E não foi exibido nada? O `var_dump` de `$ResultadoLinkATV` é o mesmo da pergunta?
Comment: Não foi um var_dump mas assim print_r($ResultadoLinkATV);
Comment: O que importa é o resultado. É o mesmo?
Comment: Sim, é o mesmo.
Comment: Vamos [continuar esta discussão no chat](http://chat.stackexchange.com/rooms/66276/discussion-between-anderson-carlos-woss-and-adventistapr).
Answer: Este problema poderia ser resolvido usando a função COUNT do SQL
SELECT COUNT(supVisitaRtv.IdVisita) AS qnt FROM supVisitaRtv WHERE Tipo = 'ATV' AND supVisitaRtv.Data = ? AND IdEmpresa = ?;

assim, o próprio banco faz o calculo de quantas visitas foram realizadas do tipo ATV pela empresa e em certa data informada;
Comment: Não acho que seja esse o problema. Ele precisa armazenar em uma mesma variável os valores dos ids retornados, não contar a quantidade de registros.
Comment: Olá @Igor Igor Martinelli, obrigado pela sugestão, mas foi como o  Anderson Carlos Woss comentou, não preciso de soma, isso eu já tenho.


How to show that two groups are not isomorphic.

Question: I have learned various theorems that tell me when two groups are isomorphic. For example, if the greatest common divisor of $j$ and $k$ is equal to one, then $\mathbb{Z}_j\oplus\mathbb{Z}_k\cong\mathbb{Z}_{jk}$. This tells us, for instance, that $\mathbb{Z}_3\oplus\mathbb{Z}_{25}\cong\mathbb{Z}_{75}$. However, how can I show that $\mathbb{Z}_5\oplus\mathbb{Z}_{15}$ is not isomorphic to $\mathbb{Z}_{75}$?
Comment: What are the orders of the elements of $\Bbb Z_5 \oplus \Bbb Z_{15}$? In particular, does that group have any element of order $75$?
Comment: Cf. https://math.stackexchange.com/questions/955577/mathbbz-mathbb2z-bigoplus-mathbbz-mathbb2z-not-isomorphic-to-ma
Comment: It hasn't got an element of order $75$.  Your broader question, however, is not generally solvable.  Even the simpler sounding question, "given the generators and relations that define a group, can I tell if the group is trivial?" is too hard.
Comment: @TravisWillse, Thank you.
Answer: If $\mathbb{Z}_{75}$ is isomorphic to $\mathbb{Z}_5 \oplus \mathbb{Z}_{15}$, $\mathbb{Z}_5 \oplus \mathbb{Z}_{15}$ has a element of order $75$.
But for all $(x,y) \in \mathbb{Z}_5 \oplus \mathbb{Z}_{15}$, the order of $x$ is $5$ and the order of $y$ is $1$, $3$, $5$, or $15$. Therefore, the order of $(x,y)$ is at most $15$.
This is contradiction.
Hence, $\mathbb{Z}_{75}$ is not isomorphic to $\mathbb{Z}_5 \oplus \mathbb{Z}_{15}$
Comment: I'm not quite sure why the order of $y$ is $3$ or $5$. The order is the lowest $k\in\mathbb{N}$ such that $k\cdot y=0$. But if we consider $y=13$, then $3\cdot y=9$ and $5\cdot y=5$. The order of $13$ is $15$, if I'm not wrong?
Comment: I do agree, however, that the highest order of $(x,y)$ is 15.
Comment: Sorry, I missed. The order of $(x,y)$ is $1$, $3$, $5$ or $15$.


Need to find top 3 employees

Question: I working with two tables
Employee ( empid integer, mgrid integer, deptid integer, salary integer)
Dept (deptid integer, deptname text)
I need to find top 3 employees (salary based), in every department. Result should have deptname, empid, salary sorted by deptname and then employee with high to low salary.
I appreciate all your help !!
Comment: what have u tried
Comment: I removed the incompatible database tags.  A correct database tag, along with sample data and desired results benefit a question.
Answer: There are two parts in this query. The inner and outer query.
First part, I am partitioning at deptid level and assigning the rank to the salaries in the descending order which solves your problem.
Second part is just a select on all the output fields by filtering out only the top three employees in each department.
Key point :- Assigning rank to the salaries for each department using ROW_NUMBER window function in the inner query solves the entire problem.
<code>SELECT deptname,empid,salary
  FROM
     (
        SELECT d.deptname,
               e.empid,
               e.salary,
               ROW_NUMBER() OVER ( PARTITION BY e.deptid ORDER BY
               e.salary DESC ) AS rank_salary_by_dept
          FROM dept d, employee e
         WHERE d.deptid = e.deptid
      )
WHERE rank_salary_by_dept <= 3
ORDER BY deptname,rank_salary_by_dept;
</code>
Comment: Thanks SOaddict. Is it possible for you to explain what the script in quotes doing ? OVER ( PARTITION BY e.deptid ORDER BY e.salary DESC ). I get the ORDER BY, but referring to "OVER: and "PARTITION BY"
Comment: I answered your question with more details.
Comment: Let me know if you still have any questions.
Comment: Yes, I have one more. How can I list all employees, their salary and the salary of the person in their department who makes the most money, but less than the employee form the same 2 tables. Thanks.
Comment: there is a up arrow above green tick

Need to find top 3 employees


Find the value $a$ that make the function is continuous:

Question: Find the value $a$ that make the function is continuous:
$$
f(x,y,z)=\left\{\begin{matrix}
\frac{x^2yz^2}{x^6+y^4+z^6} \quad if \quad x,y,z\neq 0
\\  a\qquad \qquad  else.
\end{matrix}\right.
$$
To prove a function is continuous, we need  $f(x)$ define at $x_0$ (condition 1). We also need to prove $\lim_{x \to x_0} f(x) = f(x_0)$ (condition 2).
Question1:
For this question, whatever $a$ value is, this function is not continuous at the given point. I can prove that the limit of $\lim_{x,y,z \to 0}\frac{x^2yz^2}{x^6+y^4+z^6}$ does not exists, thus it's not continuous at the given point. Is there any other alternative way to prove it?
Question 2:
Apart from that, if I have a similar example:
$$
f(x,y,z)=\left\{\begin{matrix}
g(x,y,z) \quad  if \quad x,y,z\neq 0
\\  b\quad \quad \quad \qquad  else.
\end{matrix}\right.
$$
If $\lim_{x,y,z \to 0}g(x,y,z)=k$, where $k$ is a number. Can I say that $b=k$ is the way that make this function continuous?
Comment: Replace (twice) $x,y,z\ne0$ by $(x,y,z)\ne(0,0,0)$ (which is what you really mean), and $x,y,z\to0$ by $(x,y,z)\to(0,0,0).$ Apart from that, I agree with your solutions to the 2 problems.
Answer: for 1)
you may try to prove that the $f(x,y,z)$ has partial derivatives that are continuous in $(0,0,0)$, therefore $f$ must be continuous in that point.

yes. if $f(0,0,0) = b$,
and also $\lim_{(x,y,z) \to (0,0,0)} f(x,y,z)=k$,
so $k$ must be $k=b$ for $f$ to be continuous.


making ios 6 app project compatible with iOS 5 - backwards

Question: This question is for iOS 5 with Xcode 4.2. That's what I am running for iOS development.
I have download a sample project from git hub InstaOverlay and when I look at its target it says "6.0" so I switched it to 5.0 and tried compiling the code. I wasn't able to go very far as you can see from my screenshot. Tons and Tons of errors.
So my question is, is there a problem with the code itself or projects that are made for iOS 6 can never be made to run on iOS 5? I thought users are able to make apps backward compatible?
Any suggestions
Comment: I think you'll need to be more specific - I did a straight git clone of the project, changed the deployment target to 5.0 and it built and ran without errors. So - to answer the question - the project isn't broken - it's something local to your machine.
Comment: Hi Sam, I'm Max - the developer of Instaoverlay. The issues you're encountering might be related to the XCode version rather than the iOS SDK. InstaPDF, the app that I wrote the component for is actually targeted for 5.1
Comment: Also - Are you sure you have correctly added all the dependencies?
Comment: Hi Mmackh - are you sure its just iOS 5.1 problem. I think it may not be that simple - I get most errors for CV_XADD - which is for opencv2 - unfortunately there is no way for me to verify if it really does work on iOS 5.1 or not since I am running iOS 5 with Xcode 4.2
Comment: @Adbizem - All I did was download and open instaoverlay project and try compiling it. I didn't create my own project to incorporate it - all dependencies should have been included in instaoverlay proj.
Comment: No, I'm sure that it isn't an iOS problem, because I think it is your Xcode version.
Comment: @Abizern - how more specific can I be? Do you not see my screenshot? Did you try with Xcode 4.2 or are you running the latest Xcode? To be more specific if needed this is the error I keep getting - CV_XADD expected '(' for function-style cast or type construction. Its compiling about this specific function error 22 times at various places
Answer: General answer
Yes, apps can be made backwards compatible with iOS5 or earlier. "Can be" being the important catch here -- doing so can be very time consuming, depending on what your application does, what APIs it uses, etc. On the other handle, quite simple projects can just work, if they use very standard APIs available without much change since the beginning of (iOS) time.
Obviously if your app uses iOS6 only features, you're stuck. Otherwise, yes, you can do it, but be prepared to take time doing so -- not only writing/alterting code, but testing it.
So as far as you're concerned, yes, the project is 'broken', by which we mean not written for older versions of iOS. If only it were as simple as changing a project setting!
Here's a few strategies for making backwards-compatible apps:

Where variants on an API exist, with different methods having different compatability, use the most compatible variants. For example, some NSFileManager methods appeared in newer versions of iOS, but older variations will still work. Apple tend to willy-nilly publish source code (IME) that uses the newer code without any proviso about "BTW, this won't work on older versions of iOS" so care is needed
If you want to make some functionality only appear on newer iOS versions, you need to do a run-time check that the desired methods/APIs are available, and only use them when they are. In these cases you also need to be careful linking your project and 'weak link' some items.
If you really need iOS3 compatability, you can't use ARC; it has to be old-style memory management. iOS4 supports ARC, but a few runtime limitations: auto-nilling of references isn't supported.

Movie playing is a classic example of newer and better APIs being available but older APIs still being around. The older MPMoviePlayerController was pre-iOS4, then MPMoviePlayerViewController appeared in iOS4 (note the word 'view' -- it's a fully fledged UIViewController). Typically you want to use the latter, but for iOS3 compatability you'd decide to use the former based on a runtime check.
Specific answer
Your problem with CV_XADD: this looks like a preprocessor definition that is #defined somewhere but the compiler isn't picking it up. For a hint, try looking for the definition of CV_XADD by searching for #define CV_XADD. IF you can't find that, try looking for just CV_XADD and looking for a definition in all the results.
Have you tried googling for the terms 'CV_XADD expected expression'? I get a number of hits relating to this problem.
Your project is using C++ which adds some more complexity to the mix!
Comment: thanks for detailed explanation occulus - I wanted to get a confirmation from someone more experienced than me that the project is broken. Keeps complaining about CV_XADD - which has nothing to do with Apple Apis.
Comment: Hi Sam, I've added a bit to the end of my answer about your specific problem.
Comment: lol - seriously man i give up. All I was trying to do is see what these guys had put together on github and how it works. If I can't even compile it with C++ compiler layer complexity added then its just a waste of my time. Thank you for all your explanations!


Probability that $5$ balls are black after $3$ black balls are added to urn with four balls, each having an equal probability of being white or black

Question: An urn contains $4$ balls, each having equal probability of being white or black.  $3$ black balls are added to the urn. The probability that $5$ balls in the urn are black?
My approach. The probability that the urn now has $5$ black balls is equal to the Probability of the bag having $2 $ black balls previously. And since the the probability of a black ball is equal to white ball, so out of $4$ balls 2 will be white and 2 will be Black.So the answer should be $\dfrac{1}{2}$.
Is it correct?
Comment: The distribution in the original urn is probabilistic, the probability that exactly $2$ were black is $\binom 42 \times \left(\frac 12\right)^{4}=\frac 6{16}=\frac 38$.  Also, you should specify whether you mean "at least $5$" or "exactly $5$".
Comment: okay thanx, yes i should have specified, it was 'exactly'.
Answer: Since we know that 3 balls are black, we only need to find the probability that among the rest 4 balls exactly 2 of them are black. The probability is $\frac{{n}\choose{2}}{2^4} = \frac{6}{16}=\frac{3}{8}$


Linq Comparar duas listas de tipos diferentes

Question: Tenho duas listas diferentes A List<ProdutoTag> e B = List<Tag>:
public class ProdutoTag
{
    public Int64 ProdutoId { get; set; }
    public Int32 TagId { get; set; }
    public Double Peso { get; set; }
    public virtual Tag Tag { get; set; }
    public virtual Produto Produto { get; set; }
}

public class Tag
{
    public Int32 TagId { get; set; }
    public String Descricao { get; set; }

    public virtual ICollection<ProdutoTag> ProdutosTags { get; set; }
    public virtual ICollection<Resposta> Respostas { get; set; }
}

Preciso verificar se a lista A contém todos os elementos da lista B (Se a lista A possuir outros elementos que a lista B não possui, tubo bem, mas a lista A deve ter todos os elementos da lista B).
A forma de de comparar as duas listas é através da property A.
Seria algo parecido com (onde x.ProdutosTags é minha lista A):
// Busco na base de dados todos os produtos
var produtos = _context.Produtos.ToList();
// Agora preciso apenas dos produtos que contenham todas as tags selecionadas
var selecionados = produtos.Where(x => x.ProdutosTags.Contains(B));

Como posso comparar duas listas de tipos diferentes?
Answer: Assim:
var aContemB = !b.Except(a.Select(p => p.Tag).ToList()).Any();

Ou seja, verifica se algum item de B é exceção em relação a A, e verifica se o resultado possui elementos.
Se houver algum erro, procure materializar as duas listas antes da comparação, ou seja:
var listaA = a.Select(p => p.Tag).ToList();
var listaB = b.ToList(); // Isto garante que todos os SQL foram executados antes da comparação.
var aContemB = !listaB.Except(listaA).Any();

Comment: Obrigado pela ajuda. Usei `var aContemB = !tags.Except(produtos.Select(p => p.ProdutosTags.Select(x => x.Tag)).ToList());` e estou recebendo o erro: Instance argument: cannot convert from 'System.Collections.Generic.List' to 'System.Linq.ParallelQuery>' O que estou fazendo de errado?
Comment: Acho que você terá que executar os comandos em separado. Vou melhorar o exemplo.
Comment: Muito obrigado pela ajuda, mas ainda não deu certo. Tenho uma lista de produtos. Cada produto desta lista possui uma lista de Tags (TagProduto). Preciso obter apenas os produtos cujas tags sejam as mesmas da minha lista B (onde B lista de tags)
Comment: Isto eu acho que já seria outra pergunta, que extrapola o escopo desta pergunta. Gostaria de abrir outra pergunta?


Subir arquivos para ambiente de produção

Question: Quando vamos subir um ambiente para produção em um servidor, hospedagem padrão, via ftp ou ssh.
Qual a ferramente usar para que subam apenas os arquivos necessários à aplicação, sem ter que subir testes, documentação, etc.
Eu uso php
Obrigado
Comment: http://github.com ou para privados http://bitbucket.org
Comment: O projeto está hospedado numa hospedagem padrão compartilhada ou cloud/vps/dedicated server?
Answer: As ferramentas mais comuns para tal tarefa são os controladores de versões.
Os mais populares são o GIT e Subversion, também conhecido como "SVN".
O GIT oferece o repositório público no site github.com. Há também os planos para hospedagem de repositórios privados.
Alternativamente, é possível instalar um servidor Git dentro de um ambiente privado, no seu próprio servidor, por exemplo. Dessa forma não ficaria dependente de serviços terceiros.
O Subversion é um concorrente mais antigo do git. O manuseio é mais simples e também amplamente aceito, apesar de existir controvérsias que o pejorativam em relação ao Git.
Para os que não tem condições de instalar o git ou subversion no servidor de hospedagem (normalmente em hospedagem compartilhada), tem que fazer manualmente mesmo ou criar scripts ou softwares por conta própria.
Há alguns softwares comerciais no mercado e também iniciativas open-source como essas:
https://github.com/tipui/Tipui-GIT-FTP
https://github.com/myflowpl/git-ftp
Se buscar no google, "php git ftp" encontrará alguns outros.
Esse primeiro é de minha autoria. "Tipui GIT FTP".
Há mais de 2 anos que não mexo com esses códigos, mas funciona bem.
Há certos bugs como por exemplo, falta tratamentos de erros principalmente quando há algum erro no envio de um arquivo. Também falta um meio de continuar um upload interrompido.
Outra deficiência é falta de suporte a SFTP, ou seja, FTP sob SSL.
Todo o código é escrito em PHP usando funções PHP FTP http://php.net/ftp
Quando eu tiver algum ânimo voltarei a brincar com esse projeto.