Is there a significance to the asymptotic probability of at least one occurrence of an event in n attempts?

Question: Let's look at the set of the probabilities of having at least one occurrence of an event if we make $n$ attempts, where the probability of the event occurring is $1/n$.
For example, if we are looking at the probability of the occurrence of rolling a $4$ on a die ($1/6$ chance), we will actually make $6$ attempts. The probability of success in that case (at least one occurrence of a $4$ in the $6$ attempts) is $1-(5/6)^{6} = 0.6651$ (I have rounded the results.) If we make $15$ attempts at something with a probability of its happening (on each separate occasion) being $1/15$, then the probability of its occurring at least once in those $15$ attempts is $1-(14/15)^{15} = 0.6447$.  If we use $n=1,000,000$ then we get $0.63212$.
So, we see that we have an asymptotic situation. I have always wondered if there was any other known mathematical significance to this specific approximate number/asymptote. Thanks in advance for reading and for all responses!
Comment: [This inverse symbolic calculator](https://isc.carma.newcastle.edu.au/index) is a tool that may be useful if you ever have a value that you have calculated to many decimal places and are wondering if there is a well-known closed form for it.
Comment: Just a remark: indeed, $1-((n-1)/n)^n\to (e-1)/e\approx 0.63212$.
Comment: Welcome to the site!  Great first post!  I hope to see you around on this site again.  I recommend also that you [take the tour](https://math.stackexchange.com/tour) to get a grasp on how this particular site is different from (perhaps better than?) others.  ;)
Comment: Ohh wait, the die sides and the number of rolls are *both* n at all times?
Comment: Wait, this makes no sense. Are you saying that as we try *more* times, the probability of success goes *down*? Furthermore, I'd expect that the probability of not getting a gven value in a million die rolls to be pretty miniscule.
Answer: Roll an $n$-sided die numbered $1$ through $n$. Roll it $n$ times. Your question is equivalent to the following:

What is the probability that you roll at least one $1$, over $n$ throws of this $n$-sided die?

This is equal to $1$ minus the probability that you get no $1$s during the $n$ throws. The probability of not getting a $1$ on any given throw is $(n-1)/n$, so this gives your desired probability as:
$$1 - \left(\frac{n-1}{n}\right)^n$$
$$1 - \left(1- \frac{1}{n}\right)^n$$

Look at number $1$ in this list of characterizations of the exponential function:

Define $e^x$ by the limit
$$ e^x = \lim_{n\to\infty} \left(1 + \frac{x}{n}\right)^n $$

This definition applies to your problem, when we let $x=-1$.
In the limit as $n$ goes to infinity, we can write
$$\lim_{n\to\infty} \left[\,1 - \left(1- \frac{1}{n}\right)^n\,\,\right] \,\,=\,\, 1 - \,\lim_{n\to\infty} \,\left(1+\frac{-1}{n}\right)^n\,\,=\,\, \boxed{1 - \frac{1}{e}\,} \,\,\approx\,\, 0.6321$$
Comment: I'm using chrome. The trouble with it is that if sites go down then the links stop working too making answers nonsensical. Any suggestions on how to fix this problem appreciated! ;-) Seriously though I know I can follow the link to see the info, I just think the answer would be better if it were in the answer. On StackOverflow at least we tend to frown on answers that rely on you following the link to get key information. Given the thing you have linked to is the most crucial part of your answer it seems strange not to actually have it in the answer. Your answer though, do what you want. ;-)
Comment: @Chris That makes sense. For convenience (and insurance against the possibility of links breaking), I've added an image snippet of what I had linked to.
Comment: The jump from $e = \lim (1+1/n)^n$ to $1/e = \lim (1-1/n)^n$ is nontrivial, and needs an explanation if the target audience is people who didn't even know the first limit.
Comment: This answer would be better if I hadn't had to click on the link to see the alternative characterization of e that you thought was interesting. Why not just include it in your answer (with a link if you want a reference for people to follow). Its a little annoying to read your answer and have to click out half way to be able to follow it.
Comment: @Chris What browser are you using? What OS? If it's Google Chrome then I have suggestions for you, if the OS is Windows I also have suggestions. Let me know :P
Comment: Thanks @muru for the edit
Comment: @ZubinMukerjee any time. Another SE thing is to use text where possible instead of screenshots. Text is far more accessible. :)
Comment: @JiK Good point, thank you! I have edited and made the explanation more complete, using a characterization of $e^x$ applied at $x=-1$.
Answer: The point is that $$\lim_{n \to \infty} \left(1 - \frac{1}{n}\right)^n = \frac{1}{e}$$
where $e$ is the base of natural logarithms.  This is approximately $0.3678794412$.
Comment: There was a typo (missing parentheses) in the original OP, the actual limit is different.
Comment: @anderstood I think the idea is that $1/e$ is the number you subtract from $1$ to get the limit in the question. But it might have been clearer if that had been stated explicitly.
Comment: @anderstood only by complementation, the point remains taht $\lim\limits_{n\to\infty}(1-{(\frac{n-1}{n})}^n) = 1-\tfrac 1e$.
Answer: Others have already pointed out that the probability of at least one success in $n$ independent trials, each succeeding with probability $1/n$, tends to $1-1/e \approx 0.63212$ as $n$ increases.  However, it might be instructive to work out how you could determine this limit yourself.
You already know that the exact probability of observing at least one success in $n$ trials equals $1$ minus the probability of observing no success in $n$ trials, which in turn equals the probability of a single trial failing raised to the $n$-th power.  Given the assumption that a single trial succeeds with probability $1/n$, it fails with probability $1 - 1/n$, and thus the probability $p_n$ of observing at least one success in $n$ trials is: $$p_n = 1 - \left( 1 - \frac1n \right)^n.$$
In this formula, $n$ appears twice: once in the denominator and once in the exponent.  You've already experimentally observed that, as $n$ increases, $p_n$ seems to tend to a finite limit $0 < p_\infty < 1$ that is independent of $n$.  Thus we can expect that, in the limit, those $n$'s should somehow cancel out.  Our task, then, is to somehow manipulate the expression for $p_\infty = \lim_{n\to\infty} p_n$ into a form where we can algebraically cancel out the $n$'s and obtain a closed-form expression for $p_\infty$.
To do that, we somehow need to bring the $n$'s together.  We can't get the $n$ in the exponent down, but we can raise the other $n$ into the exponent too, by replacing $1 - 1/n$ with the equivalent expression $e^{\log_e(1 - 1/n)}$ and applying the rule $(x^a)^b = x^{ab}$ to get: $$p_n = 1 - e^{\textstyle n \log_e(1 - 1/n)}.$$
(Strictly speaking, this reformulation is only valid for $n > 1$, since the expression $1 - 1/n$ needs to be positive for its logarithm to be a well defined real number.  But since we're concerned with the limit $n \to \infty$, we can safely ignore any special cases involving small values of $n$.)
Of course, we could've just as well picked any other base for the logarithm instead of $e$ above and obtained an equally valid expression for $p_n$.  However, what's special about the natural logarithm $\log_e$ is that the derivative of $\log_e(x)$ at $x=1$ equals $1$.
In particular, this means that, for values of $x$ close to $0$, we have the approximation $\log_e(1 + x) = x + o(x)$, where $o(x)$ denotes additional higher-order terms such that: $$\lim_{x\to0} \frac{o(x)}{x} = 0.$$
Letting $x = -1/n$, we get $\log_e(1-1/n) = -1/n - o(1/n)$, which we can substitute into the expression for $p_n$ above to get: $$p_n = 1 - e^{\textstyle n\left(-\tfrac1n - o\left(\tfrac1n\right)\right)} = 1 - e^{\textstyle -1 - n \cdot o\left(\tfrac1n\right)}.$$
As $n$ increases, the $n \cdot o(1/n)$ term in the exponent tends to zero, and therefore: $$p_\infty = \lim_{n\to\infty} p_n = 1 - e^{\textstyle -1} = 1 - \frac1e.$$

The general trick here is that, for $x$ close to $0$, $\log_e(1+x) \approx x$ (and, conversely, $e^x \approx 1+x$).  Thus, in particular, $(1+x)^n \approx (e^x)^n = e^{nx}$ when $x \approx 0$.
If $nx$ is also small, we can even further approximate $(1+x)^n \approx 1+nx$.  This has an intuitive probabilistic interpretation: if an experiment succeeds with a very small probability $p \approx 0$, then repeating it $n$ times yields a success probability of $1-(1-p)^n \approx 1-e^{-np} \approx np$, i.e. approximately $n$ times higher than for a single experiment.
For larger $n$, the second approximation breaks down as the likelihood of multiple successes becomes non-negligible, but the first approximation $1-(1-p)^n \approx 1-e^{-np}$, which only depends on $p$ being small, still holds.  In particular, if $n$ and $p$ are inversely proportional, such that $np = c$, then the probability of at least one success tends to $1-e^{-c}$ as $n$ get larger and $p$ gets smaller.
Another way of looking at this is that we're effectively approximating the binomial distribution of the number of successful trials out of $n$ using a Poisson distribution with the event rate parameter $\lambda = np$.  This approximation, which gets better as $n$ gets larger and $p$ gets smaller, then yields a probability of $1 - e^{-\lambda}$ of at least one event occurring.
Comment: +1 for the final paragraphs, which are the first here that do not just determine the limit -- which, pardon everyone, is a basic and easy calculus exercise -- but give some context in probability theory.
Answer: $$1- \left(\frac{n-1}{n}\right)^n=1-\left(1 - \frac{1}{n} \right)^n$$
As we take limit $n \to \infty$,
$$\lim_{n \to \infty}1-\left(1 - \frac{1}{n} \right)^n = 1-\exp(-1)$$
Hence that is why you observe the number that approximate $1-\exp(-1)$
Comment: I'm not sure why this answer is so much less upvoted than the others...


A simple query in SQL

Question: I have 2 tables . each table has two columns.
DocumentNumber      price

I want to use a query to show same documentnumber and count of ducumentnumber in each table.
I used this code.
Select  Sheet.DocumentNumber , Sheet2.DocumentNumber ,Count(sheet.documentnumber) , Count(sheet2.documentnumber)

        From Sheet,Sheet2
        where sheet.DocumentNumber=sheet2.DocumentNumber

        group by sheet.DocumentNumber , Sheet2.DocumentNumber

but instead of counting document numbers it shows me the Cartesian of two column.
And I want to show price of each table and (sheet.price) minus (sheet2.price)
please complete my query.
Answer: You should use proper join syntax.  In particular, for this, you should use full outer join because it is possible that a document has no records in one or the other table.
Second, because you don't want to count duplicates, you need to count something.  The following assumes that there is an id column (of some sort) in each table:
Select  coalesce(s.DocumentNumber, s2.DocumentNumber) as DocumentNumber,
        Count(distinct s.id), Count(distinct s2.id)
From Sheet s full outer join
     Sheet2 s2
     on s.DocumentNumber = s2.DocumentNumber
 group by  coalesce(s.DocumentNumber, s2.DocumentNumber);

If you don't have an id column, or if your database does not support full outer join, the following will also work:
select DocumentNumber, max(cnt_s) as cnt_s, max(cnt_s2) as cnt_s2
from ((select DocumentNumber, count(*) as cnt_s, 0 as cnt_s2
       from Sheet s
       group by DocumentNumber
      ) union all
      (select DocumentNumber, 0, count(*) as cnt_s2
       from Sheet2 s2
       group by DocumentNumber
      )
     ) t
group by DocumentNumber;

EDIT:
The union all approach is actually better for the price:
select DocumentNumber, max(cnt_s) as cnt_s, max(cnt_s2) as cnt_s2,
       max(price_s) - max(price_s2)
from ((select DocumentNumber, count(*) as cnt_s, 0 as cnt_s2,
              sum(price) as price_s, 0 as price_s2
       from Sheet s
       group by DocumentNumber
      ) union all
      (select DocumentNumber, 0, count(*) as cnt_s2,
              0, sum(price) as price_s2
       from Sheet2 s2
       group by DocumentNumber
      )
     ) t
group by DocumentNumber;

Note:  This version treats a missing price as 0.  You might want to replace the 0 with NULL for that situation.
Comment: Thank you Gordon. All queries you showed ,e are working. I used the 3rd one. it's awesome. but in 3rd one I want to show the price of first sheet and price of second sheet. and then the minus between price1 and price2

A simple query in SQL


Is it necessary to turn on my electronic drum kit before the amp and vice versa?

Question: I'm sorry if this is a super noob question><. I recently got my hands on an electronic kit and the store reminded me to always turn the kit on before the amp and the amp off before the kit. Is this being overly cautious or necessary to prolong the life of the amp?
Thanks
Answer: It's a good precaution.  Your mileage may vary.  High quality equipment tends to be designed (or amended) in a way where its output does not go nuts when turned off.  But that's not a hard/reliable rule.  You can turn the amp volume down to "almost off" to make a first try if the convenience of switching order is important to you.  There are also power socket lines that switch on/off in sequence in order to automate the procedure.
I also have an old amp with builtin coil reverb where you have to wait for 10 seconds after turning it off before touching the "reverb" pot: if you don't, horribly loud noises come out.  Apparently when switching off, the powers die in an order where you have some large DC value on the reverb pot and any movement/scratching of its wiper is horribly amplified.
It's a good idea to learn the quirks of your equipment in non-catastrophic settings first.  So I'd try switching the kit on and off with the amp at almost zero setting first and see what happens.
Note that the results may not be representative when you pull the power plugs and don't put them in in exactly the same orientation with respect to the wall plug next time.  Different orientations may make for different ground offsets/capacities.
Answer: The most pronounced effect is usually a DC (direct current) thump as the output kicks positive or negative due to the rapid shut-down of the (drum-kit) power supply. If this is passed into the powered amplifier and the volume is turned up it gets passed to the loudspeakers. The bass unit will get a hard push or pull (depending on polarity) and if undersized relative to the amplifier may be damaged by excessive cone excursion.
In reality, you have more risk of damage to reputation (by sounding unprofessional) than damage to equipment. My nephew tells me, "a sound engineer dies somewhere every time you pull out an input jack with the volume up".


Como fazer uma imagem e texto aparecerem ao clicar em um option?

Question: Não estou conseguindo fazer uma questão que pede:

Uma pequena biblioteca possui apenas livros de ficção e didáticos
  (Matemática, Português, etc.). Você está construindo o sistema de
  empréstimos dessa biblioteca.  Na primeira página do sistema, deve
  existir um select para que o usuário escolha entre o gênero de ficção
  ou  de didáticos.  Caso seja escolhido o gênero de ficção, o sistema
  deve mostrar, logo abaixo, a imagem da capa do livro, o autor e o
  resumo de um livro da saga Harry Potter e um livro de Sidney Sheldon.

<!DOCTYPE html>

Biblioteca

    <select id="genero" onchange="(mostrarFoto)">
        <option value="ficcao" id="ficcao"> Ficcao </option>
        <option value="didatico" "id="didatico "> Didatico </option>
    </select>

Answer: Você definiu o local onde você quer mostrar a imagem desta maneira:

Mas no seu código, você pede para ele pegar o elemento imagem-harry (que parece não existir):
var harry= document.getElementById('imagem-harry');

Além disso, a chamada ao método mostrarFoto, precisa estar entre parênteses para que o script entenda como um método de fato, ex.: mostrarFoto():
<select id="genero" onchange="(mostrarFoto)"> // precisaria ser mostrarFoto()

Eu modifiquei o seu código com essas sugestões, por favor dê uma olhada abaixo (clique em executar).

function mostrarFoto(a) {
/*
* aqui chamamos as duas divs do nosso html:
* "imagem" e "descricao"
*/
  var element = document.getElementById("imagem");
 var element2 = document.getElementById("descricao");

/*
* mostrarFoto() está recebendo uma variavel, 'a'
* que nos dirá o que o usuário escolheu
*/
    if (a == "ficcao") {
  element.innerHTML = "
<img src='http://i.imgur.com/Md05F0E.png'";
  element2.innerHTML = "
Harry Potter (Daniel Radcliffe) retorna à Escola de Magia e Bruxaria de Hogwarts, para cursar o 5º ano letivo. ... Além disto, o Ministro da Magia Cornélio Fudge (Robert Hardy) impõe à escola a presença de Dolores Umbridge (Imelda Staunton), que torna-se a nova professora de Defesa Contra as Artes das Trevas.
";
 }

 else if (a == "didatico") {
  element.innerHTML = "
<img src='http://i.imgur.com/AreoXA1.jpg' width='245'";
  element2.innerHTML = "
Papai e mamãe decidiram contar aos filhos como são feitos os bebês. E inventaram um monte de besteiras, sem saber que as crianças já sabiam de toda a verdade.
";
 }
}

Biblioteca

    <select id="genero" onchange="mostrarFoto(value)">
        <option value="escolha"> Escolha... </option>
        <option value="ficcao"> Ficcao </option>
        <option value="didatico"> Didatico </option>
    </select>

Comment: Muito obrigadooooo <3 Agora entendi o que deveria fazer.
Nem sei te dizer o quanto estou grata por você ter me ajudado e eu ter conseguido entender direitinho :D
Comment: @MikeliGuedes Que bom que deu certo! Se puder, marque a resposta como aceita clicando na marquinha do lado esquerdo do texto - aí ela sai da fila de "perguntas não respondidas" (e eu ganho pontinhos que valem mais que ouro!) O________O - Ah, e seja bem vinda ao Stack Overflow! :)


What is the I Rig

Question: I am interested in recording straight from guitar to my Ipad. I've seen the IRig for this but I am not sure what it is.
Is the IRig simply an audio jack to 3.5mm converter? Will it amplify the guitar output at all or will I need separate software?
Thanks
Answer: The I rig is a device for converting guitar output signals to signals a phone can read in an app, which can then convert it to signals a mini amp can read. In the app, one can alter volume, octave, things a conventional amp could do. However you cannot notate music with it.

What is the I Rig


Odoo 8 function call on opening (tree) view

Question: Is there a way to call a python function (server action) to a view being opened. So when I click a menuitem not only a tree view opens (window action) but also a python function executes (server action).
Maybe something like an onload() function? Or a server action from within the tree view?
Thanks
Answer: There is one way to make it happen.
Just add that functional field in tree view and make it invisible
So it will be also called in tree view
Answer: you can, for example do it from an action.server, i will give you an example that i used to open a wizard from a transient model.
<code>    <record id="action_current_account_conciliate" model="ir.actions.server">
        <field name="name">Conciliate</field>
        <field name="type">ir.actions.server</field>
        <field name="model_id" ref="l10n_ar_current_account.model_current_account"/>
        <field name="code">
            if obj.raise_imputation_wizard():
                action = {
                    "type": "ir.actions.act_window",
                    "res_model": 'current.account.imputation.wizard',
                    "view_mode": "form",
                    "target": "new",
                    "res_id": obj.wizard_id,
                }
        </field>
    </record>
</code>
with the field code you can write python code. The action was the return of the wizard (you can changue that view_mode for tree and without target new), depending on from where you want to open the tree view.
Hope it helps.


PHP: Spaces are not shown in the right place

Question: This is my program I expect the output of this program is to be like *  Increasing order but the spaces are not printed....
    *
  *  *
 *  *  *
* * * * *

<?php
$s = '|';
for($i=1;$i<=10;$i++)
{
    $c=10-$i;
    for($k=1;$k<=$c;$k++) {
            echo '';
    }
    for($j=1;$j<=$i;$j++)
    {

        echo "*";
            echo ' ';
    }
    echo '
';
}

?>

I am getting this output:
*
* *
* * *
* * * *
* * * * *
* * * * * *
* * * * * * *
* * * * * * * *
* * * * * * * * *

How do I print the spaces?
Comment: Why don't you use CSS ?
Comment: Add the CSS `white-space: pre` to the container element.
Comment: @Rimjhim Ratnani : My solution in 2 times shorter ;)
Answer: You need to use   special character to print space
Try edit your echo ' '; on echo ' ';
Answer: instead of    line "echo ' ';"
user echo "" ";"

code is html for space
Answer: Try This..

<?php
$s = '|';
for($i=1;$i<=10;$i++)
{
    $c=10-$i;
    for($k=1;$k<=$c;$k++) {
            echo ' ';
    }
    for($j=1;$j<=$i;$j++)
    {

        echo "*";
            echo ' ';
    }
    echo '
';
}

?>

Answer: i'm not sure ... but this is much shorter :)
<?php
$s = '|';
for($i=1;$i<=10;$i++)
{
    $str = str_pad("*", $i, "*", STR_PAD_BOTH);
    echo str_pad($str, 10, " ", STR_PAD_BOTH);
    echo '
';
}
?>

WORKING CODE
Answer: Instead of echo ' '; put echo " ";.
Answer: Use   to add space in your code..
$s = '|';
for($i=1;$i<=10;$i++)
{
    $c=10-$i;
    for($k=1;$k<=$c;$k++) {
            echo ' ';
    }
    for($j=1;$j<=$i;$j++)
    {

        echo "*";
            echo ' ';
    }
    echo '
';
}

Output
         *
        * *
       * * *
      * * * *
     * * * * *
    * * * * * *
   * * * * * * *
  * * * * * * * *
 * * * * * * * * *
* * * * * * * * * *


to many files when starting new jhipster project

Question: i follow the tutorial from matt on:
http://jhipster.github.io/video-tutorial/
when i do cloc . i see i have much and much more files i would expect:
<code>$ cloc .
66717 text files.
20401 unique files.
24466 files ignored.

http://cloc.sourceforge.net v 1.60  T=128.46 s (115.7 files/s, 15523.0 lines/s)
--------------------------------------------------------------------------------
Language                      files          blank            comment           code
--------------------------------------------------------------------------------
Javascript                    13322         222956         357190            1266221
HTML                            676           6984           1047          44885
CSS                              76           1883            932          22029
Java                            262           3548           1854          15641
XML                              53           3383           1395          11307
LESS                             79           1388           1546           7269
C/C++ Header                     18           1032            300           5109
YAML                            190            221            346           3466
CoffeeScript                     47            783            699           2467
make                             58            417            523           1271
Bourne Shell                     31            234            202           1097
Maven                             1             12             34            824
Perl                              2             87            170            584
DTD                               1            179            177            514
SASS                              5             42             25            273
C++                               4             43             26            260
IDL                               6             38              0            167
Bourne Again Shell                3             28             36            140
D                                 6              0              0            118
Scala                             1             16              7            118
JavaServer Faces                  3              3              0            109
Smarty                            6             17             30             91
DOS Batch                         1             24              2             64
Python                            1              7              7             36
XSLT                              1              5              0             32
C#                                2              3              1             27
ASP.Net                           2              5              0             23
C                                 1              7              4             23
OCaml                             1              5             15              6
Lisp                              1              0              0              6
PowerShell                        1              2              2              4
Lua                               1              0                  0              2
--------------------------------------------------------------------------------
SUM:                          14862         243352         366570        1384183
--------------------------------------------------------------------------------
</code>
why is that?
in total it is 610 mb large!
it seems there are a lot of node modules:
<code>$ du -h -d1
584M    ./node_modules
24K ./gulp
26M ./src
64K ./.mvn
610M    .
</code>
is this correct?
and what do i need to add to source control?
thanks
Comment: In the mean time i watched https://www.youtube.com/watch?time_continue=2776&v=kkHN2G_nXV0 and here matt explains about the node_modules. and i noticed matt did cloc before node modules were installed
Answer: This is normal. Most of those files are NPM dependencies, as you mentioned.
The generated <code>.gitignore</code> should already be configured properly and will ignore node_modules.


Very strange javascript sorting values behaviour

Question: I have been messing around with this for hours and the only thing I can narrow it down to is that if there is 14 elements to sort, it doesn't work properly, but if there is thirteen, it works fine.
I am trying to do a basic sort of DIV elements by the price values they hold inside.
Here is the simple html -

    <button id="numBnt">Numerical</button>

£10.35

£21.35

£21.35

£102.35

£10.35

£10.35

£10.95

£100.35

£100.05

£200.00

£5510.25

£19.80

£5510.25

£510.25

And the javascript
var $divs = $("div.box");

$('#numBnt').on('click', function () {
    var numericallyOrderedDivs = $divs.sort(function (a, b) {
        return parseFloat($(a).find("h2").text().replace(/£/g, '')) > parseFloat($(b).find("h2").text().replace(/£/g, ''));
    });
    $("#container").html(numericallyOrderedDivs);
});

With 13 div elements, the divs are sorted perfectly.
here is an example - http://jsfiddle.net/C2heg/380/
Then if I add another and make it 14 divs, the sort doesn't work correctly.
here is an example - http://jsfiddle.net/C2heg/378/
I am litrally banging my head of the table! Hopefully someone can shed some light on this.
Comment: problem is your code only returns a boolean. a sort callback has to return THREE values. `+1,0,-1` to indicate greater-than,equal,less-than.
Comment: Just in the interest of completeness for anyone reads this, there's no requirement to return the specific values `+1` or `-1`. All the sort function cares about is the *sign* of the result, not the magnitude, so those can be any positive number and any negative number. In any case you're 100% right on the general concept.
Answer: Use a - b instead of a > b
$('#numBnt').on('click', function () {
    var numericallyOrderedDivs = $divs.sort(function (a, b) {
        return parseFloat($(a).find("h2").text().replace(/£/g, '')) - parseFloat($(b).find("h2").text().replace(/£/g, ''));
    });
    $("#container").html(numericallyOrderedDivs);
});

Demo: http://jsfiddle.net/C2heg/381/
Answer: Neither of your fiddles are working, and it has nothing to do with the number of elements.
This works though:
var $divs = $("div.box");

$('#numBnt').on('click', function () {
    var numericallyOrderedDivs = $divs.sort(function (a, b) {
        var a = parseFloat($(a).find("h2").text().replace(/£/g, ''));
        var b = parseFloat($(b).find("h2").text().replace(/£/g, ''));

        return a - b;
    });
    $("#container").html(numericallyOrderedDivs);
});

The sort function on comparing two items should return 0 if they are equal, a positive number if first is greater than second, a negative number otherwise.
Here's the updated fiddle.
Comment: Since `a` and `b` are numbers, you can simply `return a - b;` instead of all the comparisons. If this were a case where you *did* need to use comparisons instead of subtraction (e.g. if `a` and `b` were strings), I definitely don't recommend using two different forms of comparison (the `if` statement for equality and the conditional operator for inequality). That is very confusing. Instead I would use `return a > b ? 1 : a < b ? -1 : 0;`. That keeps a consistent pattern going which helps readability.
Comment: @MichaelGeary, I was under the impression that sort expects one of -1, 0 and 1. Just checked the doc and saw it just requires less than 0, 0 or greater than 0. That said I'll update my answer. But I don't think it was confusing as you suggested (based on my original impression), rather it oversimplified it. Thanks for pointing it out to me though, it got me to update myself. Cheers!
Comment: Thanks for the update, Igwe, looks good! I overstated things when I said the previous code was "very confusing", sorry. All I meant was that it was a bit inconsistent. Of course anyone reading the code would be able to figure out what it did - the code was perfectly clear and readable. But they might scratch their head wondering why the first comparison used an `if` statement and the next one used a conditional operator. If you are doing two comparisons in a row, it helps people reading the code if you use a consistent technique for both - that's all I meant. Keep up the good work!


differentiable prove of product functions

Question: Let $E, F$ normed spaces and $f:A\rightarrow\mathbb{R}$, $g:A\rightarrow F$, with $A$ open set in $E$, and defined $h:A\rightarrow F$ by $h(x)=f(x)g(x)$.  Suppose that $f$ es differentiable in $a\in A$, $f(a)=0$, and  that $g$ is continuos at $a$. Prove that $h$ es differentiable at  $a$, with $Dh(a)=g(a)Df(a)$.
Comment: \begin{eqnarray*}
% \nonumber to remove numbering (before each equation)
   && ||h(x)-h(a)-(g(a)Df(a))(x-a)||\\
     &=& ||f(x)g(x)-f(a)g(a)-(g(a)Df(a))(x-a)-g(x)Df(a)(x-a)+g(x)Df(a)(x-a)|| \\
   &=&  ||Df(a)(x-a)(g(x)-g(a))+g(x)[f(x)-f(a)-Df(a)(x-a)]||\\
   &\leq&  ||Df(a)(x-a)||\,||(g(x)-g(a))||+||g(x)||\,||f(x)-f(a)-Df(a)(x-a)||
\end{eqnarray*}
Comment: @Christopher I was trying the above but the last inequality is not true and that I can not do.
Answer: Expanding on your last line, which seems okay to me.

I use the operator norm, denoted $|||\cdot |||$. $Df(a)$ has a norm since it is a continous linear map. So $||Df(a)(x-a)||\,||(g(x)-g(a))|| \leq |||Df(a)|||\,||(x-a)||\,||(g(x)-g(a))||$
$g$ being continous, it is locally bounded around $a$, so (locally) $||g(x)||\,||f(x)-f(a)-Df(a)(x-a)|| \leq C\,||f(x)-f(a)-Df(a)(x-a)||$.

So we can divide by $||(x-a)||$ and get $$\begin{align}\frac{||h(x)-h(a)-Dh(a)(x-a)||}{||x-a||} \leq &|||Df(a)|||\,||g(x)-g(a)|| \\&+ C\frac{||f(x)-f(a)-Df(a)(x-a)||}{||x-a||}\end{align}$$.
When $x\to a$ , the first term goes to zero because $|||Df(a)|||$ is a constant and $g$ is continous, and the second term goes to zero because of the differentiability of $f$.
Comment: you could write your arguments with other notation than that of the "or" is that I'm not quite understand that notation. I'd appreciate it.
Comment: What notation do you use ? $y(x) = y(a) + Dy(a)(x-a) + \cdots$. What goes in the $\cdots$ ???
Comment: $f:E\to F$ is differentiable in $c$ iff $$\lim_{x\to c}\frac{||f(x)-f(c)-Df(c)(x-c)||}{||x-c||}=0$$
Comment: all right, I will edit.
Comment: Justt the following second inequality is not true right? $$||Df(a)(x-a)(g(x)-g(a))+g(x)[f(x)-f(a)-Df(a)(x-a)]||\leq  ||Df(a)(x-a)(g(x)-g(a))||+||g(x)[f(x)-f(a)-Df(a)(x-a)]||\leq||Df(a)(x-a)||\,||(g(x)-g(a))||+||g(x)||\,||f(x)-f(a)-Df(a)(x-a)||$$ that was the problem in my proof
Comment: Yes, actually, all the terms concerning $f$ are real numbers, so the second axiom of a norm allows them to "get out" as absolute values.
Comment: $Df(a)(x-a)\in \mathbb{R}$?
Comment: Yes ! Since $f:A\to \mathbb{R}$, $Df(a) : A \to \mathbb{R}$.
Comment: Thanks justt...excuse my abuse could help me with this exercise http://math.stackexchange.com/questions/431059/differentiable-function-in-the-normed-space-mathcalc0-1 is that not quite understand the solution they gave me
Comment: Explain in a comment of that answer what part precisely you didn't understand.
Comment: when say The proof that
$$f(x+h)-f(x)= Df_x(h) +o(\|h\|)\tag2$$
is consecuence of the fact that $1/\sqrt{|x|}$ is also in $\mathcal C[0,1]$.


Proving convergence of $\int_0^\infty e^{-y} dy$

Question: Let $f\colon \mathbb{R}\to\mathbb{R}$ be defined as
$
\begin{equation}
  f(x)=\left\{
  \begin{array}{@{}ll@{}}
    xe^{-x^{2}}, & \text{if}\  x\geq0 \\
    0, & \text{if}\  x <0.  \\
  \end{array}\right.
\end{equation}
$
$\int_{\mathbb{R}} f \;\mathrm{dμ} =  \frac{1}{2}\int_{0}^\infty e^{-y} dy = \frac{1}{2}$, but does this integral converge at all? How can I justify the change of variable in this improper integral?

I was given a hint that monotone converging sequence I can use is $f_n = xe^{-x^2} \cdot I_{[0,n]}$. Why is the following correct
$$\ \int_{\mathbb{R}} f \;\mathrm{dμ} = \lim_{n \to \infty } \int_0^\infty f_n  dx =\lim_{n \to \infty } \int_0^n xe^{-x^{2}}  dx $$
Answer: Let $$f_n(x)=xe^{-x^2} \cdot I_{[0,n]}(x)$$ (where $I_A(x)=1$ if $x\in A$ and $0$ otherwise).
Note that $0\leq f_n(x)\leq f_{n+1}(x)$ and that $f_n \to f$ pointwise. Now, use the monotone convergence theorem.


Constantly check for object value and end process if false

Question: I'm building a control system for a machine with Node on a raspberry pi. There are certain processes that need to stop immediately if one of the safety relays opens. So, I need to checking every 100ms id the safety relays are open, and if they are, send a signal to stop running certain functions.
In general, there will be several functions that need to stop if Relays.allClosed becomes false.

var Relays = {
  relay1: false,
  relay2: false,
  allClosed: false,
  checkRelays: function() {
    if (this.relay1 == true && this.relay2 == true) {
      this.allClosed = true
    } else {
      this.allClosed = false
      console.warn("relay open")
    }
  }
}

var safetyCheck = function() { //checks if safety relays are all closed every 100 ms
  setInterval(function() {
    Relays.checkRelays()
  }, 100)
}

safetyCheck()

Machine.run = function(distance) {
  if (Relays.allClosed) { //checks before running the process if the relays are all closed for safety
    // if at any point while running this Relays.allClosed becomes false, function needs to stop running
    setTimeout(function() {
      console.log('advancing press');
      i++;
      if (i < distance) {
        pressLoop();
      }
    }, 1000)
  } else {
    console.log("can't run machine because one or more safety relay is open")
  }
}
Comment: Why not just emit an event `realyOpened` and then wait for it? And idlf that is really a "safety relay" i would not write the code in JS.
Comment: `setTimeout` only fires once, you maybe want `setInterval` instead.
Comment: How do you update `Relays.relay1` / `2` when the state of the physical hardware changes?
Comment: @JonasWilms can you elaborate on both points? emit sounds right but I would need to see an example, thanks
Comment: @Keith yeah, but the solution Jonas mentions is much more efficient and good as a principle.
Comment: What is `//...some stuff` ? Could you add a small sample?
Comment: @JonasWilms added sample, @Jamiec haven't gotten that far yet, but going to be using the `onoff` package: https://www.npmjs.com/package/onoff
Comment: What about a setter approach? Something like: `set relay({ index, value }) { this[\`relay${index}\`] = value; this.check(); }` and then you would call: `Relays.relay = { index: 1, value: true };`
Answer: What you should be doing is using something like EventEmitter to emit an event when something meaningful happens. This could be a change in state of your allClosed value (although I'd argue that your method of continually polling for a changed relay state is an anti-pattern and you should be used event-based logic throughout).
But in any case, assuming an allClosed event is raised you can capture that event and stop your running code:
Machine.run = function(distance) {
  if (Relays.allClosed) { //checks before running the process if the relays are all closed for safety
    // if at any point while running this Relays.allClosed becomes false, function needs to stop running
    let timer = setTimeout(function() {
      console.log('advancing press');
      i++;
      if (i < distance) {
        pressLoop();
      }
    }, 1000);

    myEventEmitter.on("allClosed", () => {
       clearTimeout(timer);
    })
  } else {
    console.log("can't run machine because one or more safety relay is open")
  }
}

This will cancel at the next iteration, but if pressLoop is in any way long-running, you should provision for stopping that midway too.

The below code illustrates (with buttons in place of physical relays) how you can run the whole thing a series of events.

// just jQuery for mockup - ignore
  $('.relay').on("click", function () {
      $(this).toggleClass("open").toggleClass("closed");
      events.emit("relayChanged", {id:$(this).data("id"), isClosed: $(this).is(".closed")})
  })

  function RelayMonitor(){
      var relaysClosed = {
         "1": true,
         "2": true
      }

      this.init = function(events){
        events.on("relayChanged", (args) => {
            relaysClosed[args.id] = args.isClosed;
            if(Object.values(relaysClosed).every(x => x)) {
                events.emit("allClosed");
            }
        });
      }
  }

  //const EventEmitter = require('events'); // included as cdn import here
  var events = new EventEmitter();
  events.on("allClosed", () => console.log("all relays closed"));
var monitor = new RelayMonitor()
monitor.init(events);
.closed {
background-color:green
}

.open {
background-color:red
}

<button data-id="1" class="relay closed">Relay1</button>
<button data-id="2" class="relay closed">Relay2</button>
Answer: You should go with an event based structure instead like:
  const EventEmitter = require('events');

  const input = new EventEmitter();

Through that, you can emit events as:
 relay1.watch((err, value) => input.emit("relay1", !!value));

That way, you can attach a callback to the relay at multiple positions:
 input.on("relay1", on => console.log(on));

Now to get another event when all relays are on its as easy as:
 let relaysCount = 0;
 function updateCount(on) {
   if(on) {
     relaysCount++;
     if(relaysCount === 2)
       input.emit("allOn");
   } else {
     relaysCount--;
     input.emit("someOff");
  }
 }

 input.on("relay1", updateCount);
 input.on("relay2", updateCount);

Now when starting a timeout like in your example, you can easily cancel that if some are Off:
 input.on("allOn", () => {
    const task = setTimeout(/* sth */, 1000);
    input.on("someOff", () => clearTimeout(task));
 });

Comment: Any alternative to `watch` since it has been deprecated?
Comment: Can you share a link?
Comment: @chuckieDub the link you sent?
Comment: I didn't send a link. When I search 'watch' in the docs all I can find is fs.watch https://nodejs.org/docs/latest/api/fs.html
Comment: ah gotcha :) makes sense now


How to make a JavaScript library which can work with Browser, NodeJS and Single Page Applications (React etc.)

Question: So what I want to ask is: Is there a way to convert this simple file into a library which can work with Browsers (script tag), Node JS and Single Page Applications using single codebase?
Until now, all I have been doing was using libraries but it never came to my mind that it isn't actually that simple to make one. I am working on a React application where I created a simple helper file with exports. I thought "why not make it an independent library in NPM?". Just as I started testing it independently in NodeJS environment, I came to realize that there is actually a lot of difference in the way both environments make imports.
I have slight knowledge of Webpack, but I don't know how to approach it. Would I need different codes for different environments?
Another thing that confused me was when I thought about "How do we actually import things/functions from libraries?" Like when we install any library from NPM INSTALL and we do "import { abc } from 'library'", does it look for an index.js file in the library folder or what? Or in case of Node, "let lib = require('library')", where it does it look since its a different environment than SPA?
In conclusion, I have a simple single file I want to launch in NPM as a library which could work in any environment.
Answer: This is a very broad question, so a very broad answer: Look at tools like webpack, rollup, and browserify which are often used to make Node.js things available in the browser.
Another possibility is to look at how a module like slug is coded such that it works in the browser and in Node.js, but requires some hacks (and a decent test setup) to do it. For example, it checks typeof window !== 'undefined' to switch between code that needs to run in the browser vs. code that needs to run in Node.js. And this bit at the end detects the module system being used and acts accordingly:
  if (typeof define !== 'undefined' && define.amd) { // AMD
    define([], function () { return slug })
  } else if (typeof module !== 'undefined' && module.exports) { // CommonJS
    module.exports = slug
  } else { // Script tag
    root.slug = slug
  }

Comment: After some searching, it seems that webpack use the same strategy if I make a UMD output? I also found that UMD + ES file output can be used. And mentioning UMD file as "main" and ES file as "module" in package.json will make everything work. I am yet to test it though. I am more directed toward webpack because I am more familiar with it. Is what everything I said correct?
Comment: So I used webpack to generate UMD file, and it is working in node and browser. I think I am going in the right direction now. Thanks.


Fourier Coefficients Of $\cos x$

Question:
Find the Fourier coefficients of $
f(x)=
\begin{cases}
\cos x,   \pi >x\geq 0\\
-\cos x, -\pi<x<0 \\
\end{cases}
$

When $x\in (-\pi,\pi)$

What is the value of the series at $x=0$
does the series of coefficients absolute convergent?

So we have
$a_0=\frac{1}{\pi}\int _{-\pi}^{\pi}f(x)dx$
$a_n=\frac{1}{\pi}\int _{-\pi}^{\pi}f(x)\cos(nx)dx$
$b_n=\frac{1}{\pi}\int _{-\pi}^{\pi}f(x)\sin(nx)dx$
We have that for $-\pi<x<0$ the function $f(x)$ is odd, while for $0<x<\pi$ the function $f(x)$ is even.
$a_0=\frac{1}{\pi}\int _{-\pi}^{\pi}f(x)dx=\frac{1}{\pi}\int _{-\pi}^{0}-\cos xdx+\frac{1}{\pi}\int _{0}^{\pi}\cos xdx=\frac{1}{\pi}(-sinx|^{0}_{-\pi}+\sin x|^{\pi}_0)=\\=\frac{1}{\pi}(-0+0+0-0)=0$
$a_n=\frac{1}{\pi}\int _{-\pi}^{\pi}f(x)\cos(nx)dx=\frac{1}{\pi}\int _{-\pi}^{0}-\cos x\cos(nx)dx+\frac{1}{\pi}\int _{0}^{\pi}\cos x\cos(nx)dx$
Using $\cos \alpha*\cos \beta=\frac{1}{2}(cos(\alpha+\beta)+\cos(\alpha-\beta))$ we get
$$\frac{1}{\pi}\int _{-\pi}^{0}-\cos x\cos(nx)dx+\frac{1}{\pi}\int _{0}^{\pi}\cos x\cos(nx)dx=\\=-\frac{1}{2\pi}\int _{-\pi}^{0}\cos((n+1)x)+\cos((n-1)x)dx+\frac{1}{2\pi}\int _{0}^{\pi}\cos((n+1)x)+\cos((n-1)x)dx=\\=-\frac{1}{2\pi}[\frac{sin ((n-1)x)}{n-1}+\frac{sin ((n+1)x)}{n+1}]_{-\pi}^{0}+\frac{1}{2\pi}[\frac{sin ((n-1)x)}{n-1}+\frac{sin ((n+1)x)}{n+1}]_{0}^{\pi}$$
But $\sin(0)=\sin(k\pi)=0$ for all $k\in \mathbb{N}$
So $a_n=0$
$$b_n=\frac{1}{\pi}\int _{-\pi}^{0}-\cos x\sin(nx)dx+\frac{1}{\pi}\int _{0}^{\pi}\cos x\sin(nx)dx=\\=-\frac{1}{\pi}\int _{-\pi}^{0}\cos x\sin(nx)dx+\frac{1}{\pi}\int _{0}^{\pi}\cos x\sin(nx)dx$$
Using $\sin (\alpha)*\cos (\beta)=\frac{1}{2}(\sin(\alpha+\beta)+\sin(\alpha-\beta))$
$$=-\frac{1}{\pi}\int _{-\pi}^{0}\cos x\sin(nx)dx+\frac{1}{\pi}\int _{0}^{\pi}\cos x\sin(nx)dx=\\=-\frac{1}{2 \pi}\int _{-\pi}^{0}\sin((n+1)x)+\sin((n-1)x)dx+\frac{1}{2 \pi}\int _{0}^{\pi}\sin((n+1)x)+\sin((n-1)x)dx=\\=\frac{1}{2 \pi}[\frac{\cos((n+1)x)}{n+1}+\frac{\cos((n-1)x)}{n-1}]_{-\pi}^0-\frac{1}{2 \pi}[\frac{\cos((n+1)x)}{n+1}+\frac{\cos((n-1)x)}{n-1}]_{0}^{\pi}=\\= \frac{1}{2\pi}(\frac{1}{n+1}+\frac{1}{n-1}-(\frac{(-1)^n}{n+1}+\frac{(-1)^n}{n-1}))-\frac{1}{2\pi}(\frac{(-1)^n}{n+1}+\frac{(-1)^n}{n-1}-\frac{1}{n+1}-\frac{1}{n-1})=\frac{2n}{\pi(n^2-1)}-\frac{2n(-1)^n}{\pi(n^2-1)}$$

Because we are left only with $f(x)~b_n\ sin(nx)$ at $x=0$ we have $f(x)~0$
Can we say that

$$\mid\sum\frac{2n}{\pi(n^2-1)}-\frac{2n(-1)^n}{\pi(n^2-1)}\mid\sim\sum\frac{2}{n}$$ which does not converge
Are the answers corrects? can we do the calculations shorter?
Comment: I'll try not to be harsh but: "The function is odd when $x$ is [in a certain subdomain]" makes no sense. The function either is or is not odd. In this case it is because $f(-x)=-f(x)$.

Now that you know that the function is odd , you can use the formula for the coefficients of an odd function.

The rest I haven't checked. Sorry.
Comment: The function is odd then $a_n=0$ for $n\geq0$.
Answer: There seems to be a minor mistake as $[\cos((n+1)x]_0^\pi=(-1)^{n{ \color{red}{+1}}}-1$ (and the same for $n-1$). But the rest of the calculation seems correct.
You can do the calculation shorter by noticing that $\tilde{f}$ is odd  (as a remark being odd or even is a global property of a function, a function cannot be odd on an interval), where $\tilde{f}(x)=f(x)$ for $x \neq 0$ and $\tilde{f}(0)0$.
As $\tilde{f}=f$ almost everywhere these two functions have the same Fourier coeeficients so $a_n=0$, $\forall n \geq 0$.
And using once again the fact that $\tilde{f}$ is odd you have
$$b_n= 2 \frac{1}{\pi} \int_0^\pi \cos(x) \sin(nx) dx = \frac{2}{\pi} \frac{n(1+(-1)^n)}{n^2-1}$$
The points 2 and 3 are also corrects.
Comment: To find the value of the series at $x=0$ you can indeed use Dirichlet or as you have said simply use the fact that $\sin(n0)=0$ to obtain 0.
Comment: It seems that using Dirichlet you will have $\frac{\cos(0)+(-\cos(0))}{2}=0$. Am I missing something ?
Comment: Do we need to use Dirichlet to find $f(0)$?
Comment: using Dirichlet we will get $\frac{cos(0)+cos(0)}{2}=1$

Fourier Coefficients Of $\cos x$


Regex for only numbers in square brackets

Question: I want to check if all square brackets contain only numbers, commas, and dashes inside them. How to do that?
For example:
fsf[sdff0977sf0]sda[989,-]  not ok
fsf[,,--9770-,875]sda[989,-]  ok
Comment: which language are you running?
Comment: And did you try anything yourself?
Comment: java, I tryed something like this:.*\[[0-9[^0-9]]\].*
I am really new in this stuff so i have no good ideas
Comment: @roma, always a good idea to include your original code, even if it doesn't work, even if you are not quite sure what you're doing. Otherwise it looks like you haven't tried anything and are just using StackOverflow as a problem-solving/code-writing service.
Answer: I don't know which language you are using. Here is a grep solution:
$ grep -Eo '\[([0-9]|,|-)+\]' file.txt
[989,-]
[,,--9770-,875]
[989,-]

Answer: In java you can use this pattern with the matches method:
[^\\[]*(?:\\[[0-9,-]*][^\\[]*)*+

that checks from start to end of the string if all parts in square brackets contains only digits, commas and hypens.
note: According to your requirements, the string and the content inside square brackets can be empty. However I assume that all opened square brackets are closed, and that square brackets are not nested.
fiddle
Comment: they are all closed and not nested
Answer: I would also propose something very near to heemayl's answer. In JavaScript:
var pattern = /\[[0-9,-]+\]/g;

You can play around with it here : http://regexr.com/3ajek
Now, the only problem here is that in your example the first line should be detected as "not ok" because it contains a block of brackets with invalid data. As you can see on the regexr.com example above, it will not match. But the other block of brackets on that line will match. So if you want to validate all the line, you'll have to loop on each match of bracket blocks and then check that it contains valid data. If one of the bracket block doesn't contain valid data then all the line is invalid.
Not really sure to know what you are trying to validate as we haven't got the full context of your code.
Answer: You might try something like this:
^(?!.*\[[^\]]*[^0-9\],-][^\]]*\])

See Regex 101 Demo here.
Here I am asserting that the above pattern can't be found in the string. The above pattern is an opening square bracket [ followed by any number of characters that are not closing square brackets ], followed by one character that is none of: number 0-9, closing square bracket, comma, or dash, followed (again) by any number of characters that are not closing square brackets, followed by a closing square bracket.


How can the Panels IPE "add content" modal be customized?

Question: I have a content type rendered via Panels IPE (In Place Editor) which allows authenticated users to customize the layout of their node. When users click to "add content" I would like to be able to control what appears in the modal dialogue. By default it is not very user friendly:

Ideally I would like to be able to choose what can be added, for example only "nodes", or only "views" and "widgets". I'm not sure where this can be changed or if a module exists that does this already. The only module I have found that attempts to do this is Panopoly Magic which requires an entire suite of modules called Panopoly to be installed. I don't need the majority of the functionality that Panopoly adds and hence I don't think it is a very light solution. Here is the result that can be achieved:

Is there a way the IPE add content modal can be customized?
Answer: You can do that for all panels pages from
admin/structure/panels/settings/panel-page

Also if you use panelizer you can customize what appear in IPE for every content type.
admin/structure/types/manage/[content-type]/panelizer
Also you can install panopoly_magic module without other panopoly features, only the module "panopoly_magic.info" since it does not deponent on any thing in panopoly distribution.


Change page background on click to match color of clicked page element using javascript

Question: I am following the tutorial here https://projects.raspberrypi.org/en/projects/cd-beginner-javascript-sushi/8 to make a guess the color game. The last part is a challenge to change the page background when the correct color is guessed. I've managed to change the background but it only returns the color of the last button on the page, not the correct button. Here is a codepen to demonstrate: https://codepen.io/nicdaslick/pen/QWbogQQ.
I understand what's happening, but not how to fix it. The code is inside a for loop but the suggestion in the challenge hints is to change the color inside the for loop. How do I grab the right colors or am I thinking about this wrong?
html:

Guess the colour!

        <button class="colourButton"></button>
        <button class="colourButton"></button>
        <button class="colourButton"></button>
        <button class="colourButton"></button>
        <button class="colourButton"></button>
        <button class="colourButton"></button>

<button id="resetButton">Reset game</button>

css:
.colourButton{
    background-color: rgb(255,0,0);
    width: 50px;
    height: 50px;
    border: none;
    border-radius: 50%;
    box-shadow: none;
    margin: 10px;
}

#buttonWrapper{
    width: 100%;
    display: flex;
    flex-wrap: wrap;
    justify-content: space-around;
    margin: 0 auto;
}

h1{
    text-align: center;
}

#colourValue{
    margin: 0 auto;
    text-align: center;
}

#answer{
    margin: 0 auto;
    text-align: center;
}

#reset{
    margin: 0 auto;
    text-align: center;
}

#reset-button{
    padding: 10px;
    background: none;
    border: 1px solid #000;
    margin: 10px;
}

js:
function makeColourValue(){
  return Math.round(Math.random()*255);
}

function setButtonColour(button, red, green, blue) {
  button.setAttribute(
    'style',
    'background-color: rgb('+ red +','+ green +','+ blue +');'
  );
}

var buttons = document.getElementsByClassName('colourButton');

var heading = document.getElementById('colourValue');

var answerMessage = document.getElementById('answer');

function startGame() {
  answerMessage.innerHTML = "";
  var answerButton = Math.round(Math.random() * (buttons.length - 1));

  for(var i = 0; i < buttons.length; i++) {
    var red = makeColourValue();
    var green = makeColourValue();
    var blue = makeColourValue();

    setButtonColour(buttons[i], red, green, blue);

    if (i === answerButton) {
      heading.innerHTML =`(${red}, ${green}, ${blue})`;
    }

    buttons[i].addEventListener('click', function(){
      if (this === buttons[answerButton]) {
        answerMessage.innerHTML = "Correct!";
        document.body.style.backgroundColor = 'rgb('+ red +','+ green+','+ blue+')';
      } else {
        answerMessage.innerHTML = "Wrong answer! Guess again!";
      }
    });
  }
}

startGame();

document.getElementById('resetButton').addEventListener('click', startGame);

Comment: That's better to use element.style.backgroudColor than append then attribute
Answer: One problem is your use of var instead of let or const.
When you declare a variable with var, it makes a function-scoped variable, no matter where you declare it. Therefore, inside your for loop, red, green, and blue all refer to the same values for each iteration of the loop, rather that you having a distinct value per loop iteration. Think of these variables as being hoisted and declared in the top of your startGame function.
Changing those to const or let should make the variables block-scoped, so they'll exist within the scope of the for loop. This will allow your event listeners which are also declared within the loop to close over unique values per iteration.
I would implore you to never use var ever again; it has no redeeming qualities over what let or const provide other than allowing your code to run in ancient browsers.
Answer: You can pass the event object to your function. Then access the style with event.target.style
buttons[i].addEventListener('click', function(event){
      if (this === buttons[answerButton]) {
        answerMessage.innerHTML = "Correct!";
        document.body.style.backgroundColor = event.target.style.backgroundColor
      } else {
        answerMessage.innerHTML = "Wrong answer! Guess again!";
      }
})


Routing from LAN into OpenVPN

Question: I need to set up a route from our local network into our VPN.
That is, anybody from inside the LAN should be able to communicate with machines in the VPN, without being a VPN client itself. Problem is, I'm somewhat of a dummy when it comes to networks...
The local network has an 8-bit range, 192.168.2.X
The VPN server itself is in another network, on 192.168.3.20 (8-bit)
The VPN network has a 16-bit range, 10.8.X.X
The eth0 interface of the machine running the openvpn server has a static IP at 192.168.3.20.
The tun0 interface of the vpn server itself listens to 10.8.0.1
What we have already working is that packets to 10.8.x.x in the local network get rerouted to the server:
traceroute to 10.8.0.1 (10.8.0.1), 30 hops max, 60 byte packets
 1  gateway (192.168.2.1)  2.508 ms  2.364 ms  2.325 ms
 2  10.8.0.1 (10.8.0.1)  1.898 ms  1.895 ms  1.911 ms

So I can already ssh into it over 10.8.0.1, that's fine.
However, when I try to get to a client in VPN, the result is quite a bit different:
traceroute to 10.8.0.178 (10.8.0.178), 30 hops max, 60 byte packets
 1  gateway (192.168.2.1)  2.315 ms  2.152 ms  2.036 ms
 2  192.168.3.20 (192.168.3.20)  1.764 ms  1.760 ms  1.776 ms
 3  * * *
etc...

What bugs me a bit about that is that a direct request to the server terminates at 10.8.0.1, while I would have expected it to either not work, or terminate at 192.168.3.20. So obviously I don't understand too much of what's going on here...
Going from there, I thought I could solve the issue by forwarding traffic coming in on eth0 to tun0:
sudo iptables -A FORWARD -i eth0 -o tun0 -d 10.8.0.0/16 -j ACCEPT

But that didn't have any effect. And that's pretty much where I'm stuck. I tried a few variations of the above, and played around with route in the OpenVPN config, all without any visible change.
What is interesting though is that the trace activity actually shows up in the
*VPN log, but I don't understand much of what's going on here either:
Fri Oct 19 11:57:53 2018 us=219532 GET INST BY VIRT: 10.8.0.158 -> y18022c/22.214.171.124:1194 via 10.8.0.158
Fri Oct 19 11:57:53 2018 us=219539 y18022c/18.104.22.168:1194 TUN READ [60]
Fri Oct 19 11:57:53 2018 us=219544 y18022c/220.127.116.11:1194 TLS: tls_pre_encrypt: key_id=0
Fri Oct 19 11:57:53 2018 us=219555 y18022c/22.214.171.124:1194 ENCRYPT IV: 14c0471a 9fe7860f
Fri Oct 19 11:57:53 2018 us=219580 y18022c/126.96.36.199:1194 ENCRYPT FROM: 000000ae fa450000 3cac0400 000b1135 5ec0a803 010a0800 9e98b682 bf00282[more...]
Fri Oct 19 11:57:53 2018 us=219612 y18022c/126.96.36.199:1194 ENCRYPT TO: 14c0471a 9fe7860f 00bbfc72 b50c8915 8390d362 82f0a84c c22803b1 2a7ceca[more...]
Fri Oct 19 11:57:53 2018 us=219622 PO_CTL rwflags=0x0002 ev=4 arg=0x5654a4302150
Fri Oct 19 11:57:53 2018 us=219629 PO_CTL rwflags=0x0000 ev=5 arg=0x5654a4302068
Fri Oct 19 11:57:53 2018 us=219637 I/O WAIT Tr|Tw|Sr|SW [0/63574]
Fri Oct 19 11:57:53 2018 us=219646 PO_WAIT[0,0] fd=4 rev=0x00000004 rwflags=0x0002 arg=0x5654a4302150
Fri Oct 19 11:57:53 2018 us=219652  event_wait returned 1
Fri Oct 19 11:57:53 2018 us=219658 I/O WAIT status=0x0002
Fri Oct 19 11:57:53 2018 us=219696 y18022c/188.8.131.52:1194 UDPv4 WRITE [101] to [AF_INET]126.96.36.199:1194: P_DATA_V1 kid=0 DATA c15dc78e ddd12705 8c3a860c 9cd9fe1e da29c4b2 14c0471a 9fe7860f 00bbfc7[more...]
Fri Oct 19 11:57:53 2018 us=219707 y18022c/220.127.116.11:1194 UDPv4 write returned 101
Fri Oct 19 11:57:53 2018 us=219715 PO_CTL rwflags=0x0001 ev=4 arg=0x5654a4302150
Fri Oct 19 11:57:53 2018 us=219722 PO_CTL rwflags=0x0001 ev=5 arg=0x5654a4302068
Fri Oct 19 11:57:53 2018 us=219730 I/O WAIT TR|Tw|SR|Sw [0/63574]
Fri Oct 19 11:57:53 2018 us=231770 PO_WAIT[0,0] fd=4 rev=0x00000001 rwflags=0x0001 arg=0x5654a4302150
Fri Oct 19 11:57:53 2018 us=231782  event_wait returned 1
Fri Oct 19 11:57:53 2018 us=231789 I/O WAIT status=0x0001
Fri Oct 19 11:57:53 2018 us=231799 UDPv4 read returned 53
Fri Oct 19 11:57:53 2018 us=231809 GET INST BY REAL: 18.104.22.168:1194 [succeeded]
Fri Oct 19 11:57:53 2018 us=231837 y18022c/126.96.36.199:1194 UDPv4 READ [53] from [AF_INET]220.127.116.11:1194: P_DATA_V1 kid=0 DATA 1196c495 845bb7fd e61cc8d8 ed4d427a b901d6c8 e81fe5a9 3ab1acce b5687f0[more...]
Fri Oct 19 11:57:53 2018 us=231846 y18022c/18.104.22.168:1194 TLS: tls_pre_decrypt, key_id=0, IP=[AF_INET]220.127.116.11:1194
Fri Oct 19 11:57:53 2018 us=231859 y18022c/18.104.22.168:1194 DECRYPT IV: e81fe5a9 3ab1acce
Fri Oct 19 11:57:53 2018 us=231876 y18022c/220.127.116.11:1194 DECRYPT TO: 00000036 fa2a187b f3641eb4 cb07ed2d 0a981fc7 48
Fri Oct 19 11:57:53 2018 us=231897 y18022c/220.127.116.11:1194 PID_TEST [0] [SSL-0] [>EEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEE] 0:53 0:54 t=1539943073[0] r=[0,64,15,0,1] sl=[11,53,64,528]
Fri Oct 19 11:57:53 2018 us=231905 y18022c/184.108.40.206:1194 RECEIVED PING PACKET*

My biggest problem is really that I have no idea what exactly is going on here... Why is a request to 10.8.0.1 not routed through 192.168.3.20? I mean, it would be logical that it has to go through the actual server before terminating at the VPN...? And when requests are arriving at eth0 (as is evident by 192.168.3.20 showing up in the trace), why aren't they forwarded to tun0? Is openVPN itself blocking something here?
Answer: I've insufficient points to comment but I'd like to know how you have 192.168.2.X and 192.168.3.X connected?
At a guess what you need is to push the routes for 192.168.3.X back to the other end of the VPN.
In the /etc/openvpn/server.conf add the route to 192.168.2.X:
(You probably already have the 192.168.3.X network in there)
# /etc/openvpn/server.conf
# Router Subnet
route 192.168.3.0 255.255.255.0
push "route 192.168.3.0 255.255.255.0"
# The other local Subnet that you need to tell the far end about
route 192.168.2.0 255.255.255.0
push "route 192.168.2.0 255.255.255.0"

Now provided that the the local vpn server is the default gateway for the LAN each side should be able to route to the other.
Is this what you mean?
Comment: Wow! Put your suggestion in the server config, tried, and it just works. Thanks a lot from me and my Boss! :) Concerning the connection between .2 and .3, that's handled by a forwarding rule in our firewall. I guess my major error was to assume that I didn't have to push the route to the clients, because the server should handle the forwarding. And quite honestly, I'm still not sure why the clients need to know the route too...
Comment: Glad to help ;-)
Comment: The ping comes in to the far end of the VPN and is marked as coming from 192.168.2.x If it doesnt have a specific route for 192.168.2.0/24 it will send the reply down default route, which is usually the internet router, not the VPN.

Routing from LAN into OpenVPN


How to find the area of a triangle with lengths of heights?

Question: Given the lengths of 3 heights in a triangle, I need to find its area.
Comment: Use Heron's formula
Comment: @i.m.soloveichik: Heron's formula is for three side lengths, not for three heights. You need the [area theorem](http://en.wikipedia.org/wiki/Altitude_(triangle)#Area_theorem).
Comment: @i.m.soloveichik 3 heights, not 3 sides
Comment: http://mathforum.org/library/drmath/view/61893.html
Answer: Since $h_A=\frac{2\Delta}{a}$, by Heron's formula we have:
$$\small\frac{1}{\Delta}=\sqrt{\left(\frac{1}{h_A}+\frac{1}{h_B}+\frac{1}{h_C}\right)\left(-\frac{1}{h_A}+\frac{1}{h_B}+\frac{1}{h_C}\right)\left(\frac{1}{h_A}-\frac{1}{h_B}+\frac{1}{h_C}\right)\left(\frac{1}{h_A}+\frac{1}{h_B}-\frac{1}{h_C}\right)}.$$
Comment: There is mistake somewhere. I can't get right values out of it.
Comment: @nazar554: it looks perfectly fine to me. What's wrong with that? It comes straight from the Heron's formula (http://en.wikipedia.org/wiki/Heron%27s_formula) and the substitution $a=\frac{2\Delta}{h_A}$.
Answer: You know that base times height gives you area. Let the triangle have sides $a,\ b$ and $c$ with corresponding altitudes $h_a,\ h_b,\ h_c$. Then
$$ah_a = bh_b = ch_c = 2A$$
where $A$ is the area of the triangle. Substitute these relations into Heron's formula and solve for $A$.
Edit: I didn't know the resulting formula had a name, but apparently as joriki mentions, it is the area theorem.
Answer: $$
t=area, x=ha, y=hb, z=hc
$$
$$
t=\frac{x^2*y^2*z^2}{\sqrt{(xy+yz+zx)(-xy+yz+zx)(xy-yz+zx)(xy+yz-zx)}}
$$
or
$$
t=\frac{1}{\sqrt{\frac{2}{x^2*y^2}+\frac{2}{y^2*z^2}+\frac{2}{z^2*x^2}-\frac{1}{x^4}-\frac{1}{y^4}-\frac{1}{z^4}}}
$$
Use TrianCal.esy.es (Triangle Calculator) Example: http://triancal.esy.es/?lang=en&tip=2&x=45&y=60&z=36


Cannot setup floating action buttons as class cannot be found (Android Studio)

Question: So I am pretty new to android and I am trying to setup a floating action button with the Android Design Support Library using this guide in Android Studio.
My Project: Noted build.gradle file:
// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
    repositories {
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:1.2.3'

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        jcenter()
    }
}

My Module: app build.gradle file:
apply plugin: 'com.android.application'

android {
    compileSdkVersion 22
    buildToolsVersion "22.0.1"

    defaultConfig {
        applicationId "com.example.noted"
        minSdkVersion 21
        targetSdkVersion 22
        versionCode 1
        versionName "1.0"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    compile 'com.android.support:appcompat-v7:22.2.0'
    compile 'com.android.support:support-v4:22.2.0'
    compile 'com.android.support:design:22.2.0'
}

In myactivity_main.xml I try to implement
<android.support.design.widget.FloatingActionButton
    ... />

but I get one of those Rendering Problems pop ups after building saying:
The following classes could not be found:
  -android.support.design.widget.FloatingActionButton
My guess is that I'm doing something wrong with my dependencies but I really have no idea. I have been trying to get this to work for hours with no luck and would really appreciate any help.
Thanks!
Comment: Have you installed the latest versions of the "Android Support Repository" and "Android Support Library" in the Extras section of the Android SDK manager?
Comment: @SamDozor Yes I believe so. SDK manager under extras it says I have Rev 15 ASRepository and Rev 22.2 ASLibrary.
Comment: Can you resolve `FloatingActionButton` in your code? If you can, it must be an XML issue, not a dependency issue.
Comment: @SamDozor I am not getting an error or anything in the activity_main.xml, only when clicking on the design tab I get the "Rendering Problems" notification. I can see the ``android:src="@android:drawable/ic_input_add"`` on the rendering screen but no background.
Comment: Notice that this FloatingActionButton doesn't work on API 21 & higher. See this post for more information: http://stackoverflow.com/a/30609927/3922207
Comment: @AnggrayudiH Could you explain why it doesn't work on API 21 and higher? Your linked post only shows an alternative. Why would Google release the Android Design Support Library for all Android 2.1 or higher devices but exclude their most recent release (Lollipop)?
Comment: The FloatingActionButton will be displayed as rectangle image, instead of circle. So you need that class which provided by Google on Github. If you don't believe me, test it on Lollipop emulator.
Comment: @AnggrayudiH That doesn't fix my problem of the class not being found. Thanks for the tip though!
Comment: have you done setContentView() for activity or inflater.inflate for fragment for the xml in which you are trying to put the floating button?
Answer: You need the Library design, in the build.gradle file add:
compile 'com.android.support:appcompat-v7:25.1.1'
compile 'com.android.support:design:25.1.1'

Then Sync the Gradle, build and Reresh
Answer: I had the same issue and updated the Android Support Repository", "Android Support Library"(22.2.1) and "Android SDK Tool"(24.1.2) using SDK manager now its working fine. Once update finish rebuild the project. For more https://developer.android.com/tools/support-library/setup.html
Comment: Check the build tool version in gradle file. Make sure you have the latest tool added on it. I am using "com.android.tools.build:gradle:1.2.3"
Comment: Unfortunately that didn't fix the issue.
Comment: Tnx @NiroshanChandrawijayakumar. That was really helpful for me.
Answer: I have been facing this problem recently and tried to change dependencies version, invalidating caches and restart, etc. The preview rendered once and then reopening my xml file, it raised the same error.
Clicking on the refresh button at the preview window solved to me (momentarily) the problem, letting me see the layout and its elements properly.
Answer: The latest version of Android Studio 3.1.2 seems to not like compile in build.gradle file. Instead I used implementation and it worked fine.
implementation 'com.android.support:design:27.1.1'

Answer: If you are using androidx, you need to use:

implementation 'com.google.android.material:material:1.2.1'

(or whatever latest version you want).
The action button in the XML looks like:
    <com.google.android.material.floatingactionbutton.FloatingActionButton
        android:id="@+id/delete_buttom"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintBottom_toBottomOf="parent"
        android:layout_margin="20dp"
        android:src="@drawable/ic_baseline_delete_24px" />

Answer: I had the same problem with Android Studio complaining that it couldn't instantiate FloatingActionButton.  The "Exception Details" showed this:
java.lang.IllegalArgumentException: You need to use a Theme.AppCompat theme (or descendant) with the design library.
    at android.support.design.widget.ThemeUtils.checkAppCompatTheme(ThemeUtils.java:33)
    at android.support.design.widget.FloatingActionButton.<init>(FloatingActionButton.java:159)
    at android.support.design.widget.FloatingActionButton.<init>(FloatingActionButton.java:153)

Basically, I was using Material.Light as my theme, but I needed to use an AppCompat theme.  I switched to AppCompat.Light and the problem was solved!
Answer: I had the same issue and could solve it this way : https://stackoverflow.com/a/59211828/12337593


Prove: For a harmonic function $u$, $|z|^{1-\epsilon}|u(x,y,z)| \leq (x^2+y^2)^{0.5-\epsilon}$ implies $u = 0$ for $0 < \epsilon < 0.5$

Question: Prove: For a harmonic function $u: \mathbb{R}^3 \rightarrow \mathbb{R}$, if for all $(x,y,z) \in \mathbb{R}^3$ $|z|^{1-\epsilon}|u(x,y,z)| \leq (x^2+y^2)^{0.5-\epsilon}$ then $u = 0$ for $0 < \epsilon < 0.5$.
I'm pretty sure that this can be proved with the mean value theorem for harmonic functions over spheres starting with the point $(0,0,0)$ and then showing that the proof can be done for any point.
I tried using spherical coordinates to show that the integral over a sphere has to be $o(R^3)$ for a sphere with a radius of $R$, but I'm having a bit of trouble showing that the integral converges and I would appreciate any help.
Comment: Do you want absolute values on u in the inequality?
Comment: Yes, I'll edit that in, thanks.
Answer: Probably, my answer is not that strict; but I hope it'll give you some useful idea.
Let us rewrite our condition in the form:
$$
|u(x,y,z)|\leq\frac{(x^2+y^2)^{0.5-\epsilon}}{|z|^{1-\epsilon}}.\tag 1
$$
Let us consider some ray starting at $(0,0,0)$. We will evaluate right-hand side (RHS) of $(1)$ along this ray as $r\to\infty$. $x=\alpha r$, $y=\beta r$, $z=\gamma r$. $\alpha,\beta,\gamma=\mathrm{const}$, $r\to\infty$.
$$
x\propto r,~~y\propto r;~~x^2\propto r^2;~~y^2\propto r^2;~~ x^2+y^2\propto r^2
\\
(x^2+y^2)^{0.5-\epsilon}\propto r^{1-2\epsilon}
\\
z\propto r;~~ |z|\propto r^{1-\epsilon}
\\
\mathrm{RHS}\propto r^{-\epsilon}\propto \frac{1}{r^\epsilon}
$$
For any $0<\epsilon<0.5$ RHS decays at $r\to\infty$ faster, than just a constant $\propto r^0$. Our $u(x,y,z)$ should as well decay along this ray not slower than $r^0$.
The general expression for the harmonic function is
$$
u(r,\theta,\varphi)=\sum_{l=0}^\infty\sum_{m=-l}^{l}(A_lr^l+B_lr^{-l-1})Y_l^m(\theta,\varphi).\tag 2
$$
(see Eq. (20) here http://mathworld.wolfram.com/LaplacesEquationSphericalCoordinates.html)
I suppose, that we consider only $u(x,y,z)$, that are finite at $(0,0,0)$. So we may disregard $r^{-l-1}$ terms in $(2)$. Our $u(x,y,z)$ should decay at $r\to\infty$ faster that $r^0$, so all $r^l$ terms in $(2)$ also vanish. The only opportunity for $u(x,y,z)$ is to be zero. Spherical functions $Y_l^m(\theta,\varphi)$ should not cause any trouble here.


Getting errors trying to embed tweets using markup (not using api)

Question: We are using a cms, where we are storing data about tweets. Since all the data already exists in our db (when people save tweets into it), there is absolutely no reason to use the api to embed tweets, but rather use the twitter supplied js file that loops through all embeds on a page.
However, although the dynamically generated markup from our cms is almost identical and it works with the twitter js file, (check this codepen http://codepen.io/anon/pen/pyyKdL) in our cms i get the error that tweetId is required. However, i am not using the api at all, i just generate the markup with handlebars (since the data is there....).
code from codepen:

    Support your local record shop & pick up the Reapers 7" on @recordstoreday on 16 April https://t.co/lgniyAJk3c pic.twitter.com/usqrRdW8Bz

— muse (@muse) March 8, 2016

Any ideas?
Answer: It seems the twitter script for embedding all markup tweets on a page WILL NOT RUN locally for some reason, all while getting a completely unrelated error (tweetId is not present). Fixed by getting all files to a staging environment (usually the second step, once something works locally).


How to make windows authentication work in IIS?

Question: I am building an ASP.NET MVC intranet app for my organization and want to get the network user name. I have the following in my Web.config
<system.web>
     <authentication mode="Windows"> </authentication>
     <authorization>
        <allow users="*"/>
        <deny users="?"/>
     </authorization>

When I am debugging with IIS Express, Request.LogonUserIdentity.Name gives my windows username.
However, when in deploy my app on IIS, Request.LogonUserIdentity.Name is coming as "NT AUTHORITY\IUSR" instead of the windows username.
In IIS, for my app, I have enabled just Windows Authentication and disabled other types of authentication.
What change do I need to make in IIS so that Request.LogonUserIdentity.Name gives the logged in windows username?
Comment: What happens if you remove the allow element?
Answer: Find any guide from Microsoft at Google, and they will tell you that you forgot to enable Windows authentication on IIS and disable anonymous authentication.
Comment: @Khyron Do you know IIS at all? Seeing IUSR means anonymous authentication is on, and how can this be not the answer?
Comment: This answer is not relevant given information stated in the question.
Comment: Ironically, that's a better answer.
Comment: @Lex Li No, as I said in the question, Windows Authentication is enabled and all other authentication disabled.
Comment: Thanks, I missed to turn off anonynous authentication for the "Web Site". I only turned it off for the Application.


How can I make a Dynamic Dropdown in WordPress using wp job board pro plugin?

Question: Certainly! I'm using the wp job board pro plugin on my WordPress site and need assistance creating a form exclusively within this plugin. Despite searching through various Google articles and ChatGPT resources, I couldn't find a reliable guide. While I understand the concept of conditional fields, the plugin lacks an option to define conditions. Specifically, I want to implement a dropdown functionality where selecting a country in the first dropdown dynamically updates the second dropdown with corresponding states. For instance, if I choose India in the first dropdown, the second dropdown should display states like West Bengal. Can you guide me on achieving this?
given options are
I am expecting to get dynamic dropdown using wp job board pro plugin in WordPress
Comment: This question needs some code. See [how to ask a good question](https://stackoverflow.com/help/how-to-ask).
Answer: A: Most dynamic dropdown plugins are designed to be compatible with a wide range of themes, but it's advisable to check the plugin documentation for specific compatibility information, look for more
Answer: Understand WP Job Board Pro Custom Fields:
WP Job Board Pro allows you to create custom fields for your job listings. You'll utilize this feature to create the dynamic dropdown.
Create a Custom Field:
Go to your WordPress admin dashboard and navigate to "WP Job Board" > "Settings" > "Custom Fields". Create a new custom field of type "Dropdown".
Implement a Dynamic Dropdown:
To make the dropdown dynamic, you'll need to populate its options dynamically based on some criteria. For example, let's say you want to populate the dropdown with a list of countries.
Utilize a Callback Function:
You can use a callback function to dynamically generate the options for the dropdown. Here's an example of how you might do this:
function populate_country_dropdown_options(){

    $countries = array(
        array(
            'value' => 'CAN',
            'description' => 'Canada'
        ),
        array(
            'value' => 'PK',
            'description' => 'Pakistan'
        ),
        array(
            'value' => 'US',
            'description' => 'United States'
        ),
    );

       return $countries;
}


Jquery accordion disable further clicks on slidedown

Question: I am new to jquery and I have implemented an accordion which slidesdown depending on the "clicked" div and other div slidesup. However, once a div is slidedown I dont want any more click events to be fired on it.How do I achieve this?
I have many divs like the one below -

First accordion

jquery:
$(document).ready(function() {
$('.content').hide();
$('.trigger').click(function() {
$('.content').slideUp("fast");                                                                                $('.trigger').not(this).children('.head').children('.image').attr('src','help_arrowUp.png')
$(this).siblings('.content').slideDown('normal');
$(this).children('.head').children('.image').attr('src', 'help_arrowDown.png');
});
});

Appreciate any help. Thank You.:)
Answer: $('.content').not(this).slideUp("fast");
$(this).slideDown('normal');

use it like this
Comment: what you have mentioned is similar to what I am doing currently. I want to disable any more click events on a div when it is already slid down i.e, the currently selected div on slidedown, must not respond to any more click events on the same current div.


Show that the arc length integral is continuous in $C^1$

Question: I came across this question and I am not sure how to prove it.
Show that the arc length integral is continuous in $C^1$.
Comment: Could you be a little more specific? The $C^1$ norm on what exactly? Presumably the space $C^1([a,b], \Omega)$ where $\Omega \subset \mathbb R^n$?
Comment: I assume you tried to write down $\operatorname{length}(\gamma_1)-\operatorname{length}(\gamma_2)$ as the difference of two integrals? Which can be combined into integral of the difference? Where the integrand somewhat resembles the expression we see in the Mean Value theorem?
Comment: Unfortunately I didn't have room in my schedule to take a calculus of variations so I have been teaching it to myself and found this question in a textbook. I mean the norm commonly used in C^1 which measures the size of the function and its derivative
Answer: Let $f,g$ be two $C^1$ functions on $[a,b]$.
We have
$$
\sqrt{1+f'^2}-\sqrt{1+g'^2}=\frac{f'^2-g'^2}{\sqrt{1+f'^2}+\sqrt{1+g'^2}}.
$$
So
$$
|\sqrt{1+f'^2(x)}-\sqrt{1+g'^2(x)}|\leq\frac{|f'^2(x)-g'^2(x)|}{2}\leq\frac{|f'(x)-g'(x)|(|f'(x)|+|g'(x)|)}{2}
$$
for all $x\in(a,b)$.
Now fix $f$ and take $g$ such that $\|g'-f'\|_\infty\leq 1$. Then $\|g'\|_\infty\leq 1+\|f'\|_\infty$, so
$$
|\sqrt{1+f'^2(x)}-\sqrt{1+g'^2(x)}|\leq\frac{(1+2\|f'\|_\infty)}{2}\|f'-g'\|_\infty
$$
for all $x\in(a,b)$.
Denote
$$
I(f):=\int_a^b\sqrt{1+f'^2(x)}dx
$$
the arclength function.
We have, with $f$ and $g$ as above,
$$
|I(f)-I(g)|\leq \frac{(b-a)(1+2\|f'\|_\infty)}{2}\|f'-g'\|_\infty.
$$
So $I(f)$ is locally Lipschitz with respect to $\|f'\|_\infty$. A fortiori, with respect to the usual $C^1$ norm $\|f\|_\infty+\|f'\|_\infty$.
Hence it is continuous at $f$ for all $f$ in $C^1$.


How to convert multi nested object into multidimensional array using javascript?

Question: Current format:
{
  "SD": {
    "Key": "SD",
    "City": "San Diego",
    "Name": "Padres"
  },
  "WSH": {
    "Key": "WSH",
    "City": "Washington",
    "Name": "Nationals"
  }
}

Expected format:
[
  {
    "Key": "SD",
    "City": "San Diego",
    "Name": "Padres"
  },
  {
    "Key": "WSH",
    "City": "Washington",
    "Name": "Nationals"
  }
]

Answer: You can do that with Object.values(...) which makes an array out of all the values from your object:

const obj = {
  "SD": {
    "Key": "SD",
    "City": "San Diego",
    "Name": "Padres"
  },
  "WSH": {
    "Key": "WSH",
    "City": "Washington",
    "Name": "Nationals"
  }
}

console.log(Object.values(obj));
Answer: It looks like Object.values is the answer, you can use it like this.
Object.values(your_object)

And it will return your expected format, here is the documentation on how it works if you would like to read further.
Object.values Documentation


Unexpected else

Question: I am grappling with the error:
unexpected 'else' (T_ELSE) i
My code is:

<?php if(!empty($custarea)){ ?>

     Minimum Order Amount -
     <?php
        echo $areaMinAmt;
     ?>

    <?php} ?>
    <?php else { ?>

        Choose area to know min delivery amount

    <?php }?>

What am I doing wrong?
Answer: youre missing a bracket because youve forgotton a space after your opening php tag.
If  you template with php, use the non-bracket technique as follows.  Its much easier to debug:

    <?php if ( !empty( $custarea ) ): ?>

            Minimum Order Amount -
            <?php
            echo $areaMinAmt;
            ?>

    <?php else: ?>

            Choose area to know min delivery amount

    <?php endif; ?>

Answer:

<?php if(!($custarea)){ ?>

     Minimum Order Amount -
     <?php
        echo $areaMinAmt;
     ?>

    <?php   }  else { ?>

        Choose area to know min delivery amount

    <?php }?>

Unexpected else


Complementary events and conditioning

Question: If we have two events, $A$ and $B$, it is sure that
$$P(A\mid B) + P(A^C\mid B) = 1$$
However, it seems me that
$P(A\mid B) + P(A \mid B^C) = 1$ is false in general
I don't remember why it is so. How can this fact be explained in the simplest way?
Comment: Draw a Venn diagram and contemplate it briefly.
Comment: Consider the case where A is the proposition "true", which always has a probability of 100%. Consider the case where it is instead the proposition "false", which always has a probability of 0%. So your sum can have a value anywhere from 0 to 2.
Comment: Think carefully about A="I win the lottery", B = "it rains the day I buy the ticket", for both the first and second scenario.
Answer: All you need is just one counterexample.
Consider $\Omega = \{1, 2, 3\}$ with $P(\{1\}) = P(\{2\}) = P(\{3\}) = \frac{1}{3}$, $A = \{1, 2\}, B = \{2, 3\}$, then
\begin{align}
& P(A|B) = \frac{P(\{2\})}{P(\{2, 3\})} = \frac{1/3}{2/3} = \frac{1}{2}, \\
& P(A|B^c) = \frac{P(\{1\})}{P(\{1\})} = \frac{1/3}{1/3} = 1,
\end{align}
which results in $P(A|B) + P(A|B^c) = \frac{3}{2} > 1$.
Another more extreme counterexample is for any sample space $\Omega$, take $A = \Omega$, and $B$ be any event with $0 < P(B) < 1$, then $P(A|B) + P(A|B^c) = 1 + 1 = 2 > 1$.

More in-depth analysis:  As you used the notation $P(A|B)$ and $P(A|B^c)$, which are meaningless unless $0 < P(B) < 1$, it can be assumed that $0 < P(B) < 1$. Under this condition,
\begin{align}
& P(A|B) + P(A|B^c) = \frac{P(A \cap B)}{P(B)} + \frac{P(A \cap B^c)}{P(B^c)} = 1 \tag{$*$}
\end{align}
if and only if
\begin{align}
P(A \cap B)P(B^c) + P(A \cap B^c)P(B) = P(B)P(B^c). \tag{1}
\end{align}
If $P(B) = \frac{1}{2}$, then $(1)$ implies $P(A) = \frac{1}{2}$.  Hence for any event $A$ whose probability is not $\frac{1}{2}$, the statement $(*)$ is false.
If $P(B) \neq \frac{1}{2}$, let $p := \max(P(B), P(B^c))$. Hence the left-hand side of $(1)$ is bounded above by $pP(A)$ and below by $(1 - p)P(A)$, $(1)$ thus implies that $pP(A) \geq p(1 - p) \geq (1 - p)P(A)$ or $P(A) \in [1 - p, p]$, which means that for any event $A$ whose probability is outside $[p, 1 - p]$, $(*)$ is false.
$(*)$ is not always false, of course. For example, if $\Omega = A \cup B$, $A \cap B = \varnothing$, then $A = B^c$, whence
\begin{align}
P(A|B) + P(A|B^c) = P(A|B^c) = \frac{P(B^c)}{P(B^c)} = 1.
\end{align}
Answer: The conditional probability that you don't have red hair, given that you are male, is more than $0.9.$
The conditional probability that you don't have red hair, give that you are not male, is more than $0.9.$
The sum of those two probabilities is not $1.$
Answer: To see why $P(A\mid B) + P(A \mid B^C) = 1$ is not generally true, consider the case where $A$ is always guaranteed to happen, regardless of what happens with $B$. Then both $P(A \mid B)$ and $P(A \mid B^{C})$ are equal to $1$, so you obtain $2=1$.

Complementary events and conditioning


How to make whole screen scrollable in Flutter?

Question: I have an issue with the whole screen scrolling in Flutter. Only the Expanded widget is able to scroll on-screen in my app but I want to make the whole screen scrollable. How can I do that? Here is my code e.g.
Widget build(BuildContext context) {
  return Scaffold(
    key: scaffoldKey,
    backgroundColor: Colors.white,
    appBar: AppBar(
      title: Text(
        'My App',
        style: AppTheme.of(context).title1,
      ),
      elevation: 0,
      backgroundColor: Colors.amber,
    ),
    body: Column(
      mainAxisSize: MainAxisSize.max,
      children: [
        Padding(
          padding: EdgeInsetsDirectional.fromSTEB(10, 20, 10, 0),
          child: Column(

        . // Padding repeats two more times
        .
        .
        .

        Expanded(
            child: MyWidget(
                myProp1: value1,
                myProp2: value2,
                myProp3: value3,
                myProp4: value4,
                myProp5: value5,
                myProp6: value6
            ) // MyWidget
        ), // Expanded
      ],
    ), // Column
  ); // Scaffold
}

I've tried to wrap Column with SingleChildScrollview widget but it didn't work for me. I guess I can not use Expanded widget in SingleChildScrollview. I also tried to use Container or etc. instead of Expanded and Column widgets but I couldn't solve this issue. Can anybody help me with it?
Answer: There is no need to wrap MyWidget with Expanded. Just Change Column into ListView:
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      appBar: AppBar(
        title: Text(
          'My App',
        ),
        elevation: 0,
        backgroundColor: Colors.amber,
      ),
      body: ListView(
        children: [
          Padding(
              padding: EdgeInsetsDirectional.fromSTEB(10, 20, 10, 0),
              child: Column(
                children: [
                  Padding(
                    padding: const EdgeInsets.all(8.0),
                    child: Container(
                      height: 500,
                      decoration: BoxDecoration(color: Colors.black),
                    ),
                  ),
                  Padding(
                    padding: const EdgeInsets.all(8.0),
                    child: Container(
                      height: 500,
                      decoration: BoxDecoration(color: Colors.black),
                    ),
                  )
                ],
              ))
        ],
      ), // Column
    ); // Scaffold
  }

Comment: Thanks, it works. I changed `Column` into `ListView` and I wrap `MyWidget` with only `SizedBox`. If I use **MyWidget** without **SizedBox** even though I changed **Column** into **ListView** I'm getting this error:
`RenderFlex children have non-zero flex but incoming height constraints are unbounded.`
Comment: It's bit hard to understand since I dont know content of the MyWidget but possible reason is Column expects his height to be given by its parent. So you either specify it by giving SizedBox or wrap it by Expanded to show that it can expand any available space it wants to
Answer: You also can use the SingleChildScroll view as Child of Expanded widget will work fine


Select by month

Question: I have a dateframe with a date field called datum
df['datum'].iloc[0]
Out[58]: datetime.datetime(2016, 5, 2, 2, 0, tzinfo=psycopg2.tz.FixedOffsetTimezone(offset=120, name=None))

type(df['datum'].iloc[0])
Out[59]: datetime.datetime

I want to select rows with a month <= 6:
df.loc[df['datum'].dt.month <= 6]
AttributeError: Can only use .dt accessor with datetimelike values

But all rows are datetimes?
df['datum'] = df['datum'].apply(pd.to_datetime, errors='raise')

no error.
Answer: It seems there are object datetimes, so for converting to Timestamps need:
print (df['datum'].dtype)
object

df['datum'] = pd.to_datetime(df['datum'], utc=True)

df.loc[df['datum'].dt.month <= 6]

Select by month


Windows Server 2019 VMware VM shutting down itself

Question: This Windows Server VM is under host Esxi version 7.0 update 3. It's a DB server, hence quite critical in production.
Some points that I need to make:

The event occurs randomly (non specific days and times), with a rate of 2-3 times per week.  The machine shuts down and never boots back up again. Someone has to do it manually.

Known errors are logged by Windows during start-up, but apparently have nothing to do with the cause of the shutdown itself. These are errors 307 and 304.

Passing to what is logged by the host (esxi), I quote below what has been logged at vmware logs repeatedly:

2023-01-18T19:52:14.697Z In(05) vmx - TOOLS autoupgrade protocol version 0
2023-01-18T19:52:14.735Z In(05) vmx - ToolsGetAppInfoEnabledFromConfigStore: Returning the cached value: '1'.
2023-01-18T19:52:14.758Z In(05) vmx - GuestRpc: Got error for channel 0 connection 4: Remote disconnected
2023-01-18T19:52:14.758Z In(05) vmx - GuestRpc: GuestRpcResetVsockChannel: channel 0
2023-01-18T19:52:14.758Z In(05) vmx - GuestRpc: Closing channel 0 connection 4
2023-01-18T19:52:14.758Z In(05) vcpu-1 - GuestRpc: Reinitializing Channel 0(toolbox)
2023-01-18T19:52:14.758Z In(05) vcpu-1 - Tools: [AppStatus] Last heartbeat value 111591 (last received 0s ago)
2023-01-18T19:52:14.758Z In(05) vcpu-1 - TOOLS: appName=toolbox, oldStatus=1, status=0, guestInitiated=1.
2023-01-18T19:52:23.626Z In(05) vcpu-0 - CDROM: Unknown command 0x35.
2023-01-18T19:52:23.626Z In(05) vcpu-0 - CDROM sata0:0: CMD 0x35 (SYNC CACHE) FAILED (key 0x5 asc 0x20 ascq 0)
2023-01-18T19:52:23.980Z In(05) vcpu-1 - E1000: e1000e-- tx queue 1 is enabled.
2023-01-18T19:52:23.981Z In(05) vcpu-2 - CDROM-IMG:  Ignoring a Unit Start or Stop
2023-01-18T19:52:26.045Z In(05) vcpu-3 - PCIXHCI: Interrupt type changed from MSIX to INTX
2023-01-18T19:52:26.724Z In(05) vcpu-0 - PIIX4: PM Soft Off.  Good-bye.
2023-01-18T19:52:26.724Z In(05) vcpu-0 - Chipset: The guest has requested that the virtual machine be powered off.
2023-01-18T19:52:26.724Z No(00) vcpu-0 - ConfigDB: Setting softPowerOff = "TRUE"
2023-01-18T19:52:26.728Z In(05) vcpu-0 - VMX: Issuing power-off request...
2023-01-18T19:52:26.728Z In(05) vmx - Stopping VCPU threads...
2023-01-18T19:52:26.728Z In(05) vcpu-0 - VMMon_WaitForExit: vcpu-0: worldID=1638402
2023-01-18T19:52:26.728Z In(05) vcpu-2 - VMMon_WaitForExit: vcpu-2: worldID=1638407
2023-01-18T19:52:26.728Z In(05) vcpu-1 - VMMon_WaitForExit: vcpu-1: worldID=1638406
2023-01-18T19:52:26.728Z In(05) vcpu-3 - VMMon_WaitForExit: vcpu-3: worldID=1638408

That line lead us to suspect it is a windows related problem:

2023-01-18T19:52:26.724Z In(05) vcpu-0 - Chipset: The guest has requested that the virtual machine be powered off

Licensing status is activated. Moreover, we have checked that the power management settings are ok (the machine doesnt enter to sleep mode).
Maybe, some update did that?
Any ideas what to look for or how to troubleshoot this please?
Answer: Check the System event log in the Windows guest machine.
If there really was an unclean shutdown, you will find event ID 41.
Otherwise, you will find event ID 1074, which should give you some information about who or what requested the shutdown.
Comment: Hi, as I mention above, only 304 and 307 errors are logged in windows event viewer.
Comment: This is not possible. You should see either an event 1074 during a clean shutdown, or an event 41 when the system boots after an unclean shutdown.
Comment: See also here for other event IDs to check: https://www.shellhacks.com/windows-shutdown-reboot-event-ids-get-logs.
Comment: Hi @Massimo!
You were RIGHT! I turns out I wasn't looking at the correct events.


Selecting an additional empty row that does not exist

Question:
Possible Duplicate:
Include a blank row in query results

I would like to add an empty row to my result set at the very top of my SQL query.
The query I am using is this:
SELECT
    PROFILETITLE, DOCID
FROM
    PROFILES
WHERE
    COMPANYCODE = ?
ORDER BY
    PROFILETITLE

Comment: What is an empty row? Assuming that `DOCID` is an `int`, define empty for an integer.
Comment: Oh, I am sorry - an row that gives an blank result for that row.
Answer: Try to use union all
SELECT null as PROFILETITLE, null as DOCID
UNION ALL
SELECT PROFILETITLE, DOCID
FROM PROFILES
WHERE COMPANYCODE=?
ORDER BY PROFILETITLE

but if you wont to add header, and if DOCID  is int type, you have to use union all and cast as below
SELECT 'PROFILETITLE' as PROFILETITLE, 'DOCID' as DOCID
UNION ALL
SELECT PROFILETITLE, CAST ( DOCID AS varchar(30) )
FROM PROFILES
WHERE COMPANYCODE=?
ORDER BY PROFILETITLE

Answer: Try this:
SELECT '' AS PROFILETITLE, 0 AS DOCID
UNION ALL
SELECT PROFILETITLE, DOCID
FROM PROFILES WHERE COMPANYCODE = ?
ORDER BY PROFILETITLE

Note that when using UNION, and all other set operations, columns have to be matched in types, So you have to alias the first two empty values with PROFILETITLE and DOCID. And you have to watch out the types of the two columns as well to be matched in order to work properly. May be you need to select NULL instead of '' and 0.
Comment: yes: [SQL-Fiddle test](http://sqlfiddle.com/#!3/3144b/3)
Answer: You could add an "empty row" if all columns are varchar and empty means '' in this way:
SELECT PROFILETITLE, DOCID
FROM PROFILES
WHERE ...

UNION ALL

SELECT '' AS PROFILETITLE, '' AS DOCID

ORDER BY
  CASE WHEN PROFILETITLE='' AND DOCID='' THEN 0 ELSE 1 END ASC
, PROFILETITLE ASC

Answer: You can use SQL Union
SELECT PROFILETITLE, DOCID
FROM PROFILES
WHERE COMPANYCODE=? ORDER BY PROFILETITLE
UNION ALL
SELECT 0, ''
FROM SYSIBM.SYSDUMMY1

You can replace SYSIBM.SYSDUMMY1 with your temporary table
Answer: a union all would do the job
SELECT
'' as PROFILETITLE,
'' as DOCID
UNION ALL
SELECT PROFILETITLE, DOCID
FROM PROFILES
WHERE COMPANYCODE=? ORDER BY PROFILETITLE


Add value to a custom composite element in webform via hook_update_N

Question: Testing out some bits with webform. I have created a webform via my module. In it I have a number of elements including a custom composite. Inside the custom composite I have several elements, one is a select element with a list of options (i.e. allowed values).
Now comes time I need to do some updates. That is run hook_update_N on an existing module/set-up.  I have updates for all other fields (not webform) working correctly. Rough code shown below:
<code>/**
  * Update for mymodule to add more options to the paragraph and webform custom composite.
  */
 function mymodule_update_8001() {
   // Updates the paragraph allowed field
   $fields = \Drupal::entityTypeManager()->getStorage('field_storage_config')->loadByProperties(array('field_name' => 'myfield'));

   foreach ($fields as $field) {
     $allowed = $field->getSetting('allowed_values');

     // New value(s) to add here.
     $allowed['test'] = 'bob was here...';
     $field->setSetting('allowed_values', $allowed);
     $field->save();
   }

   // Code to update the custom composite element to go here.

 }
</code>
I know it is rough code, ignoring that, still getting my head around the changes to Webform too.  I know the \Drupal::entityTypeManager()->getStorage method doesn't work for webform composite custom elements and can't see any update function in the composite example module.
So the question is how to I get the options (allowed values) of a select in a custom composite from the webform so I can edit, add, update, etc... when I do other updates to my module?
The method noted in How do I programmatically update the allowed values of a list field? works for basic fields but with for dynamic options. It will not cover what I need here as (a) it is not performing an update of existing fields and (b) doesn't appear to work with custom composite in WebForm, or at least I cannot get it to work, with a select.
Comment: Possible duplicate of [How do I programmatically update the allowed values of a list field?](https://drupal.stackexchange.com/questions/242006/how-do-i-programmatically-update-the-allowed-values-of-a-list-field)
Comment: That is doing dynamic allowed list, it doesn't appear to work with custom composite elements on Webforms.
Comment: Breaking this down into steps - `$webform = \Drupal::entityTypeManager()->getStorage('webform')->load('webform id');` gets the webform, `$elements = $webform->getElement('element id');` gets the composite component. Now how do you get the element of that component and set the options? Will report back once got that bit figured out.
Answer: After trawling through the Webform source think I have an answer.
<code>/**
 * Update using hook_update_N for mymodule to add more options to a webform custom composite.
 */

function mymodule_update_8001() {

    . . .

    // Update a composite element in a webform
    $webform = \Drupal::entityTypeManager()->getStorage('webform')->load('webform_id');
    $elements = $webform->getElementsDecodedAndFlattened();

    // Add new options here.
    $elements['my_composite_id']['#element']['my_composite_element_id']['#options']['my_new_option'] = 'My new option text';

    $webform->setElements($elements);
    $webform->save();

    . . .

}
</code>
Please let me know if there is a better way.