Tabela dinâmica com adição de linhas e colunas

Question: É possivel criar uma tabela dinamica com adição de linhas e colunas?
Conforme a imagem, a situação é:
- Inicia uma tabela com 3 colunas e uma linha;
- Considerando que a primeira linha e a primeira coluna teria que ser editável(ser possível o usuario digitar nela);
- Dentro das linhas vazias trariam radio button;
Agora vem a parte que eu não consigo achar uma solução:
- Quando clica no botão + da horizontal vai adicionar mais uma coluna( no máximo 5 colunas);
- Quando clica no botão + da vertical vai adicionar mais uma linha;
- E precisam estar sempre batendo a coluna com as linhas, conforme o exemplo na imagem.
É possivel fazer uma tabela tão dinâmica assim?
Answer: Você terá alguns desafios para resolver, como por exemplo identificar corretamente os "radio buttons" para cada pergunta, mas deixo um código para sugestão.

//Adiciona linhas
$(".add-row").click(function () {
    if ($('.row-title').val() == '') {
        alert('Digite o título da pergunta');
        return;
    }

    if ($("#pergunta tbody tr td").length) {
        //clona a última linha
        $tr = $("#pergunta tbody tr:last-child").clone(true);
        var index = $("#pergunta tbody tr").length;
        var name = 'rd[' + (index + 1) + ']';
        //altera o nome e a propriedade checked do input
        $tr.find('td').children('input').attr('name', name).prop('checked', false);
        //altera o texto da primeira célula com o valor do input
        $tr.children('td:first-child').text($('.row-title').val());
        //adiciona no corpo da tabela
        $("#pergunta tbody").append($tr);
    } else {
        $("#pergunta tbody tr").append('' + $('.row-title').val() + '	');
    }

});
//Adiciona colunas
$(".add-col").click(function () {

    if ($("#pergunta tbody tr td").length) {

        if ($('.col-title').val() == '') {
            alert('Digite a resposta');
            return;
        }

        var qtdMax = 5;//quantidade máxima de colunas
        if ($("#pergunta thead tr th").length < qtdMax) {
            //adiciona nova coluna com o texto do input
            $("#pergunta thead tr").append('' + $('.col-title').val() + '	');
            //percorre cada linha do corpo da tabela
            $("#pergunta tbody tr").each(function () {
                //verifica o nome dos inputs da linha correspondente
                var name = 'rd[' + ($(this).index() + 1) + ']';
                //adiciona o input na coluna
                $(this).append('<input type="radio" name="' + name + '">	');
            });
        }
    } else {
        alert('Adicione a primeira pergunta antes de adicionar respostas!');
    }

});

    <input type="text" class="row-title" />
    <button type="button" class="add-row">
        + Pergunta
    </button>

    <input type="text" class="col-title" />
    <button type="button" class="add-col">
        + Resposta
    </button>

Comment: @abfurlan muito obrigada pela sua ajuda!!!
Comment: @IsabellaMeirelles veja minha edição, acredito que agora ficou ok
Comment: @abfurlan resolveu sim!!! obrigada pela sua grande ajuda!!!
Comment: Não entendi o voto contra, seria importante o Feedback do pq negativar a resposta, assim talvez pudesse melhorá-la.
Comment: Desculpe não ter informado antes, só dei o ponto negativo pelo fato de não ter seguido o máximo de 5 colunas citado acima, e claro que esse ponto pode ser revertido.
Comment: @MateusVeloso ok entendo, eu fiz o código na correria e não me atentei, mas já corrigi
Comment: @abfurlan seu exemplo está ótimo, eu vou trabalhar em cima dele, uma pergunta, no seu exemplo apenas consigo selecionar uma radio, isso deve ser o que vc falou sobre o desafio de identificar uma radio para cada pergunta, vc tem alguma sugestão do caminho pra isso?
Comment: @IsabellaMeirelles sim é um dos desafios, o nome dos inputs estavam idênticos e por isso só conseguia seleciona um, veja minha edição com uma ideia de como resolver este problema.
Comment: @abfurlan posso aproveitar e fazer outra pergunta? se eu quisesse retirar a linha que corresponde a: "resposta" e os dois radiosbuttons(que é a linha que já vem no html, e deixar pra deixar apenas ser pra essa adição ser feita via os inputs(como já ocorre nas proximas linhas criadas), mudaria toda a lógica aplicada no js? eu tentei fazer uma mudança pra isso mas sempre desconfigura a tabela toda
Comment: @IsabellaMeirelles sim, neste caso muda a lógica, terá que fazer algumas verificações, mas acredito que o mais fácil será criar a tabela do zero quando ainda não houver pergunta. Assim que tiver um tempo vejo se consigo editar.
Comment: @abfurlan obrigada, estou tentando alterar mas ainda sem sucesso, to penando bastante
Answer: Primeira conselho que lhe dou, se realmente precisa de algo tão dinâmico, jQUery não é o caminho, tente o VueJS.
Abaixo segue um exemplo completo, veja que manipular a tabela nem é tão doloroso.

var app = new Vue({
  el: '#tabela',
  data: {
    respostas: [
      { texto: 'Sim' },
      { texto: 'Não' }
    ],
    perguntas: [
      {
        texto: 'Pergunta 1',
        respostas: [
          { selecionado: false },
          { selecionado: false }
        ]
      }
    ]
  },
  methods: {
    addResposta: function (event) {
      var count = this.respostas.length + 1;
      if (count <= 5) {
        this.respostas.push({ texto: 'Resposta ' + count });
        this.perguntas.forEach(function (pergunta) {
          pergunta.respostas.push({ selecionado: false });
        })
      } else {
        alert('Não é possivel adicionar mais que 5 perguntas');
      }
    },
    delResposta: function (indice) {
      this.respostas.splice(indice, 1);
      this.perguntas.forEach(function (pergunta) {
        pergunta.respostas.splice(indice, 1);
      })
    },
    addPergunta: function (event) {
      var count = this.perguntas.length + 1;
      var respostas = this.respostas.map(function () {
        return { selecionado: false };
      })
      this.perguntas.push({
        texto: 'Pergunta ' + count,
        respostas: respostas
      });
    },
    delPergunta: function (indice) {
      this.perguntas.splice(indice, 1);
    }
  }
})
.resposta {
  white-space: nowrap;
}
.resposta input[type='text'] {
  width: 75px;
}

.pergunta {
  width: 150px;
}

.padrao {
  width: 75px;
}

input {
  box-sizing: border-box;
}

input[type='radio'] {
  text-align: center;
  width: 75px;
}

      Respostas

      Perguntas

        <input type="text" class="resposta" v-model="resposta.texto" />
        <input type="button" value="X" v-on:click="delResposta(indice)" />

        <input type="button" class="padrao" value="Adicionar" v-on:click="addResposta" />

        <input type="text" class="pergunta" v-model="pergunta.texto" />

        <input type="radio" v-bind:name="'resposta' + indice" class="resposta" v-model="resposta.selecionado" />

        <input type="button" class="padrao" value="Remover" v-on:click="delPergunta(indice)" />

        <input type="button" class="pergunta" value="Adicionar Pergunta" v-on:click="addPergunta" />

        <input type="button" class="padrao" value="Salvar" />

Comment: nossa, esse exemplo está incrível, infelizmente ainda sou iniciante e não tive contato com vueJS, mas com certeza vou tentar entender esse exemplo e quem sabe conseguir aplicar. Obrigada!!!
Answer:

function myFunction() {
    var table = document.getElementById("myTable");
    var row = table.insertRow(0);
    var cell1 = row.insertCell(0);
    var cell2 = row.insertCell(1);
    cell1.innerHTML = "NEW CELL1";
    cell2.innerHTML = "<input type='text' >";
}

    Row1 cell1
    Row1 cell2

    Row2 cell1
    Row2 cell2

    Row3 cell1
    Row3 cell2

<button onclick="myFunction()">Try it</button>

Olá acredito que seja este o caminho para o que voce busca, um botão e sua tabela vai automaticamente pelo click do botão sendo mudada.


Regular expression to match the different calendar date format dates "M{0,1,2}/D{1,2}/Y{2,4}", "Y{4}"

Question: dates are given as list of strings, require a regular expression to match the different possible date formats. preferably in python
dates = ["04/20/2009", "04/20/09", "4/20/09","4/3/09","6/2008","12/2009","2009","2010"]
df = pd.Series(dates)

Comment: What is your question? What have you tried so far? Please read [ask] if you haven't already.
Comment: considering ``` re.findall('(?:[\d]{0,2}/){0,2}[\d]{2,4}', dates[i]) ``` what does ``` ?: ``` do in regex or where can I learn for details?
Comment: I forgot to mention, please [edit] the question to add details.
Answer: You don't need a regular expression.  Specify the data type:
import pandas as pd
dates = ["04/20/2009", "04/20/09", "4/20/09","4/3/09","6/2008","12/2009","2009","2010"]
df = pd.Series(dates,dtype='datetime64[ns]')
print(df)

Output:
0   2009-04-20
1   2009-04-20
2   2009-04-20
3   2009-04-03
4   2008-06-01
5   2009-12-01
6   2009-01-01
7   2010-01-01
dtype: datetime64[ns]


Determine if equation will generate perfect squares

Question: Given the following quadratic equations:

$4n^2 + 128n - 131$
$4n^2 + 16n - 11$
$4n^2 + 24n - 3$

Is it possible to determine how many values of n will generate a perfect square?  Or better yet, is it possible to determine which values of n will generate a perfect square?
Comment: Here you can complete the square, set the quadratic equal to an unknown $m^2$, rearrange and factor, $$(2n+a+m)(2n+a-m)=b,$$ then look at the prime factorization of $b$ and check when $k=(d+b/d-2a)/4$ is an integer for not-necessarily-positive divisors $d|b$, in which case $n=k-a$ and $m=\pm(2k+a)$.
Comment: Do you need it specifically just for those 3 equations? Or will you need a general method for any of the form?
Comment: For $4n^2+4kn-p$, it is, as the answers make clear, straightforward. Complete the square to get $(2n+k)^2-k^2-p=y^2$, and rewrite as $(2n+k-y)(2n+k+y)=k^2+p$.  Then we get all solutions by factoring $k^2+p$.  But note for example that if we change the $4n^2$ to $3n^2$, things get **very** much harder.
Comment: @RagibZaman I needed a general method for any equation of the form 4n^2 + 4kn - p.
Comment: @anon Could you provide an example using one of the equations I gave?
Comment: I mistyped above, it should read $n=k$ and $m=\pm(d-b/d)/2$. I'll take the last one as an example. Complete the square for $4(n+3)^2-39$, then equate to $m^2$ and obtain $$(2n+6+m)(2n+6-m)=1\cdot3\cdot13.$$ For $4|(d+39/d-12)$ we can use $d=1,3,13,39$ or their negatives, which gives $n=1,7,-13,-7$ corresponding to squares of $m=\pm5,\pm19$.
Comment: Thanks!! I'm not sure how to mark comments as an answer, so I'll mark everything I can. This really helped.
Answer: You can complete the square.  For the third example, $4n^2+24n-3=(2n+6)^2-39.$  As $(n+1)^2-n^2=2n+1$, this cannot be a perfect square for any $2n+6$ greater than $20$, leaving only $7$ possibilities.
We can do better.  You want $(2n+6)^2-39=p^2.$  This means $39=(2n+6-p)(2n+6+p)$.  There will be one solution for each way to factor $39$ into two numbers.  Because of the $2n,$ you need the sum of the numbers to be even, which will be true for odd numbers like $39$ and will be the case for your other three examples.
Answer: HINT: Let's rearrange the first equation:
$4n^2-4n+132n+1-132=(2n-1)^2+132(n-1)=m^2$ now we can easily see that $n-1$ has to be $0$ so $n=1$
For the second equation we may write:
$4n^2+4n+12n+1-12=(2n+1)^2+12(n-1)=m^2 \Rightarrow n=1$
For the third equation:
$4n^2+20n+4n+25-28=(2n+5)^2+4(n-7)=m^2 \Rightarrow n=7$
Comment: That is implied by the fact that "now we can easily see that $n-1$ has to be $0$"
Comment: For the first, n=81 works as well.  For the third, n=1 works.
Comment: @Ross,I didn't say that these solutions are unique
Comment: and how is that a hint?


Theta complexity of the expression

Question: Why is the complexity of expression is given as follows?

$(1 + 2 + 3 + … + (n – 2) + (n – 1) + n)! = \Theta((n^2)!)$
$1 + 2 + 2^2 + … + 2^{n-2} + 2^{n-1} + 2^n = \Theta(2^{n + 1})$
$\log(1) + \log(2) + … + \log(n – 1) + \log(n) = \Theta(n  \log(n))$
Comment: $$1+2+...+n=\frac{n\cdot(n+1)}2$$$$1+2+...+2^n=2^{n+1}-1$$$$\log(1)+\log(2)+...<\log(n)+\log(n)+...=n\log(n)$$$$\log(1)+\log(2)+...+\log(n)\geq\log(\frac n2)+...+\log(n)\geq\log(\frac n2)+\log(\frac n2)+...+\log(\frac n2)=\frac n2\log(\frac n2)$$
Comment: It's a little strange to see this presented as a "complexity." Certainly you are using Theta to describe the behavior of a function and not the space or time complexity of an algorithm.
Answer: The first one is actually false. We have $1+2+...+(n-1)+n=n(n+1)/2=\Theta(n^2)$, however that does not imply that we can take a factorial on both sides. Consider the fact that $n!\neq\mathcal{O}((n-1)!)$, since the ratio is $n$ and can therefore be arbitrarily large.
For the second one, we use the geometric series formula $1+2+2^2+...+2^n=2^{n+1}-1$.
The third one is the most interesting one. I hope it is clear why $\log(1)+\log(2)+...+\log(n)=\mathcal{O}(n\log(n))$. For the other way around, we note that $\log(1)+\log(2)+...+\log(n)\geq\log(n/2)+\log(n/2+1)+...+\log(n)\geq(n/2)\log(n/2)$.

Theta complexity of the expression


Terraform pass multiple subnet-ids as a list to another resource

Question: This is a simplified version of the Terraform config where I'm trying to pass a list of subnet-ids to aws_ec2_transit_gateway_vpc_attachment resource. Is there a way to acheive this?
provider "aws" {
  region  = "eu-west-1"
}

variable "tgw_id" {
  default = "tgw_aa_bb_cc"
}

variable "vpc" {
  default = "10.10.0.0/16"
}

variable "tgw_subnets" {
  default = ["10.10.1.0/24", "10.10.2.0/24", "10.10.3.0/24"]
}

variable "availability_zones" {
  default = ["eu-west-1a", "eu-west-1b", "eu-west-1c"]
}

resource "aws_vpc" "new_vpc" {
  cidr_block = var.vpc
}

resource "aws_subnet" "tgw_subnet" {
  for_each = toset(var.availability_zones)
  vpc_id            = aws_vpc.new_vpc.id
  cidr_block        = var.tgw_subnets[index(var.availability_zones, each.value)]
  availability_zone = each.value
}

resource "aws_ec2_transit_gateway_vpc_attachment" "vpc_attachment" {
  subnet_ids = I want to pass the 3 subnet ids created on the previous step as a list
  transit_gateway_id = var.tgw_id
  vpc_id = aws_vpc.new_vpc.id
}

I've tried using 'data' block but ideally want to avoid using it.
Answer: You can use splat expression:
subnet_ids = aws_subnet.tgw_subnet[*].id

Comment: That worked thanks. I found another way as well. [for k, v in aws_subnet.tgw_subnet : aws_subnet.tgw_subnet[k].id]


Find the sum to n terms of the series

Question: Find the sum to n terms of the series
$$\frac {\sin x}{\cos x+\cos2x} + \frac {\sin2x}{\cos x+\cos4x} +
\frac {\sin3x}{\cos x + \cos6x} +\dotsb $$
How can I solve this?
Here is what I did for the first term:
$$\frac {\sin\bigl(\frac{3x}{2} - \frac x2\bigr)}
  {2\cos\bigl(\frac{x}{2}\bigr)\cos\bigl(\frac {3x}{2}\bigr)}$$
After opening $N^r$ by $\sin(A-B) = \sin A\cos B - \cos A\sin B$ we get
$$ \frac 12\left(\tan\frac {3x}{2} - \tan\frac {x}{2}\right)$$
But this doesn't work out for the remaining terms. Am I missing something here or is this method completely wrong? Any hints? Help please!
edit : Please give a hint. I want to do it on my own :)
Comment: What is the source of the problem? Had the $r$th term been $$\dfrac{\sin x}{\cos x+\cos2mx},$$  we could write $$\cos x+\cos2mx=2\cos\left(m+\dfrac12\right)x\cdot\cos\left(m-\dfrac12\right)x$$  and $$\sin x=\sin\left[\left(m+\dfrac12\right)x-\left(m-\dfrac12\right)x\right]=\cdots$$
Comment: @labbhattacharjee shouldn't the rth term be $ \frac {sin(mx)}{cosx + cos2mx} $ ?
Comment: That's why has the term been. What's the source?
Comment: @labbhattacharjee No I mean rth term for $N^r$ should be $sin(mx)$ instead of $sinx$ and what do you mean by source? Are you asking me where did I find this problem?
Comment: @Subham, Yes, the origin, I'm interested on
Comment: @labbhattacharjee Why? I found this in my study material for IITJEE. Im preparing for that. I haven't joined any coaching programs that is why I ask my doubts here.
Comment: @labbhattacharjee actually I solved it. Where do I post my solution? Do I edit the post or do I post an answer below?
Answer: So I figured out the answer :
$ S = \frac {sinx}{cosx+cos2x} + \frac {sin2x}{cosx+cos4x}+ \frac {sin3x}{cosx+cos6x} + \quad ...$
Multiply both sides by $2sin\frac x2$
Take the first term :
$$\frac {2sin\frac x2sinx}{cosx+cos2x}$$
$$\frac {cos\frac{x}2-cos\frac {3x}2} {2cos\frac {3x}2cos\frac x2}$$
$$\frac 12(sec \frac {3x}2- sec \frac{x}2)$$
Now by same method we extend this to $n\ terms$ and add them
Finally we get,
$$2sin\frac x2S = \frac 12(sec (2n+1)\frac x2- sec \frac x2)$$
$$\therefore \quad S = \frac 14cosec\frac x2(sec(2n+1)\frac x2 - sec\frac x2)$$
This is the answer.
Comment: Why don't you mark this as accepted?

Find the sum to n terms of the series


If $f :X \to Y$ is a diffeomorphism, then $df_x$ is an isomorphism of vector spaces.

Question: ${\bf Proposition}$: If $f: X \to Y$ is a diffeomorphism, then $df_x$ is an isomorphism of tangent spaces.
${\bf Proof}$: Let $f: X \to Y$ be a diffeomorphism. Then $f$ is a smooth bijection and so is $f^{-1} : Y \to X$. Since $f$ is a bijection, $\dim X = \dim Y$. Therefore, $\dim T_x(X) = \dim T_y(Y)$ for all $x \in X, y \in Y$. Take any $h_1, h_2 \in T_x(X)$ for some $x \in X$ and take $\alpha \in \mathbb{R}$. If $f(x) = y$, we need to show that $df_x(h_1 + h_2) = df_x(h_1) + df_x(h_2)$ and that $df_x(\alpha h_1) = \alpha df_x(h_1)$ and that $df_x:T_x(X) \to T_{y}(Y)$ is a bijection.
$df_x$ is a linear map so it is trivially true, by the definition of linearity, that it preserves the vector space structure between $T_x(X)$ and $T_y(Y)$.
To prove that it is a bijection, I need to show that $df_x(T_x(X)) = T_y(Y)$ and that if $df_x(h_1) = df_x(h_2)$, then $h_1 = h_2$. How can I go about proving these surjective and injective properties?
Thanks.
Comment: Do you know what the chain rule says?  That gives the easiest proof of this statement that I know of.
Comment: One place where you go wrong is the statement "Since $f$ is a bijection, $\text{dim} \, X = \text{dim} \, Y$." There exists a bijection between $\mathbb{R}$ and $\mathbb{R}^2$, but they have different dimensions.
Comment: You only need to show it is injective - it's a map between vector spaces of the same dimension. To this end, it's enough to check that the image of the basis vectors of one tangent space form a linearly independent set.
Answer: If $f$ is a diffeomorphism then is has inverse say $g$. Let $p \in X$ and $f(p) \in Y$ then first recall that;
$$(f \circ g)_{*,f(p)} =f_{*,p} \circ g_{*,f(p)}$$
By definition of $g$ is follows that;
$$f_{*,p} \circ g_{*,f(p)} = (f \circ g)_{*,f(p)} = (\iota_Y)_{*,f(p)}$$
$$ \hspace{-.3in} g_{*,f(p)} \circ f_{*,p} = (g \circ f)_{*,p} = (\iota_X)_{*,p}$$
$$\\$$
Remark: Here $f_{*,p} = d_pf$. I've become accustomed to the other notation.


Is there any closed form for $\displaystyle \prod_{n=1}^{\infty} \left(1-\frac{1}{\zeta(n)}\right)$

Question:
How do i evalulate the following infinite product? $$\displaystyle  \prod_{n=2}^{\infty} \left(1-\frac{1}{\zeta(n)}\right)$$
Notation: $\zeta(n)$ is Riemann zeta function.

I'm interested to evaluate the above product. As per the wolfram alpha  check the infinite product  is approximately going to $0$ but not $0$ which doubt me that it may have certain closed form.
I tried in the following manner.
Let the sequence for $n\geq 1$ be  $\zeta_n =1-\frac{1}{\zeta(n)}$ and we are supposed to find the $P=\displaystyle \prod_{1\leq n} \zeta_n$.  Since zeta function  is decreasing for all $n\geq 2$ function ie $\zeta(n)>\zeta(n+1)$  which is trivial to prove by definition. Now we note that $$\zeta_{n+1}-\zeta_n=\frac{1}{\zeta(n)}-\frac{1}{\zeta(n+1)}<0$$ which implies $\zeta_{n+1} < \zeta_{n} $ and  shows our sequence is decreasing sequence. Hence $\operatorname{sup}\left\{ \zeta_n:  n\in\mathbb N\right\}=1$  and $\operatorname{inf}\left\{\zeta_n: n\in\mathbb N\right\}=0$ as $\displaystyle \lim_{n\to \infty}\frac{1}{\zeta(n)}=1$  and thus we have
bound  $0< P <1$.
I'm stuck here. I wish to know  if the product has any closed form or it is $0$.
Thank you.
Comment: I'm not quite sure I understand your question. Isn't most of the factors in your product less than 1/2? Wouldn't that mean the answer is just 0?
Comment: your product needs to start from $n=2$, since $\zeta(1)$ is not defined.
Comment: Trebor.  I see since $ \zeta(2) <2$ and hence  $\frac{1}{\zeta(2)}  > \frac{1}{2}$ a nd hence $1-\frac{1}{\zeta(2)} < \frac{1}{2}$. Thank you for hint.
Comment: GreginGre,  I have edited the post. Thank you.
Answer: Let $P = \prod_{n=2}^\infty (1 - 1/\zeta(n))$. (We skip $n=1$ since $\zeta(1)$ is a pole of $\zeta$.) Then note,
$$\ln(P) = \sum_{n=2}^\infty \ln \left( 1 - \frac{1}{\zeta(n)} \right)$$
$\zeta(n)$, as $n \to \infty$ along the positive integers (greater than one), is clearly a positive, monotone decreasing sequence, bounded below by its limit of $1$. Thus, each logarithm has an argument which is slightly less than one, i.e. $1 - 1/\zeta(n) < 1$. Thus, the summands are each less than $\log(1) = 0$. Moreover, $1 - 1/\zeta(n) \to 0$ since $\zeta(n) \to 1$. Thus, $\log(1 - 1/\zeta(n)) \to -\infty$. Then clearly the sum, too, is $-\infty$.
Thus,
$$P = e^{\ln(P)} = 0$$
and thus, your product is zero.
Comment: Thank you for the solution :) .  I even tried taking logarithmic  but I  didn't see the sum is going to $-\infty$  rather I notice that the sum is going to $+\infty$.


What chord is the open C slid up 2 frets?

Question: What would you call this chord? The guitar is in standard tuning. No capo.
It's basically the open C fingering slid up 2 frets, while keeping the open strings open.
Answer: Even though Shevliaskovic's suggestion that this could be an Em9 (no 5) chord is theoretically correct, it is hardly ever used that way. If that voicing were used as an Em9 chord there would be no reason to indicate that the low E string should be muted (note the cross on the low E string). With the note D in the bass, the Em9 chord would have its seventh in the bass, which is not impossible, but which only happens if there's an appropriate reason for it in a specific context. It definitely wouldn't be the standard way to voice an Em9 chord.
You can check if in the piece where you found that chord it is really used as an Em9 chord, by simply replacing it by a standard Em voicing and checking if it sounds right. I suppose it doesn't.
I've seen this chord being used very often, and I've used it myself very often, and in all cases it is used as a chord with the root D. One of the many examples where you can see and hear it is in The A Team by Ed Sheeran (2:43). Here it is definitely used as a D chord (actually E because of the capo on the 2nd fret).
So, what should this chord be called then? It is used as a D major chord with some added colors. There is no 5th, but that's pretty common because the 5th usually doesn't add much color anyway. It has an added 9th, a standard tension in popular music. And it also has an added 4th, which is usually frowned upon when used with a major chord. However, on the guitar in this very voicing with the open G string it simply sounds good in certain contexts. If the guitar were tuned differently, people probably wouldn't play that chord.
If you really want a chord symbol (which doesn't make so much sense because this voicing is specifically used on the guitar, not so much on other instruments), use D add(4,9) (no 5). But as I said, the specific voicing is important here, so if you want to communicate that chord/voicing to others, you should better specify how to play that chord instead of using a chord symbol which does not indicate a voicing.
Comment: I'm changing this to this accepted answer because it describes the context in which I'm playing it. Em definitely doesn't sound right as a replacement. I'm playing it in a little progression with a D major, and replacing this chord with just the D there works.
Answer: This could be Em 9 without the 5th, which is a common note to omit, with the 7th on the bass; third inversion.
So, if you played it in root position, it would be: E,G, (B which is omitted),D,F#.
Comment: There's no C so it can't be a D9. A 9th chord implies that there is a 7th.
Comment: @Dom correct, I forgot that
Comment: From Dom's comment I take it that your first shot was in fact some D chord. And yes, it can't be a D9 but it *can* be a D add 9, which is also how it is usually used.
Answer: It can function as an Em9 (ii,vi) a Dmaj11 (I) or a D11 (V). The key and the chords before and after in the progression will define its function. If it comes after a CM in the key of G, it would possible to call it a D11 (V). Since it doesn't have the leading tone that makes it a true dom chord (c) it could also be used as a pivot chord to the key of D the chord would function as a Dmaj11 (I). If it comes after a CM in the key of G, it's likely functioning as an em9 Chord (vi). It could also be functioning as an em9 (ii) In the key of D.
tldr; Its function depends on what key you're in.


Is it possible to get user country name without any api or third party code?

Question: I was wondering if there was a way to determine the user country name in php without any api or third party help.
Comment: So did you do any research to find out?
Answer: No, there isn't, unless you want to maintain your own database of (country, IP range) pairs.
However, if you want information about a visitor's language, an alternative solution would be to process $_SERVER['HTTP_ACCEPT_LANGUAGE']. Note that it's not a trivial task, as it can hold multiple languages (with different preferences) and it could hold unknown langauges to your program. Furthermore, this value can be manipulated by a malicious user, so the usual precautions when dealing with user input are necessary.
Answer: Yes, possible. But nobody suggests that way because it is not an easy task. You have to find create a database of all IP Address range with country, location, ISP etc. So, it looks like a tough job, right?
Well, fortunately, there is another way with PHP 'Geo IP Location' Package. You can download these from here as a PHP Phar Package. Then use this code:
<?php

require_once("geoip2.phar");

use GeoIp2\Database\Reader;

// Start

$reader = new Reader('/path/to/GeoLite2-Country.mmdb');
$record = $reader->country($_SERVER['REMOTE_ADDR']);

// Print/Echo

echo $record->country->isoCode . "\n");
echo $record->country->name . "\n");
echo $record->mostSpecificSubdivision->name . "\n");
echo $record->mostSpecificSubdivision->isoCode . "\n";
echo $record->city->name . "\n");
echo $record->postal->code . "\n");
echo $record->location->latitude . "\n");
echo $record->location->longitude . "\n");

?>

Answer: PHP has a built in GeoIP that does just that.
You might have to install it as a plugin, which should be too hard...
GeoIP


GlassFish on CentOS 7 (systemd) - "asadmin restart-domain" doesn't work as expected

Question: I use the following systemd script for GlassFish 4 on CentOS 7:
[Unit]
Description = GlassFish Server v4.1
After = syslog.target network.target

[Service]
User=glassfish
ExecStart = /usr/bin/java -jar /home/glassfish/glassfish4/glassfish/lib/client/appserver-cli.jar start-domain
ExecStop = /usr/bin/java -jar /home/glassfish/glassfish4/glassfish/lib/client/appserver-cli.jar stop-domain
ExecReload = /usr/bin/java -jar /home/glassfish/glassfish4/glassfish/lib/client/appserver-cli.jar restart-domain
Type = forking

[Install]
WantedBy = multi-user.target

The issue that when execute command "asadmin restart-domain" via web application itself or via NetBeans IDE, or via GlassFish Web admin page => Server => Restart - all processes of GlassFish got halted thus no one able to relaunch the GlassFish again.
In CentOS 6 with original GlassFish script (SysV) - everything works fine.
Any ideas how to fix that?
Edit 1:
1) status of the process after failed restart
# systemctl status glassfish
● glassfish.service - GlassFish Server v4.1.2
    Loaded: loaded (/etc/systemd/system/glassfish.service; enabled; vendor preset: disabled)
    Active: inactive (dead) since Thu 2017-05-25 02:25:46 CDT; 11s ago
  Process: 13465 ExecStop=/usr/bin/java -jar /local/glassfish4/glassfish/lib/client/appserver-cli.jar stop-domain (code=exited, status=0/SUCCESS)
  Process: 13338 ExecStart=/usr/bin/java -jar /local/glassfish4/glassfish/lib/client/appserver-cli.jar start-domain (code=exited, status=0/SUCCESS)
 Main PID: 13351 (code=exited, status=0/SUCCESS)

May 25 02:25:24 dev3.local systemd[1]: Starting GlassFish Server v4.1.2...
May 25 02:25:28 dev3.local java[13338]: Waiting for domain1 to start ....
May 25 02:25:28 dev3.local java[13338]: Successfully started the domain : domain1
May 25 02:25:28 dev3.local java[13338]: domain  Location: /local/glassfish4/glassfish/domains/domain1
May 25 02:25:28 dev3.local java[13338]: Log File: /local/glassfish4/glassfish/domains/domain1/logs/server.log
May 25 02:25:28 dev3.local java[13338]: Admin Port: 4848
May 25 02:25:28 dev3.local java[13338]: Command start-domain executed successfully.
May 25 02:25:29 dev3.local systemd[1]: Started GlassFish Server v4.1.2.
May 25 02:25:46 dev3.local java[13465]: CLI306: Warning - The server located at /local/glassfish4/glassfish/domains/domain1 is not running.
May 25 02:25:46 dev3.local java[13465]: Command stop-domain executed successfully.

2) status of the process after failed restart (having RestartForceExitStatus=SIGUSR1 in systemd config file)
#systemctl status glassfish
● glassfish.service - GlassFish Server v4.1.2
    Loaded: loaded (/etc/systemd/system/glassfish.service; enabled; vendor preset: disabled)
    Active: failed (Result: exit-code) since Thu 2017-05-25 02:15:16 CDT; 15s ago
  Process: 12994 ExecStop=/usr/bin/java -jar /local/glassfish4/glassfish/lib/client/appserver-cli.jar stop-domain (code=exited, status=0/SUCCESS)
  Process: 12859 ExecStart=/usr/bin/java -jar /local/glassfish4/glassfish/lib/client/appserver-cli.jar start-domain (code=exited, status=0/SUCCESS)
 Main PID: 12872 (code=exited, status=12)

May 25 02:13:36 dev3.local java[12859]: domain  Location: /local/glassfish4/glassfish/domains/domain1
May 25 02:13:36 dev3.local java[12859]: Log File: /local/glassfish4/glassfish/domains/domain1/logs/server.log
May 25 02:13:36 dev3.local java[12859]: Admin Port: 4848
May 25 02:13:36 dev3.local java[12859]: Command start-domain executed successfully.
May 25 02:13:37 dev3.local systemd[1]: Started GlassFish Server v4.1.2.
May 25 02:15:15 dev3.local systemd[1]: glassfish.service: main process exited, code=exited, status=12/n/a
May 25 02:15:16 dev3.local java[12994]: CLI306: Warning - The server located at /local/glassfish4/glassfish/domains/domain1 is not running.
May 25 02:15:16 dev3.local java[12994]: Command stop-domain executed successfully.
May 25 02:15:16 dev3.local systemd[1]: Unit glassfish.service entered failed state.
May 25 02:15:16 dev3.local systemd[1]: glassfish.service failed.

Comment: Found the similar issue here (with no solution): https://stackoverflow.com/questions/38609584/glassfish-fails-to-restart-from-web-portail-but-works-with-asadmin-command
Answer: need to add to the section [Service] Restart=on-failure
Comment: Please explain this better!
Answer: I suspect what it does is it sends a SIGUSR1 signal to the glassfish process, which then by defaults to exiting.  I'd try by adding RestartForceExitStatus=SIGUSR1 to the service and see if that helps.
Comment: Hi Tollef, thank you for the advice, unfortunately didn't help... I have added daemon status output after failed restart with and without suggested param. Any other suggestions are highly appreciated! )
Comment: Does using `RestartForceExitStatus=12` (from the output) work better? Does it always exit with 12?
Comment: With status 12 it exits only when param `RestartForceExitStatus=SIGUSR1` is present in the glassfish systemd conf file. Without `RestartForceExitStatus=SIGUSR1` it exits with code 0. I have added `RestartForceExitStatus=12` - looks like it helps only once: you can do restart of glassfish one time, on the second try - it exits with code 0 again and doesn't start again.


What should $a, b \in\Bbb{R}$ be that polinom $x^5+ax^3+b\in\Bbb{R}[x]$ would have at least one non-zero repeated root.

Question: What should $a, b\in\Bbb{R}$ be that polinom $x^5+ax^3+b\in\Bbb{R}[x]$ would have at least one non-zero repeated root.
Well, what I found out by myself are there: $$1)\quad  b=0,\quad then\quad
x^5+ax^3=x^3(x^2+a),\quad a\in\Bbb{R}$$
$$2) \quad a=0,\quad then\quad x^5+b=0, \quad x=-b^{\frac{1}{5}}, \quad b=n^5,\quad n\in\Bbb{R}$$
But these are only several variants...
Comment: Pretty weird wording and pretty hard to understand: do you mean to find out the values of the coefficients $\;a,b\in\Bbb  R\;$ ( there is no $\;c\;$ !) such that the quintic has **at least** two repeated roots? Negating too much can be confusing...at least for me.
Comment: @DonAntonio I think "not less than one" would mean at least one.
Comment: @PaulSundheim Perhaps...I honestly don't know. Maybe the poster will address this question.
Comment: Sorry, it's really hard to translate the exercise from Lithuanian to English in mathematical terminology.
Simply telling, I just need to find this polinom would have at least one non-zero repeated root.
Comment: If a polynomial has a repeated root $x_1$ then $f'(x_1)=0$.
Comment: As to why the repeated root $x_1$ must satisfy $f'(x_1)=0$ for a polynomial; since we have for some polynomial $g(x)$ that $f(x)=(x-x_1)^2g(x)$ from that $f'(x)=2(x-x_1)g(x)+(x-x_1)^2g'(x)=(x-x_1)(2g(x)+(x-x_1)g'(x))$
Comment: And, of course, a=b=0 has a rerepeated root.
Answer: Let $f(x)=x^5+ax^3+b$. If $\phi$ is a repeated root, then $f(\phi)=f'(\phi)=0$.
$$f'(\phi)=5\phi^4+3a\phi^2$$
$$\phi f'(\phi)-5f(\phi)=0$$
$$5\phi^5+3a\phi^3-5\phi^5-5a\phi^3-5b=0$$
$$-2a\phi^3-5b=0$$
So $f(\phi)=(\phi^2+a)(\frac{-5b}{2a})+b=0$.
$$\phi^2=\frac{-3a}{5} \quad\text{or}\quad b=0$$
$b=0$ is an answer.
If $b\ne0$, then
$$\left(\frac{-3a}{5}\right)^3=\phi^6=\left(\frac{-5b}{2a}\right)^2$$
That is $108a^5+3125b^2=0$.
Answer: The polynomial $x^5+ax^3+b$ has (at least) a repeated root iff its discriminant is zero, i.e. iff $b=0$ or $108 a^5 + 3125 b^2=0$.
Answer: Hints:
If $\;f(x)=x^5+ax^3+b\;$ , then a root is multiple iff it is also a root of the polynomial's derivative:
$$f'(x)=5x^4+3ax^2=x^2(5x^2+3a)$$
so if $\;b=0\;$ then $\;x=0\;$ is a multiple root, otherwise , if $\;w\neq0\;$ is a multiple root, it must be that both
$$\begin{cases}w^5+aw^3+b=0\implies&a=-\cfrac{w^5+b}{w^3}\\{}\\
5w^2+3a=0\implies&a=-\cfrac{5w^2}3\end{cases}\;\;\;\implies 3w^5+3b=5w^5\implies$$$${}$$
$$\implies2w^5=3b\implies w=\sqrt[5]\frac{3b}2$$
Try now to find out the conditions on the coefficients.
Answer: The discriminant of your polynomial is $b^2 (108 a^5 + 3125 b^2)$.  There is a repeated root iff this is $0$.  That occurs of course for $b=0$, but then the root in question is $0$.  Otherwise, you want $a = (-3125 b^2/108)^{1/5}$.


Get function result or value from an object by property

Question: TS Playground
I'm trying to figure out the correct type for a utility function getProp that will index an object by key and return the primitive value at that index or the result of the function at that index.
declare interface App {
  name: () => string
  version: string
  id: number
}

const getProp = function<C extends App, S extends keyof App>(context: C, prop: S) : C[S] extends (...args: any[]) => any ? ReturnType<C[S]> : C[S] {
  const method = context[prop];
  if (typeof method === 'function') {
    return method(); // Error: Type 'string' is not assignable to type 'C[S] extends (...args: any[]) => any ? ReturnType<C[S]> : C[S]'.
  } else {
    return method; // Error: Type '() => string' is not assignable to type 'C[S] extends (...args: any[]) => any ? ReturnType<C[S]> : C[S]'.
  }
};

declare var app : App;

// These are all correct despite the errors
getProp(app, "id") // => number
getProp(app, "name") // => string
getProp(app, "version") // => string

The type presented here "works" but TypeScript is giving me errors on the lines indicated. Is there a better way to type this properly without errors or should I just drop in my old friend //@ts-ignore?
Answer: When we use Generic Functions the actual type instantiation happens when we invoke it, getProp<App, 'name'>
Hence the Typescript compiler needs to be sure that the types we are using must be compatible and follow the constraints.
Since the Return Type of getProp is conditional we can make use of assertion/aliasing to inform the typescript compiler of the state in which this branch will be reached
In your code, the compiler was complaining that it is possible that you are returning some code (which might not match the return value) at the time of declaration!
Hence by aliasing it, we make sure that the types will be of this ReturnType only!
To avoid Repetition I created a new type alias PropReturnType<T>
declare interface App {
  name: () => string
  version: string
  id: number
}

type PropReturnType<T> = { [K in keyof T]: T[K] extends (...args: any[]) => any ? ReturnType<T[K]> : T[K] }

const getProp = function<C extends App, S extends keyof C>(context: C, prop: S): PropReturnType<C>[S]{
  const method = context[prop];
  if (typeof method === 'function') {
    return method();
  } else {
    return method as PropReturnType<C>[S];
  }
};

declare var app: App;

getProp(app, "id") // => number
getProp(app, "name") // => string
getProp(app, "version") // => string

CODE PLAYGROUND
Comment: @Bishwajitjha cool, I was actually going for not needing the `[K in keyof T]` part at all.. [like this](https://tsplay.dev/WYk7rN)
Comment: Oh yes, fair enough, we can save on that `[K in keyof T]` mapping over part.
Though I just started with a general solution by using mapped types just in case some other transformations were required. But in this case, we can just directly use conditional type!
Also, both of the solutions would be equally good from the performance point of view anyway because `Indexed access` types are evaluated `cold/ lazily` i.e. Only the key which we are indexing gets computed
Comment: After checking around and verifying some cases. Seemingly, this answer fits the above question
Comment: @Bishwajit jha Neat solution! +1, How do you decide to go with object approach for the `PropReturnType`? In other words, how do you decide to do `PropReturnType[S]` and not `PropReturnType`.. I tried the latter but never struck me to use the former so
Comment: @tanmay Thanks :)
Yeah both of them should work correctly!
I just used the `Indexed Access`  Directly on the `PropReturnType`, because it would just be repetitive to write the constraints in type alias again when the `getProp()` already has that.
Just in case you wanna see how the latter approach would look [Code Link](https://tsplay.dev/wgg39w)


Get Neighboring Entities

Question: I'm writing a function which gets neighboring (Previous and Next) entities from the database based off of a date.  I've figured out how to return the neighbors in 2 queries but I would prefer if I could pull both entities at once.
public interface IHasDateRange
{
    DateTime StartDate { get; set; }
    DateTime EndDate { get; set; }
}

public static (TEntity Previous, TEntity Next) GetNeighborsOrDefault<TEntity>(
    this IQueryable<TEntity> query, JustDate startDate)
        where TEntity : class, IHasDateRange
{
    var previous = query.Where(x => x.StartDate < startDate)
            .OrderByDescending(x => x.StartDate)
            .FirstOrDefault();

    var next = query.Where(x => x.StartDate > startDate)
        .OrderBy(x => x.StartDate)
        .FirstOrDefault();

    return (previous, next);
}

I'm would like to pull out the previous and next in a single query, preferably in a way which doesn't generate a behemoth of sql from translating an overly complex Expression.
EDIT
I'm thinking there is a way to do it if I remove the Where for the start date filter and calculate the distance instead I'm still stuck but I have a feeling something should work.
var previous = query
    .Select(x => new {
        Entity = x,
        Distance = DbFunctions.DiffDays(x.StartDate, startDate)
   })
    .Where(x => x.Distance != 0);

Note: it is assumed that every entity has a Unique startDate.
Is there a simple way I can pull out the previous and next entities in a single query?
Answer: How about taking the before and after ones and eliminating the middle?
I believe this will still generate two separate SQL queries - one to get the Count() and one to get the results, but unless you want to add ROW_NUMBER support to EF (you can extend EF Core for it), I don't think there is a better way:
var previousAndNext = query.OrderBy(x => x.StartDate)
        .Skip(query.Where(x => x.StartDate < startDate).Count()-1)
        .Take(3)
        .Where(x => x.StartDate != startDate)
        .Take(2) // if startDate not in DB, just get previous and next
        .ToList();

Comment: I like this, Idea, I can't think of a way to do it right now, but I think there may be a crafty way to do this with select/selectMany, Join would work but I think that might make generate a query that takes longer than just selecting them individually.
Answer: That's the same as getting the two entities off of (and including) the first date before startDate.
query.Where(e => e.StartDate != startDate
    && e.StartDate >= query.OrderByDescending(e1 => e1.StartDate)
        .Where(e1 => e1.StartDate < startDate).Select(e1 => e1.StartDate).FirstOrDefault())
    .OrderBy(e => e.StartDate)
    .Take(2)

As you see, you can't avoid running two queries, although the second query now is a subquery in one main query.
In EF6, this generates a moderately complex query like this:
SELECT TOP (2)
    ...
    FROM ( SELECT
        ...
        FROM  [dbo].[Entity] AS [Extent1]
        INNER JOIN  (SELECT TOP (1) [Project1].[StartDate] AS [StartDate]
            FROM ( SELECT
                [Extent2].[StartDate] AS [StartDate]
                FROM [dbo].[Entity] AS [Extent2]
                WHERE [Extent2].[StartDate] < @p__linq__1
            )  AS [Project1]
            ORDER BY [Project1].[StartDate] DESC ) AS [Limit1] ON 1 = 1
        WHERE ( NOT (([Extent1].[StartDate] = @p__linq__0) AND ((CASE WHEN ([Extent1].[StartDate] IS NULL) THEN cast(1 as bit) ELSE cast(0 as bit) END) = 0))) AND ([Extent1].[StartDate] >= [Limit1].[StartDate])
    )  AS [Project2]
    ORDER BY [Project2].[StartDate] ASC

I was pleasantly surprised to see EF core 3.1.3 generate a rather simple query like this:
SELECT TOP(@__p_2) ...
FROM [Entity] AS [e]
WHERE (([e].[StartDate] <> @__startDate_0) OR [e].[StartDate] IS NULL) AND ([e].[StartDate] >= (
    SELECT TOP(1) [e0].[StartDate]
    FROM [Entity] AS [e0]
    WHERE [e0].[StartDate] < @__startDate_1
    ORDER BY [e0].[StartDate] DESC))
ORDER BY [e].[StartDate]

Comment: Thanks I'll verify this when I get back to my computer later
Comment: Whats `Trials`?

Get Neighboring Entities


Matching of Vertices with Maximal Degree in Bipartite Graph

Question: Let G be a bipartite graph and let A be the set of vertices of maximal
degree. Show that there is a matching in G that covers A where A is not necessarily in one partite.
I am trying to apply a similar proof as that of Konig's Theorem but I am having trouble.
Answer: Add more edges (and maybe more vertices) until the bipartite graph is $\Delta(G)$-regular. What can you say about regular bipartite graphs?
Comment: I don't think we can use this
Comment: Why not? Sounds like fair game to prove a generalization using a basic lemma.
Comment: What are you talking about?
Comment: Regular bipartite graphs have perfect matchings.
Comment: and how do we use that?
Comment: Aw man, you want me to spoil the entire solution? Well, consider what happens when you remove all the extra edges.
Comment: What happens? ${}{}$
Comment: Let us [continue this discussion in chat](https://chat.stackexchange.com/rooms/107012/discussion-between-magma-and-jorge-fernandez-hidalgo).
Comment: thank you so much! I was really over thinking it.


Evaluating the series with arctangents: $\sum_{r=1}^\infty \tan^{-1}\frac{2r}{2+r^2+r^4}$

Question:
If $$S=\sum\limits_{r=1}^\infty\tan^{-1}\left(\frac{2r}{2+r^2+r^4}\right)$$ then what is cot S?
Options: A) 1; B) 3; C) 1/3; D) 2

Does it converge? I don't really know how to find the convergence point. I tried using Abel's translation or make substitutions, regroup the terms, but didn't find it. How is it done?
Comment: Are you sure you want to sum over $i$? As written, the series doesn't converge unless the summand is $0$.
Answer: I think your series should be $\text{arccot}\left(\dfrac{2r}{2+r^2+r^4} \right)$ or $\arctan\left(\dfrac{2r}{2+r^2+r^4} \right)$. The main trick is the following.
Note that
\begin{align}
\arctan\left(\dfrac{2r}{2+r^2+r^4} \right) & = \arctan\left(\dfrac{(r^2+r+1)-(r^2-r+1)}{1+(r^2+r+1)(r^2-r+1)} \right)\\
& = \arctan(r^2+r+1)-\arctan(r^2-r+1)\\
& = \arctan(r(r+1)+1)-\arctan((r-1)r+1)\\
\end{align}
Hence,
$$\sum_{r=0}^n \arctan\left(\dfrac{2r}{2+r^2+r^4} \right) = \arctan(n(n+1)+1)-\arctan(1)$$
Adapt this to your problem at hand.


Ajuda com Foreign Key, MySQL - Xampp

Question: Banco de dados MySQL
Pergunta 1:
Estou tentando deletar uma Foreign Key e está dando esse erro:
#1044 - Acesso negado para o usuário ''@'' ao banco de dados 'information_schema'

Código: alter table informacoesproduto drop foreign key informacoesproduto_ibfk_1;

Pergunta 2:
Queria saber como renomear uma Foreign Key, pois quando eu fui criar, acabei botando um caracter especial no nome(+), então agora não estou conseguindo deletar.
Código: alter table informacoesproduto drop foreign key fk_exemplo+teste;
Comment: Lupart, faça apenas uma pergunta por página.
Answer: Pergunta 1:
Como o erro mostra, teve o acesso negado. Isso pode ser porque o usuário que está logado não tem permissão na tabela "informacoesproduto", precisa confirmar.
Para ver as permissões, use o comando:  show grants for 'usuario'
Pergunta 2:
Não é possível renomear uma constraint, você precisa apagar (drop foreign key)  e criar novamente. Coloque o nome entre aspas:
alter table informacoesproduto drop foreign key `fk_exemplo+teste`,
      add constraint `nome-correto` foreign key (`nome-do-campo) references `nome-da-tabela`(`nome-do-campo-na-outra-tabela`);

Comment: Quem negativou poderia por obséquio apontar aonde se encontra informação equivocada nessa resposta?

Ajuda com Foreign Key, MySQL - Xampp


Javascript needs to be shorten

Question: The code below is supposed to be a random color change  but I definitely did the long way in creating it. I also included the child function Calculator. I am willing to take suggestions as well if any of this can be made better. I tried to see if their could be a way to create this all in one line, but I had no luck. Also I tried to create a loop for the code but it was just too complicate for me. Can anyone help make the code less repetitive?
function calculator() {
    x = Math.floor((Math.random() * 10) + 1);
    return x;
}

function randomColor() {
    calculator();
    if (x == 1) {
        h.classList.remove("red");
        h.classList.remove("tan");
        h.classList.remove("green");
        h.classList.remove("light_blue");
        h.classList.remove("yellow");
        h.classList.remove("pink");
        h.classList.remove("purple");
        h.classList.remove("black");
        h.classList.remove("white");
        h.classList.add("sky");
    }
    else if (x == 2) {
        h.classList.remove("sky");
        h.classList.remove("tan");
        h.classList.remove("green");
        h.classList.remove("light_blue");
        h.classList.remove("yellow");
        h.classList.remove("pink");
        h.classList.remove("purple");
        h.classList.remove("black");
        h.classList.remove("white");
        h.classList.add("red");
    }
    else if (x == 3) {
        h.classList.remove("red");
        h.classList.remove("sky");
        h.classList.remove("green");
        h.classList.remove("light_blue");
        h.classList.remove("yellow");
        h.classList.remove("pink");
        h.classList.remove("purple");
        h.classList.remove("black");
        h.classList.remove("white");
        h.classList.add("tan");
    }
    else if (x == 4) {
        h.classList.remove("red");
        h.classList.remove("tan");
        h.classList.remove("sky");
        h.classList.remove("light_blue");
        h.classList.remove("yellow");
        h.classList.remove("pink");
        h.classList.remove("purple");
        h.classList.remove("black");
        h.classList.remove("white");
        h.classList.add("green");
    }
    else if (x == 5) {
        h.classList.remove("red");
        h.classList.remove("tan");
        h.classList.remove("green");
        h.classList.remove("sky");
        h.classList.remove("yellow");
        h.classList.remove("pink");
        h.classList.remove("purple");
        h.classList.remove("black");
        h.classList.remove("white");
        h.classList.add("light_blue");
    }
    else if (x == 6) {
        h.classList.remove("red");
        h.classList.remove("tan");
        h.classList.remove("green");
        h.classList.remove("light_blue");
        h.classList.remove("sky");
        h.classList.remove("pink");
        h.classList.remove("purple");
        h.classList.remove("black");
        h.classList.remove("white");
        h.classList.add("yellow");
    }
    else if (x == 7) {
        h.classList.remove("red");
        h.classList.remove("tan");
        h.classList.remove("green");
        h.classList.remove("light_blue");
        h.classList.remove("yellow");
        h.classList.remove("sky");
        h.classList.remove("purple");
        h.classList.remove("black");
        h.classList.remove("white");
        h.classList.add("pink");
    }
    else if (x == 8) {
        h.classList.remove("red");
        h.classList.remove("tan");
        h.classList.remove("green");
        h.classList.remove("light_blue");
        h.classList.remove("yellow");
        h.classList.remove("pink");
        h.classList.remove("sky");
        h.classList.remove("black");
        h.classList.remove("white");
        h.classList.add("purple");
    }
    else if (x == 9) {
        h.classList.remove("red");
        h.classList.remove("tan");
        h.classList.remove("green");
        h.classList.remove("light_blue");
        h.classList.remove("yellow");
        h.classList.remove("pink");
        h.classList.remove("purple");
        h.classList.remove("sky");
        h.classList.remove("white");
        h.classList.add("black");
    }
    else if (x == 10) {
        h.classList.remove("red");
        h.classList.remove("tan");
        h.classList.remove("green");
        h.classList.remove("light_blue");
        h.classList.remove("yellow");
        h.classList.remove("pink");
        h.classList.remove("purple");
        h.classList.remove("black");
        h.classList.remove("sky");
        h.classList.add("white");
    }
}

Comment: What does `h`, `classList` and `x` stand for? Post a reproducible code that we can try in our browsers. Thanks.
Answer: Use an array that maps numbers to colors. You can then loop over the array, either adding or removing the class as necessary.

const colors = ["red", "tan", "green", "light_blue", "yellow", "pink", "purple", "black", "white", "sky"];

function calculate() {
  return Math.floor(Math.random() * colors.length));
}

function randomColor() {
  let x = calculate();
  for (let i = 0; i < colors.length; i++) {
    if (i == x) {
      h.classList.add(colors[i]);
    } else {
      h.classList.remove(colors[i]);
    }
  }
}
Answer:
Store your colors into Array
When removing multiple classLists classes, from that array of colors, use the spread operator ...colors
Remember, you need to get a random from 0, not from 1 - since Array indeces are 0 based.

const EL_btn = document.querySelector("#btn");
const EL_div = document.querySelector("#div");

const colors = ["chartreuse", "coral", "chocolate", "crimson", "pink", "purple", "gold", "darkviolet", "deeppink"];

const changeColor = () => {
  const rand = ~~(Math.random() * colors.length);
  EL_div.classList.remove(...colors); // Remove all
  EL_div.classList.add(colors[rand]); // Add one
}

EL_btn.addEventListener('click', changeColor);
changeColor(); // Init!
.chartreuse { background:chartreuse; }
.coral      { background:coral; }
.chocolate  { background:chocolate; }
.crimson    { background:crimson; }
.pink       { background:pink; }
.purple     { background:purple; }
.gold       { background:gold; }
.darkviolet { background:darkviolet; }
.deeppink   { background:deeppink; }
<button id="btn" type="button">CHANGE COLOR</button>

TEST

If the array of colors is huge, spreading inside classList.remove() might be an expensive operation, than storing the current class inside a data-color attribute might leverage that process. Remove the class stored inside the data-color attribute and set a new random class:

const EL_btn = document.querySelector("#btn");
const EL_div = document.querySelector("#div");

const colors = ["chartreuse", "coral", "chocolate", "crimson", "pink", "purple", "gold", "darkviolet", "deeppink"];

const changeColor = () => {
  const rand = ~~(Math.random() * colors.length);
  const color = colors[rand];
  EL_div.classList.remove(EL_div.dataset.color); // Remove remembered one
  EL_div.classList.add(color);                   // Add new one
  EL_div.dataset.color = color;                  // Remember new one for later
}

EL_btn.addEventListener('click', changeColor);
changeColor(); // Init!
.chartreuse { background:chartreuse; }
.coral      { background:coral; }
.chocolate  { background:chocolate; }
.crimson    { background:crimson; }
.pink       { background:pink; }
.purple     { background:purple; }
.gold       { background:gold; }
.darkviolet { background:darkviolet; }
.deeppink   { background:deeppink; }
<button id="btn" type="button">CHANGE COLOR</button>

TEST

Javascript needs to be shorten


How can we show/prove that a rank-$1$ matrix is non-convex?

Question: In my optimization problem, I have a matrix $X = v v^H$ where $H$ denotes the complex conjugate transpose and $v \in \mathbb C^n$. This is a rank-$1$ matrix. In the published literature, it is mentioned that rank-$1$ matrix is also non-convex but I am unable to understand this. Can someone explain this to me why rank-$1$ matrix is also non-convex?
Comment: How can a matrix be convex?
Comment: @copper.hat: Well, it's shaped like a rectangle, and rectangles are convex...
Comment: You will easily find two $2\times 2$ rank-1 matrices whose certain convex combination is not a rank-1 matrix.
Comment: Are you asking to show that the collection of rank one matrices are not convex? Note that $1$ is of rank one, and so is $-1$, but $0 = 1+(-1)$ is not.
Comment: @MichalAdamaszek Well, I have just one nxn matrix (X=vv^H) and I have to check how is it non-convex? I know if we have a set of matrices, we can check for some certain combinations of matrices of that set, which can provide a zero rank matrix (and thus indicates that set of matrices is non-convex).  But, I have only one nxn matrix.
Comment: You write you have an optimization problem, where you want to optimize something over the set of rank-1 matrices plus some other constraints. But that set is not convex.
Comment: Please explain what you mean by a matrix being convex. A set can be convex, a function can be convex, but a matrix is neither a set nor a function. A matrix can only be positive (semi)definite, negative (semi)definite, or indefinite. A set of matrices can be convex or nonconvex.
Answer: Let me give this a go since I was wondering the same thing. Are you asking why the set of rank 1 matrices is not convex? Let's consider the following:
$x_1 = [0,1]^T$, $x_2 = [1,0]^T$. Therefore $x_1x_1^T = \begin{bmatrix}
0 & 0 \\
0 & 1
\end{bmatrix}$ and $x_2x_2^T = \begin{bmatrix}
1 & 0 \\
0 & 0
\end{bmatrix}$.
We note at this point that both $x_1x_1^T$ and $x_2x_2^T$ fall into the set of rank-1 matrices. However, their combination does not, and we can demonstrate this:
$\theta x_1x_1^T + (1-\theta)x_2x_2^T = \begin{bmatrix}
1-\theta & 0 \\
0 & \theta
\end{bmatrix}$, which is a rank-2 matrix. We cannot express this in the form $x_0 x_0^T$, (because what would $x_0$ be to allow me to get $x_0 x_0^T$ as seen above?) and it does not fall into the same set as the first two matrices $x_1x_1^T$ and $x_2x_2^T$.
Therefore the set of rank-1 matrices is not convex.


rubbing alcohol to clean guitar

Question: I am still kind of a beginner in the music field; I'm learning classical guitar by myself, and have no one that I can consult or ask locally!
So I'm asking if cleaning Classical Guitars (the strings and the body) by rubbing alcohol has any negative effect in the long time - may that damage/ruin the strings for example or something like that?
Comment: I'm surprised to see this question hasn't had an update since COVID-19. I guess there is this thread: https://music.stackexchange.com/questions/99973/what-are-some-ways-to-sanitize-an-acoustic-guitar
Answer: I personally would never recommend this.
It might be OK for a typical mass produced modern instrument with a thick poly finish, but even then I don't think I would want it finding its way through minor finish cracks and getting into the timber.
More seriously I'm sure it would be bad for a higher end shellac/French polished classical. (Most of us don't have one of those yet though!)
Also it may affect the rosewood or ebony in the fingerboard - I suspect it would dry out the oils in such timbers leading to shrinkage or cracking, unless again it's under a thick poly-type finish.
(Someone else might advise if they have used it on the fingerboard and used lemon oil or similar to restore the oils afterwards. I personally use nothing but simple dry cloths for cleaning up the inevitable dust or finger oils, plus a bit of breath if clearing stubborn dirt.)
Comment: Denatured alcohol is a solvent for shellac which can also be used to remove it from wood, so YES I agree "it would be bad."
Answer: You're really asking about two different things, strings and the guitar body. Another area of hot topic is also the fretboard.
Strings
For a classical guitar, you generally have these made from two materials: nylon (or some other synthetic or semi-synthetic material) and steel windings. The life of these treble/bass strings are totally dependent on use. Your perspiration chemistry will determine how well these hold up to standard use and abuse. But in general many players use a dry microfiber cloth to wipe the strings off after use. This usually helps most people with sustaining the life of the average string. For those of us (myself including) with more damaging effects on strings; treated wipes or applications can be used too. It's important to remember that anything you put on the string shouldn't be put anywhere else on the guitar though; as the testing and "guarantee" of such item (if it even exists) will only apply to the strings themselves.
Body
Like the strings mentioned above, bodies can consist of many different woods and even more finish types which all will have different reactions to solvents used for cleaning on them. In general; most players and manufacturers will agree that using rubbing alcohol on a finish like the body (or top, back, sides, neck, etc.) is a bit too harsh of a cleaner. Depending on the finish type; the alcohol could (worse case) eat away or wear down the finish, or even cause it to "cloud" over and haze. Most guitar owners clean their bodies with dry, lint-free cloths, and many manufacturers suggest this same method. Like Taylor, Alvarez (expand "How Should I Clean My Guitar"), and Martin. Some manufacturers recommend a polish (as in a few examples above) but note their suggestion of a clean, dry cloth for cleaning the body.
Fretboard (if you care)
You didn't mention the fretboard but I can assume that it may come up, especially if you happen to get some rubbing alcohol on the strings (and potentially the fretboard). Rubbing alcohol tends to have a drying property and the same can apply to untreated/finished wood, which generally is the most common type of fretboard on a classical guitar. It's important not to get anything on the fretboard as most manufacturers will not recommend it.
Continuous application of rubbing alcohol to an unfinished fretboard will more than likely cause it to visually look dried out, and even may cause the wood to crack inside the grain.

If you are going to use rubbing alcohol use the suggestion that most cleaners have on the back of bottles: use it in an inconspicuous place to see if there is any sort of reaction.
But best bet is to go with something specialized from the manufacturer, or just a dry lint-free cloth to wipe away smudges and grime (if it's really bad, dampen the cloth ever-so-slightly, but be sure the finish doesn't sit with water on it).
Comment: I should also note, the affect of a string cleaner on the nylon strings may be drastically different than on the wound strings, even if they have a nylon core themselves. In the case of unwound nylon strings I stick to a clean, dry cloth.
Answer: I would never use alcohol on a fretboard or bridge. The natural oils in the wood, if kept humidified, are all it takes.
Answer: It's not very common, but some classical guitars (and maybe acoustic as well?) have shellac finish. Alcohol dissolves shellac, and you should keep it away from such instrument. Even alcohol based deodorant on your clothes can damage it.
Answer: I've never done that:)
There is something peculiar I found. Brasso (https://en.wikipedia.org/wiki/Brasso). When the guitar had grime on it, Brasso really cleans it well, plus it doesn't dampen the body of the guitar.
I always use Brasso for cleaning my guitar. Hope this helps!
Comment: Brasso is ammonia and oxalic acid. Oxalic acid is a wood bleach and can destroy colored finishes. In addition is has abrasives in it. Abrasive is another word for "removes material from the surface".

rubbing alcohol to clean guitar


Racket/Scheme - (define ((function-name arg1) arg2) (body ...)) - Notation

Question: What is the name of this notation / what does it represent?
(define ((function-name arg1) arg2) (body ...))

I understand that in Racket/Scheme you can define a function in the following two ways:
(define (function-name arg1 arg2 ...) (body ...))

(define function-name (lambda (arg1 ...) (body ...))

However, I recently came across this notation in Software Design For Flexibility by Chris Hanson and Gerald Jay Sussmaan:
(define ((function-name arg1) arg2) (body ...))

I noticed that this notation works in Scheme (which the book is written in) and Racket as well.
Does anyone know the name of this notation with the function application in the define statement arguments? / What it might represent?
Comment: In Racket, it's called the "Curried Function Shorthand". See https://docs.racket-lang.org/guide/define.html#%28part._.Curried_.Function_.Shorthand%29
Answer: This is definitely unusual, and I've never seen it explicitly documented anywhere, but it does work on at least some scheme implementations (Chicken, Racket, whatever other scheme you tried accept it, Guile doesn't).
The wording of R7RS gives some insight:

(define (〈variable〉 〈formals〉)〈body〉)

〈Formals〉 are either a sequence of zero or more variables, or a sequence of one or more variables followed by a space-delimited period and another variable (as in a lambda expression). This form is equivalent to (define〈variable〉(lambda (〈formals〉)〈body〉)).

So this:
(define ((example a) b) (printf "~A~%~A~%" a b))

can be considered equivalent to
(define (example a) (lambda (b) (printf "~A~%~A~%" a b)))

which is in turn equivalent to
(define example (lambda (a) (lambda (b) (printf "~A~%~A~%" a b))))

and the schemes that accept this notation probably do a transformation like that internally at some point as part of how they implement define-ing a function. That does match the behavior of example on chicken when defining it using the first form.
Answer: This is an extension and not part of Standard Scheme. This extension has been available in MIT/GNU Scheme for quite some time, and some other implementations have adopted it.
The R7RS spec does not show a form that matches the OP posted example definition. The closest match is this in 5.3. Variable definitions:

(define (<variable> <formals>) )
<Formals> are either a sequence of zero or more variables, or a sequence one or more variables followed by a space-delimited period and another variable (as in a lambda expression).

The definition in question is:
(define ((function-name arg1) arg2) (body ...))

Here, (function-name arg1) would have to be considered a variable in order to match the description in the Standard; but it is not a variable, or even an identifier.
From 3.1. Variables, syntactic keywords, and regions:

An identifier that names a location is called a variable and is said to be bound to that location.

It is worth pointing out that Appendix B of Hanson and Sussman's book briefly discusses this construction:

In MIT/GNU Scheme we can use the sugar recursively, to write:
(define ((compose f g) x)
  (f (g x)))

Now, on p. 17 of the MIT/GNU Scheme Reference Manual (11.1) it is shown that:
(define (name1 name2 ...)
  expression
  expression ...)

is equivalent to:
(define name1
  (named-lambda (name1 name2 ...)
    expression
    expression ...))

Note that the syntax shown in the MIT/GNU manual shows this for lambda:

lambda formals expr expr ...  [extended standard special form]

Here, formals is described as "the formal parameter list," but note that the term variable is not used. The term variable is used elsewhere in the manual, e.g., in the descriptions of let forms.
The named-lambda special form is described:

named-lambda formals expression expression ...  [special form]
The named-lambda special form is similar to lambda, except that the first "required parameter" in formals is not a parameter but the name of the resulting procedure; thus formals must have at least one required parameter. This name has no semantic meaning, but is included in the external representation of the procedure, making it useful for debugging. In MIT/GNU Scheme, lambda is implemented as named-lambda, with a special name that means "unnamed".

So, the definition (define ((function-name arg1) arg2) (body ...)) can be rewritten as:
(define (function-name arg1)
  (named-lambda ((function-name arg1) arg2) (body ...)))

by the above transformation rule provided by the manual, since the formal parameter list has been extended in MIT/GNU Scheme in such a way that it is not restricted to containing variables only.
This last result can then be expanded again (recursively), using the same rule:
(define function-name
  (named-lambda (function-name arg1)
    (named-lambda ((function-name arg1) arg2)
      (body ...))))

Since named-lambda is like lambda, i.e., different only in that there is some extra metadata associated with it, but semantically identical, we can write the semantic equivalent:
(define function-name
  (lambda (arg1)
    (lambda (arg2)
      (body ...))))

This is just a definition for a higher order procedure. So the notation in question is just syntactic sugar to facilitate the definition of higher order procedures. Note that SRFI 201 aims to provide this capability for other Scheme implementations, and calls this the "higher-order define form," and also "the 'currying' variant of the define form."
Returning to the example procedure from Appendix B of Software Design for Flexibility, it can be seen to demonstrate how this syntactic sugar can be used to express the idea of function composition neatly.
(define ((compose f g) x)
  (f (g x)))

Here, compose is a procedure which takes two arguments, f and g, and which returns a procedure that takes one argument x:
1 (user) => (define my-composition (compose square cube))
;Value: my-composition
1 (user) => (my-composition 2)
;Value: 64


Dropping the condition in Hilbert's Nullstellensatz

Question:
Hilbert Nullstellensatz is not valid for a field which is not algebraically closed.

Nullstellensatz implies that every maximal ideal in $K[x_1,\dots,x_n]$ is of the form $(x_1-a_1,\dots,x_n-a_n)$. So I think I need a counterexample if the field is not algebraically closed, or is there another theorem for those fields ? (see here)
Answer: In $\mathbb R[x]$, $(x^2+1)$ is a maximal ideal not of the form $(x-a)$.
Answer: Let $I=(x^2+1)\subset \mathbb Q[x]$. Then $I$ is a maximal ideal in $\mathbb Q[x]$ which is not of the form $(x-a)$ for any $a\in \mathbb Q$.


How to compile console application to 3.5 version

Question: I have a .net Console application in 1.0 version. I have converted that application into 2010. Now need to compile the application in .Net 3.5. Is there any way where I can set the compile version for console application. However, when I compile the Class Library there is a Target Framework option in the property of the project. But in the Console application I do not see any option.
Answer: Open Project Properties Page, and change Target Framework to your desire
Comment: This option is not available on Console Application.
Comment: There always have Target framework for .net project. You should check again


Input tag elements not visible. ASP.NET

Question: My input elements will not show on screen when I run the webapplicatioin.
here is my html
@model Boekingssysteem.ViewModels.BewerkDocentViewModel;
@{
    ViewData["Title"] = "Docent bewerken";
}

@ViewData["Title"]

        <form asp-action="BewerkDocent" method="post" class="form-inline justify-content-center">
            <input type="hidden" asp-for="RolId" />
            <input type="hidden" asp-for="Rnummer" />

                    <input type="text" disabled class="form-control" id="inputRnummer" asp-for="Rnummer" class="form-control" />

                    <button type="button" class="btn btn-outline-primary w-100">Richtingen</button>

                    @Html.DisplayNameFor(model => this.Model.Voornaam)
                    <input type="text" class="form-control" asp-for="Voornaam" class="form-control" />

                    @Html.DisplayNameFor(model => this.Model.Achternaam)
                    <input type="text" class="form-control" asp-for="Achternaam" class="form-control" />

                @Html.DisplayNameFor(model => this.Model.Email)
                <input type="email" class="form-control" asp-for="Email" class="form-control placeholder=" email@example.com"" />

            <input type="submit" class="btn btn-primary" value="Bevestig"/>
        </form>

Here is a screenshot of the page
enter image description here
under every label should be a textbox and on the bottom should be an submit button.
but it is not showing.
does anyone know what's wrong?
I tried to disable javascript but no help.
I tried to search the web but I can't find any answers.
Comment: Try to add `Layout = null;` line after `ViewData["Title"] = "Docent bewerken";` in the view and check result. In additional try to use _**View Page Source**_ in the browser to analyze you page content. Usually this related to your CSS declarations.
Comment: all seems fine. Can you share any CSS applied to input tag?
Comment: that removes all the css. But i can see the textboxes back
Comment: its just bootstrap that I use
Comment: @gilleslag: Check this: [Make input invisible through css?](https://stackoverflow.com/q/1078451/6630084)
Comment: input {
    height: 30px;
    width: 30px;
    appearance: none;
    background-color: black;
    border-radius: 50%;
    opacity: 0;
}

@MuhammadSaqlain
input:hover {
    cursor: pointer;
}
Comment: Thanks for the help. in css I should set opacity to 1 instead of 0. That fixed the problem
Answer: Remove opacity: 0; from the <input> style. This property with value 0 make your button transparent. Default value is 1.

Input tag elements not visible. ASP.NET


Penalizing outliers in a dataset

Question: I have a dataset of ages ranked from smallest to highest. Next to each entry, I have calculated the respective ranked percentile. I then have to remove all values above the 99.5% percentile from the dataset (i.e. what we deem as outliers). Once these have been removed, I have to recalculate the ranked percentile values for the remaining entries, such that the new highest value has a percentile value of 1 (or 100%). For the outliers that were removed, I have to somehow penalize these values and then assign a percentile value based on the remaining data.
I have not come across any method in statistics of "penalizing" outliers, however, I have been asked to do this. Is there such a method of "penalizing" outliers in statistics, apart from removing the outliers completely?
Comment: Why do you have to remove what you call outliers? If they are correct, you're just throwing away information. Why would you? You haven't mentioned any reason that these values could cause any problem at all, were they handled just like all other observations. (Of course this is different oif some age values are, say, >200 or smaller than zero, but for finding this out you don't look at percentiles.
Comment: This is an old question, but all the talk of "have to" makes me think it was an assignment, and not a very good one!
Comment: Why do you deem those to be outliers?
Answer: Penalizing part comes in the estimation portion. Robust Statistics is the field for this. M-estimators is an example of how the penalizing works or where it takes place. Basic idea is that it uses influence functions which measures the impact of each data point to the estimated  parameter statistics and adjustment is done accordingly.
An example that incorporates this approach can be done in R using the MASS::rlm()
Comment: While this link may answer the question, it is better to include the essential parts of the answer here and provide the link for reference.  Link-only answers can become invalid if the linked page changes. - [From Review](/review/late-answers/354052)
Comment: @ShawnHemelstrand Thank you for the advice. I notice I was being very lazy and now I know how that impacts the quality of the answer.
Comment: Thank you for the edit.
Answer: Well if we think of regularization, than high coefficients will be penalized. How do we get high coefficients, maybe through outliers which distort the mean impact of a variable.
One way I could think of, that the type of regression will automatically penalize for such a case, and that we have a regularization on the outlier. Maybe you start your search for regularization of outliers to get more info.
If you should really use weights to penalize your age, then you could define every age below the threshold with a w0=1 and all other values above that threshold  with a rising declining weight.
in market research when we try to get e represntative data set we do the same with some sorts of working class (we weight them up) so they represent a specific ratio of a speciic workerclass in the country, if we didn't get enough ppl in our dataset of that workerclass/proportion.
In summary: all i can think of is regularization of outliers. like for coefficients in lasso and ridge. But I have the feeling that would be done somehow automatically if the coefficient is pushed e.g. to zero, but I made no experiments on that. may be one of the other collagues here has a different insight.
Update:
This link however tells exactly, the same with regularization what i mentioned previously ago: maybe you have a look at it.
https://datascience.stackexchange.com/questions/63900/how-regularization-helps-to-get-rid-of-outliers

Penalizing outliers in a dataset


Cauchy criterion for sine series with factorial

Question: $$a_n=\frac{sin1!}{1*2}+\frac{sin2!}{2*3}+\frac{sin3!}{3*4}+...+\frac{sinn!}{n(n+1)}$$
I have this series and I don't understand how to apply the cauchy criterion
$$\lvert a_{n+p}-a_n \rvert \lt ε$$
The only result I get is this one:
$$\lvert a_{n+p}-a_n \rvert$$=$$\lvert \sum_{k=1}^{n+p} \frac{sink!}{k(k+1)}- \sum_{k=1}^{n} \frac{sink!}{k(k+1)} \rvert$$
What do I do next?What do I apply?
Answer: |$\sum_{k=1}^{n+p}\frac{\sin(k)!}{k(k+1)}-\sum_{k=1}^n\frac{\sin(k!)}{k(k+1)}|=|\sum_{k=n+1}^{n+p}\frac{\sin(k!)}{k(k+1)}|\leq\sum_{k=n+1}^{n+p}\frac{|\sin(k!)|}{k(k+1)}\leq\sum_{k+n+1}^{n+p}\frac{1}{k(k+1)}=\sum_{k=n+1}^{n+p}(\frac{1}{k}-\frac{1}{k+1})=\frac{1}{n+1}-\frac{1}{n+p+1}<\frac{1}{n+1}$
And from here it is easy.
Answer: Hint: $|\sin(x)|\le 1$.  Estimate $\left|\sum_{k=n+1}^{n+p} \frac{1}{k(k+1)}\right|$.


PostgreSQL 9.2 set enable_nestloop has no effect

Question: I try to changing nestloop
set enable_nestloop=1

When I look
show enable_nestloop;
 enable_nestloop
-----------------
 on
(1 row)

all is ok. But it has no effect.
If changing this param in config file and then reload config from cli, all work fine.
Why set not working for me?
Comment: What do you mean with "*has no effect*"?
Comment: Query planning not changed
Comment: You did see the comment [in the manual](http://www.postgresql.org/docs/current/static/runtime-config-query.html): "*It is impossible to suppress nested-loop joins entirely, but turning this variable off discourages the planner from using one if there are other methods available*" (plus: the default is `on` anyway)
Comment: My mistake, bad example. I know that it's "on" by default. I needed in application turning it to "off" for some queries and after return to "on". Maybe you know how to implement it?
Comment: If you have a slow query, it's probably better to post the query and get help on how to improve it: https://wiki.postgresql.org/wiki/Slow_Query_Questions
Comment: It's not so simple. I use postgre as DB for [1C](http://www.1c.ru), and I can't tuning many queries for increasing speed. Max what i can - turning to "off" and "on" state  of `nestloop`.
Comment: Are you sure using nested loops would result in a more efficient query plan than the one you're seeing? If you're _positive_ the planner is doing the wrong thing, make sure statistics for the relevant tables are up to date, and maybe bump up the collection target.
Comment: Yes, I'm sure. I tested speed of some operations in 1C with different state of nestloop. And in result part of queries working faster with disabled nestloop, other when it enable. That kind of problem not only at me, but no one didn't write solution.
Answer: enable_nestloop is a testing parameter. It is on by default, which is why turning it on had no effect. It's there so you can turn it off to tell the query planner "please don't use a nested loop unless you have no other way to execute this query". It does this by forcing the cost estimate for nested loops very high.
This is not a query hint you can use to say "please use a nested loop for this query". It doesn't work like that.
It's strongly recommended that you not use these testing parameters for production use. Forcing a plan now may have unfortunate consequences later. If at all possible, use the cost parameters like random_page_cost and effective_cache_size to guide the planner into choosing the most appropriate plan its self.
If you absolutely must use params like this in your app, use SET LOCAL to set them just within one transaction.
There is no way to set them for a single statement then automatically unset them. That's partly because they're just not meant to be used that way. They're designed not to be query hints.
Comment: Thanks, Craig, and would you please let me know the best option to disable the nested loop for just one query?
Comment: @LingYanMeng It's in the answer above.


Every $\tau$ in the U.H.P. is equivalent to *exactly one* point in the region

Question: In Ahlfors' complex analysis text, page 281 he states the following theorem:

Theorem 8. Every point $\tau$ in the upper half plane is equivalent under the congruence subgroup mod 2 to exactly one point in $\overline{\Omega} \cup \Omega'$.

Here $\Omega$ is the region bounded by the lines $\Re z=0, \Re z=1$ and the upper half of the circle $|z-1/2|=1/2 $, $\Omega'$ is its reflection across the imaginary axis, and the closure is taken in the upper half plane.
Also, the congruence subgroup mod 2 is the group of all Möbius transformations $ \frac{a \tau+b}{c \tau+d}$ with integer entries, determinant $\pm 1$, where $a \equiv d \equiv1$ (mod 2) and $b \equiv c \equiv 0$ (mod 2).
I have read the proof given in the book, and I'm stuck at the last stage, namely proving that the equivalent point is unique.
Suppose $\tau$ is in the upper half plane, and let $T',T''$ be two elements of the subgroup, such that both $\tau'=T' \tau$ and $\tau''=T'' \tau$ lie in $\overline{\Omega} \cup \Omega'$, why must $\tau'=\tau''$?
I can see that $T'^{-1} \tau'= T''^{-1} \tau''$ which proves that $\tau',\tau''$ are equivalent under the subgroup, but this is still not enough to show that they coincide.
Any help is appreciated, thanks!
EDIT: at the end of the chapter Ahlfors writes

The uniqueness follows readily from the fact that the $S_k$ as well as the $S_k'$ are mutually incongruent. We shall leave it to the reader to work out the details.

here $S_k,S_k'$ are some fractional linear maps which "generate" the subgroup. There is a relevant figure that I can't show here sadly...
Answer: Let $G$ be the ($\pm$) modular group $SL^{\pm}(2,\mathbb Z)$ and $H$ its subgroup formed by the matrices that are $\equiv I\mod 2$. Ahlfors observes that $H$ has index $6$ in $G$, and writes down the coset representatives $S_k^{-1}$ on page 281.
Theorem 2 says that the orbit $G \cdot \tau$ has exactly one point (call it $g\tau $) in $\overline{\Delta}\cup \Delta'$. Suppose $g\tau \in \overline{\Delta}$. Then  for every $k=1,\dots,6$ the orbit $G\cdot \tau$ has exactly one point in $S^{-1}_k(\overline{\Delta} )$, namely $S_k^{-1}g \tau $. The union of these six sets is   all the shaded parts $\overline{\Omega}\cup\Omega'$. Exactly one of the points $S_k^{-1}g \tau $ is in $H\tau$, because exactly one of the elements $S_k^{-1}g$ is in $H$. Moreover, $G\tau$ does not meet any non-shaded parts of $\overline{\Omega}\cup\Omega'$, because it does not meet $\Delta'$.
The case $g\tau \in  {\Delta'}$ is the same, except with $S_k'$ instead of $S_k$.

Remark 1: the proof would be more transparent if we used a different fundamental domain of $H$ instead of $\overline{\Omega}\cup\Omega'$, namely the union of $S^{-1}_k(\overline{\Delta} \cup \Delta')$ over $k$.
Remark 2: The deduction of Theorem 8 from Theorem 2 can be summarized as follows: once we have a fundamental domain $D$ for group $G$, we get a fundamental domain for its subgroup $H$ by taking the union of the images of $D$ under coset representatives, one from each coset (including $H$ itself).
Comment: Thank you! Could it be that we should use the direct $S_k$ rather than the inverses $S_k^{-1}$?
Comment: @user1337 Possibly; the direct maps $S_k$ also form a set of coset representatives. The choice depends on how the picture looks like, i.e. what maps will send $\Delta$ onto those non-shaded bits on the picture. I don't have the book with me now.
Comment: I think I got it, thanks again.


Complex exponents and matrices

Question: If the matrix $A$ is defined as:
$$A_{m,n} =
 \begin{pmatrix}
  a_{1,1} & a_{1,2} & \cdots & a_{1,n} \\
  a_{2,1} & a_{2,2} & \cdots & a_{2,n} \\
  \vdots  & \vdots  & \ddots & \vdots  \\
  a_{m,1} & a_{m,2} & \cdots & a_{m,n}
 \end{pmatrix}$$
is it possible to define the following matrices:
$B=i^{A_{m,n}}$ and $C=\left(A_{m,n}\right)^i$
where $i=\sqrt{-1}$?
Thanks
Comment: Exponent relates to lograithms and logarithms relate to power series expansions, check [this](http://www.physicsforums.com/showthread.php?t=280530) out for more info.
Comment: The matrix must be square ($m=n$ in your notation). Then the simplest examples are 2x2-triangular (Carleman)-matrices of the form $$ A= \begin{bmatrix} 1& a\\ 0 & b \end{bmatrix}$$ which can easily be diagonalized and then your formulae can be applied according to the rules of diagonalized matrixes.
Answer: You can define such matrices, but be cautious, because such powers are not uniquely defined. For example, $i^{1/2}= \{exp(i\pi/4), exp(5i\pi/4)\}$.
Comment: You say I can define such matrices, but you don't say how.
Comment: @Riccardo.Alestra Use the identity $z^w = exp(w Ln(z))$ with complex logarithm defined [here](http://en.wikipedia.org/wiki/Complex_logarithm), $z,\,w\in\mathbb C$
Answer: For any square real or complex matrix $A$, the matrix $\exp A$ is defined as $\sum_{k=0}^\infty A^k/k!$. If you write $\mathrm i$ as $\exp (2n\pi\mathrm i+\pi \mathrm i/2)$, with $n\in \Bbb Z$, you can then get various matrix representations of $\mathrm i^A$. For non-square matrices, addition and multiplication, and so powers and exponentials, can be generalized by thinking of them as infinite matrices with all but a finite number of entries zero.
You need someone else to say what meaning might be ascribed to such expressions as $A^\mathrm i$.

Complex exponents and matrices


file upload using Webservice

Question: I am using Drupal 7 and trying to upload a file
function upload_service_menu() {
  $items = array();

  $items['api/v1/upload'] = array(
    'title' => 'File Upload Service',
    'description' => 'Upload files to public directory on this server',
    'page callback' => 'upload_service_job',
    'access arguments' => array('access content'),
    'type' => MENU_CALLBACK,
  );
  return $items;
}

/**
 * Function to get the path, download and store the file on our server.
 */
function upload_service_job() {

    $file = $_FILES;

    $validators = array();
    $file = file_save_upload($file, $validators, 'public://');
    if($file){
        echo "Sucess";
    }else {
        echo "fail";
    }
}

and my local form is
<form action="http://example.com/api/v1/upload/" method="post"
enctype="multipart/form-data">
<input type="file" name="file" id="file">

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

But i am not able to upload file. Seems file_save_upload($file, $validators, 'public://'); function is not working .I checked permissions also..
Can anybody tell me what to do.
Thanks
Comment: "fails" and "does not work" are two of most useless statements in IT. Please describe what exactly happens, how does it look like, what are error messages on both ends of file transmission (Apache error.log, Drupal watchdog, browser's console, whatever applicable). Only with that data we might be able to answer.
Comment: there is no error. as this function is not working
$file = file_save_upload($file, $validators, 'public://');
Comment: How do you know which function fails if there is no error message anywhere?
Comment: $file = file_save_upload($file, $validators, 'public://');
    if($file){
        echo "Sucess";
    }else {
        echo "fail";
    }
it prints fails.
Comment: In the source code of [`file_save_upload`](https://api.drupal.org/api/drupal/includes!file.inc/function/file_save_upload/7) there is `drupal_set_message` before each `return FALSE` - switch theme to one that can display these messages and post the one that will appear.
Answer: $_FILES is

An associative array of items uploaded to the current script via the HTTP POST method.

file_save_upload() takes as its first parameter

A string specifying the filepath or URI of the uploaded file to save.

Your code essentially does this
$file = file_save_upload($_FILES, $validators, 'public://');

So you're currently passing an array to a function that's expecting a string.
You're probably looking for something along the lines of
$file = file_save_upload($_FILES['file']['name'], $validators, 'public://');

file upload using Webservice


Directional derivative of a two dimensional piecewise function

Question:
Let $f:\mathbb{R^2} \rightarrow \mathbb{R}$ with $f(x,y)= \begin{cases}
      \frac{x^4y}{x^4+y^4} & (x,y)\neq(0,0) \\
      0 & (x,y)=(0,0)
      \end{cases}$
Show that $f$ is differentiable in all directions $v=(a,b)$. Is $f$ differentiable in $(0,0)$?

I'm a little confused by the question possibly because I'm wrong about the definition of directional derivative but we define a directional derivative as: $$D_vf(x_0,y_0)=v \cdot \nabla f(x_0,y_0)= v \cdot \begin{pmatrix} \partial_xf(x_0,y_0) \\ \partial_yf(x_0,y_0) \end {pmatrix}  $$
Applying the definition we have $$D_vf(x,y)=v\cdot \begin {pmatrix}  \frac{4x^3y^5}{(x^4+y^4)^2} \\\frac{x^4(x^4-3y^4)}{(x^4+y^4)^2}
\end {pmatrix} $$
However unless I made a big mistake the limits of the individual partial derivatives don't converge to zero so the function shouldn't be differentiable, so how does the directional derivative exist? Is there a problem with what I've done so far or is the statement wrong?
Answer: HINT
To tackle the first part, it is advisable to apply the definition:
\begin{align*}
D_{v}f((0,0)) & = \lim_{t\to 0}\frac{f((0,0) + tv) - f(0,0))}{t} = \lim_{t\to 0}\frac{f(ta,tb)}{t} = \lim_{t\to 0}\frac{t^{5}a^{4}b}{t^{5}a^{4} + t^{5}b^{4}} = \frac{a^{4}b}{a^{4} + b^{4}}
\end{align*}
and the desired result holds.
Can you handle the second part?


How do I get vagrant halt to successfully shut down debian jessie vm on yosemite host?

Question: Whenever I attempt to run vagrant halt, it says "default: Attempting graceful shutdown of VM..." but eventually times out and says " default: Forcing shutdown of VM..." sometimes this works and sometimes it leaves the VM in running state, according to the VirtualBox UI.
Here are the details of the system:
Host: OS X 10.10.5 Yosemite, Virtual Box 5.0.4, w/extension pack, Vagrant 1.7.4
VM: Debian Jessie 8.2.0 64bit, 2 GB Ram
Help! It seems like vagrant halt should be able to gracefully stop the VM?
Comment: do you have left over processes blocking the shut down ? can you run from the VM `sudo shutdown -h now` and see if it fails or always run -
Answer: This was a bug in vagrant, here is the pull request that fixed it:
https://github.com/mitchellh/vagrant/pull/6315
Version 1.7.5 will include this fix.


Textbooks for topology dimension theory.

Question: I'm reading Munkres's  and notice the "dimension theory". I'm interested in it, yet I still have some questions:
(i) What's the motivation of (general topology) dimension theory?
(ii) Is dimension theory useful, i.e. has it solved some non-trivial problems?
(iii) Are there any good textbooks about this topic?
Thank you for your help!
Comment: For (iii) Engelking is a classic, Pears is also good
Answer: The primary motivation in the discovery of it (around 1910/1920) was trying to distinguish the different $\Bbb R^n$ topologically: it hadn't been shown in general that $\Bbb R^n \not\simeq \Bbb R^m$ when $n \neq m$ (some special cases were known), while there were examples of space filling curves, all sorts of fractal-like planar sets whose "dimension" was unclear etc. So some topologists defined functions "$\dim$" with integer values on topological (or metric, or even smaller classes) spaces that were topological invariants (so homeomorphic spaces had the same value ) hoping to find one for which they could show $\dim(\Bbb R^n) = n$. In the end several such functions were defined by different people (Lebesgue, Brouwer, Urysohn among them) and finally Brouwer succeeded (using deep theorems like his fixed point theorem and others) to show that indeed $\Bbb R^n$ had dimension $n$ for some dimension function. Soon people began generalising and unifying the different functions, especially in the realm of separable metrisable spaces, where most of such functions all coincide in value.
A good general overview (almost encyclopedic) is Engelking, theory of dimensions, finite and infinite. A good book on separable metric spaces only is Jan van Mill's  infite-dimensional topology, an introduction and prerequisites, who treats the basic dimension theory, Brouwer's fixed point theorem, and AR/ANR theory in just a few chapters, including a self-contained proof of the Jordan Curve Theorem. Too bad it's out of print nowadays.. (but a good library will have a copy).
The main problem it solves is the fact that the $\Bbb R^n$ are mutually non-homeomorphic but there are many other interesting results and still loads of open problems too. See Engelking's book for the frontier of research.
Comment: What about Hurewicz and Wallman?
Comment: @bof It's older and I don't know it as well as Engelking. But it's a classic indeed.


What are the assumptions that we make when we compute KL Divergence between two distributions?

Question: Let us assume that we compute the KL Divergence between p and q. Is it necessary that both p and q belong to the exponential family of distributions. Moreover, is it necessary, that both p and q should be of the same family, i.e. either both should be gaussian, or both should be dirichlet and so on.
Comment: No. In computing KL divergence between two distributions, you do not need to make these assumptions. The most you *might* need to assume is that $p$ and $q$ have the same support, but I might be wrong about that.
Comment: The values for which the densities $p$ and $q$ take positive values. For example, the support of a Normal distribution is $\mathbb{R}$, the support of a Gamma distribution is $(0,\infty)$, the support of a Beta distribution is $(0,1)$ etc.
Comment: What is meant by support here?
Comment: Can someone comment how to compute distance between function when they dont have a common support? or KL divergence if you want to be specific. Generic answer is appreciated.
Comment: Reference would be helpful for KL divergence in extended form when support is different.
Answer: KL divergence will always exist when P & Q have same support. They donot have to be in same family of distributions. Infact most of the times Q in unimodal and P is not(the idea of approximate inference).
A class of inference which gives nice examples for how complex P and Q would be Variational Inference which is essentially an approximate inference method (Also common in literature and implementations available for many methods). For example, you could look at LDA (Latent Dirichlet Allocation) inference and learning ( detailed derivations can be found in appendix).
P.S. I am not aware of any extended form when support for P and Q do not match.
Answer: To be really technical about it, KL(p,q) is finite whenever q has a Radon-Nikodim (I might be wrong on the spelling here) compared to p. In english, if for all events A, p(A)>0 implies q(A>0)
Otherewise, it is well-defined as infinite