Cronômetro Regressivo Completo em JS Puro - Contagem Problemática

Question: Gente, estou criando um cronômetro regressivo acompanhado dos botões (iniciar, pausar, resetar, reiniciar e salvar tempo) sendo que o tempo inicial é definido num input também.
Procurei diversas vezes em diversas postagens no pt.stackoverflow e em outros fóruns da internet, achei no máximo cronômetros regressivos, mas não com as mesmas funcionalidades e apesar de ter tentado adaptar não consegui. Em nosso fórum só se encontra perguntas parecidas, mas a linguagem não é a mesma e quando é (js puro), a finalidade é muito diferente.
Meu código está com problema de contagem, já observei problemas quando são mais que 10 minutos ou menos que 1. Gostaria de uma resolução em JS Puro! Observe o código:
Javascript
    function transporta(mensagem){
            var docsetmin = document.getElementById('setminutos');
            var docsetsec = document.getElementById('setsegundos');
            var docrestamin = document.getElementById('restamin');
            var docrestasec = document.getElementById('restasec');

            if(docsetsec.value <= 59){
                docrestamin.value = docsetmin.value;
                docrestasec.value = docsetsec.value;
                setTimeout(cronometro, 1000, 'start');
            }
            else{
                alert('Há problemas com o tempo configurado!');
            }

        }

        function cronometro(option, message){

            var docsetmin = document.getElementById('setminutos');
            var docsetsec = document.getElementById('setsegundos');
            var docrestamin = document.getElementById('restamin');
            var docrestasec = document.getElementById('restasec');
            var docsetminval = docsetmin.value;
            var docsetsecval = docsetsec.value;
            var docrestaminval = docrestamin.value;
            var docrestasecval = docrestasec.value;

            if(option == 'start'){
                start(message);
            }
            if(option == 'pause'){
                docrestamin.placeholder = docrestamin.value;
                docrestasec.placeholder = docrestasec.value;
                alert('Cronômetro Pausado');
                docrestamin.value = '--';
                docrestasec.value = '--';
                document.getElementById('paused').innerHTML = 'Pausado em: ' + docrestamin.placeholder + ':' + docrestasec.placeholder + '.';
            }
            if(option == 'reset'){
                docsetmin.value = '00';
                docsetsec.value = '00';
                docrestamin.value = '00';
                docrestasec.value = '00';
                docrestamin.placeholder = '';
                docrestasec.placeholder = '';
                docsetmin.placeholder = '';
                docsetsec.placeholder = '';
            }
            if(option == 'resume'){
                document.getElementById('paused').innerHTML = '';
                docrestamin.value = docrestamin.placeholder;
                docrestasec.value = docrestasec.placeholder;
                cronometro('start', message);
            }
            if(option == 'save'){
                alert(docsetmin.value + ':' + docsetsec.value);
            }
        }

        function start(alerta){

            var docsetmin = document.getElementById('setminutos');
            var docsetsec = document.getElementById('setsegundos');
            var docrestamin = document.getElementById('restamin');
            var docrestasec = document.getElementById('restasec');

            /* Se for mais que 10 minutos */
            if(docrestamin.value > 10){

                /* Se for mais que 10 segundos */
                if((docrestasec.value <= 59) && (docrestasec.value > 10)){
                    docrestasec.value = docrestasec.value - 1;
                    setTimeout(start, 1000);
                }

                /* Se for menor ou igual a 10 segundos e mais que 0 segundos */
                if((docrestasec.value <= 10) && (docrestasec.value > 0)){
                    var ts = docrestasec.value - 1;
                    docrestasec.value = '0' + ts;
                    setTimeout(start, 1000, 'start');
                }

                /* Se for menor ou igual a 0 segundos */
                if(docrestasec.value <= 0){
                    docrestasec.value = '59';
                    docrestamin.value = docrestamin.value - 1;
                    setTimeout(start, 1000, 'start');
                }
            }

            /* Se for menor ou igual a 10 minutos e mais que 0 minutos */
            if((docrestamin.value <= 10) && (docrestamin.value > 0)){

                /* Se for mais que 10 segundos */
                if((docrestasec.value > 10) && (docrestasec.value <= 59)){
                    docrestasec.value = docrestasec.value - 1;
                    setTimeout(start, 1000, 'start');
                }

                /* Se for menor ou igual a 10 segundos e mais que 0 segundos */
                if(docrestasec.value <= 10 && docrestasec.value > 0){
                    var ts = docrestasec.value - 1;
                    docrestasec.value = '0' + ts;
                    setTimeout(start, 1000, 'start');
                }

                /* Se for menor ou igual a 0 segundos */
                if(docrestasec.value <= 0){
                    var tm = docrestamin.value - 1;
                    docrestamin.value = '0' + tm;
                    docrestasec.value = 59;
                    setTimeout(start, 1000, 'start');
                }
            }

            /* Se for menor ou igual a 0 minutos */
            if(docrestamin.value <= 0){

                /* Se for mais que 10 segundos */
                if((docrestasec.value <= 59) && (docrestasec.value > 10)){
                    docrestasec.value = docrestasec.value - 1;
                    setTimeout(start, 1000, 'start');
                }

                /* Se for menor ou igual a 10 segundos e mais que 0 segundos */
                if((docrestasec.value <= 10) && (docrestasec.value > 0)){
                    var ts = docrestasec.value - 1;
                    docrestasec.value = '0' + ts;
                    setTimeout(start, 1000, 'start');
                }

                /* Se for menor ou igual a 0 segundos */
                if(docrestasec.value <= 0){
                    if((docrestamin.value = '00') && (docrestasec.value = '00')){
                        alert('O tempo acabou!');
                    }
                }
            }
        }

        function Onlynumbers(){
            var tecla = event.keyCode;
            if((tecla >= "48") && (tecla <= "57") && (tecla = "186")){
                return true;
            }
            else{
                return false;
            }
        }

CSS3
    body{padding: 20%;}
        header{text-align: center;}
        section{align-items: center; justify-content: center; display: flex; vertical-align: middle;}
        .btn{color: black; border: none; background-color: white; margin-left: 0.5%; margin-right: 0.5%; text-align: center;}
        .border{border: 1px solid black;}
        .border{transition: background-color 0.4s ease-in 0.2s; transition: color 0.01s ease-in;}
        .border:hover{background-color: #1397D4; color: white;}

HTML

Cronômetro Regressivo

        <input placeholder="m" class="btn" id="setminutos" type="text" name="minutos" size="2" maxlength="2" onkeypress="return Onlynumbers()">
        :
        <input placeholder="s" class="btn" id="setsegundos" maxlength="2" type="text" name="segundos" size="2" onkeypress="return Onlynumbers()">
            <button id="comece" class="btn border" type="button" onclick="transporta()">Iniciar</button>
            <button class="btn border" onclick="cronometro('pause');">Pausar</button>
            <button class="btn border" onclick="cronometro('reset')">Resetar</button>
            <button class="btn border" onclick="cronometro('resume')">Reiniciar</button>
            <button class="btn border" onclick="cronometro('save')">Salvar Tempo</button>

                <input class="btn dnone" id="restamin" type="text" name="minutosresta" size="2" maxlength="2" onkeypress="return Onlynumbers()">

:

                <input class="btn dnone" id="restasec" maxlength="2" type="text" name="segundosresta" size="2" onkeypress="return Onlynumbers()">

Answer: segue codigo html, css e javascript. copie o codigo em tres arquivos separados e faça a modificação a seu gosto:

var configMinuto;
var configSegundo;
var mostrarValor;
var evento = null;
var contador = null;
var minuto = 0;
var segundo = 0;

function IniciarCronometro(valor){
 this.evento = valor;
 this.configMinuto = document.getElementById('min').value;
 this.configSegundo = document.getElementById('seg').value;
 this.mostrarValor = document.getElementById('mostrarValor');

 if (evento=="start"){
  if(!document.getElementById('min').readOnly){
   if(!this.validarNumero(this.configMinuto)){
    alert("Campo minuto não é um número!");
    return;
   }
   if(!this.validarNumero(this.configSegundo) || document.getElementById('seg').value > 59){
    alert("Campo segundo não é um número válido (0 a 59)!");
    return;
   }

   document.getElementById('min').readOnly = true;
   document.getElementById('seg').readOnly = true;
   document.getElementById('btnIniciar').disabled  = true;
   document.getElementById('btnResetar').disabled  = false;
   document.getElementById('btnPausar').disabled  = false;
   this.minuto = document.getElementById('min').value;
   this.segundo = document.getElementById('seg').value;

   document.getElementById('mostrarValor').classList.remove('mostrarValor');
   document.getElementById('mostrarValor').classList.add('mostrarValor2');
   document.getElementById('exibe').classList.remove('Classexibe');
   document.getElementById('exibe').classList.add('Classexibe2');

  }else{
   if(this.segundo == 0 && this.minuto != 0){
    this.segundo = 59;
    this.minuto--;
   }else{
    this.segundo--;
   }
   if(this.minuto == 0 && this.segundo == 0){
    document.getElementById('min').readOnly = false;
    document.getElementById('seg').readOnly = false;
    document.getElementById('btnIniciar').disabled  = false;
    document.getElementById('btnResetar').disabled  = true;
    document.getElementById('btnPausar').disabled  = true;
    this.mostrarValor.value = "00:00";

    document.getElementById('mostrarValor').classList.remove('mostrarValor2');
    document.getElementById('mostrarValor').classList.add('mostrarValor');
    document.getElementById('exibe').classList.remove('Classexibe2');
    document.getElementById('exibe').classList.add('Classexibe');

    clearTimeout(this.contador);
    return;
   }

   novoMinuto = null;
   novoSegundo = null;
   if(this.minuto <= 9){
    novoMinuto = "0" + this.minuto;
   }else{
    novoMinuto = this.minuto;
   }
   if(this.segundo <= 9){
    novoSegundo = "0" + this.segundo;
   }else{
    novoSegundo = this.segundo;
   }
   this.mostrarValor.value = novoMinuto + ":" + novoSegundo;
  }
 }
 clearTimeout(this.contador);
 this.contador = setTimeout('IniciarCronometro(evento)', 1000);
}

function validarNumero(valor){
 return !isNaN(parseFloat(valor)) && isFinite(valor);
}

function PausarCronometro(){
 if(document.getElementById('btnPausar').value=="PAUSAR"){
  document.getElementById('btnPausar').value = "VOLTAR";
  this.evento = "pause";
 }else{
  document.getElementById('btnPausar').value = "PAUSAR";
  this.evento = "start";
 }
}

function ResetarCronometro(){
 document.getElementById('min').readOnly = false;
 document.getElementById('seg').readOnly = false;
 document.getElementById('btnIniciar').disabled  = false;
 document.getElementById('btnResetar').disabled  = true;
 document.getElementById('btnPausar').disabled  = true;
 document.getElementById('btnPausar').value = "PAUSAR";
 this.mostrarValor.value = "00:00";

document.getElementById('mostrarValor').classList.remove('mostrarValor2');
 document.getElementById('mostrarValor').classList.add('mostrarValor');
 document.getElementById('exibe').classList.remove('Classexibe2');
 document.getElementById('exibe').classList.add('Classexibe');

 clearTimeout(this.contador);
}
html, body {
 height: 99%;
}
body {
 background-color: #f0f0f0;
}
.mostrarValor{
 text-align: center;
 border:0px solid white;
 font-size: 50pt;
}
.mostrarValor2{
 text-align: center;
 border:0px solid white;
 font-size: 50pt;
 animation: fade 10000ms infinite;
}

.Classexibe{
 text-align:center;
}
.Classexibe2{
 text-align:center;
 animation: fade 10000ms infinite;
}
section {
 width: 450px;
}

.btn {

 width:100px;
}

@keyframes fade {
 0% {bakcground-color:white;}
 25% {background-color:orange;}
 50% {background-color:green;}
 75% {background-color:red;}
 100% {background-color:white;}
}
<!DOCTYPE html>

<meta charset="UTF-8"/>
<title>CRONÔMETRO</title>
<link rel="stylesheet" type="text/css" href="style.css" />

   <fieldset class="Classexibe" id="exibe"><legend>Exibição</legend>

<input class="mostrarValor" type="text" id="mostrarValor" size="2" readonly="readonly" value="00:00"/>

   </fieldset>
   <fieldset><legend>Configuração</legend>

Colocar minutos:   <input type="text" id="min" size="2" maxlength="3"/>

Colocar segundos: <input type="text" id="seg" size="2" maxlength="2"/>

   </fieldset>
   <fieldset><legend>Comandos</legend>

     <input class="btn" type="button" value="INICIAR" id="btnIniciar" onclick="IniciarCronometro('start')" />
     <input class="btn" type="button" value="PAUSAR" id="btnPausar" onclick="PausarCronometro()" disabled="disabled" />
     <input class="btn" type="button" value="RESETAR" id="btnResetar" onclick="ResetarCronometro()" disabled="disabled" />

   </fieldset>

Comment: Olá Saulo! Muito obrigado por me ajudar... Estava desesperado, recomecei do 0 com o switch e deu certo! Gostei muito da sua lógica! Se possível, pode me explicar o clearTimeout e o ParseFloat? Obs.: O input #mostrarValor tem que ter o size 5, para o tempo poder ser visualizado por completo... Muito obg! Salvou muito!
Comment: clearTimeout cancela o setTimeout. Coloquei o setTimeout em uma variável global para poder cancelar com a função clearTimeout.
Já o ParseFloat() pega os primeiros caracteres separado por espaço e converte em um float (número real).
O ideal é contar em milisegundos e essa contagem em milisegundos mudar mudar o segundo e o segundo mudar o minuto. No exemplo que fiz, coloquei o segundo para mudar o minuto. digo isso porque se pausar, haverá uma pequena defasagem ao retornar mas como disse, é resolvido colocando em milisegundos.
Abraço


C++ DLL special characters

Question: I'm sending an user-generated string from my program into a C++ DLL function I'm making. It works fine, until I send a string like "åäö". My function looks something like this:
export void showMessage(char* str) {
    MessageBox(NULL, str, "DLL says", MB_OK);
}

When "åäö" is sent from the program, a message with "åäö" popups up. How do I convert it into "åäö"? What library is needed? I'm using Code::Blocks for the DLL.
Comment: That is indeed utf-8.  Not the system code page that MessageBoxA() or the utf-16 string that MessageBoxW() needs.  Use MultiByteToWideString() to make the latter work.
Comment: There's no reason to make `str` a `char *` instead of a `const char *`. It's functions like this that disallow doing `str.c_str()` as an argument for no good reason. And you should be using the wide version of `MessageBox` if you want Unicode characters.
Answer: The characters you are using appear to be in the extended ASCII table (value greater than 127), and will depend on the code page you are using, which is a less than portable approach, since the system running your code needs to make environment changes outside of the program itself.
Instead of using MessageBox, use the Unicode enabled version, MessageBoxW, and look up the Unicode encodings for the characters you specified.
References

Unicode Versions and ANSI Versions of Functions, Accessed 2014-06-06, <http://zone.ni.com/reference/en-XX/help/371361J-01/lvexcodeconcepts/unicode_ansi_version_functs/>
ASCII Table Lookup, Accessed 2014-06-06, <http://www.theasciicode.com.ar/extended-ascii-code/capital-letter-a-ring-uppercase-ascii-code-143.html>
Unicode Lookup, Accessed 2014-06-06, <http://unicodelookup.com/>

C++ DLL special characters


How can I have a dynamic image show when someone clicks the Facebook Like button and Posts to Facebook?

Question: Currently, when someone 'likes' a link and creates a Facebook post (via the like button), it will only grab the one image that I specify in the meta tag (via the og:image property).
What is the best way to allow people to post a dynamic image with dynamic description? In my case, I have several items (with image & description) listed on a page that the user should be able to 'like' and post on their wall. Any advice would be much appreciated.
Thanks!
Comment: Show what you have tried so far
Answer: Change the meta tag on click: use this example and modify it to your needs.
<code><!DOCTYPE html>
<head>
<meta charset="utf-8">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
<title>Title Of Page</title>
</head>
<body>
<input type="button" value="Click Me" onclick='$("title").html("Changed Dynamically");'/>
</body>
</html>
</code>
Comment: Doesn't FB have to crawl the site to get the updated image? I'm not sure that would work.


linux print just Outgoing bandwidth

Question: i want to get just the outgoing bandwidth example "343 MBit/s"
so i want a command to get  just this example:   "343 MBit/s"
so it can be
nload

or iftop  command
example:
 rates:    270Mb   244Mb   283Mb

Comment: Stack Overflow is a site for programming and development questions. This question appears to be off-topic because it is not about programming or development. See [What topics can I ask about here](http://stackoverflow.com/help/on-topic) in the Help Center. Perhaps [Super User](http://superuser.com/) or [Unix & Linux Stack Exchange](http://unix.stackexchange.com/) would be a better place to ask. Also see [Where do I post questions about Dev Ops?](http://meta.stackexchange.com/q/134306)
Answer: iftop -t -s 1 -n -N 2>/dev/null | awk '/Total send rate:/ {print $6}'

this is command from which i get just example: 149Mb

linux print just Outgoing bandwidth


What does it mean for right equivariant maps to be left translations?

Question: My book is Connections, Curvature, and Characteristic Classes by Loring W. Tu (I'll call this Volume 3), a sequel to both Differential Forms in Algebraic Topology by Loring W. Tu and Raoul Bott (Volume 2) and An Introduction to Manifolds by Loring W. Tu (Volume 1).
I refer to Section 27.1 (part 1), Section 27.1 (part 2), Section 27.1 (part 3) and Section 27.1 (part 4).
Question: About Lemma 27.7, what exactly is going on?
Based on my understanding, given next, I think $f$ should be assumed to have the action on $G$ in the range as $G$'s law of composition. There might be some understanding, for those already familiar with this topic, of Lemma 27.7 based on its use later in Section 27.1. But, as a beginner, I'm not sure that I dare to read the rest of Section 27.1 without first understanding Lemma 27.7. (Anyway, the rest of Section 27.1 doesn't seem to be used in the rest of this book except in Example 27.10 and Problem 31.1.)
This is what I understand:

Let $G$ be any group, not necessarily a Lie group or a topological group, with law of composition $\text{Law}: G \times G \to G$, $\text{Law}(g,h) \in G$ for all $g,h \in G$. Let $1_G$ be the identity of $G$. Let $N$ and $M$ be any sets, not necessarily manifolds or topological spaces. Let $\zeta: N \times G \to N$, $\sigma: M \times G \to M$ be right actions by $G$ to the sets, respectively, $N$ and $M$. Let $f: N \to M$ be a right $G$-equivariant map. Let $x \in N$, and let $g \in G$. Then $f(\zeta(x,g)) = \sigma(f(x),g)$.
In (1), choose $N = M = G$ and then choose $x = 1_G$. Then $f(g) =$ $ f(\zeta(1_G, g))$ $ = \sigma(f(1_G),g)$.

2.1. Edit: I made a mistake. I assumed that we have $\zeta(1_G, g) = g$ for any action $\zeta$. Rather, we have, similar to (4) below, that $\zeta = \text{Law}$.

"Left translation" is any map $l_h: G \to G$, where $l_h(g) = \text{Law}(h,g)$, with $h \in G$.
Somehow, $\sigma = \text{Law}$.
By (2) and (4), $f(g) = \text{Law}(f(1_G),g)$
By (3) and (5), $f = l_h$, with $h=f(1_G)$.
Answer: Your understanding is perfectly correct.
To say that a map is $G$-equivariant requires an action of $G$ on both the domain and target of the map. When both the domain and target are the group $G$ itself, a 'canonical' action is defined by the group law. That is, in a setting such as Lemma 27.7. in the book, the action is not usually explicitly specified, as there is only one natural interpretation of the statement.
Comment: Yes to both of your points. In your notation $\sigma$ and $\zeta$ in this case are the group law.  And in pretty much every context that immediately comes to mind, by default the canonical action of a group on itself is through the group law.
Comment: But $G$ can act on itself in many ways.  For example, all these are examples of right actions:  $g\ast_1 h = hg$, $g\ast_2 h = g^{-1} h$, $g\ast_3 h = g^{-1} h g$.   If I was writing this in a paper, I would definitely specify the action of $G$ on itself.  It may also be worth pointing out that $\ast_1$ and $\ast_2$ are actions of the group $G$ on the *set* $G$, while $\ast_3$ is an action of the group $G$ on the *group* $G$.  That is, the homomorphism $g\ast_3 \cdot:G\rightarrow G$ is actually a group isomorphism, while $g\ast_1\cdot :G\rightarrow G$ is merely a set bijection.
Comment: Thanks. Do you mean additionally that we have not only $\sigma = \text{Law}$ but also $\zeta = \text{Law}$?
Comment: In that case, I think I made a mistake. I edited post. Please see (2.1)
Comment: Also, if I were to read something like we have a $G$-equivariant map $f:N \to G$ or $f: G \to M$, then by default, the canonical action on $G$ is the law?
Comment: Thanks @JasonDeVito and Eero Hakavuori!


show this $(f(x))''+2\ge 0$,for any real numbers, where $f(x)=\frac{x^2-1}{x^{2n}-1}$

Question: When I did a question today, I turned to the following question
let $n$ be postive integer,and  $x\in R$, let $f(x)=\dfrac{x^2-1}{x^{2n}-1}$,show this
$$(f(x))''+2\ge 0 \tag{1}$$
For example $n=2$
then
$$(f(x))''+2=\dfrac{2x^2(x^4+3x^2+6)}{(x^2+1)^3}\ge 0$$
$n=3$,then
$$(f(x))''+2=\dfrac{2x^4(x^8+3x^6+6x^4+17x^2+15)}{(x^4+x^2+1)^3}\ge 0$$
and when $n=4$,see links1
$n=5$ see  links2,
$n=6$ see links3
always hold,so How to prove for $(1)$,maybe this usefull:
\begin{align*}(f(x))''+2&=(f(x)+x^2)''=\left(\dfrac{x^{2n+2}-1}{x^{2n}-1}\right)''\\
&=\dfrac{x^{2n-2}(4n^2(x^2-1)(x^{2n}+1)-2n(3x^2+1)(x^{2n}-1)+2x^2(x^{2n}-1)^2)}{(x^{2n}-1)^3}\end{align*}see links4
Comment: This strategy might help. Let $g:=1/f$ so $f^{\prime\prime}+2=(2g^{\prime2}-gg^{\prime\prime}+2g^3)/g^3$, so you want to prove$$2g^{\prime2}-gg^{\prime\prime}+2g^3\ge0.$$It's safe to multiply by an odd power of $g=1+y+\cdots+y^{n-1}\ge1>0$, where $y:=x^2\ge0$. Then$$\begin{align}2g^{\prime2}-gg^{\prime\prime}+2g^3&=8y(1+2y+\cdots+(n-1)y^{n-2})^2\\&-2(1+y+\cdots+y^{n-1})^2(1+6y+\cdots+(n-1)(2n-3)y^{n-2})\\&+2(1+y+\cdots+y^{n-1})^3.\end{align}$$This only need be $\ge0$ for $y\ge0$, which will happen if e.g. all coefficients are $\ge0$.
Answer: As stated above in a comment, we can write
$$f(x)=\frac{1}{1+x^2...+x^{2n-2}}=\frac{1}{g(x)}$$
which yields that
$$f''(x)+2=\frac{2g'^2-gg''+2g^3}{g^3}$$
so we only have to decide the sign of the numerator, given that $g(x)>0$ for all x. Since $f(x)=f(-x)$ it also follows that the second derivative is even, which allows us to only examine $x\geq 0$. It seems that the coefficients of the numerator are explicitly positive, so let us see how we can prove this. First, write out the expressions for $g'^2 , gg''$:
$$2g'^2=\left(\sum_{r=0}^{n-1}\sum_{l=0}^r+\sum_{r=n}^{2n-2}\sum_{\ell=r-n+1}^{r}\right)8\ell(r-\ell)x^{2r-2}$$
$$g''g=\left(\sum_{r=0}^{n-1}\sum_{l=0}^r+\sum_{r=n}^{2n-2}\sum_{\ell=r-n+1}^{r}\right)2\ell(2\ell-1)x^{2r-2}$$
Subtracting these two we see that
$$2g'^2-gg''=-\sum_{r=0}^{n-1}x ^{2r-2}r(1+r)+\sum_{r=n}^{2n-2}[4(r-n)^2+6r-5n+1]x^{2r-2}$$
Note that in the 2nd sum all the coefficients are positive and in the 1st sum negative. We will prove that the expansion of $2g^3$ exactly cancels out the $n-1$ smallest powers (note that $r=0$ does not contribute but is included for convenience).
After some manipulations we see that
$$g^3=\sum_{r=0}^{3n-3}x^{2r}\sum_{s=\max\{0,r-n+1\}}^{r}\sum_{m=\max\{0,s-n+1\}}^{s}1$$
Here, all coefficients are manifestly positive as well. Now for $0\leq r\leq n-2$ we immediately see that after performing the sum and a change of index:
$$2g^3=\sum_{r=0}^{n-2}x^{2r}\sum_{s=0}^r\sum_{m=0}^s 1+...=\sum_{r=0}^{n-1}x^{2r-2}r(1+r)+\sum_{r=n-1}^{3n-3}A_{nr}x^{2r}~, ~A_{nr}>0$$
which finally shows that the first $n-1$ coefficients are cancelled and the remaining expression is a polynomial in $x^2$ of degree $3(n-1)$ with positive coefficients and therefore is positive for all $x>0$. At $x=0$ evidently, $f''(0)+2=0$ and hence $f''(x)+2\geq 0$ for all $x$, with a zero of order $2n-2$ at the origin.


Server Backup reports incomplete backup [0x80070020] due to item in System Volume Information Folder

Question: My Windows Server 2012 R2 Essentials server has started throwing the same error each time during daily backups, each backup has this error in the failed items backup log:

Error in backup of E:\System Volume Information\SRM\quota.md during write: Error [0x80070020] The process cannot access the file because it is being used by another process.

E: is a parity Storage Space. Each backup status is now incomplete but otherwise all other data appears to have been backed up. It does mean however that each backup task now runs a full backup on E: rather than incremental because of the "failure" status.
I tried using the Dashboard to exclude this path from backup however I just got a different error related to items under the System Volume Information folder. There seems to be a underlying issue as to why System Volume Information is now causing problems, but I'm not sure what it is. As far as I'm aware I am not using any Quota functionality unless Windows itself is doing something I'm not aware of.
Additionally the core configuration of the server has not changed, so I am slightly confused as to why the backup is now "failing".
Comment: What were the results of a disk/file-system check (`chkdsk`)?
Comment: @Ƭᴇcʜιᴇ007 I haven't run one yet, because the Storage Space is large 6TB pool.
Comment: Welp, I'd say start running it... ;)   You are saying you have unexpected file access problems, so a CHKDSK is the first (or one of the first) steps that should be done to confirm/deny file-system corruption.  Once you've done that, come back and update your question with the results...
Comment: *so I am slightly confused as to why the backup is now "failing"* - A chkdsk likely will eliminate your confusion.  I presume you have restarted?
Comment: Fair point. I have only held off because `E:` holds various network shares so chkdsk will force it to be dismounted and become unavailable for a while. I will report my findings. I have already restarted the server and it hasn't fixed it.
Comment: `chkdsk` ran, a few cleanup operations on index entries occurred but other than that FS appears clean. Will have to wait until next backup occurs to see if it fixed it.
Comment: [This is all I could find](http://www.clickbay.de/win/wintip/w2003-01-quota.htm) but appears some services have files in use and locked.
Comment: Slightly different error `Error in deletion of [E:\System Volume Information\SRM\] while pruning the target VHD: Error [0x80070020] The process cannot access the file because it is being used by another process`. Still appears to be some form of lock on the folder
Comment: A similar problem I found: https://social.technet.microsoft.com/Forums/windowsserver/en-US/a9ec7dc7-2f87-4a1e-bebe-e1717b4b1565/cannot-backup-dsystem-volume-informationsrmquotamd?forum=winservergen. However I'm not using WSUS but it seems exclude rules seem to be related. I am excluding some items on `E:/`.
Comment: I always delete that junk and recycler before proceeding to do any backups.
Answer: While this doesn't explain why 0x80070020 error occurs. The problem appears to be when wbadmin.exe is provided an exclude flag. Running whole backup of the E:/ storage space completed successfully.
A similar problem was reported related to WSUS:
https://social.technet.microsoft.com/Forums/windowsserver/en-US/a9ec7dc7-2f87-4a1e-bebe-e1717b4b1565/cannot-backup-dsystem-volume-informationsrmquotamd?forum=winservergen
Ultimately for whatever reason Windows doesn't like the exclude option in the backup now. It had worked fine up until a few weeks ago and the only thing that would of changed would of been the amount of data being excluded overtime.
I suspect this is a bug in Windows.


accessing fields in a view template

Question: I have a view that I want to create a view template for in my theme.
So, I have created: views-view--homepage-suppliers.tpl.php
I have then several content items of content type: Supplier that the view uses.
The have various fileds, such as title, field_supplier_image
How do i then access these fields in this view template?
Is it something along the lines of:
$rows['field_supplier_image']?
thanks
Answer: It would appear your using a 'Display output' template when you probably want a 'Row style' output so you can access fields. You will need to change your tempate by going to 'advanced > theme information', it will probably be something similar to 'views-view-fields--homepage-suppliers.tpl.php'.
You can then get a nid from the field and access a whole host of information through the node object.
  $nid = $row->{$view->field['field_supplier_image']->field_alias};
  $node = node_load($nid);

If you var_dump() the $node variable you can see what you have to play with.
Comment: That's exactly what I was after!!
Comment: Any chance of ticking this as answered then? ;-)
Answer: I ended up using this in a field template:
$row->field_field_link_text[0]["rendered"]["#markup"]

Answer: You can access fields through the $view->result object.
Here's an example I use to create a ical calendar:
(views-view--ical.tpl.php)
BEGIN:VCALENDAR
VERSION:2.0
METHOD:PUBLISH
<?php
define('CRLF',"\r\n");
global $base_url;
$ical_time_format='Ymd\THis\Z';

function ical_extract_value($field,$key='value'){
    return $field['und'][0][$key];
}

function ical_shorten_line($line){
    $line=str_replace(array("\r\n","\n"),'\n',$line);
    return trim(chunk_split($line,76,"\r\n "));
}

print 'PRODID:'.$base_url.'/'.current_path().CRLF;

foreach ($view->result as $node){
        $data=$node->_field_data['nid']['entity'];
//      print_r($data); // uncomment to see available data
        print 'BEGIN:VEVENT'.CRLF;
        print 'UID:'.$data->nid.'@'.$base_url.CRLF;
        $description = ical_extract_value($data->body);
        print ical_shorten_line('DESCRIPTION:'.$description).CRLF;
        print 'DTSTART:'.date($ical_time_format,ical_extract_value($data->field_start)).CRLF;
        print 'DTEND:'.date($ical_time_format,ical_extract_value($data->field_start,'value2')).CRLF;
        /** other fields here **/
        $keywords = ical_extract_value($data->field_tag_list);
        $keywords = str_replace(' ', ',',$keywords);
        print ical_shorten_line('CATEGORIES:'.$keywords).CRLF;
        print 'END:VEVENT'.CRLF;
} ?>
END:VCALENDAR

As you can see, a certain field value can be accessed by $view->result[n]->filed_xxx['und'][0]['value'].

accessing fields in a view template


Problems upgrading .NET remoting services to 4.0 in IIS

Question: I'm trying to upgrade a legacy .NET remoting web services project to .NET 4.0 in IIS7.  The old project is currently running fine on 2.0.  All of the projects in the solution were upgraded to 4.0, rebuilt and deployed to a new web application running in a 4.0 integrated app pool on a different server.  All of the URIs to the services are configured in the web.config using *.rem extensions.  Whenever I try to make calls to the services on this new project I am getting server 500 errors complaining that there was a problem with the resource I am trying to access.
When checking the Handler Mappings in IIS for this application, I've notice some strange behavior.  Whenever I try to edit the 'HttpRemotingHandlerFactory-rem-Integrated-4.0' handler (which is the one I'm assuming would need to be used given the version and type of app pool I run) I get the following errors:
1) Unrecognized attribute 'targetframework' referring to the 'targetFramework="4.0"' in my web.config
2) If I remove that attribute, then I get the 'The assembly Foo could not be loaded because it was built using a newer framework than the one currently loaded'
Anywhere I've checked says that this means I need to change the app pool to be running on 4.0 instead of 2.0, but it's ALREADY running 4.0!  I've checked everywhere I can, I've even changed the Default Web Site to be in a 4.0 app pool as well with no luck.  Is there some obscure setting somewhere that I am just missing, or something that I'm not thinking of?
Answer: I was able to get past the issue by changing the mode from Integrated to Classic, and running the app pool as myself (to be changed later into a user created specifically for this web app).  I still get the error messages when trying to edit the integrated rem handler though, maybe it's just an issue with that particular handler.


MATLAB code for an array consisting of matrices

Question: I want to write MATLAB code that includes an array consisting of all $2 \times 2$ square matrices whose elements are elements of $\Bbb{Z}_2= \{0,1\}$, e.g.,
$$
\begin{pmatrix}
0 & 0 \\
0 & 0
\end{pmatrix},\quad
\begin{pmatrix}
1 & 0 \\
0 & 0
\end{pmatrix},\quad
\begin{pmatrix}
0 & 1 \\
0 & 0
\end{pmatrix},\quad
\begin{pmatrix}
0 & 0 \\
1 & 0
\end{pmatrix},\quad
\begin{pmatrix}
0 & 0 \\
0 & 1
\end{pmatrix},\quad
\begin{pmatrix}
1 & 1 \\
0 & 0
\end{pmatrix},\quad \cdots$$
And how can I generalize the same thing with $\Bbb{Z}_2$ for $n \times n$ square matrix? Please help!
Comment: Use the 3rd dimension, i.e., use a $2 \times 2 \times 2^4$ matrix.
Answer: You can start with
n = 2
M = dec2bin(0:2^(n*n)-1,n*n)

then convert strings to matrices.
Comment: haha, very nice!! +1
Comment: @grixor- Can you tell me how to convert it into matrices.
Answer: The MATLAB code below generates a $50 \times 50$ array in which each element is a random $100 \times 100$ square binary matrix. You can just change the parameters $n,I$ and $J$ as you wish.
n = 100;
I = 50;
J = 50;
M = [];
for j=1:J
    for i=1:I
       M{i,j} = round(rand(n,n));
    end
end

Comment: Please, why the downvote?


Printing via Google Cloud Print

Question: I am trying to print a .txt file that my application saves via FileWriter.
The file it saves is /sdcard/StudentLatePass.txt
When the print button is clicked, the SD file is saved and then it needs to print. I've been following the google cloud print tutorial.
package com.android.upgrayeddapps.latepass;

import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.Button;
import android.widget.Toast;

public class StudentActivity extends Activity
{
    EditText txtData;
    Button btnPrintTardy;

    public void onCreate(Bundle savedInstanceState)
    {
         super.onCreate(savedInstanceState);
         setContentView(R.layout.student);

        //Displays the Custom dialog for student login
        AlertDialog.Builder builder;
        AlertDialog alertDialog;

        Context mContext = this;
        LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(LAYOUT_INFLATER_SERVICE) ;
        View layout = inflater.inflate(R.layout.studentlogin, null);

        builder = new AlertDialog.Builder(mContext);
        builder.setView(layout);

        alertDialog = builder.create();
        alertDialog.show();

        txtData = (EditText) findViewById(R.id.editText1);

        btnPrintTardy = (Button) findViewById(R.id.btnPrintTardy);
        btnPrintTardy.setOnClickListener(new OnClickListener() {

        public void onClick(View v) {
            // write on SD card file data in the text box
            try {
                File myFile = new File("/sdcard/StudentLatePass.txt");
                myFile.createNewFile();
                FileOutputStream fOut = new FileOutputStream(myFile);
                OutputStreamWriter myOutWriter =
                                        new OutputStreamWriter(fOut);
                myOutWriter.append(txtData.getText());
                myOutWriter.close();
                fOut.close();
                Toast.makeText(getBaseContext(),
                        "Done writing SD 'StudentLatePass.txt'",
                        Toast.LENGTH_SHORT).show();
            } catch (Exception e) {
                Toast.makeText(getBaseContext(), e.getMessage(),
                        Toast.LENGTH_SHORT).show();
            }

        }// onClick
        }); // btnWriteSDFile

        btnPrintTardy.setOnClickListener(new OnClickListener() {
        public void onClick(View v) {
            //Print using Google Cloud Print
            Intent printIntent = new Intent(this, PrintDialogActivity.class);
                printIntent.setDataAndType(docUri, "text/plain");
                printIntent.putExtra("title", "Student Late Pass");
                startActivity(printIntent);

            }// onClick
    });// btnPrintSDFile

    }

    // Clear all activities on the top of the stack and deliver the intent to (on top now) MainActivity with a new Intent
    public void onGotoLatePassActiviy(View View)
    {
        Intent intent = new Intent(View.getContext(), LatePassActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        StudentActivity.this.finish();
    }
}

For the life of me I have tried to change the docUri, docMimeType and docTitle to everything under the sun to print this file.
My current modified code is
btnPrintTardy.setOnClickListener(new OnClickListener() {
        public void onClick(View v) {
            //Print using Google Cloud Print
            Intent printIntent = new Intent(this, PrintDialogActivity.class);
                printIntent.setDataAndType(docUri, "text/plain");
                printIntent.putExtra("title", "Student Late Pass");
                startActivity(printIntent);

            }// onClick
    });// btnPrintSDFile

I am still getting red squigglies under the docUri, and when i pass the intent to Print
Comment: Hover over the "red squigglies" and what does it say?
Answer: Try this and see what happens:
Intent printIntent = new Intent(StudentActivity.this, PrintDialogActivity.class);
That should resolve the first "red squigglies".

Here is what you could try for the URI problem.
File file = new File("/sdcard/StudentLatePass.txt");
intent.setDataAndType(Uri.fromFile(file), "text/*");

Comment: I think both of you just made my day.
Comment: vwola, now do you know what i need to change the docUri to? The file it saves is at /sdcard/StudentLatePass.txt
Comment: I added some more information, let me know if it works. Give me a +1 if it works. =)
Comment: Don't forget to +1 us if this was helpful to you. =)

Printing via Google Cloud Print


coldfusion application.cfc not found

Question: I've been having a sporadic problem for a few weeks where on restarting the CF Server (Enterprise 9) one of my applications runs without ColdFusion referencing all the variables in the Application.cfc file. It's in the same folder as the CFML pages, it IS properly capitalised as Application.cfc, but it seems to just be ignored. Obviously this causes problems with datasource name and all the other variables I set in Application.cfc. For reference, I'm using an Application.cfc file based on Ben Nadel's excellent intro at http://www.bennadel.com/blog/726-ColdFusion-Application-cfc-Tutorial-And-Application-cfc-Reference.htm . Usually my requested template runs as an include and I can see it in the stack using debugging output, now I can't see it there at all. It's as if the file just doesn't exist.
Has anyone else experienced this, or can you think of possible solutions? Note that at times a restart has got the whole thing running perfectly smoothly.
Re folder structure it's really simple: the Application.cfc file is in the web root along with executable CFML templates - included templates, images, CSS etc are in separate folders referenced via relative paths.
There is another application with its own similar Application.cfc file that is in a sub-directory of the web root. This is running perfectly.
Comment: It would be best to post the Application.cfc so we can scout for any potential issues. Also some information about the directory structure.
Comment: OK - I seem to have fixed this, by using CF Admin to set the 'Application.cfc/Application.cfm lookup order' to 'Default order' rather than 'Until web root'. Perhaps there was some conflict because there are multiple web root folders on the server?
Comment: Thanks, travis. No, the application names are distinct. The problem seems to have been connected to ColdFusion's settings for locating the Application.cfc file as outlined in my comment above.
Comment: Also post the file/directory structure of the relationships between the file being requested, the Application.cfc, the web root and the ColdFusion root.
Comment: Are the application names the same in both application.cfc? If they are, and a user visits the sub-application first, the main application will be defined per the settings in the sub-application.
Answer: Try clearing your template cache.  I've see cases where CF just gets flakey and the cached files are causing issues.  Another option: Does ColdFusion have permissions to read/execute the Application.cfc?  If this WAS an issue but is no longer an issue I've seen cases where the template cache was causing these files not to be found.  Again, delete these files (from disk, not the cfadmin) and try again.

coldfusion application.cfc not found


Speeding up launch of Amazon EC2 Windows instances

Question: I'm working on a Web service which is hosted on EC2 and needs to have a varying number of instances running, depending on load.  We have the basic service up and running, but one of the things we're struggling with is the time it takes to provision and launch a Windows instance (we are using some third prty tools that only run on Windows).  I've seen this take anywhere from 10 minutes up to a pretty staggering 45 minutes.
Does anyone have any tips on how to speed up the launch of an EC2 instance ?  Since the AMIs for Windows servers are large compared to Linux AMIs, for example, I'm wondering if one thing might be to make sure that the S3 bucket containing the AMI is located in the same zone where the instance is launched, which would presumably make provisioning the new instance faster.
Answer: The Amazon windows instances reboot on start because the default configuration of the "EC2 Config" windows service is to rename your host to the internal DNS name of the instance. Renaming hosts requires a reboot on windows. If you do not need to use the internal DNS name of your instance then you might benefit by disabling the SetComputerName feature. Windows instances also have the advantage of not having to initialize the startup drives where you might have already bundled your configuration again saving some more time in instance start up. All of this is possible via the EC2 Windows Configuration Service.
Windows Configuration Service:
http://docs.amazonwebservices.com/AWSEC2/latest/UserGuide/appendix-windows-config.html
My Windows small instances normally take 15-18 minutes to boot (larger ones are faster). Depending on your requirements, you might be able to bundle all your software within the AMI and be able to have everything boot up and running within that period. I understand the reservations for not bundling everything into an AMI but it might be worth the improvement in start up time to have production AMIs with everything bundled in them. Keep the build scripts separate if you want in your build environments.
Additionally, now that Amazon had released EBS root volumes as opposed to instance-store root volumes. Windows small images running on an EBS volume boots up in almost 5 minutes versus the almost 20 minutes it took before. Also you don't need to terminate - you can stop/start them - depending on your setup this potentially shaves a few more minutes in some start up scripts.
Essentially customizing your Windows EC2 Config service, your AMI and potentially using an EBS boot volume should reduce start up times to almost 5 minutes. You can avoid the sysprep that run on an ec2 instance startup depending on your app, especially for development purposes. An non-sysprepped m1.large image that avoids a hostname change on startup can start up in about 2 minutes which is not bad at all.
At this time, as far as I understand it, that's the best you can do with Windows on Amazon EC2 but that really is not too bad. If you are able to forecast close to 10 minutes in to the future based on average usage patterns, you should be able to spin up extra instances and handle the additional load.
Comment: The internal host rename is a great tip - thanks !  I want to try out EBS root volumes too, not least because it will make backups a lot easier.

I guess I'll have to forecast a 10 minute average startup time; that's not such a problem in itself, but the high variability of the startup times is still a real pain.
Comment: This ought to be referenced in the AWS docs.
Answer: I installed 3 instances last night of a vanilla Windows 2003 server.  The first two took about 45 minutes, the 3rd, about an hour later, took a full 2 hours before it was ready!
Those had nothing in them at all, without any S3 usage.  I doubt there is a way to speed up that fundamental step apart from waiting for Amazon to make deployment speed improvements over time.  So, I would conclude that a certain delay is to be expected and Kurt's advice is good, which is to keep 1 or 2 in reserve already prepared.
Another thing you could do is to create a new instance of your AMI type a few times and time it.  Then try a few times with your S3 storage and see how much time that adds to it.  I assume that the availability zone should match between the image and S3, although I don't know how much time difference that will make.
Once you've determined the max time to provision, keep ahead of the load/usage by that many minutes.
Comment: @gareth - this is because the machine has the same name as another on the network (I.e. it's an image).  The EC2ConfigService detects this, assigns a new name, and reboots it.  You can disable that with the installed ec2config configuration util.
Comment: Thanks for the suggestions - 2 hours is pretty extreme.

One thing I've noticed since asking this question is that EC2 sometimes reboots Windows instances immediately after startup.  I don't know why this is (I haven't figured out a pattern as to why some instances get rebooted while others don't), but it can add another 5 or 10 minutes to the startup time.
Answer: Have a minimal system, keep as much as possible in EBS might help? Or perhaps take an Apache style approach and run one or two in reserve?
Answer: We've run into this exact problem, but in a very serious way -- our new startup extends Amazon EC2 into a Virtual Lab environment (multi-user, policies, sharing etc.) and so we needed to speed up the start time of Windows machines. Our biggest decision was to support only EBS based volumes in our application, because they're the only ones that can start up in 5-10 minutes. In our testing we found instance-store startup times to vary widely and sometimes take excessive amounts of time, which made them useless for us.
Simon @ LabSlice Virtual Lab Management on EC2


Xaml Grid element to PDF

Question: I need to create a pdf file from wpf C# application. I need to apply style to the pdf exactly the same as XAML. I can't just copy the xaml page since the data can be different when the pdf is being created. I'll have to do the data processing when the user clicks export button. The pdf will have text, images and background images. I was thinking to have an html file for designing the pdf and then pass the data. But I don't know how to proceed. Any suggestion or sample example would be a great help.
Answer: Yes by exporting to XPS then convrting to PDF, by using a converter like: NiXPS.
Here is an example for this:
<code>    private void SaveVisuals(XpsDocumentWriter xpsdw, List<Visual> vc)
{
    // Setup for writing multiple visuals
    VisualsToXpsDocument vToXpsD = (VisualsToXpsDocument)xpsdw.CreateVisualsCollator();

    // Iterate through all visuals in the collection
    foreach (Visual v in vc)
    {
        vToXpsD.Write(v);   //Write each visual to single page
    }

    // End writing multiple visuals
    vToXpsD.EndBatchWrite();
}
</code>
More on this: On MSDN
Another way could be to render your document into an image first, then you can easily put your image to a PDF file (of course this has some disadvantages, but this is a quick way to go).
For converting HTML to PDF you could be using wkhtmltopdf for example, but there are many different tools out there.
Here you can find a .NET implementation: Pdf API and HTML to PDF Converter for .NET
If you want to render your Visuals to image, any WPF Visual object can be rendered into a bitmap using RenderTargetBitmap.
Example from MSDN:
<code>        DrawingVisual drawingVisual = new DrawingVisual();
        DrawingContext drawingContext = drawingVisual.RenderOpen();
        drawingContext.DrawText(text, new Point(2, 2));
        drawingContext.Close();

        RenderTargetBitmap bmp = new RenderTargetBitmap(180, 180, 120, 96, PixelFormats.Pbgra32);
        bmp.Render(drawingVisual);
        myImage.Source = bmp;
</code>
You can render any visual this way. You don't have to display it, but you can.
If you want to keep up the responsiveness of the UI you should do this export operation in a seperate thread, not the event processing thread.
Comment: Any sample application for second suggestion as well,i.e., converting to image and then rendering?
Comment: So while the image is being rendered, will UI change be  visible to user? I mean, lets say there are two grids which user can export to pdf. Currently the user is viewing 1st grid. Now he presses export and i again give him the option of which grid they want to export, So if they select the 2nd grid, will the 2nd grid be visible on the UI?
Comment: How would I dynamically add the data to the html file from C# code. I have just created a simple wpf application with xaml and C# file. How would I use Html file in my aplication, load the data into it and then export it. Totally new in this, so again got back to square 1

Xaml Grid element to PDF


Convert string to HTML element using JavaScript or jQuery

Question: I have a string like this:
i1:1,i3:5,i2:5

How can I convert it to a HTML element like this using pure JavaScript or jQuery?

What I have tried so far:
document.write('
i1:1,i3:5,i2:5
');

Comment: What have you tried so far?
Answer: split the initial string on the comma, then map over the resulting array. On each iteration of map you can then split on the colon, and return a HTML string. You just need to make sure you join the array that map returns into a new string before you add it to the DOM.

const str = 'i1:1,i3:5,i2:5';

const result = str.split(',').map(el => {
  const [key, value] = el.split(':');
  return `<li id="${key}" value="${value}">${value}</li>`;
}).join('');

const ol = document.querySelector('ol');
ol.insertAdjacentHTML('beforeend', `<ul>${result}</ul>`);

Additional documentation

Destructuring assignment

Template literals

insertAdjacentHTML
Comment: PS: `value` is an absolutely [*valid* attribute on a `OL > LI` element](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/li#attr-value), reintroduced in HTML5 - **but only valid in the scope of an `` (Ordered List) parent.**
Answer: With jQuery:
function createUlListByString(myString) {
    var elements = myString.split(',');
    var ul = $('
');

    elements.forEach(function(item) {
        item = item.split(':');
        var li = $('
'+ item[1] + '
');
        ul.append(li);
    });

    return ul;
}

var ul = createUlListByString('i1:1,i3:5,i2:5');

Vanilla JavaScript:
function createUlListByString(myString) {
    var elements = myString.split(',');
    var ul = document.createElement('ul');

    elements.forEach(function(item) {
        item = item.split(':');
        var li = document.createElement('li');
        li.id = item[0];
        li.value = item[1];
        ul.append(li);
    });

    return ul;
}

var ul = createUlListByString('i1:1,i3:5,i2:5');

Answer: I believe that my simple solution using method forEach() and method split() will not be superfluous, which will split the string into an id and a value taken from an array of similar data.

let ul = document.createElement("ul");
document.body.appendChild(ul);

["i1:1", "i3:5", "i2:5"].forEach(function (li) {
    let id_value = li.split(":");
    ul.innerHTML += "
" + id_value[1] + "
";
});

console.log(ul.outerHTML);


Como mudar o format do Datepicker dinamicamente?

Question: Queria saber se existe alguma forma de mudar o formato do datepicker dinamicamente, usando radio buttons, mas da forma que eu estou tentando não está dando certo ...
HTML
<input id="periodo" name="periodo" type="text" placeholder="Período">

<input id="radioDDMM" type="radio" name="typePeriodo" checked data-type="dd/mm" />
Dia/Mês

<input id="radioMMYYYY" type="radio" name="typePeriodo" data-type="mm/yyyy" />
Mês/Ano

JQuery
$(document).ready(function () {

    $('#periodo').datepicker({
        format: "dd/mm",
        startView: "days",
        minViewMode: "days",
        language: 'pt-BR',
        endDate: '0m',
        orientation: 'bottom',
        autoclose: true
    });

    $("[name='typePeriodo']").on('change', function () {
        var type = $(this).attr('data-type');
        if (type == "dd/mm") {
            $('#periodo').datepicker({
                altFormat: "dd/mm",
                startView: "days",
                minViewMode: "days",
            })
        } else if (type == "mm/yyyy") {
            $('#periodo').datepicker({
                altFormat: "mm/yyyy",
                startView: "months",
                minViewMode: "months",
            })
        }
    });
});

Comment: Não sou um expert em web, mas acho que tu vais precisar de alguma coisa que implemente o data pattern "Observable". Acho que angular, ou [ko](https://knockoutjs.com/documentation/introduction.html) tem isso
Answer: No evento change dos radio utilize o método destroy para inserir o novo formato.

destroy
Argumentos: nenhum
Remova o datepicker. Remove eventos anexados, objetos anexados
  internos e elementos HTML adicionados.
Alias: remover
Fonte: https://bootstrap-datepicker.readthedocs.io/en/latest/methods.html?highlight=reset#destroy

$('#periodo').datepicker({
  format: 'MM dd',
  startView: "days",
  minViewMode: "days",
});

$("[name='typePeriodo']").on('change', function() {
  var type = $(this).attr('data-type');
  $('#periodo').val("").datepicker("destroy");
  if (type == "dd/mm") {
    $('#periodo').datepicker({
      format: 'MM dd',
      startView: "days",
      minViewMode: "days",
    })
  } else if (type == "mm/yyyy") {
    $('#periodo').datepicker({
      format: "mm-yyyy",
      startView: "months",
      minViewMode: "months"
    })
  }
});

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

<link href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.6.4/css/bootstrap-datepicker.css" rel="stylesheet" />

<input id="periodo" name="periodo" type="text" placeholder="Período">

<input id="radioDDMM" type="radio" name="typePeriodo" checked data-type="dd/mm" />
Dia/Mês

<input id="radioMMYYYY" type="radio" name="typePeriodo" data-type="mm/yyyy" />
Mês/Ano


What exactly is the concept of returning to the one?

Question: In riff writing, Tom Morello mentions his style with Tim Commerford was returning to the one. Is this basically just using the tonic chord as a drone? What exactly is meant by that? I believe I can give two examples of the type of riff writing.

Heavy riffs: As the lead guitarist for Rage Against the Machine, Tom
tends to favor the kind of heavy, mid-tempo rock that sounds best in
the keys of E and F#. Those guitar riffs more often return to the
"one," meaning they always return to the root note at the beginning of
each bar of music, giving them a repetitive, funky rhythm.
Alternatively, some of Tom's Audioslave riffs are chord progressions
with a harmonic, melodic feel.

SOURCE
So is this typically what riff writing comprises of a drone on the tonic that goes somewhere and returns at the beginning of the next bar?
Comment: Can you post the quotation you're asking about in the question? Some more context would be helpful.
Comment: OK I have found some more info on the Masterclass website
Comment: 'One' could be both the tonic and the 1st beat of the bar. In fact both are used in the vast majority of songs - it establishes the tonality on the most important part of the bar.
Comment: *Returning* to the one only happens when you have *left* the one, which by definition is not a drone. A drone is staying on the same note(s) the whole time.
Answer: Aside from the word "drone", yes this is what Morello is talking about. There's a tonic note for each of his riffs, most commonly D, E, or F#, and usually the first note of his riffs is that tonic.
By the way, that is not a drone. A drone is a note that is held for a while or indefinitely. Only one of his riffs would I say involves a drone, which is the verse "bagpipe" riff from "Voice of the Voiceless" where he actually plays the riff with the pitch knob on a Digitech Whammy Pedal.
"Killing In The Name" is an easy example of his riff writing. For both the verse and chorus riffs, the first note is D, which is the tonic of the song. Same with the verse riffs to "Freedom" and "Know Your Enemy" - there are many examples.
There are also some exceptions, such as the intro/interlude riff for "Know Your Enemy" which starts on E even though the song is in F#.
This is part of Morello's style and is a popular way to write riffs in general, but not all solid riffs start on the tonic or the one. "Whole Lotta Love" and "Heartbreaker" by Led Zeppelin are examples of classic riffs that don't start on the one.
Comment: Yes both "Whole Lotta Love" and "Heartbreaker" start with pickup notes, but then land on root on 1.


Some basic terms from finite group theory, normalising and centralising

Question: In a proof a read the following "Since $H$ and $N$ normalize each other, if follows that $H \subseteq C_G(N)$". I thought normalising just means that one subgroup is normal with respect to the other, but that does not seems to be meant here.
So what does it mean to say that a subgroup $A$ normalises another subgroup $B$?
And further, it is often read that a subgroup $A$ centralises another subgroup $B$, and I guess this means that $A \le C_G(B)$, right?
Answer: To say "$H$ normalizes $N$" means that for each $h \in H$ we have $hNh^{-1}=N$. Neither $H$ nor $N$ needs to be a subgroup of the other for this to make sense, although both have to be a subgroup of the same group $G$.
Comment: @Stefan: Yes, you are using "centralizing" correctly. There is similar notation for "normalizing", namely $A \le N_G(B)$ means "$A$ normalizes $B$". Both of $C_G(B)$ and $N_B(G)$ are subgroups of $G$.
Comment: thanks, but that does not implies $H \le C_G(N)$ if $H$ and $N$ normalise each other, because why should that imply that the elements of $H$ permute with alle the elements from $N$?
Comment: I overread something, in the proof it is supposed that $H \cap N = \{1\}$, then the conclusion follows.
Comment: But is my usage of the term "centralising" right?
Answer: Let $H,N$ normalize each other and $H\cap N =e$ then $H \subseteq C_G(N)$;
Let $x=hnh^{-1}n^{-1}$ since $H$ normalize $N$, $hnh^{-1}\in N \implies x\in N$
since $N$ normalize $H$, $nh^{-1}n^{-1}\in H \implies x\in H$
As a result $x\in H\cap N \implies x=e \implies hn=nh$.


Decoding the binary part of a Discovery udp packet payload for Tp-Link Tapo c200 IoT IP camera

Question: I'm trying to figure out the API stack of this tplink C200 camera, it's not publicly available. I could figure out most of the Api calls with relative ease using fiddler and Wireshark, but a bit of binary frame in the beginning of a discovery call is baffling me.
Camera's android App starts broadcasting this udp packet to 255.255.255.255 as soon as user logged in for the first time:
0000   ff ff ff ff ff ff 20 4e 7f d9 64 3e 08 00 45 00   ...... N..d>..E.
0010   02 11 08 88 40 00 40 11 b0 46 c0 a8 bf 65 ff ff   ....@.@..F...e..
0020   ff ff cd ed 4e 22 01 fd 1e c3 02 00 00 01 01 e5   ....N"..........
0030   11 00 08 34 d4 be c1 46 b6 89 7b 22 70 61 72 61   ...4...F..{"para
0040   6d 73 22 3a 7b 22 72 73 61 5f 6b 65 79 22 3a 22   ms":{"rsa_key":"
0050   2d 2d 2d 2d 2d 42 45 47 49 4e 20 50 55 42 4c 49   -----BEGIN PUBLI
0060   43 20 4b 45 59 2d 2d 2d 2d 2d 5c 6e 4d 49 49 42   C KEY-----\nMIIB
0070   49 6a 41 4e 42 67 6b 71 68 6b 69 47 39 77 30 42   IjANBgkqhkiG9w0B
0080   41 51 45 46 41 41 4f 43 41 51 38 41 4d 49 49 42   AQEFAAOCAQ8AMIIB
0090   43 67 4b 43 41 51 45 41 33 72 4e 70 4f 66 6b 59   CgKCAQEA3rNpOfkY
00a0   35 35 4d 6a 32 62 6c 77 4e 39 6d 30 5c 6e 62 56   55Mj2blwN9m0\nbV
00b0   50 72 79 76 32 37 68 6c 61 7a 6f 46 37 78 4d 55   Pryv27hlazoF7xMU
00c0   46 4f 46 57 6b 62 63 61 6f 4a 41 67 6e 52 79 45   FOFWkbcaoJAgnRyE
00d0   36 42 56 30 77 70 47 71 68 79 4f 69 49 4f 72 34   6BV0wpGqhyOiIOr4
00e0   35 50 49 55 74 62 54 51 52 45 44 56 34 75 5c 6e   5PIUtbTQREDV4u\n
00f0   2b 4b 6f 55 75 6b 41 4c 71 6c 2f 42 42 6b 41 34   +KoUukALql/BBkA4
0100   76 67 6a 67 4f 55 45 30 79 53 74 36 74 77 61 79   vgjgOUE0ySt6tway
0110   6a 2b 6b 33 73 6e 6b 2f 56 70 49 6a 61 44 74 36   j+k3snk/VpIjaDt6
0120   32 6f 33 62 35 70 6e 44 4b 45 68 48 4c 56 45 66   2o3b5pnDKEhHLVEf
0130   5c 6e 79 6c 4a 30 6b 45 6e 58 4e 43 54 35 68 73   \nylJ0kEnXNCT5hs
0140   6b 64 68 39 66 59 38 78 74 6d 62 42 6d 57 31 47   kdh9fY8xtmbBmW1G
0150   2b 6e 54 6c 30 73 43 47 54 2f 75 75 77 65 31 6b   +nTl0sCGT/uuwe1k
0160   74 67 45 78 7a 70 43 67 57 77 62 75 71 78 49 49   tgExzpCgWwbuqxII
0170   47 54 5c 6e 66 63 58 31 79 52 6d 54 73 77 37 53   GT\nfcX1yRmTsw7S
0180   66 73 5a 71 58 4f 61 39 50 6f 36 62 68 65 73 48   fsZqXOa9Po6bhesH
0190   4e 78 4c 33 48 53 52 35 72 43 6f 73 6f 6f 72 75   NxL3HSR5rCosooru
01a0   34 7a 67 71 6a 6b 64 62 42 2f 57 2b 46 71 6d 35   4zgqjkdbB/W+Fqm5
01b0   42 6d 71 50 5c 6e 44 51 75 4c 6b 49 6c 4c 4a 2b   BmqP\nDQuLkIlLJ+
01c0   34 56 32 71 35 63 48 41 73 67 4d 54 38 48 52 78   4V2q5cHAsgMT8HRx
01d0   31 5a 74 50 75 55 54 78 45 49 66 55 49 4e 58 64   1ZtPuUTxEIfUINXd
01e0   41 57 67 4b 36 75 4d 75 4e 74 4d 4e 5a 56 4f 50   AWgK6uMuNtMNZVOP
01f0   6b 2f 71 54 31 30 5c 6e 72 51 49 44 41 51 41 42   k/qT10\nrQIDAQAB
0200   5c 6e 2d 2d 2d 2d 2d 45 4e 44 20 50 55 42 4c 49   \n-----END PUBLI
0210   43 20 4b 45 59 2d 2d 2d 2d 2d 5c 6e 22 7d 7d 00   C KEY-----\n"}}.

it goes out in intervals, till Camera replies back. I tried to imitate the packet and I was unsuccessful because I couldn't replicate these bytes (beginning of the Data frame):
(002B->003A): 02 00 00 01 01 e5 11 00 08 34 d4 be c1 46 b6 89
As you noticed immediately after this the ASCII readable message starts ({"params":...), I repeated the discovery steps few times and I noticed these bytes are somehow related to the local bound port on the app side that the udp discovery message is sent via, here are the examples I gathered:
Frame in udp packet                 port
0200000101e511000d554fad4de6fb2b    49411
0200000101e5110003ef2ad6767c88ee    49417
0200000101e511000c74622ed5e0246e    50248
0200000101e511000376feec3ed43466    50260
0200000101e51100046c5d74ee1a8de1    50797
0200000101e5110000503e7aa816e491    50802
0200000101e511000fdfc58e766d3742    52169
0200000101e511000e13aaabcd1a38ba    52332
0200000101e511000834d4bec146b689    52717
0200000101e511010000027822e38756    52956
0200000101e5110003e10659047571be    53370
0200000101e511000cbad8000079daf0    53500
0200000101e5110002e5bc217cb12739    57161
0200000101e511000922aa242d80ae84    58170
0200000101e511000d8945e5e21b2265    58421
0200000101e511000f97146569f2cbfe    58425
0200000101e511000d66c663c5ac4d69    59985
0200000101e511000105947d8d9e16f9    61818
0200000101e511000c9ed77f9024d65f    61879
0200000101e5110008b9a7fbc1624863    61927
0200000101e511000b3d5323ee84b6b7    62182
0200000101e511000f7b9b183a81ff80    62996
0200000101e511000da2e8028da2f46a    63043
0200000101e5110000c4390fbdc258e2    63046

I cannot find the relation, I tried few different IoT protocols and hashing methods, Does anybody know what are these or how are they calculated?
P.S.
Those port number are somehow coded inside those frames, it should be an industrial coding, simple hash or xor encryption. Any idea?
Comment: What's the one, focused question here? You should take a look at https://stackoverflow.com/help/how-to-ask, as the current question sounds most like "What does all of this mean?"
Answer: It looks like the app is generating an RSA public/private key pair and is broadcasting the public key within a JSON object.  The port in use has nothing to do with the key pair.  In fact, even if the same port is ever reused again, the key pair will still be different. If you want to know more about RSA, maybe start here? https://en.wikipedia.org/wiki/RSA_(cryptosystem)
Comment: I actually noticed that, but the UDP packet data starts at 002B, before the json object these bytes are added: 0200000101e511000d554fad4de6fb2b, in my tests I noticed by adding these bytes and set the port to the corresponding value, the camera replies back with it's own rsa public key. but if I leave those bytes empty, omit them or fill with different values, I get no answer.
Comment: The IP total length is 529 bytes (0x0211), so subtracting 20 bytes for the IP header length itself and 8 bytes for the UDP header, you end up with 501 bytes (0x01f5).  There looks to be 16 bytes for the payload header, so 501-16=485 (0x01e5), so the 5th and 6th bytes of those 16 bytes of payload is the length field in big-endian format.  Other bytes could be payload types, checksums, sequence numbers, who knows.
Comment: No idea if this packet format is exactly the same, but considering the PktLength matches what I discovered on my own, maybe Slide 37 of this document helps? https://www.troopers.de/downloads/troopers17/TR17_fgont_-iot_tp_link_hacking.pdf
Comment: Just got off work, those are brilliant, thank you. I'll try this evening and let you know, thanks again :)
Answer: edit: This has stopped working - it may be that a firmware update was pushed to change what the plugs respond to? Unsure. Will investigate at some point.
It may be a late reply but I was recently working on this problem myself and can share what I figured out:

The first four bytes are always 2, 0, 0, 1.
The next two bytes are the length of the json bytestring that comes later, encoded as a two-byte number in big-endian.
The next two bytes are 17 (11 in hex) and 0.
The next 4 bytes are completely randomly generated - they can be anything. The Tapo android app that I examined to figure this out generated a random value from 0 to 268435456 and converted that to a 4-byte big-endian value for this purpose.
The final step is a little trickier: insert the number 1516993677 encoded to a 4-byte big endian value, but then overwrite it with a crc32 checksum on the whole byte array (including the json on the end). That should give you a value that you can send and have tp-link smart plugs/cameras respond to.

Here's a couple of python functions that I ended up using to generate these bytes in my own project:
from random import randrange
from zlib import crc32
from Crypto.PublicKey import RSA

def get_payload():
    key = RSA.generate(2048).publickey().exportKey('PEM')

    # newline on the end and no spaces in separators to perfectly match
    #  the packets sent by vendor apps
    payload = json.dumps(
        {'params': {'rsa_key': key.decode('utf-8') + '\n'}},
        separators=(',', ':')
    )

    # Fun fact: the P100 plugs will respond just the same if you send
    #  b'\x02\x00\x00\x01\x00\x00\x11\x00\x0e\xd7\xd6\xac\x84\x0e\xfdY'
    #  which is the result of passing an empty string to build_packet()
    #
    # We send a full packet anyway, however, in case future firmware
    #  updates fix that
    return build_packet(payload)

def build_packet(string):
    # Magic prefix bytes generated by reverse-engineering the Tapo android app
    #  algorithm found in com\tplink\tdp\common\b.java
    prefix = b'\x02\x00\x00\x01\x00\x00\x11\x00\x00\x00\x00\x00Zk|\x8d'

    output_array = bytearray(prefix + string.encode('utf-8'))

    # Insert dynamic bytes that change based on the string / randomness
    output_array[4:6] = len(string).to_bytes(2, 'big')
    output_array[8:12] = randrange(268435456).to_bytes(4, 'big')

    # Insert checksum based on current array
    output_array[12:16] = crc32(output_array).to_bytes(4, 'big')

    return bytes(output_array)

(You can see a little more of how this was figured out in the commit history at the above link)


non-isosceles triangles with vertices in a 20-sided regular polygon.

Question: Suppose $A_1A_2 . . . A_{20}$ is a $20-$sided regular polygon.
How many non-isosceles (scalene) triangles
can be formed whose vertices are among the vertices of the polygon but whose sides are not
the sides of the polygon?
I could'nt find a cute answer to this problem. My answer is different from those at other websites. Not to mention that the answers are also different at different websites.
Comment: Can you give the websites on which there are answers ?
Comment: Please provide your answer, as well as links to those "other websites". (The original source of the problem would be helpful, as well.) Otherwise, we could just be duplicating existing work, which is a waste of time and effort for everyone involved.
Answer: We first count all nondegenerate triangles containing no edge $A_iA_{i+1}$, and then subtract  the isosceles triangles among these.
Put the first vertex $v_1$ at $A_0=A_{20}$. If you put $v_2$ at $A_2$ or $A_{18}$ then there are $15$ allowed $A_i$ left for $v_3$. If you put $v_2$ at an $A_i$ with $3\leq i\leq 17$  then there are $2\cdot 3=6$ forbidden $A_i$ for $v_3$. It follows that you can choose $(v_1,v_2,v_3)$ in
$$20\cdot2\cdot 15+20\cdot 15\cdot 14=4800$$
ways, giving rise to ${1\over6}\cdot4800=800$ different triangles.
The tip of an isoscles triangle can be chosen in $20$ ways, and then the base in $8$ ways. Since there is no equilateral triangle possible  it follows that there are $160$ isosceles triangles.
The total number of admissible triangles  therefore is $640$.
Answer: We will show that the number of non-isosceles (scalene) triangles that can be formed whose vertices are among the vertices of a regular polygon of $n$ sides but whose sides are not the sides of the polygon is
$$2n\left(\left[\frac{n-7}{2}\right] + \left[\frac{n-10}{2}\right]+\cdots \right)$$ where $[\cdot]$ is the greatest integer function. In particular, when $n=20$, there are
$$40\left(\left[\frac{13}{2}\right] + \left[\frac{10}{2}\right]+ \left[\frac{7}{2}\right]+\left[\frac{4}{2}\right] \right) = 640$$
triangles.
We start with counting the number of triples $(d_1, d_2, d_3)$ such $2 \leq d_1 < d_2 < d_3$ and $d_1+d_2 +d_3 = n$. Putting $x_i = d_i-1$, we need the number of solutions $(x_1, x_2, x_3)$ such that $x_1 < x_2 < x_3$ and $x_1 + x_2 + x_3 = n-3$.
For any positive integers $N, p$ let $Q(N,p)$ denote the number of solutions to $$x_1 + x_2 + x_3+ \cdots +x_p = N$$ with $x_1 < x_2 < x_3 < \cdots < x_p$ and $P(N,p)$ denote the number of solutions to $$x_1 + x_2 + x_3+ \cdots +x_p = N$$ with $x_1 \leq x_2 \leq x_3 \leq \cdots \leq x_p$. We can call these solutions as distinct $p$ partitions  of $N$ and $p$ partitions of $N$ respectively.
If $(x_1, x_2, \ldots, x_p)$ is a distinct $p$ partition of $N$, then $(x_1, x_2-1, x_3-2, \ldots, x_p-(p-1))$ is a $p$ partition of $N - \frac{1}{2}p(p-1)$ and similarly if $(y_1, y_2, \ldots, y_p)$ is a $p$ partition of $N - \frac{1}{2}p(p-1)$, then $(y_1, y_2+1, \ldots, y_p+(p-1))$ is a distinct $p$ partition of $N$. Hence we have
$$Q(N,p) = P\left(N-\frac{1}{2}p(p-1), p\right)$$
Again, if $(x_1, x_2, \ldots, x_p)$ is a $p$ partition of $N$, then $(x_1-1, x_2-1, \ldots, x_p-1)$ is a partition of $N-p$ with at most $p$ parts. Thus
$$P(N,p) = P(N-p, 1) + P(N-p, 2) + \cdots + P(N-p, p)$$
Replacing $N$ by $N-1$ and $p$ by $p-1$ we get
$$P(N-1,p-1) = P(N-p, 1) + P(N-p, 2) + \cdots + P(N-p, p-1)$$
Hence
$$P(N,p) = P(N-p, p) + P(N-1, p-1)$$
We need $Q(n-3, 3)$. Noting that $P(m,2) = \left[\frac{m}{2}\right]$ for any positive integer $m$, we have
\begin{align*}
Q(n-3,3) &= P(n-6, 3) \\
&= P(n-9,3) + P(n-7, 2) \\
&= P(n-9, 3) + \left[\frac{n-7}{2}\right] \\
&= P(n-12, 3) + P(n-10, 2) + \left[\frac{n-7}{2}\right] \\
&= P(n-12, 3) + \left[\frac{n-10}{2}\right] + \left[\frac{n-7}{2}\right]
\end{align*}
Hence we have
$$Q(n-3, 3) = \left[\frac{n-7}{2}\right] + \left[\frac{n-10}{2}\right]+\cdots $$
For any distinct 3 partition $(d_1, d_2, d_3)$ of $n-3$ we obtain two non isosceles triangles with one of the vertices as $A_i$: $(A_i, A_{i+d_1}, A_{i+d_1+d_2}$ and $(A_i, A_{i-d_1}, A_{i-d_1-d_2})$ where all additions and subtractions are modulo $n$ and the vertices are named as $A_0, A_1, \ldots, A_{n-1}$. Hence the number of distinct triangles is
$$2n\left(\left[\frac{n-7}{2}\right] + \left[\frac{n-10}{2}\right]+\cdots \right)$$
Updated on 5 December 2016:
Is it possible to find a closed form for $$Q(n-3, 3) = \left[\frac{n-7}{2}\right] + \left[\frac{n-10}{2}\right]+\cdots $$
Yes, one can obtain the following:
\begin{equation}
Q(n-3,3)=
\begin{cases}
\frac{1}{12}(n-6)^2, &\text{if $n = 0\mod 6$;}\\
\frac{1}{12}((n-6)^2-1), &\text{if $n = 1\mod 6$;}\\
\frac{1}{12}((n-6)^2-4), &\text{if $n = 2\mod 6$;}\\
\frac{1}{12}((n-6)^2+3), &\text{if $n = 3\mod 6$;}\\
\frac{1}{12}((n-6)^2-4), &\text{if $n = 4\mod 6$;}\\
\frac{1}{12}((n-6)^2-1), &\text{if $n = 5\mod 6$;}
\end{cases}
\end{equation}
How does one get the above forms?
Suppose that $n = 0\mod 6$. Now, compute the values of $Q(n-3,3)$ for some initial values, say $12, 18, 24, 30, 36, \ldots$. These are respectively $3, 12, 27, 48, 75, \ldots$. We use the Newton's interpolation formula. Given values
$$
 \begin{array}{ccccc}
 x_0 & x_1 & x_2 & x_3 & \cdots \\
 f(x_0) & f(x_1) & f(x_2) & f(x_3) & \ldots
 \end{array}
 $$
\end{center}
with $x_{i+1} - x_i = h$ for all $i$, we have, by Newton's formula
$$f(x_0+th) = f(x_0) + \frac{t}{1!}\Delta f(x_0) + \frac{t(t-1)}{2!}\Delta^2 f(x_0) + \cdots $$
where $\Delta f(a) = f(a+h) - f(a)$ is the finite difference of $f$ at $x=a$.\ Consider the following difference table
$$\begin{array}{cccc}
n & Q(n-3,3) & \Delta & \Delta^2\\
 12 & 3 &  &  \\
 18 & 12 & 9 &  \\
 24 & 27 & 15 & 6 \\
 30 & 48 & 21 & 6 \\
 36 & 75 & 27 & 6 \\
 42 & 108 & 33 & 6
\end{array}
$$
Noting the second difference is a constant, writing $f(n) = Q(n-3,3)$ we obtain
\begin{align*}
f(n) =& f\left(12 + \frac{n-12}{6} \times 6\right) \\&= f(12) + \frac{\frac{n-12}{6}}{1!}\Delta f(12) + \frac{\frac{n-12}{6} \cdot \frac{n-18}{6}}{2!}\Delta^2 f(12) \\
&= 3 + \frac{9}{6}(n-12) + \frac{1}{12}(n-12)(n-18) \\
&= \frac{1}{12}(n-6)^2
\end{align*}
Other expressions can be similarly obtained.
Answer: Given a regular polygon of $2n$ sides,
start by counting all the distinct triangles that can be formed
from the vertices of a $2n$-gon:
$
\binom{2n}{3}.
$
Then eliminate the ones that don't belong to the set by counting these
disjoint sets of triangles:

Isoceles triangles. There are $n - 1$ different possible lengths for each of the equal sides, and $2n$ possible placements of the vertex between those sides, so $2n(n-1)$ such triangles if $n$ is not a multiple of $3$. (If $n=3k$ then the preceding procedure counts each equilateral triangle three times and we must remove the duplicates. Compare this answer.)
Triangles with exactly one side on the $2n$-gon. Note that no such triangle can be isoceles. There are $2n$ ways to choose the side on the $2n$-gon, and the third vertex can be any of the $2n-4$ points not adjacent to the vertices of the common side, so there are $2n(2n-4)$ such triangles.

There is no need for a third set of triangles consisting of those that share two sides in common with the $2n$-gon; those were included among the isoceles triangles.
The total number of triangles in all three excluded sets is
$2n(n - 1) + 2n(2n-4) = 2n(3n-5)$.
So the total number of scalene triangles not sharing a side with
the $2n$-gon is
$$
\binom{2n}{3} - 2n(3n-5).
$$
Setting $2n = 20$, we have
$$\binom{2n}{3} - 2n(3n-5) = \binom{20}{3} - 20(25) = 1140 - 500 = 640.$$
Answer: Total number of $\triangle  =  $no. of $\triangle$ with no side common $+$ no. of $\triangle$ with one side common $+$ no. of $\triangle$ with two sides are common
$\bullet\;$ Triangle with one side common $\displaystyle = \binom{n-4}{1} \times n$
$\bullet\;$ Triangle with two sides are common $\displaystyle  = n$
So no. of $\triangle$ with no side common $$ = \binom{n}{3}-n(n-4)-n$$
Put $n=20$
Comment: You forget to get rid of the isosceles triangles.
Answer: Let $a<b<c$ be the "sidelengths" of the triangle. The given conditions then enforce
$$a=2+x_1,\quad b=3+x_1+x_2,\quad c=4+x_1+x_2+x_3$$
with
$$x_i\geq 0\quad(1\leq i\leq 3),\qquad 3x_1+2x_2+x_3=11\ .\tag{1}$$
Choosing $x_1:=0, 1, 2, 3$ in turn produces $6+5+3+2=16$ solutions of $(1)$. Each of the $16$ resulting shapes can be placed in $40$ ways, hence there are $640$ admissible triangles in all.
Answer: No. of scalene triangles
$$= C_{20}^3-180= \frac{20\cdot 19\cdot 18}{6} - 180 = 960$$
Comment: This would include the triangles whose sides are common with that of polygon.


How to calculate the angles from angle-side couples in a series of triangles (with an algebraic solution)?

Question: In this image, the red and black labels are known, and the aim is to calculate one of the blue angles or sides (the rest will follow).

There is no standard trigonometric solution, as we know only one angle and one side for each triangle. However, I believe there should be an algebraic solution for the common variables we have for different angles.
For example,
$$\frac{\sin b}{2A} = \frac{\sin c}{C} = \frac{\sin d}{D} $$
$$\frac{\sin b1}{A} = \frac{\sin c}{B} = \frac{\sin a}{D} $$
$$\frac{\sin b2}{A} = \frac{\sin e}{C} = \frac{\sin d}{B} $$
When knowing only $2A$ and $b$ for the main triangle, there are unlimited solutions. However, the given $a$ restricts to one single solution. This is why I believe this problem is solvable.
Comment: There are infinitely many solutions:  as $B$ changes, so do $b_1$ and $b_2$.
Comment: @AndrewChin draw the triangle with arbitrary values for $A$, $a$, and $b$. Only single values will fit $B$, $b1$, and $b2$. I mean you cannot redraw a different triangle with the same $A$, $a$, and $b$.
Comment: My mistake, I did not see that $b$ was fixed.
Answer: It is difficult to analyze this symbolically, but at least I can give the equations and you can check if they have solutions for certain values of the given quantities. The strategy is to obtain two equations relating $D$ and $C$. Let $M=\cos\left(b_{1}+b_{2}\right)$ and $S=\sin\left(b_{1}+b_{2}\right)$. By inspection of the figure, we easily obtain the following equation:
$$ C=\frac{2A\sin\left(b_{1}+a\right)}{\sin\left(b_{1}+b_{2}\right)} \tag{1}$$ Now $$\cos\left(a-b_{2}\right)=\cos\left(\left(a+b_{1}\right)-\left(b_{1}+b_{2}\right)\right)=M\cos\left(a+b_{1}\right)+S\sin\left(a+b_{1}\right) \tag{2}$$
We also have: $$B^{2}=A^{2}+C^{2}-2AC\cos\left(a-b_{2}\right) \tag{3}$$
$$B^{2}=A^{2}+D^{2}+2AD\cos\left(a+b_{1}\right) \tag{4}$$ Equating $(5)$ and $(6)$ gives
$$C^{2}-D^{2}=2A\left(C\cos\left(a-b_{2}\right)+D\cos\left(a+b_{1}\right)\right) \tag{5}$$ We also have $$ 4A^{2}=D^{2}+C^{2}-2DC\cos\left(b_{1}+b_{2}\right) \tag{6}$$ Here comes the tedious part, you substitute from $(2)$ into $(5)$, use the identity $\cos\left(a+b_{1}\right)=\sqrt{1-\sin^{2}\left(a+b_{1}\right)}$, and substitute for $\sin\left(a+b_{1}\right)$ from $(1)$ and finally solve $(5)$ and $(6)$ simultaneously. You can do that because both equations will only have $C$ and $D$ as unknowns in terms of known quantities then. You will get a monstrous polynomial and the situation will probably be quite complicated even if you substitute numbers for the known quantities. It would be interesting to know if this gives the solution(s) though.
One more thing, note that there will be  more to do if you were able to find suitable solutions for $(5)$ and $(6)$, namely, you will have to deal with the following system of equations, with $b$ given, you have: $$b_{1}+b_{2}=b \tag{7}$$
$$\sin\left(b_{1}\right)=\frac{A\sin a}{D} \tag{8} $$
$$\sin\left(b_{2}\right)=\frac{A\sin\left(a\right)}{C} \tag{9}$$
So $a$ can't be given arbitrarily. This says that this arrangement you are considering is quite special, if it exists (After playing around with some values, I think this can't exist due to the presence of some heavy constraints on $A$, $C$ and $a$, but attempting to prove this in general would be tedious).
Answer: Apply the sine rule to the two divided triangles to get
$$D = \frac{\sin a}{\sin b_1} A, \>\>\>\>\> C = \frac{\sin a}{\sin b_2} A$$
Substitute above $D$ and $C$ into the cosine formula below
$$4A^2 = D^2+C^2 -2DC \cos b$$
to obtain
$$\frac4{\sin^2a} = \frac1{\sin^2 b_1} + \frac1{\sin^2 b_2}  -\frac{2\cos b}{\sin b_1\sin b_2} \tag1$$
Along with
$$b_1+b_2=b\tag2$$
the two equations (1) and (2) determine $b_1$ and $b_2$. All other blue angles and sides can then be calculated.
Comment: Sorry, but I didn't follow the last line. How do eqs.(1) and (2) give $b_1$ and $b_2$?
Comment: @Googlebot - you have two equations (1) and (2), and two unknowns $b_1$ and $b_2$. For example, if you substitute $b_2=b - b_1$ into (1), you can solve for $b_1$


How to route specific IPv6 address & port to another port?

Question: I just got a VPS with an IPv4 address as well as a bunch of IPv6 addresses configured and I'm new to routing in Ubuntu/Linux. I would like to route requests with a specific IPv6 and port (i.e. port 80) as destination to a specific port on that address (i.e: port 8000).
In pseudo-code, what I want is the following:
if($DESTINATION_IP == [specific IPv6-address]:80)
    route to port: 8000

When an application is listening on [specific IPv6-address]:8000, it will receive the requests sent to [specific IP-address]:80. But when I use [another IPv6-address]:80, it will not route to that port.
It seems pretty simple and I think I would have to use ip6tables for the job, but I don't know how to achieve this.
Many thanks.
Comment: Thanks. That is one option I considered. But as I understand it, a service listening to ports < 1024 needs root/su access. Port 80 is just an example (the port most webservices use). I want to be able to route to another port when someone reaches my VPS with a specific IPv6-address as a destination, without having to grant root access to the service.
Comment: It is probably easier to listen on port 80 or another port and route/proxy with that application (i.e. by using a webserver). Although it's not quite the solution to the problem described here, it is the solution to the underlying problem.
Comment: Could you not just set the service to listen on port 80 for the specific address in the first place?
Comment: While it may be easier to install a new application to function as a proxy, it's not necessarily simpler as it adds complexity to the software stack. Adding Apache + mod_proxy to replace a basic functionality of iptables seems rather klunky.
Answer: You cannot forward ports with ip6tables, as the relevant netfilter targets are IPv4-only (due to their relation to NAT, which IPv6 gets rid of).
The best solution, of course, is to have the application listen on the correct address and port to begin with, and then drop privileges.
If you really need to do this, because you have a poorly written application that can't listen on ports below 1024, set up xinetd to do the port forwarding. For instance (this is untested):
service dumb-app
{
    flags       = IPv6
    type        = UNLISTED
    socket_type = stream
    protocol    = tcp
    wait        = no
    user        = root
    bind        = 2001:db8::f04d
    port        = 80
    redirect    = ::1 8000
}

Comment: I went with the 'best solution' after all. In my case it proved to be way easier to indeed use nginx (or another webservice meant for this) to listen on port 80 (or another port) and proxy to another port, based on the hostname or path.
I did not try your xinetd solution, but it might be useful for future reference. I will edit the example port 1000 in my question, because you use a different example and port 1000 is <1024.
Comment: @StefanLasiewski Exactly, IPv4 is not involved. What are you trying to say?
Comment: How would one do this with ip6tables only? Can `ip6tables` direct `[specific IPv6-address]:443` to either `[specific IPv6-address]:8443` or to the localhost/loopback address `[::1]:8443`? `iptables` did this [using the NAT table](https://stackoverflow.com/questions/24736543/tomcat-7-automatically-redirect-https-requests-to-port-8443), but NAT isn't supported in the CentOS5 version of netfilter.
Comment: (Side note: I read that [Kernel >= 3.9.0 & ip6tables version 1.4.18 provides NAT again](http://mirrors.bieringer.de/Linux+IPv6-HOWTO/nat-netfilter6..html))
Comment: @StefanLasiewski That's what I said!
Comment: As I read your question, you are saying that ip6tables cannot forward to an IPv4 target. That makes sense, since we're talking about *ip6&tables. I simply want to use ip6tables to direct one port to a different port. I inherited this software, I need to enable it for IPv6 with as few changes as possible, and I'd like to avoid using yet-another-piece-of-software like xinetd or an Apache proxy.


Given a positive numbers $a$ so that $a\neq 1$. Prove that $\frac{\log a}{a-1}\leqq\frac{1+a^{1\div 3}}{a+a^{1\div 3}}$ .

Question:
Given a positive numbers $a$ so that $a\neq 1$. Prove that
  $$\frac{\log a}{a- 1}\leqq \frac{1+ a^{1\div 3}}{a+ a^{1\div 3}}$$

Note $\log a= \log_{e} a$ .
It would be hard if derivative the polynomial $\frac{\log a}{1- a}+ \frac{1+ a^{1\div 3}}{a+ a^{1\div 3}}$ , even Wolfram|Alpha. I need to the helps
Yes, Mr. Michael Rozenberg
Take $x= a^{3}$
$$\frac{{\rm d}}{{\rm d}x} \left ( \frac{1+ x}{x+ x^{3}}- \frac{\log x^{3}}{x^{3}- 1} \right )= \frac{1}{x+ x^{3}}- \frac{3}{(x^{3}- 1)x}- \frac{(3x^{2}+ 1)(1+ x)}{(x+ x^{3})^{2}}+ \frac{3x^{2}\log x^{3}}{(x^{3}- 1)^{2}}= 0$$
I can't solve it
Comment: Take $a=x^3$. If you want to see my full solution, show please your attempts.
Comment: Please do not rollback to the previous version. I edited your post to use more common symbols, so that they are easier to search for.
Comment: please see. i added some
Comment: thank you a real lot!
Answer: Let $a>1$ and $a=x^3$.
Thus, we need to prove that $f(x)\geq0,$ where
$$f(x)=\frac{(1+x)(x^3-1)}{3(x^3+x)}-\ln{x}.$$
But, $$f'(x)=\frac{(x-1)^4(x^2+x+1)}{3(x^3+x)^2}\geq0,$$
which gives $f(x)\geq0.$
The case $0<a<1$ is the same.


What to consider when selecting the number of keys for a keyboard

Question: I might be planning to buy a keyboard in the near feature, now I see they come in different amount of keys. It makes me wonder for how many keys I should go, more allows more complex music...
But how do I get an idea of the complexity of music that a certain amount of keys allow?
Edit: Are there lists of repertoire available that use the outer octaves of the keyboard, or should I instead ask a new question for them?
Comment: @tom: 88 keys is precisely standard for a piano. :P I know what I'm talking about. Good luck finding one that has any less, for sure. Electronic keyboards are another matter I suppose...
Comment: I've never seen a list of repertoire x number of keys. As a rough answer, if you want to play songs, tunes, four octaves should do. If you want to play classic baroque music, five octaves (think harpsichord), for classic romantic you need a full keyboard. But really, why don't you just get a full 88-keys and save yourself the trouble?
Comment: @NReilingh Do you realize you just linked Tom Wijsman to a question he answered with the accepted answer (a pretty knowledgeable one if I might add).
@Tom Wijsman I realize that you're an enthusiast and not a "professional" in regards to piano music.  You'd benefit from asking for a list of repertoire that uses the outer octaves of the keyboard, something which definitely wouldn't have been done until the extra octaves were added, and even then many composers did not use them.  Make your decision based on how large that list is (or how important you find it to be)
Comment: Having played classical music on piano for more than 15 years, I have occasionally reached the lowest key (A0) and the highest key (C8) on a normal 88-key piano while playing some romantic-era songs. Having encountered music from the Renaissance to modern music, I have never ever been in a situation that requires the 89th key and I don't think you should be either. I guess the only songs that might use the 89th keys are just post-modern songs, which very few piano virtuosi do play.
Comment: What do you want to play? Classical? Jazz? Rock accompanyment? It depends a huge lot on this. For the first two, the standard 88 keys should be enough. What are your options?
Comment: @Noldorin: I don't think 88 keys are standard for a piano keyboard, or at least not from an enthusiast perspective. I would be playing different types of music, my music taste is kind of all-round with some exceptions. I think style should not matter, I've seen a site mention complexity but I don't have an idea how the complexity scale maps back to the amount of keys...
Comment: possible duplicate of [Will a 61-key keyboard severely restrict my piano repertoire?](http://music.stackexchange.com/questions/492/will-a-61-key-keyboard-severely-restrict-my-piano-repertoire)
Answer: While 61 keys might be fine for a synth being used, say in a band, I would recommend at least 76 keys for playing piano music.
The deciding factor for me getting 88-key keyboards the last 10 years, though, has been they are often the only models with weighted hammer-action-like keys.


Como atualizar o valor do output em tempo real

Question: Olá, em uma apostila que estou lendo tem um trecho para atualizar o valor do output com base em um input type="range".
  Tem os códigos e tudo, mas apesar de estar igual(ou pelo menos parece), não consigo ver o por que de não funcionar então se possível alguém poderia me dar uma luz?
Segue o código do fildset onde o input e o output estão;
<fieldset class="tamanhos">
    <legend>Escolha o Tamanho:</legend>
    <input type="range" min="36" max="46" step="2" name="tamanho" id="tamanho">
    <output for="tamanho" name="valortamanho" id="valortamanho">42 </output>
</fieldset>

Código do javascript;
 var inputTamanho = document.querySelector('[name=tamanho]')
 var outputTamanho = document.querySelector('[name=valortamanho]')
 /*pg 199*/
function mostraTamanho(){
    outputTamanho.value = inputTamanho.value
}

inputTamanho.oninput = mostraTamanho

Answer: Tente usar o oninput diretamente na função deste modo:

window.onload = function() {
  var inputTamanho = document.querySelector('[name=tamanho]');
  var outputTamanho = document.querySelector('[name=valortamanho]');
  inputTamanho.oninput = function() {
    outputTamanho.value = inputTamanho.value;
    console.log(inputTamanho.value);
  }
}
<fieldset class="tamanhos">
  <legend>Escolha o Tamanho:</legend>
  <input type="range" min="36" max="46" step="2" name="tamanho" id="tamanho">
  <output for="tamanho" name="valortamanho" id="valortamanho">42 </output>
</fieldset>
Comment: Muito obrigado, esta atualizando normalmente nesse modo.


vba stuck in a loop and not moving on to next command

Question: i have written the following code:
Public Sub SortMyData()

'approach: convert line to string and concatenate to that as it's a lot less picky than Excel's formats, then replace cell value with the new string.
'          Excel will then define the string type as either Percentage or Scientific depending on the magnitude.
Dim i As Integer
Dim g As Integer
Dim N_Values As Integer
Dim IntermediateString As String

N_Values = Cells(1048576, 2).End(xlUp).Row 'retrieves the final filled row in column 2 (B)

For i = 6 To N_Values 'iteration loop from 6 (first row of value) to N_Values (last filled row)

    If Cells(i, 2).NumberFormat <> "0.0%" Then
        IntermediateString = Cells(i, 2).Value
        Cells(i, 2).NumberFormat = "0.0%"
        Cells(i, 2).Value = Cells(i, 2).Value / 100
    Else
        MsgBox ("The Range of Cells Has Already Been Formated as Percentage")
    End If
Next i

For g = 6 To N_Values 'iteration loop from 6 (first row of value) to N_Values (last filled row)
    If Len(Cells(g, 3) > 3) Then
        Cells(g, 3).Value = Cells(g, 3).Value / 1000
    Else
        MsgBox ("Data is correct so no action will be taken")
    End If
Next g
End Sub

the code runs fine but it does not move onto the secont if statement, it just keeps on running the first one and displaying the MsgBox ("The Range of Cells Has Already Been Formated as Percentage") so i dont know where i have made a mistake?
i am a rookie by the way so go easy on me!
Comment: what value do you get for `N_Values` ? debug it in F8 mode, Or use last row in this method `N_Values = Cells(Rows.Count, "B").End(xlUp).Row`
Comment: What second if statement? Do you mean the second loop? That won't run until you dismiss somewhere between 0 and N_Values - 6 message boxes.
Comment: As above; you are looping from row 6 to N_Values first for column 2, then doing it again for column 3.  It will complete all of one before it does the other.  Put both `IF` statements inside the first loop and delete the second one...
Answer: You declare the string :
Dim IntermediateString As String

Then you affect a value to it (by the way, the .Value is optional, cells(x, y) and cells(x, y).Value are the same) :
IntermediateString = Cells(i, 2).Value

But then you don't do anything with this string, so I'm pretty sure that's not what you intended to do (you could comment both of those line, your program would run the same way).
Also, seeing as your program is coded, you should have at most as much messages "The Range of Cells Has Already Been Formated as Percentage" as the number of lines in the B column, but it should eventually keep going to reach second if statement.
I suggest you open the execution window (Ctrl + G), and replace the occurences of "MsgBox" in your code by Debug.Print. You will see the message in the execution window, but it won't pause the execution of the program (much better way to debug)