Permission denied (publickey) when attempting to connect Ubuntu EC2 instance via SSH

Question: I'm attempting to connect to my EC2 Ubuntu instance via SSH with my private key. I had no problem connecting to the server before using the sudo reboot command.
Now, I cannot connect to the instance using any of the keys that I have set up on this instance. I had also set up a backdoor user that could be used to log in to the instance in the event that this happened and I cannot log in with this user either.
No matter what I do, I receive a permission denied (publickey) response. I attempted to restart the instance from the EC2 web console, and the restart action did nothing. I've since been able to stop the instance and attach its root volume to another instance and the SSH config looks fine to me.
Any suggestions for what I could look for?
Comment: You can mount the disk to another EC2 and investigate.
Comment: If you restarted your instance, your ip may have changed, did you double-check that you're trying to connect to the correct instance?
Comment: Hey, I've already had this out with AWS Support multiple times. I'm not that much of an amateur that I'm not checking the IP of the server. I've checked the IP (from the EC2 console), the key file, the permissions of the key file, the sshd_config file, the authorized_keys file. I've checked EVERYTHING and it's all okay. Thanks for the suggestion, though.
Answer: In your case, I would create an AMI of this instance and launch a test box with associated PEM key you have.
When it clears status checks you should then be able to get back into the box with your private key. If not, that particular service may be down. I am surprised AWS support was unable to help.


When do I need "Negotiate Client Certificate" to be set to Enabled?

Question: I optionally want to support Client Certificates. That's why I set Client certificates to Accept on IIS. This works on most machines. However, on some machines IIS returns a 500. This can either be "solved" by setting Client certificates to Ignore (which is not an option to me) or by setting Negotiate Client Certificate to Enabled (this can either be done with netsh http add ... or by changing DefaultFlags to 2 in HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\HTTP\Parameters\SslBindingInfo\0.0.0.0:443\; can this also be changed in IIS Manager?). While (enabling) this setting sounds reasonable just from looking at the name I don't understand why it's needed on some machines but not on others...
Answer: TL;DR
You can enable this all the time if you require client-certificate to access any resource on the server. The primary reason is that some clients do not allow TLS re-negotiation due to possible Man-in-the-Midddle (MITM) attacks.
You can disable this if your clients support TLS re-negotiation and the MITM risk is acceptable.
Description
IIS has two ways to negotiate TLS:

Where the client sends the client certificate in the initial request. This is useful when all resources on the server require TLS client authentication.
Where the client doesn't send the client in the initial request, but later after IIS performs a TLS re-negotiation. This is useful when only some resources require TLS client authentication.

The Negotiate Client Certificate setting determines which is used, the first if enabled, and the second if disabled. Here is more from Microsoft's blog:

If this setting is enabled, the client certificate will be sent by the client browser when the initial secure connection with the web-server is negotiated.
If it is disabled, an initial secure connection will be negotiated between the web-server and the browser based on the server certificate, and then the connection will be re-negotiated when the client sends the client certificate.

https://blogs.msdn.microsoft.com/friis/2017/01/16/the-complete-list-of-changes-to-make-to-activate-client-certificate-mapping-on-iis-using-active-directory/

Client Support and Error
The issue is that some clients do not re-negotiate the TLS session. If the client does not do this, you may encounter the following error in the server log. Setting Negotiate Client Certificate to Enabled can fix this.
The following fatal alert was generated: 20. The internal error state is 960.

https://blogs.iis.net/rickbarber/require-client-certificates-in-iis-7-5

TLS Re-Negotiation MITM Attack
A reason some clients do not re-negotiate the TLS connection is due to Man-In-The-Middle (MITM) attacks associated with TLS re-negotiation:

Since the discovery of the MITM attack arround SSL Renegotiation, the answer in alot of circles has been to hangup on renegotitation requests.

Make IIS require SSL client certificate during initial handshake
http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.156.4428&rep=rep1&type=pdf
https://security.stackexchange.com/questions/63867/ssl-tls-renegotiation-handshakes-mitm-plaintext-data-injection-medium-or-low

The clients requiring Negotiate Client Certificate likely do this to prevent MITM attacks during TLS re-negotiation.
Summary
If you have no issue requiring client certificates for all IIS resources, enabling this feature may allow you to interoperate with more clients and enable you to further protect your traffic.
Disable this to support differential TLS client authentication support while understanding the MITM risks.


Two dimensional array - Make the child arrays keys same as all

Question: I have a two dimensional array like this:
Array
(
    [0] => Array
        (
            [Product_Main_category] =>  Value
            [Product_Sub_category1] =>  Value
            [Product_Sub_category2] =>  Value
            [Product_Title] =>  Value
)
 [1] => Array
        (
            [Product_Main_category] =>  Value
            [Product_Sub_category1] =>  Value
            [Product_Sub_category2] =>  Value
            [Product_Title] =>  Value
            [Product_SKU] =>  Value
            [Product_MODEL] =>  Value
            [Product_manf_link] => Value
            [Product_manf_Image_link] => Value
)
 [2] => Array
        (
            [Product_Sub_category1] => Value
            [Product_Title] =>  Value
            [Product_SKU] =>  Value
            [Product_MODEL] =>  Value
            [Product_manf_link] => Value
            [Product_manf_Image_link] => Value
)

I want to make the child array keys same for all like if one child array have extra keys then all other child arrays must have those keys but can be empty.
like:
Array
(
    [0] => Array
        (
            [Product_Main_category] =>
            [Product_Sub_category1] =>
            [Product_Sub_category2] =>
            [Product_Title] =>  Value
            [Product_SKU] =>  Value
            [Product_MODEL] =>  Value
            [Product_manf_link] => Value
            [Product_manf_Image_link] =>
)
 [1] => Array
        (
            [Product_Main_category] =>  Value
            [Product_Sub_category1] =>  Value
            [Product_Sub_category2] =>  Value
            [Product_Title] =>  Value
            [Product_SKU] =>  Value
            [Product_MODEL] =>  Value
            [Product_manf_link] => Value
            [Product_manf_Image_link] => Value
)
 [2] => Array
        (
           [Product_Main_category] =>  Value
           [Product_Sub_category1] =>  Value
           [Product_Sub_category2] =>  Value
           [Product_Title] =>
           [Product_SKU] =>
           [Product_MODEL] =>
           [Product_manf_link] => Value
           [Product_manf_Image_link] => Value
)

The child arrays are being made dynamically I am setting the in the main array like this
$array[] = $sub;

Maybe after completing the main array which is $array we can do that?
Thank you.
Please let me know if this is a possible duplicate so I can close it myself not by down votting.
Comment: But why you need such kind of array..
Comment: @Uchiha I am creating csv file and it creates problem in it.
Answer: First you need to accumulate all the keys somehow. I think it would be better to do this while you build the array, but if it needs to be done afterward, you could use something like this.
$all_keys = array_reduce($old_array, function($keys, $item){
  return array_merge($keys, array_keys($item));
}, array());

Then make a template with empty values for the unique keys
$template = array_fill_keys(array_unique($all_keys), '');

You can apply the template to your old array to generate one where each child array contains all the same keys.
$new_array = array_map(function ($item) use ($template) {
  return array_merge($template, $item);
}, $old_array);

If you would rather modify the existing array instead of creating a new one, it can be done this way
array_walk($old_array, function(&$child, $key, $template){
  $child = array_merge($template, $child);
}, $template);

Comment: Thank you for your answer please let me check and try.


Visual Studio 2010 and UTF-8 encoding

Question: Is there a way that I can save my Visual Studio 2010 files as UTF-8 encoded?  I'm using VS.NET 2010 as a PHP editor using VS.PHP.
If there is a macro that will launch during the saving process that will handle this, that would be fine too.
Thanks in advance!
Comment: I went ahead and started using Notepad++ as that gave me everything I needed.
Answer: File → Advanced Save Options. At least in Beta 2.
Answer: In Visual Studio 2010 Final:
File → Save as → In the "Save File as" dialog window click the small arrow in the "Save" button and select "Save with Encoding..."

Visual Studio 2010 and UTF-8 encoding


How people found or derived shortcuts for derivatives?

Question: Maybe it is a soft question, I can't find any information about this. How people understood that we can use derivative shortcuts instead of calculating limits and how did they derive them?
By shortcuts I mean rules like $(x^n)^{'} = nx^{n-1}$. I find them somehow intuitive, like if we have a linear function, its derivative should be constant, etc. But I can't figure out how one can derive those shortcuts. Any references, links will be appreciated.
P.S. I am also interested in historical part who found them. Were they proved at once by someone? Did Newton or Leibniz know these shortcuts?
Comment: They were found by applying $f (x+\delta x) - f(x)=f'(x)$ to a wide range of powers and then proving that it holds for all $n$.
Comment: Like any other shortcut ever in mathematics, it can be used because the long way of doing it has already been done and proven, so instead of doing it again from scratch each time, we just remember the result and apply it. Other examples include a lot of formulas like the binomial theorem and the quadratic formula.
Comment: @MohammadZuhairKhan, did Newton know them? Or is there a name of the mathematician, who found them? I mean explicitly shortcuts.
Comment: They were probably found by Newton or Leibniz but the $2$ answers are way simpler and relevant.
Comment: If you are still interested in the history part, you can ask specifically for that on https://hsm.stackexchange.com/.
Answer: You can compute directly from the definition of the derivative. For your power rule example, there are some ways to do this, none of which are L'Hopital's rule.
$$
\lim_{h\to 0}\frac{1}{h}((x+h)^n-x^n)\\
\stackrel{\text{binomial formula}}{=}
\lim_{h\to 0}\frac{1}{h}\left(x^n-x^n+nx^{n-1}h+h^2\sum_{k=0}^n{n \choose k}x^{n-k}h^{k-2}\right)\\
=nx^{n-1}+\lim_{h\to 0}h\sum_{k=0}^n{n \choose k}x^{n-k}h^{k-2}=nx^{n-1}
$$
the derivative of $f(x)=x^n$ at $x$.
Comment: I thought that I saw a meta post: https://math.meta.stackexchange.com/questions/27625/for-limits-without-lhospital-is-the-intent-to-not-use-the-definition-of-the-der
Answer: If you can take limits on tangents to the line $x^2$ as you approach some point on the line then you are virtually there.
Rather than just calculate limits for individual functions such as $x^2$ to get $\dfrac{dx^2}{dx}=2x$ all you need do is repeat the same for general forms such as $x^n$ which yields the general form of the derivative $\dfrac{dx^n}{dx}=nx^{n-1}$.
Comment: After noticing that the formula seems to be $(x^n)' = nx^{n-1}$ one can use induction over $n$ to prove it (one needs the formula for derivative of a product).
Comment: @md2perpe good point; can I add to the answer?
Comment: Of course you can.


On the definition of modular forms

Question: In many books, I see people defining modular forms to be holomorphic/meromorphic  functions in the upper half plane such that it is invariant under the $|_k$ action of the group $\operatorname{SL}_2(\mathbb{Z})$ or under a congruence subgroup of it ($f|_k A=f \quad \forall A\in \operatorname{SL}_2(\mathbb{Z})$  ).
In the same time, they define the slash operator $|_k$ for bigger groups like $\operatorname{SL}_2(\mathbb{R})$ or $\operatorname{SL}_2(\mathbb{Q})$, but I never saw anyone define modular form to be invariant under the $|_k$ action of $\operatorname{SL}_2(\mathbb{R})$ or $\operatorname{SL}_2(\mathbb{Q})$
My question: why $\operatorname{SL}_2(\mathbb{Z})$ and its subgroups are always used to define modular forms, and why we do not define them usually for bigger groups?
Thanks.
Comment: The orbit of a point under $SL_2(\mathbb R)$ is the whole upper half plane, so specifying its value at a point would specify the whole function (if you can even do so coherently; I haven't checked). Similarly the orbit of a point under the action of $SL_2(\mathbb Q)$ is dense in the upper half plane, so if you want your modular forms to be continuous the above remark still applies.
Answer: Mike Miller's response is clear and cuts to the chase. If you are still somewhat unsatisfied, to help build intuition consider the following observations:

Defining the Modular group as $SL_2(\mathbb{Z})$ allows us to make the claim that if $f$ is a weakly modular function, then $f$ is periodic on $\mathbb{Z}$. Indeed since $\alpha = \left( \begin{array}{cc} 0 & 1 \\ 1 & 1 \end{array} \right) \in SL_2(\mathbb{Z})$ we have that $f(z + 1) = (0(z) + 1)^{k}f(z) = f(z)$.
Note that this is not a unique property of $SL_2(\mathbb{Z})$ since $\alpha$ is also an element of $SL_2(\mathbb{R})$ but $SL_2(\mathbb{Z})$ is in a loose sense the "smallest" group that has this property. But you should still be upset at me since this I should more appropriately and accurately call the action of $SL_2(\mathbb{Z})$ on modular forms in general (not just weakly modular functions) as being "integrally periodic", i.e. the symmetry involved in the periodicity of modular forms is somewhat related with cyclotomy, for which it comes to no surprise that the more modern approaches to the study of modular forms have been along the lines of Galois representations. But I should not talk more about this since it is beyond my scope at the moment.
The most important reason though that the modular group is $SL_2(\mathbb{Z})$, denote by $G$, is that when we are investigating forms which are invariant under a particular subgroup of $G$, we most notably look at congruence subroups such as $$\Gamma_0(N) = \{\left( \begin{array}{cc} a & b \\ c & d \end{array} \right) \in SL_2(\mathbb{Z}) \mid c \equiv 0 \pmod N\}$$ and $$\Gamma_1(N) = \{\left( \begin{array}{cc} a & b \\ c & d \end{array} \right) \in SL_2(\mathbb{Z}) \mid a \equiv d \equiv 1 \pmod N, c \equiv 0 \pmod N\}$$ Now one thing to notice here is that since these are indeed subgroups of $SL_2(\mathbb{Z})$ the elements of these groups have determinant equal to $1$. In particular, when we look at $\Gamma_1$, we could simply have made the definition exclude the condition that $a \equiv 1 \pmod N$ since if $d \equiv 1 \pmod N$ then $a$ must in fact be congruent to $1$ modulo $N$ since the entries are integral. This trend of "forcing" entries to be certain values occurs frequently, especially when we try to understand things like what is a complete set of coset representatives, $\{\beta_j\}$, for $\Gamma_1 \alpha \Gamma_1 = \cup_j \Gamma_1 \beta_j$ and $\alpha = \{\left( \begin{array}{cc} 1 & 0 \\ 0 & p \end{array} \right)$, $p$ a prime.

One thing you may have already noticed is that the notion of a congruence subgroup doesn't make sense if the entries are not integral. As to why we study congruence subgroups in the first place is a question that spans centuries of Number Theory. If you wish to learn more, Diamond and Shurman's A First Course in Modular Forms does a good job of exploring the interplay between Modular Forms and Elliptic curves from an advanced standpoint.
Comment: From item 1, $ \det \alpha = \det \begin{pmatrix} 0&1\\1&1\\ \end{pmatrix} = -1$, so $\alpha \not \in{SL_2(\mathbb{Z})}$...?
Comment: @DanielLautzenheiser I believe T. Ochse meant $\begin{pmatrix} 1 & 1 \\ 0 & 1 \end{pmatrix}$.

On the definition of modular forms


Select data com Between no formato Varchar

Question: Estou refazendo a pergunta pois não consegui o resultado desejado, gostaria de fazer um select no campo data porém o between não está funcionando, acredito que seja devido ao meu campo data estar no formato VARCHAR, testei o código abaixo:
("SELECT * FROM caixa WHERE data BETWEEN '01/05/2017' AND '31/05/2017'");

porém  ele selecionou todos os registros e não apenas os que possuiam data entre 01/05/2017 e 31/05/2017.
Comment: O formato que está gravando no varchar é dd/mm/yyyy ?
Comment: sim. está no mesmo formato do código acima.
Answer: O correto é armazenar datas em campos do tipo date, datetime ou timestamp, mas caso você não possa reestruturar sua tabela, com a função STR_TO_DATE você consegue converter string para date. No seu caso ficaria assim:
SELECT * FROM caixa WHERE STR_TO_DATE(data, '%d/%m/%Y') BETWEEN STR_TO_DATE('01/05/2017', '%d/%m/%Y') AND STR_TO_DATE('31/05/2017', '%d/%m/%Y');

Para saber mais sobre STR_TO_DATE clique aqui.
Answer: Gambiarra
SELECT
    *
FROM
    caixa
WHERE
    DATE_FORMAT (
        DATA,
        '%Y-%m-%d %H:%i:%s') BETWEEN '2017-05-01 00:00:00' AND '2017-05-31 23:59:59'

O Certo
Mudar o tipo de campo para um campo tipo data. Tem vários conforme mencionado na outra resposta.
Comment: No caso se eu mudar eu perderei todos registros certo? Essa gambiarra tem algum contra?(além da bagunça)
Comment: Deixar o tipo de campo como varchar complica quando você precisa fazer verificações como agora. Tem que ficar quebrando a cabeça para converter os dados. Quando se trabalha com o dado correto isso é evitado. Cria uma coluna do lado do tipo `timestamp`.
Comment: Daí você faz um update para atualizar essa coluna com a data correta, fazendo a conversão da outra coluna.
Comment: ok obrigado pela dica, mas no caso seria no formato date e ele salvaria no formato yyyy-mm-dd certo?
Comment: Isso mesmo. Salvaria dessa forma, com hora, minuto e segundo...
Answer: SELECT * FROM caixa WHERE cast(data as date) BETWEEN '01/05/2017' AND '31/05/2017'

Comment: Esse `CAST` não funciona porque o conteúdo do campo data esta no formato `DD/MM/AAAA`, neste caso o `CAST` retorna `NULL`.
Comment: Funciona no SQL Server, não funciona mesmo pro Mysql


Graph, two colors, no path length 3

Question: I've just begun studying graph theory and I have some difficulty with this problem. Could you tell me how to go about solving it?
In a graph $G$ all vertices have degrees $\le 3$. Show that we can color its vertices in two colors so that in $G$ there exists no one-color path, whose length is $3$.
And a similar one.
There's this quite popular lemma that if in a graph all vertices have degrees $\ge d$, then in this graph there's a path whose length is $d$. In all proofs I've seen so far it only says that since minimal degree of these vertices is $d$, then there exist some vertices whose degree is $d$, and so all others must have degrees greater than $d$. I have no idea how to get path length from this. Could you help me with that, too?
Answer: EEDDIITT: Let $C=\{0,1\}^V$ be the set of  2-colourings $f\colon V\to\{0,1\}$.
Any connected component of $G$ that consists of an isolated vertex or of two vertices joined by an edge, can clearly be ignored.
Thus we may assume wlog. that $\rho(a)\ge1$ for all vertices $a$ and $\rho(a)\ge2\lor \rho(b)\ge2$ for all edges $ab$.
For $f\in C$ and $S\subseteq V$, let
$$ f_S(v)=\begin{cases}1-f(v)&\text{if }v\in S\\f(v)&\text{if }v\notin S\end{cases}$$
be the colouring obtained by flipping the colour for all vertices in $S$.
For $f\in C$ and $v\in V$ and $n\in\mathbb N$, let $S_n(f)$ be the set of monochromatic length $n$ paths, i.e.
$$ S_n(f)=\left\{(v_0,\ldots,v_n)\in V^{n+1}\mid \forall 0< i\le n\colon\  v_{i-1}v_{i}\in E, f(v_i)=f(v_0), i=n\lor v_{i+1}\ne v_{i-1}\right\}.$$
Let
$$N=\min_{f\in C}|S_3(f)|,$$
$$M=\min_{f\in C, |S_3(f)|=N} |S_1(f)|$$
and fix a colouring $f\in C$ with $|S_3(f)|=N$, $|S_1(f)|=M$.
Lemma 1:
Every vertex has a neighbour of different colour. Or: Every vertex is incident with a bichromatic edge.
Proof:
Assume $a\in V$ has only vertices of the same colour. Using the fact that $\rho(a)\ge1$, let $b$ be a neighbour of $a$.
Let $g=f_{\{a\}}$.
Then $S_3(g)\subseteq S_3(f)$ and $S_1(g)\subsetneq S_1(f)$ because any difference can only come from paths containing $a$ and in fact $ab$ is no longer monochromatic with colouring $g$. Then $|S_3(g)|\le N$, $|S_1(g)|<M$ contradicts minimality of $f$. $_\square$
Lemma 2:
If $ab$ is an edge with $f(a)\ne f(b)$ then $a$ has a neighbour $c\ne b$ with $f(c)\ne f(a)$ or $b$ has a neighbour $c\ne a$ with $f(c)\ne f(b)$. Or: At least one endpoint of a bichromatic edge is incident with another bichromatic edge.
Proof:
Assume otherwise and let $g=f_{\{a,b\}}$.
Then $S_3(g)\subseteq S_3(f)$ and $S_1(g)\subsetneq S_1(f)$ (for the latter making use of $\rho(a)\ge 2\lor \rho(b)\ge 2$), again leading to a contradiction to the minimality of $f$. $_\square$
Theorem: $N=0$.
Proof:
Assume otherwise and let $(a,b,c,d)\in S_3(f)$ (note that possibly $d=a$, but $a,b,c$ are distinct).
By lemma 1, $b$ has a neighbour $x$ with $f(x)\ne f(b)$.
By lemma 2 applied to $bx$, $x$ has at least one neighbour $y\ne b$ with $f(y)\ne f(x)$, hence at most one neighbour $z$ with $f(z)=f(x)$.
Let $g=f_{\{b\}}$.
Then from the edges $ba$, $bc$ and $bx$ we learn that $|S_1(g)|=|S_1(f)|-1$, hence $|S_3(g)|>|S_3(f)|$ by minimality of $f$.
Since $(a,b,c,d), (d,c,b,a)\in S_3(f)\setminus S_3(g)$, there must be at least three paths in $S_3(g)\setminus S_3(f)$. In fact, paths always come in pairs (with their reverses), hence there must be at least four such paths.
Since $b$ can only occur as start- or endpoint, at least two paths must start at $b$ (and two end there).
These necessarily have the forms $(b,x,z,v)$ and $(b,x,z,w)$ with $v\ne w$.
By definition of $S_3(g)$, vertices $b,x,z$ are distinct. Then $f(z)=g(z)=g(b)\ne f(b)$ and since $z\ne x$, $z$ is not a neighbour of $b$. Consequently, $v\ne b$ and $w\ne b$.
Therefore $b\notin\{x,z,v,w\}$ and $g(x)=g(z)=g(v)=g(w)$ implies $f(x)=f(z)=f(v)=f(w)$, contradicting lemma 1 (applied to $z$). $_\square$

For the second problem, what you write about the proofs makes little sense.
However:
Let $v_0v_1\ldots v_r$ be a path of maximal length $r$.
Then there is no vertex $v_{r+1}$ adjacent to $v_r$ such that $v_0v_1\ldots v_rv_{r+1}$ is a path. That is: All edges incident with $v_r$ are among the $r$ edges $v_0v_1, v_1v_2, \ldots, v_{r-1}v_r$. This implies $r\ge d$.
Comment: I'm sorry. I don't understand the first one. You say that in the beginning $a_1, a_2, x_1, y_1$ have the same color. Then we change $a_2$'s color (the rest stays the same, doesn't it?) and now $a_3$ is the only neighbour of $a_1$ having the same colour. Then how can $a_2, a_3, x_2, y_2$ be monochromatic?
Comment: By minimality, there must be a new such path and it must involve $a_2$ and it cannot involve the neighbours $a_1$ and $x_1$ of $a_2$, hence it must start $a_2a_3\ldots$.
Comment: Meanwhile, I've generously restructured the first part to avoid my originally intended recursive construction and lay more weight on the idea of a "minimal counterexample" (which is just induction in disguise). Unfortunately, this is way more explicit than it should be for a homework hint ...

Graph, two colors, no path length 3


Do $k$-means, dbscan, and hierarchical clustering all rely on (pseudo)metrics?

Question: I seems to me that the clustering methods $k$-means, dbscan, and hierarchical clustering all work on distance measures $d$ that are (pseudo)metrics, i.e., fulfill the following requirements:
$$ d(x,x)=0 $$
$$ d(x,y) = d(y,x) $$
$$ d(x,z) \leqslant d(x,y) + d(y,z) $$
I am wondering whether this algorithms also work on distance measures between two datapoints that do not fulfill those requirements, for example by not fulfilling the triangle inequality?
Comment: Lewian has given a good answer. Just to add on the topic: About k-means, look [here](https://stats.stackexchange.com/q/81481/3277). About hierarchical linkages, look one of paragraphs [here](https://stats.stackexchange.com/a/217742/3277).
Answer: $k$-means in its standard form uses the Euclidean distance. This is necessary because otherwise the optimally cluster-representing centroids would not be means and the name $k$-means wouldn't be justified. Unfortunately these days a number of authors use the term $k$-means for something more general involving other types of distances, but that is misleading use of terminology.
In principle you can use properly distance-based methods such as dbscan and single, average, or complete linkage hierarchical clustering (but not Ward's method, which like $k$-means relies on the Euclidean distance) with general dissimilarities that do not fulfil the triangle inequality. Whether this is appropriate depends on the specific situation and dissimilarity. I suspect that dbscan may produce results that are hard to interpret, because it is based on nieghbourhoods, and the concept of a neighbourhood becomes weird if it is possible that $d(x,z)=100$ but $d(x,y)=d(y,z)=0.1$ so that $x$ and $z$ both are in a close neighbourhood of $y$ but are extremely far from each other. That said, some dissimilarities that violate the triangle inequality only do so in rather mild ways.


Laravel 5.1 reusing events

Question: I have setup an event in Laravel 5.1 so that when a user is created, this event creates a user role (by creating a new row in the role_user table in the database).
I now want to setup a new event for when a user gets updated called UserUpdated.  However when this new event is called, I want to reuse the listener I created for the UserCreated event which is called AssignRole.
I have copied the listener below:
<?php

namespace SimplyTimesheets\Listeners\User;

use App\Events\User\UserCreated;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use App\Repos\User\UserRepoInterface;
use App\Repos\User\RoleRepoInterface;

class AssignRole
{
    /**
     * Create the event listener.
     *
     * @return void
     */
    public function __construct(UserRepoInterface $user, RoleRepoInterface $role)
    {
        $this->user = $user;
        $this->role = $role;
    }

    /**
     * Handle the event.
     *
     * @param  UserCreated  $event
     * @return void
     */
    public function handle(UserCreated $event)
    {
        $user = $this->user->findUserById($event->user->id);
        $role = $this->role->findRoleById($event->request->role_id);

        return $user->roles()->save($role, ['cust_id' => $event->user->cust_id]);
    }
}

How can I reuse AssignRole in my new event handler, UserUpdated?
Answer: Don't typehint the UserCreated event type. You lose a little bit of control, but it'll help you achieve what you want.
<?php

namespace SimplyTimesheets\Listeners\User;

use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use App\Repos\User\UserRepoInterface;
use App\Repos\User\RoleRepoInterface;

class AssignRole
{
/**
 * Create the event listener.
 *
 * @return void
 */
public function __construct(UserRepoInterface $user, RoleRepoInterface $role)
{
    $this->user = $user;
    $this->role = $role;
}

/**
 * Handle the event.
 *
 * @param  $event
 * @return void
 */
public function handle($event)
{
    $user = $this->user->findUserById($event->user->id);
    $role = $this->role->findRoleById($event->request->role_id);

    return $user->roles()->save($role, ['cust_id' => $event->user->cust_id]);
}
}

Then, in your EventServiceProvider, you can assign the same listener to multiple events:
   'App\Events\User\UserCreated' => [
        'App\Handlers\Events\AssignRole@handle',
    ],
    'App\Events\User\UserUpdated' => [
        'App\Handlers\Events\AssignRole@handle',
    ],

Laravel 5.1 reusing events


How can I create OpenCV framework?

Question: I use OpenCV library in my Mac creating programs and compiling it with Terminal and makefiles.
It's so easy install opencv using macports and create a generic makefile to build your project.
I want to use this library with Xcode to create a app for my mac and think create a OpenCV framework is the best way.
I read this entry to compile it with Xcode but i don't know how to continue to create a framework. link
Thanks in advance
Answer: if you just want to use (and don't insist on compiling it yourself...) someone already made a framework out of opencv:
http://www.ient.rwth-aachen.de/cms/software/opencv/
Also helpful might be:
http://stefanix.net/opencv-in-xcode
Hope this helps!

How can I create OpenCV framework?


Prove these two projections are equivalent

Question:
Problem: Let $e_1, e_2, f_1$ and $f_2$ be projections of $M$ which is a Von Neumann algebra, such that $e_1e_2=f_1f_2=0$. If $e_1+e_2=f_1+f_2$, $e_1 \sim e_2$ and $f_1 \sim f_2$, prove that $e_1 \sim f_1$.

My attempt: Suppose $e_1$ and $f_1$ are not equivalent then by the comparison lemma there is a central projection $p$ such that either $pe_1\prec pf_1$ or $pf_1\prec pe_1$ (In this notation, for example $pe_1\prec pf_1$ means $pe_1$ is equivalent to a subprojection of $pf_1$ but $pe_1$ and $pf_1$ are not equivalent). Let's assume $pe_1\prec pf_1$. Then we have: $$pe_2 \sim pe_1\prec pf_1\sim pf_2.$$
Thus $pe_2\prec pf_2$. Moreover, since $p$ is central and $e_1e_2=f_1f_2=0$, we infer that $pe_1+pe_2\preceq pf_1+pf_2$. I wonder if we are allowed to replace $\preceq$ with $\prec$ in the last relation. At this stage, I don't know how to arrive at a contradiction while we already have $pe_1+pe_2=pf_1+pf_2$.
Any help would be highly appreciated.
Answer: It looks to me like this approach cannot work. To replace $\preceq$ with $\prec$ what you need is precisely to solve the original question! Since you want to say that $pe_1+pe_2=pf_1+pf_2$ contradicts $pe_1\prec pf_2$.
Now here is what comes to mind.
We have $e_1\sim 1-e_1$, $f_1\sim 1-f_1$. Since $e_1+e_2=f_1+f_2$, for simplicity we may assume that $e_1+e_2=f_1+f_2=1$, as everything happens below this projection (i.e., we can work on the von Neumann algebra $(e_1+e_2)M(e_1+e_2)$).
There exists a central projection $q$ such that $qe_1$ is properly infinite, and $(1-q)e_1$ is finite. This allows us to consider separately the cases where $e_1$ is finite, and where $e_1$ is properly infinite.
If $e_1$ is finite, so is $1-e_1\sim e_1$, and then $1=e_1\lor(1-e_1)$ is also finite. Let $p$ be a central projection  with $pe_1\preceq pf_1$. We immediately get $p(1-e_1)\preceq p(1-f_1)$. So there exist projections $g_1,g_2$ with $g_1\leq f_1$, $g_2\leq 1-f_1$, and $pe_1\sim pg_1$, $p(1-e_1)\sim p g_2$. Then
$$
p=pe_1+p(1-e_1)\sim pg_1+pg_2\leq pf_1+p(1-f_1)=p.
$$
As $p$ is finite, this implies $pg_1+pg_2=p$. So $p(f_1-g_1)+p(f_2-g_2)=0$; this is a sum of projections, so $pg_1=pf_1$, $pg_2=pf_2$. It follows that $pe_1\sim pf_1$. In other words, $pe_1\prec pf_1$ is impossible. As can also also reverse roles, we get that $e_1\sim f_1$. So we have proven that $(1-q)e_1\sim (1-q)f_1$.
It remains to deal with $qe_1$, which  is properly infinite. We have that $q$ is properly infinite; indeed, if $p\leq q$ is central and finite, then $pqe_1$ is finite so $pqe_1=0$ since $qe_1$ is properly. By the equivalence we have $pq(1-e_1)=0$, and so $p=pqe_1+pq(1-e_1)=0$.
Note that $qf_1$ is also properly infinite; if it weren't there would be a central projection $p\leq q$ with $pqf_1$ finite. By the equivalence we would have $pq(1-f_1)$ finite and then $p=pqf_1+pq(1-f_1)=p$ finite. This in turn makes $pqe_1$ finite, and then $p=0$ as above.
By this answer that you probably know about, we have
$$
qe_1\sim qe_1\lor q (1-e_1)=q=qf_1\lor q(1-f_1)\sim qf_1.
$$
Finally, from $qe_1\sim qf_1$ and $(1-q)e_1\sim(1-q)f_1$ we get $e_1\sim f_1$.
Comment: First of all, thank you very much for your answer. I got two questions. Why does such $q$ exist? And, regarding the infinite case, in the post, it's supposed that $M$ is a factor but in this problem we have an arbitrary VN algebra.
Comment: For $q$, see Proposition 6,3,7 in Kadison-Ringrose. As for the other answer, "factor" was only used to get that $e_1$ is properly infinite, which is a given here.
Comment: And after finding such $q$, how does that allow us to consider those two separate cases? Thank you for the reference.
Comment: I added some more detail.
Comment: Thank you. I appreciate your help.


macOS Catalina + Xcode 11 Error on reading file from project

Question: After upgrading to macOS Catalina with latest Xcode 11, I am not able to read files directly from user path when doing unit testing, example:
PROJECT_DIR + "/FolderX/myFile.json",
I keep getting error Thread 1: EXC_BAD_ACCESS (code=1, address=0x8)
This is also happened when I am trying to open a couchbase lite database with custom path.
Error:
error opening!: 14
Cannot open database, Error : Error Domain=SQLite Code=14 "unable to open database file" UserInfo={NSLocalizedDescription=unable to open database file}
I believe this is an issue due to the read write access between my simulator and the latest Catalina.
My current workaround is to add my files and database to target membership and read the files directly from [NSBundle bundleForClass:[self class]].bundlePath.
Is there any better fix to this? Like tweaking any setting to allow it to read files from custom path like in older versions?
Answer: You might try looking in SystemPreferences > Security&Privacy > Privacy tab. From there, scroll down to "Files and Folders" <-- There's where you can see programs and the folders they have been granted access to in Catalina.
Personally, I didn't have time to waste figuring out how the new file permissions are supposed to work, so I let Xcode have full disk permission. (Right above the "files and folders" is "Full Disk Access".
Of course, that solved all my issues... after I get a chance to play with the new file permissions, I may revoke that access and give it explicit folder access.
Comment: I have added everything, the Xcode, simulator, build server into the Full Disk Access settings.
I am still getting read permission error.

I am trying to read file outside of my simulator.
Answer: Well if anyone is still struggling with this, I've moved all my projects outside of ~/Documents/
it is strange that projects under ~/Documents/ doesnt get asked for read permission, other paths do!
I end up putting all my projects under ~/workspace/
** for those who doesnt know, ~/ means /Users/{your username}/
Answer: Check your File Access settings in the App Sandbox in your project's settings, under Signing and Capabilities. For example, I couldn't access files in /Users/Bert/Downloads, even after turning on Full Disk Access in Security and Privacy in System Preferences. I had to grant read access to the Downloads Folder in App Sandbox settings.


Is it wrong to use Binary Vector data in Cosine Similarity?

Question: I am doing Information Retrieval using Cosine Similarity.
My data is a binary vector.
Since most of the references I read were using non-binary vector (non-binary matrix) data, I am wondering if it is wrong to use binary vector data in the cosine similarity function.
Answer: Consider looking at the Jaccard coefficient and Tanimoto coefficient. These two are probably a bit more sensible for binary data.
You can obviously use cosine distance, but computing it this way makes things overcomplicated when you have binary data. The dot product boils down to computing the size of the intersection set, the vector length are the number of bits set. Realizing that you are just looking at set sizes leads to more straightforward and fast ways of computing these things.
Answer: Using binary vector data works perfectly for doing cosine similarity studies. Actually, it makes the arithmetic much simpler because the magnitude of each vector is simply equal to the squareroot of the sum of its entries.
Comment: see also the Ochiai coefficient
Answer: You may perfectly use cosine similarity to compare binary vectors.
But if computational performance is an important issue you may use Hamming Distance instead, since it is just the number of positions at which the corresponding symbols are different.
Answer: In a similar senario with binary vectors (recommender systems in my case which can be see as a special case of information retrieval) I had very good success with cosine similarity.
When measuring Rankscore I got much better rate on my retrievals when I used Cosine similarity than with the Tanimoto coefficient, but this might be very application specific. You should probably experiment with different similarity measurements and see what yields the best result in you application.
I compare the result of the effects from different similarity measures between my binary vectors here. As mentioned above I have the greatest success with cosine similarity.


Postgres - connection timeout

Question: When I trying connect to my postgres database, I always receiving connection time out error. For instance I want to connect from pqadmin. Can you please help with it ?
Comment: Seems that probrem is resolved. Thanks @Yaron for your support !
Comment: There are too many reasons for that, can you try and run `pgadmin` on the same server Posgress is running on?
Comment: I think no. But my postgres works via pythonanywhere postgres concole
Comment: So it's working from your machine through Python but not using `pgadmin` or it's a different machine?
Answer: PostgreSQL databases on PythonAnywhere are protected by a firewall, so external computers can't access them directly -- you need to use a thing called an SSH tunnel, which opens a secure SSH connection to PythonAnywhere, then sends the Postgres stuff over it.
This help page on the PythonAnywhere site has the details on how to set that up.

Postgres - connection timeout


Enabling Cookies in Chrome version 86 using Selenium

Question: I am trying to use Selenium with Java with update chrome version 86 for automation, but it shows third-party cookies disable. The site I am working on needs 3rd party cookies.
I tries to enable cookies using following code:
    ChromeOptions options = new ChromeOptions();
    options.addArguments("incognito");
    options.addArguments("start-maximized");
    // options.addArguments("disable-infobars");
    options.addArguments("ignore-certificate-errors");
    options.addArguments("disable-popup-blocking");
    options.addArguments("disable-extensions");
    options.addArguments("disable-notifications");
    options.addArguments("no-sandbox");
    options.addArguments("allow-running-insecure-content");
    options.setAcceptInsecureCerts(true);

    options.setExperimentalOption("excludeSwitches", Collections.singletonList("enable-automation"));

    HashMap<String, Object> prefs = new HashMap<String, Object>();
    prefs.put("profile.default_content_settings.cookies", 0);
    options.setExperimentalOption("prefs", prefs);

    Boolean headless = Boolean.valueOf(ApplicationProperties.getInstance().getProperty("headless"));
    if (Boolean.TRUE.equals(headless)) {
        options.addArguments("headless");
        options.addArguments("window-size=1600x1200");
    }

    options.setCapability(ChromeOptions.CAPABILITY, options);
    options.setCapability(CapabilityType.UNEXPECTED_ALERT_BEHAVIOUR,
    UnexpectedAlertBehaviour.IGNORE);````

Not enabling cookies. Guide me what to do?
Comment: This maybe help https://stackoverflow.com/questions/19211006/how-to-enable-cookies-in-chromedriver-with-webdriver
Comment: Have the same issue. Also tried c#: var experimentalFlags = new List
            {
                "same-site-by-default-cookies@2", "cookies-without-same-site-must-be-secure@2", "enable-removing-all-third-party-cookies@2"
            };
            options.AddLocalStatePreference("browser.enabled_labs_experiments",
                experimentalFlags);
Comment: Duplicate for https://stackoverflow.com/questions/64281247/c-sharp-selenium-chromedriver-add-user-profile-preference
Comment: It may be duplicate issue! But after version updatation of google , nothing is working
Comment: Greate simple solution https://stackoverflow.com/a/65007362/8951897
Answer: I found a workaround to enable third-party cookies on the browser new tab start page (I'm using Robot Java library library to open a new tab because other methods do not open the appropriate page).
Full answer here.
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.remote.RemoteWebDriver;
import java.awt.*;
import java.awt.event.KeyEvent;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

public void enableThirdPartyCookies(WebDriver driver) throws Exception {
    ArrayList<String> windowHandles = new ArrayList<String> (driver.getWindowHandles());

    // Activate Browser window
    driver.switchTo().window(driver.getWindowHandle());

    // Open New Tab Ctrl + T
    Robot robot = new Robot();
    robot.keyPress(KeyEvent.VK_CONTROL);
    robot.keyPress(KeyEvent.VK_T);
    robot.keyRelease(KeyEvent.VK_T);
    robot.keyRelease(KeyEvent.VK_CONTROL);

    // Wait for open new tab
    int retries = 100;
    for (int i = 0; i < retries; i++)
    {
        Thread.sleep(100);
        if (driver.getWindowHandles().size() > windowHandles.size())
            break;
    }

    // Enable Third Party Cookies
    if (driver.getWindowHandles().size() > windowHandles.size())
    {
        driver.close();
        windowHandles = new ArrayList<String> (driver.getWindowHandles());
        driver.switchTo().window(windowHandles.get(windowHandles.size() - 1));
        List list = driver.findElements(By.id("cookie-controls-toggle"));
        Optional<WebElement> selectedCookieControlsToggle = driver.findElements(By.id("cookie-controls-toggle")).stream()
                .filter(x -> x.getAttribute("checked") != null).findFirst();
        Optional.ofNullable(selectedCookieControlsToggle).get().get().click();
    }
}

Using:
ChromeOptions options = new ChromeOptions();
options.addArguments("–no-sandbox");
options.addArguments("incognito");
options.addArguments("start-maximized");
WebDriver driver = new ChromeDriver(options);
enableThirdPartyCookies(driver);

Answer: Code in Kotlin the looks like
val prefs: MutableMap<String, Any> = HashMap()
prefs["profile.cookie_controls_mode"] = 0
chromeOptions.setExperimentalOption("prefs", prefs)
desiredCapabilities.setCapability(ChromeOptions.CAPABILITY, chromeOptions)


Questions regarding X509 certificate authentication in Azure IotHub

Question: I have been using Device Provisioning Service to provision the device using device/leaf certificate that is signed by CA Authority. The DPS(Device Provisioning Service) service registers device in assigned Iothub.
I noticed that the thumbprint in IotHub for this device is different than the thumbprint in the cert provided to the DPS(device cert). I wanted to check and see if anyone knows how DPS creates these thumbprint?
It also looks like if the device uses another/different certificate signed by the same CA to connect to Iothub, they can do that without any issue. Is there a setting that checks for individual thumbprint or is the authentication only based on possession of cert that was signed by the same CA as in DPS?
Your help is much appreciated.
Comment: Benefits of X.509 CA certificate [authentication](https://learn.microsoft.com/en-us/azure/iot-hub/authenticate-authorize-x509#benefits-of-x509-ca-certificate-authentication)
Comment: Does this mean I can use any certificate signed by the same CA to authenticate to IotHub once the device is registered to the IotHub(using a different device certificate signed by the same CA)?
Comment: Yes, you can use any certificate signed by the same CA like Intermediate certificate,[Device certificates](https://learn.microsoft.com/en-us/azure/iot-dps/tutorial-custom-hsm-enrollment-group-x509?tabs=windows&pivots=programming-language-csharp#create-an-x509-certificate-chain)
Answer: When you use a CA signed certificate with DPS the DPS will add your device to the IoT hub using self-signed authentication. However, it uses an SHA256 fingerprint rather than the SHA1 that you are likely used to.
You can view the SHA256 fingerprint with OpenSSL using the command:
<code>openssl x509 -noout -text -in <yourcert.pem> -fingerprint -sha256
</code>
The IoT hub will try both the SHA1 fingerprint and the SHA256 fingerprint thus it works.
Comment: Someone was asking.. Is there any option to force CA Authentication and not use thumbprint in IOT Hub after provisioning using DPS with a CA Cert?
Comment: No. Presumably because the IoT hub does not have the certificate chain that signed the DPS X.509 client certificate.
Answer: A thumbprint, also known as a fingerprint or hash, is a unique value derived from a certificate's contents. It is commonly used to identify certificates and verify their integrity. The thumbprint is typically generated using a cryptographic hash function.

DPS likely extracts and stores a different format of the thumbprint than what's present in the device certificate. This could be due to variations in hashing algorithms or the specific fields used for calculating the thumbprint.
You can verify this by using the same hashing algorithm and fields on the device certificate to generate the thumbprint and compare it with the one displayed in IoT Hub.
Yes, a device can use a different certificate signed by the same CA to connect to IoT Hub/DPS but the certificate is registered with the same IoT Hub/DPS and The device possesses the private key with the certificate.
Steps to Provision an X.509 certificate simulated device from DOC
Add the IOT hub to Linked IoT hubs

Create a device enrollment.

The code was taken from  git.


How to format the Excel document created by POI

Question: I am working in an application where I am creating an Excel document using POI. The problem is, when generating the Excel without any data is fine, but when I am putting the data with it then the headers are going down. My code:
            HSSFWorkbook hwb = null;
            hwb = new HSSFWorkbook();
            HSSFSheet sheet = hwb.createSheet("new sheet");

            HSSFRow rowhead = sheet.createRow((short) largest);

            HSSFCell intervieweeName = rowhead.createCell(0);
            intervieweeName.setCellValue("Interviee Name");

            HSSFCell interviewTiming = rowhead.createCell(1);
            interviewTiming.setCellValue("Interview Timing");

    for (int large = 0; large < largest; large++) {

            int i=0;
            HSSFRow array1 = sheet.createRow((short)large);
            for ( i = i + large; i < interviewerNameList.size(); i++) {
            HSSFCell tracker1 = array1.createCell(0);
            HSSFCell tracker2 = array1.createCell(1);

            tracker1.setCellValue(interviewerNameList.get(large));
            tracker2.setCellValue(interviewTimingToFrom1.get(large));

            }
            }

The problem is that the heading Interviee Name and Interview Timing are coming after the values.
Comment: @Gagravarr i did not understand can you point out and correct my mistake??
Comment: Sorry, re-read it now. Why are you putting the header row at the end, on (row=largest)? Why not put them in the first row (0) and put your values in subsequent (1+) rows?
Comment: @Gagravarr please edit my code it will be helpful
Answer: Your problem is that you're writing the header into the last row
HSSFRow rowhead = sheet.createRow((short) largest);
...
for (int large = 0; large < largest; large++) {
    HSSFRow array1 = sheet.createRow((short)large);

That puts the header at the end, and loops from 0 to that to create the data rows
Change it instead to be something like:
HSSFRow rowhead = sheet.createRow(0);
...
for (int large = 0; large < largest; large++) {
    HSSFRow array1 = sheet.createRow(large+1);

That way, the large variable remains unchanged for your data lookup, but you populate things in row 1 onwards


Can't I run an app after installing .NET Framework 4?

Question: Please use simple English, my language skills are not as good as yours! :)
I installed .NET Framework 4 for one app but when I run the setup for that app, I see this error:

Installer information
Microsoft .NET framework 3.5 SP1 or greater
  needs to be installed!

I installed .NET Framework 4 and 3 SP1 but I can't insatll my app! The app programer said that just .NET Framwork 4 should be installed!
Comment: I would suggest to uninstall .NET and reinstall. Something did work properly.
Answer: the Installer for .NET 4 does not include the installer for .NET 3.5 you need to install the .NET 3.5 framework as well as the .NET 4 framework.
Here's the link for the standalone installer:
http://download.microsoft.com/download/2/0/e/20e90413-712f-438c-988e-fdaa79a8ac3d/dotnetfx35.exe


Mudar Onclick Javascript não funciona

Question: Olá
Eu estou desenvolvendo um script bem simples em javascript, onde ao clicar pela primeira vez no botão, ele chama a função aluno() e ao clicar a segunda vez no mesmo botão chama a função professor(), mas não estou conseguindo alterar o conteudo de onclick, onde eu posso estar errando ?

        <title>Mudar Botão</title>

        <input type="button" id="btnAlunos" value="Alunos" onclick="alunos()" />

Agradeço desde já
Comment: faz o seguinte , faz as 2 funções bindadas a um id diferente qando vc clika na primeira apos executar a função q vc quer muda o id do item clikado para o id que corresponde a ação da segunda função.
Answer: Para o caso que voce quer fazer, isso já resolve e nao precisa trocar a função do click, apenas ceritificar de chamar o metodo que quer:

function aluno()
{
  alert("Eu sou um aluno");
}

function professor()
{
  alert("Agora eu sou professor");
}

document.getElementById("btnAlunos").onclick = function ()
{

  var btnAlunos = document.getElementById("btnAlunos");

  if(btnAlunos.value == "Professor")
    {
      professor();
      }
  else
    {
  aluno();
    }

  btnAlunos.value = "Professor";
};

<title>Mudar Botão</title>

<input type="button" id="btnAlunos" value="Alunos" onclick="alunos()" />

Comment: Todas as sugestões são bem legais, obrigado a todos pelas ajudas.
Answer: Em seu modelo você está complicando várias coisas. Além de trabalhar com eventos dinâmicos. Para simplificar, porque não fazer a function aluno() alterar o onclick() para professor e vice-versa?
Seu exemplo ficaria desta forma:

function aluno()
{
  document.getElementById("btnAlunos").value = 'Professor';
  document.getElementById("btnAlunos").setAttribute('onclick','professor()');
  alert("Eu sou um aluno");
}

function professor()
{
  document.getElementById("btnAlunos").value = 'Aluno';
  document.getElementById("btnAlunos").setAttribute('onclick','aluno()');
  alert("Agora eu sou professor");
}
<input type="button" id="btnAlunos" value="Alunos" onclick="aluno()" />

Note que não necessito alterar o id. Apenas alterei o value para indicar o texto do botão, e altero o onclick() em cada função com o setAttribute().
Comment: Seu código pode ser melhor passando o objeto como parâmetro @Randrade. Digo ``....
Comment: @Marconi Com certeza ficaria melhor. Mas preferi deixar o mais próximo do código do AP possível, para não complicar muito. Mas obrigado pelo comentário, se o AP entender as mudanças que eu fiz de boa, eu altero um pouco mais.
Answer: Vou explicar primeiro porque o teu código não funciona:
Esta linha não funciona pois quando é lida pelo browser o elemento com esse ID ainda não existe:
document.getElementById("btnProfessor").onclick = function() {
    professor();
};

se vires na consola isso dá até erro pois estás a chamar .onclick em cima de null que é a resposta de document.getElementById("btnProfessor") quando o elemento não é encontrado.
Na verdade não precisas desta linha pois o código funciona com o outro .onclick visto que ele está amarrado ao elemento, independentemente do ID ou conteúdo ter sido mudado ou não.
Outra coisa que não funciona como esperas é  btnAlunos.onclick = "professor()";, a questão aqui é a diferença entre propriedades e atributos. Já falei sobre isso (e outros aqui) noutra resposta, mas basicamente tens de mudar o atributo no HTML e não na propriedade do elemento DOM. Podes fazer isso assim: btnAlunos.setAttribute('onclick', "professor()");. Com estas mudanças o teu código já começa a aproximar-se do que queres (https://jsfiddle.net/8hvx41ke/).
Porem podias fazer essa funcionalidade assim:
document.getElementById("btnAlunos").onclick = function() {
    var idOriginal = this.id;
    this.value = "Professor";
    this.id = "btnProfessor";
    idOriginal == "btnProfessor" ? professor() : aluno();
};

e sem onclick no HTML. Repara que dentro dessa função no JavaScript o this é o elemento clicado, e podes ter uma pergunta (ternário) a decidir sobre que função chamar. Neste caso ficaria assim:

function aluno() {
    alert("Eu sou um aluno");
}

function professor() {
    alert("Agora eu sou professor");
}
document.getElementById("btnAlunos").onclick = function() {
    var idOriginal = this.id;
    this.value = "Professor";
    this.id = "btnProfessor";
    idOriginal == "btnProfessor" ? professor() : aluno();
};
<input type="button" id="btnAlunos" value="Alunos" />

jsFiddle: https://jsfiddle.net/8hvx41ke/2/

Mudar Onclick Javascript não funciona


Oreo textview auto multiple line abnormal

Question: This is my Code, it is normal before Android 8.0, but in Android 8.0, it's auto to multiple line in different location. Any one can know why ?

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.lwz15.myapplication.MainActivity">

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginLeft="16dp"
        android:layout_marginRight="16dp"
        android:textSize="16dp"
        android:text="请将设备插上电源后,等待一段时间后,直到设备启动完成"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</android.support.constraint.ConstraintLayout>

Comment: What is the expected result and what is abnormal?
Comment: What is the behaviour you're looking for?
Comment: the normal result before android 8.0 is that the first line should arrive at the right end of the screen. In android 8.0, the first line ends in advance
Answer: You should set your text android:gravity. It will set the correct way for the current language of the device:
<TextView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginLeft="16dp"
    android:layout_marginRight="16dp"
    android:textSize="16dp"
    android:gravity="start"
    android:text="请将设备插上电源后,等待一段时间后,直到设备启动完成"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintRight_toRightOf="parent"
    app:layout_constraintTop_toTopOf="parent" />

Comment: Could you check this at start of your app? `Log.v( LOG_TAG, "Locale: " + getResources().getConfiguration().locale );`
Comment: Locale: zh_CN this is the log
Comment: Thanks for your help, I have resolved this problem with a weird solution. I use the edittext instead of the textview, and set edittext as follows: android:editable="false"  android:background="@null".  This can help me, but I don't know why.
Comment: By the way, this is not a bug of android 8.0. It only happens in XiaoMi Mix Phone.


Are parallel octaves okay in other styles of music?

Question: In a musical theatre piece is it wrong to have lots of parallel octaves in the voices?
Comment: It sounds from the title like you've already guessed the answer - nothing in music can be said to be *wrong* as such (apart from, maybe, the use of sounds that will kill or injure?), but if you've set up an expectation that a piece will be in a certain style, doing something that isn't associated with that style may surprise your audience and be more likely to *subjectively* sound wrong/like a mistake.

Songs in musical theatre can themselves be in almost any style, but they tend to be somewhat consistent with expectations for that style to improve accessibility to an audience.
Comment: Wrong and right shouldn't really be the issue. There has always been lots of postulation, leading to theory, but the bottom line should always be- if it sounds good, it probably is - and vice versa.
Answer: The rules about parallal octaves only apply when writing Bach chorale-type harmony where the aim is rich harmony with no one part "sticking out" disproportionately.  Because this is often the first type of harmony we are taught to write, we can fall into the trap of thinking it's the ONLY way of doing it!
Orchestration is all about doubling lines, often in different octaves.
For instance, there's the "Glenn Miller" voicing - clarinet and tenor sax double the tune an octave apart, the other reeds fill in harmonies inside that.  This works for voices as well. (Note, though that the aim is to emphasize the melody, and it works.  Don't double something that you DON'T want emphasized.)
It can also be very effective to have just two musical lines, either in homophony or in counterpoint, with a mix of high and low voices on each.
I could find many more examples.  But yes, octave doubling is fine.  Just be aware of what it will sound like, and make sure you WANT that effect.
Comment: I would add a point of clarification here that Dom mentioned in his answer.  The concept of avoiding parallel octaves/fifths is to maintain the independence of the voices within the harmony. So I would describe it more as a voice "disappearing" when it has parallel motion.  I would ultimately say that a line being doubled with octaves is not actually separate voices, so there is no parallel octaves between voices to be considered here.
Answer: The only time you shouldn't have parallel octaves is when you are voice leading and want two parts to be completely independent. The reason why you wouldn't use it is that it makes two voices that should be independent sound as one.
It's used very, very frequently as doubling a line by octave is very effective at making it stand out. For example in Day Tripper the guitar and the bass play the same riff so everything in that riff is considered parallel octaves, but it sounds just fine and actually puts more emphasis on the riff. Pretty much any time you play the same chord shape on guitar, like moving from an A shaped D chord to an A shaped E chord or from power chord to power chord, the result is every note has a parallel octave. This is still used all the time though and does create a distinct effect when it is used.


Receber valor booleano via javaScript num popUp para ser usado em outra pagina

Question: Tenho uma pagina que abre um popUp de confirmação, o popUp é chamado com o  window.showModalDialog, preciso pegar true ou false desse popUp, para trabalhar na pagina 1 onde o valor devolvido será usado, mas não estou conseguindo, me indicaram usar o window.open ao invés do  window.showModalDialog, ele até abre o popUp mas não retorna o valor, mas não funciona, estou usando VB.Net
//Pagina 1
var Retorno = window.showModalDialog("../Popup/FramePop.aspx?Pagina=PopConfirmacao.aspx")

document.getElementById('idAquiDoElemento').value = Retorno;

//javaScript do botão confirmar no popUp aberto em outra página aspx

function ConfirmarDados(acao, document)
{

            window.returnValue = acao;

}

Answer: Já consegui, passei uma funcao javaScript via url ao abrir o popUp, e depois na função do popUp eu consegui acessar e trabalhar o valor nela.
//Pagina 1
function FnAtualiza(retorno) {
            document.getElementById('idAquiDoElemento').value = retorno;
        return retorno;
    }

var Retorno = window.showModalDialog("../Popup/FramePop.aspx?Pagina=PopConfirmacao.aspx", { confirmaContatoCallback: FnAtualiza})
document.getElementById('idAquiDoElemento').value = Retorno;
//javaScript do botão confirmar no popUp aberto em outra página aspx
function ConfirmarDados(acao)
{
       var dialogArguments = window.dialogArguments;
        dialogArguments.confirmaContatoCallback(acao);
        window.close();

}


d3 drag only works when axis ticks are highlighted

Question: I'm working on a package that merges Angular and D3 (v3) and specifically and trying to incorporate D3's dragging feature into the package. I'm very close to being successful, but when my plots render for the first time, I am unable to drag the elements (in this case rectangles) unless I use my cursor to select the text on the x-axis. After the text is highlighted, the user can drag the rectangles and the feature seems to work perfectly, but I really would like to fix the initial bug.
I've replicated the issue in a Github.io project found here. I define the dragging behavior from d3 in the library ivml.0.0.0 (included in the repo) in lines 903-966 which I'll include below:
    if (Bars.events.dragE) {

        // Note: xs(0) refers to pixel value at 0 on the x-scale. Must be reset for generalizability

        // function returns width (in pixels) of bar. Used to ensure drag doesn't exceed plot area

        function returnw(d, i){
            if (values_function(d, i) <= 0) {
                Bars.elements.barController.offset(position_function(d, i), xs(0) - xs(values_function(d, i)), values_function(d, i));
                return xs(0) - xs(values_function(d, i));
            }
            else {
                Bars.elements.barController.offset(position_function(d, i), xs(values_function(d, i)) - xs(0), values_function(d, i))
                return Math.abs(xs(0)-xs(values_function(d, i)))
            }
        }

        var drag = d3.behavior.drag()
        .on('dragstart', draginit)
        .on('drag', dragmove)
        .on('dragend', dragfin);

        function draginit(d){
            d3.event.sourceEvent.stopPropagation();
            // replace fill color with variable for user input function
            Bars.events.dragE(d, i, d3.select(this).attr('style', 'fill: yellow; stroke: black; stroke-width: 3px;'))
        }

        function dragmove(d){
            var svgwidth = Bars.elements.chartController.plotObject.attributes.width //margin of plotObject
            var svginterval = svgwidth/(Bars.elements.chartController.plotObject.attributes.xmax-Bars.elements.chartController.plotObject.attributes.xmin) //number of pixels between whole numbers in coordinate plot
            Bars.events.dragE(d, i,
            d3.select(this)
                .attr("x", function(d, i){
                    if (d3.event.x < 0) {return 0}
                    else if (d3.event.x + returnw(d,i) > svgwidth){ return (svgwidth - returnw(d,i))}
                    else {return xs(Math.floor(d3.event.x/svginterval)) } })); //this function ensures value will be a whole number

            var valuechange = d3.event.x < 0 ? 0 : (d3.event.x + returnw(d,i) > svgwidth ? svgwidth - returnw(d,i) : d3.event.x);

            console.log("Start value changed to: ", Math.floor(valuechange/svginterval));
        }

        function dragfin(d){
            Bars.events.dragE(d, i, d3.select(this).attr('style', 'stroke: black; stroke-width: 0px;')
            .attr('fill', Bars.attributes.fill))

        }

        rects.attr("cursor", "ew-resize")
        .on('dragstart', function(d, i){
            Bars.events.dragE(d, i, d3.select(this).call(drag))
        })
        .on('drag', function (d, i) {
            window.dragThis = this;
            Bars.events.dragE(d, i,
                d3.select(this).call(drag))
        })
        .on("dragend", function(d, i){
            Bars.events.dragE(d, i, d3.select(this).call(drag))

        })
    }

I'm still somewhat new to both Angular and Javascript/D3, so I might be missing something really basic, but any insights would be greatly appreciated!
Answer: I have written a d3v5 of the bar-graph-drag behavior that you want and there is no problem with any selection needed first. I suggest to skip the D3-Angular interface and draw the D3 stuff yourself in D3v5 by calling a function that draws the graph based on the data supplied in an argument.
In the original bar graph data the bar value was the frequency field of the object.

<!DOCTYPE html>

<meta charset="utf-8">

<svg width="960" height="500"></svg>

Comment: Normally I would agree with you and just use D3 (and use the latest version), but a main objective for the Angular-D3 interface is to make building interactive visualizations more intuitive and approachable for people who aren't familiar/comfortable with D3. Thanks, though!
Comment: I have had a look at your git repository and it is very much unreadable. What I see about the Angular-D3 stuff is that it is some kind of wrapper for D3 with just a different syntax and it does not make it easier. It only obfuscates the nice D3 API. You need to understand D3 before you can write these wrapper calls.


Authenticating SVN users with Apache against Linux user accounts

Question: Is it possible to tie authentication for SVN under Apache against system user accounts, rather than defining the passwords with htpasswd? I'd rather use Apache than SVN + SSH authentication.
Answer: Using mod_auth_external and pwauth should work. What you're actually trying to do is authenticate against PAM.


Jazz Waltz Time Signature

Question: Lately I've been playing (in big band) a couple of 'jazz waltzes' - namely All Blues and Bluesette, as references -  and one of my own compositions. They're written in 3/4, but always get counted in using two bars. Sort of making them more like 6/8, as they're none of them slow 3/4 tunes. I keep thinking they ought to be written as 6/8, but they're not. Is the reason that 3/4 is maybe easier to write and read, even though every 2nd bar only has about the same emphasis as the 2nd half of a 6/8 bar? My tune has that same feel as well. I guess there's the possibility of 6/4, but they're definitely written in 3/4, although I've had a trawl, and All Blues appears to be in all three incarnations.
Question is, which is preferable for a standard jazz waltz, and for what reasons?.
Comment: Note, waltzes aren't always slow. The original Viennese waltz can be quite lively; it's the American "Cinderella at the ball" tradition that turns it into a slow-dance.
Comment: Is "trawl" a typo or is "having a trawl" an idiom of some kind?
Comment: "All Blues" isn't a waltz.
Comment: @Aaron - I label it as a jazz waltz.
Comment: @ToddWilcox - it means looking through lots of options already posted.
Comment: That's probably why you're confused about time signatures. You're taking pieces that aren't waltzes and arbitrarily labeling them.
Comment: @ToddWilcox 'Trawl' is a fishing metaphore.
Comment: @Aaron - you could easily segue from All Blues to Bluesette and back, so I'm saying they're both jazz waltzes. If not, the whole question is void.
Comment: Ahh... "I've had a trawl" means "I've trawled [through some things]". Sort of an idiom in a way.
Comment: That's more or less what I'm saying: the question is based on a false premise.
Comment: In your defense, though, [LearnJazzStandards](https://www.learnjazzstandards.com/blog/learning-jazz/jazz-advice/9-jazz-waltz-tunes-know/) lists both "All Blues" and "Bluesette" as waltzes. (Personally, I think Miles Davis, though perhaps not Toots Thielemans, is rolling in his grave.)
Comment: @Aaron 'All Blues' may not be a jazz waltz in the strictest sense, but the same considerations (3/4 vs. 6/4) apply. I've always thought of it as being in 6/4.
Answer: Since a jazz waltz written in 3/4 almost always has a two-bar feel it would make more sense to rewrite it in 6/4, and I've often seen jazz waltzes notated that way. On the other hand, 6/4 can be harder to read. It's a matter of choice: both 3/4 and 6/4 work.
A jazz waltz in 6/8 would look very strange for the same reason a standard swing tune in 4/8 would look strange.
Here's an example of how ugly 6/8 can be (The beginning of a transcription of Wayne Shorter's solo on 'All Blues' from V.S.O.P. 'Tribute to Miles'):

For comparison here's the start of George Coleman's solo on the same tune (but a different recording) notated in 6/4:
Comment: @Tim The main reason 6/8 looks wrong is the fact that the eighths are straight and the sixteenths swung.
Comment: @Tim Those transcriptions are not necessarily correct.
Comment: Thanks for a swift response. Bluesette has several postings in 6/8, if you care to look. Odd to me too. Guess it might be like swing time - notated one way, played another.
Comment: Interesting that in one bar there's C#7, and the very next there's Db7. And both have different chord changes from what I'm used to.
Comment: As you're probably well aware, I don't believe a lot on the 'net, but they're there nevertheless.
Comment: Seems like 18/8 (without all the triplets and ties) would be just as good for a two-bar swing feel "waltz".  (Not that I've ever seen one written that way.)
Answer: Great question, +1. Regarding songs in 3/4 time being counted in using 2 bars, isn't that more of less the same as going 1,2,1234 in 4/4 time? To me the purpose of either is to give the band the opportunity to feel the tempo better and have a little more prep time before the downbeat.
When I think of 6/8 in the historic and traditional sense I think of music that has a 2 pulse triplet feel, TA ta ta TA ta ta etc. This is not what jazz waltzes are or feel like. On top of that you would have to apply a swing 16th feel to make it swing. Playing swing feel on 8th notes in 3/4 time on a jazz waltz is common but swing 16th notes in 6/8 is not typically done.
If you think of songs like "Someday My Prince Will Come" or "Alice in Wonderland" performed in a jazz style there is a strong sense of a bar every 3 beats, both melodically and rhythmically. The melody and harmony both generally move in increments of a bar. A fast tempo may make a 3/4 jazz song feel like 2 bars is one bar but that is not enough of a reason in my opinion to write in say, 6/4 when players historically conceptualize these types of songs in 3.
Those reasons plus the fact that the use of 3/4 is already firmly established as the way pieces with this feel are notated makes a good case for sticking with 3/4.
Comment: I did consider the 1,2,1234 count in, but it isn't universal. In one band, all we got were 6 grunts! Funny how a 100 piece orchestra only gets the last upbeat...  I am trying to differentiate between two quick bars of 3/4 and one bar of 6/8, that to me, can feel pretty much the same. Hence the question. Some Day, yes, played that many times, and somehow, 3/4 is more appropriate. Probably the phrasing.
Comment: @Tim You're right, there is no universal way to count off a song, but that is true of any time signature. To me the main difference is that in a jazz waltz I feel every beat, 3 in every bar. In 6/8 I feel 2 pulses per bar and the 8th notes are triplet subdivisions. In order to write jazz in 6/8 you must then subdivide the 8ths into swing 16ths. It is not intuitive.
Answer: A waltz, particularly the faster sort, is potentially counted 'in one'.   And musical 'ones' tend to group with either one or two neighbours, becoming 'twos' or 'threes'.  But I see no harm in notating a jazz waltz in 3/4. We're used to swinging 8ths not 16ths.
I wouldn't make too much out of the two-bar count-in.   A swing 4 is normally counted in '1,2,1-2-3-4'.   Doesn't mean it should be written in 8/4.
Comment: Not thought about it before, but while swing 4 is counted in 1-2-1234, straight 4 is usually 1234, even for the same tempo. Strange! As the beats themselves are exactly the same, it's their sub-division which is different. Maybe that's what gives a dep drummer a clue...

Jazz Waltz Time Signature


Rspec test mailer from controller with params in helper

Question: I'm having a rather odd rspec failure that feels like a test configuration issue or a bug in rspec or rspec-rails (rspec 3.4.0 and rspec-rails 3.4.2).  I'm hoping for any advice about the matter:
I have a controller test which simply invokes a mailer method whose template utilizes that helper and I get an error from the helper function where I use the params.
describe MyController, :type => :controller do
  describe "POST send_a_specific_type_of_email" do
    it "sends the fact sheet" do
      ActionMailer::Base.deliveries = []
     post :send_a_specific_type_of_email, params
     expect(ActionMailer::Base.deliveries.count).to eq(1)
    end
  end
end

This results in an error which relates to a helper method I have which utilizes params.
Failure/Error: if params[:some_value] == "on"

ActionView::Template::Error:
 undefined method `params' for #<MyMailer:0x007fdcf56020f0>
# ./app/helpers/mycontroller_helper.rb:139:in `display_mycontroller_price'
# ./app/views/mycontroller/_items.html.erb:26:in `_app_views_mycontroller__items_html_erb__2241527061928464634_70293475039080'
# ./app/views/production_mailer/email_mycontroller.html.erb:17:in `_app_views_production_mailer_email_mycontroller_html_erb___301577404429349505_70293454886780'
# ./app/models/production_mailer.rb:51:in `email_mycontroller'
# ./app/controllers/mycontroller_controller.rb:40:in `send_a_specific_type_of_email'
# ./lib/authenticated_system.rb:75:in `catch_unauthorized'
# ./spec/controllers/mycontroller_controller_spec.rb:109:in `block (4 levels) in <top (required)>'
# ------------------
# --- Caused by: ---
# NoMethodError:
#   undefined method `params' for #<MyMailer:0x007fdcf56020f0>
#   ./app/helpers/mycontroller_helper.rb:139:in `display_mycontroller_price'

I've tried setting an expectation for the helper and mailer to return nil if that mailer method or helper method is called but they never resolve that error.  I'm both confused and surprised that stubbing the mailer OR helper methods did nothing.
Here's how I've tried stubbing:
# does nothing
expect(MyHelper).to receive(:display_mycontroller_price).and_return(nil)

# does cover up the issue but causes the above test to fail because
# deliver_now quantities are no longer being checked, thus negating the purpose of the test in the first place
expect(FactSheetHelper).to receive(:display_factsheet_price).with(project.data).and_return(0)
expect(ProductionMailer).to receive(:params).and_return(params)
expect(message_delivery).to receive(:deliver_now)

How can I stub that Helper method from a controller spec test succesfully, or is this a bug in rspec somewhere?
Comment: Maybe I'm missing something, but you shouldn't have access to params inside your mailer's views.
Comment: The params are used in the helper, not in the view.  The mailer's view calls the helper.  I'm not aware that that's problematic.
Comment: It is, you can't do that. If your helper uses params you can only use it in controllers or views.
Answer: The error says it all, you can't use params inside a Mailer (or within the context of a Mailer through a Helper). Refactor, so you pass the value as an argument to the mailer method instead.
Comment: Thanks.  I was clearly confused.  I had a bug that made me think this was working when testing manually and so I thought it was a rspec thing.


Is there a way to define generic props when using vue3 with tsx

Question: We have a simple way to define generic vue components when we are in functional mode:

type Loading = { status: 'LOADING' }
type Error = { status: 'ERROR'; message: string }
type AsyncData<T> = Loading | { status: 'LOADED'; value: T } | Error

type Props<T> = {
  data: AsyncData<T>
  renderItem: (item: T) => JSX.Element | null
}

const LoadingElement = <T,>(props: Props<T>) => {
  return (
    <div class={`${props.data.status === 'LOADING' ? styles['top-level'] : ''}`} style={props.data.status !== 'LOADED' ? 'display: flex; justify-content: center' : ''}>
      {props.data.status === 'LOADED' ? props.renderItem(props.data.value) : null}
      {props.data.status === 'ERROR' ? (

          <HelpTooltip icon="error-warning" text={props.data.message} />

      ) : null}
      {props.data.status === 'LOADING' ?

 : null}

  )
}

With this I can use like this:

<LoadingElement data={utilisateur.value} renderItem={item => <>{item ? `${item.prenom || '–'} ${item.nom || '–'}` : '–'}</>} />

where item is correctly typed.
My main issue is when using defineComponent (ie. when I need to use ref, or watch, or computed,...) I cannot find a way to correctly generify the component.
The least worst we have is to wrap our component inside a functional one.
For example:
const GenericComponentHack = <T>() =>
  defineComponent<Props<T>>({ setup(props) => {
    return () => <OtherComponent {...props} />
  })

export const GenericComponent = <T>(props: Props<T>): JSX.Element => {
  const GenericComponentHackInstance = GenericComponentHack<T>()
  // @ts-ignore
  return <GenericComponentHackInstance {...props} />
}

This feels quite ugly, is there another way to do this?
Answer: Yeap, defineComponent has another signature with a function since 3.3 version.
You can read more about this here
The example from the doc:
const Comp = defineComponent(
  <T extends string | number>(props: { msg: T; list: T[] }) => {
    // use Composition API here like in


A number with greatest amount of factors that are prime and at the same time finding the upper limit of non-composite factors for a number

Question: So we have a number $n$ which is composite and odd at the same time.
And task was to prove that all of its prime factors must be at most $\frac{n}{3}$.
Second task was to justify how many prime factors the number $n$ could have.
My attempt: I'm not sure if it's even necessary but I know by definition of a composite number $n=km$ for some $1 <k,m<n.$ And $n=2l+1$ for some $l\in\mathbb{N}$.
I also know that this theorem (I don't think it has a name) that for this number $n$ which we know that $n>1$ has a prime factor $p$ such that $p|n$.
I have just begun studying these sorts of topic. Please help, thanks in advance.
Comment: Comments are not for extended discussion; this conversation has been [moved to chat](https://chat.stackexchange.com/rooms/88775/discussion-on-question-by-javacoder-a-number-with-greatest-amount-of-factors-tha).
Answer: Since $n$ is odd, $2$ is not a factor of $n$, so the least prime factor of $n$ could be $3$.  Therefore, any prime factor of $n$ could not be more than $n/3$.
To maximize the number of prime factors of $n$, minimize the size of each prime factor, i.e., choose $3$ as each prime factor, i.e., make $n=3^r$, so $n$ has $r$ prime factors, where $r=log_3 n$.
Comment: Hi did you have a chance to read my last comment, and thanks lots!


Get content of facebook like box plugin with curl

Question: I'm working on a website which should be fully visible for users in a place that Facebook.com is banned for them. so my Facebook like box plugin will not appear for them. ( in order to not localize this question, assume that I want to bypass all client-side firewalls and show like box plugin as a simple HTML in my website (my website is not banned there)).
My server can access Facebook.com and I thought that i can get content of my plugin using curl (in my server's computer) and then execute and show content of that page as a simple HTML in any part of my website. So I just wrote following script:
<?
$c = curl_init('https://www.facebook.com/plugins/likebox.php?href=http%3A%2F%2Fwww.facebook.com%2Fstevejobs&width=292&height=258&colorscheme=dark&show_faces=true&border_color&stream=false&header=false');

curl_setopt($ch, CURLOPT_HTTPHEADER, array('Host: www.facebook.com', 'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
', 'Accept-Language: en-us,en;q=0.5', 'Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7', 'Accept-Encoding: gzip, deflate'));
curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows NT 6.1; rv:5.0) Gecko/20100101 Firefox/5.0");

curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt(CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_BINARYTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);

$html = curl_exec($c);

if (curl_error($c))
    die(curl_error($c));

$status = curl_getinfo($c, CURLINFO_HTTP_CODE);

curl_close($c);
?>

Surprisingly above code works for https://www.youtube.com( which is banned there too ) or https://www.google.com but not working with that URL or even simply https://www.facebook.com in my server.
Another question : if I use https://www.youtube.com instead of Facebook.com I still can't get CSS files or Javascript files which used in YouTube.com( because they are banned too and clients can't download it either). I just can see texts and some images. I also want curl to automatically get content of CSS and Javascript files.
I also used YQL in order to get content of like box plugin from Facebook.com but I got following result:
YQL statement:
select * from html where url = 'https://www.facebook.com/plugins/likebox.php?href=http%3A%2F%2Fwww.facebook.com%2Fstevejobs&width=292&height=258&colorscheme=dark&show_faces=true&border_color&stream=false&header=false'

Result:
    <?xml version="1.0" encoding="UTF-8"?>
<query xmlns:yahoo="http://www.yahooapis.com/v1/base.rng"
    yahoo:count="0" yahoo:created="2011-11-11T11:41:10Z" yahoo:lang="en-US">
    <diagnostics>
        <publiclyCallable>true</publiclyCallable>
        <url
            error="Redirected to a robots.txt restricted URL: https://www.facebook.com/plugins/likebox.php?href=http%3A%2F%2Fwww.facebook.com%2Fstevejobs&amp;width=292&amp;height=258&amp;colorscheme=dark&amp;show_faces=true&amp;border_color&amp;stream=false&amp;header=false"
            execution-start-time="1" execution-stop-time="6"
            execution-time="5" http-status-code="403"
            http-status-message="Forbidden" proxy="DEFAULT"><![CDATA[https://www.facebook.com/plugins/likebox.php?href=http%3A%2F%2Fwww.facebook.com%2Fstevejobs&width=292&height=258&colorscheme=dark&show_faces=true&border_color&stream=false&header=false]]></url>
        <user-time>6</user-time>
        <service-time>5</service-time>
        <build-version>23377</build-version>
    </diagnostics>
    <results/>
</query>

It looks like there are some problem with facebook.com's robots.txt. I should mention that above YQL statement works for other websites( like https://www.youtube.com or https://www.yahoo.com ).
Thanks in advance
Comment: Setting Host: is CURLOPT_HTTPHEADER isn't necessary; it's set for you automatically. And setting an Accept-Encoding header unilaterally is a bit dodgy, if the client doesn't support both types of compression. It could be that Facebook is using various heuristics in the request to try to keep robots out, and this request isn't sufficiently similar enough to a browser's request to pass their checks. Are you sure you don't need a cookie for this to work?
Answer: there are mistakes in your code:
1- change $c to $ch in all parts of your code.
2- add "echo $html" after curl_exec function.
3- as @Dan mentioned in a comment, CURLOPT_HTTPHEADER isn't necessary. simply remove it.
4- setting curlopt_cookiejar isn't necessary but I always set it with curl. ( just to make sure that everything works fine )
5- remove everything before <!DOCTYPE in order to show content properly.
try following code:
$ch = curl_init('https://www.facebook.com/plugins/likebox.php?href=http%3A%2F%2Fwww.facebook.com%2Fstevejobs&width=292&height=258&colorscheme=dark&show_faces=true&border_color&stream=false&header=false');

curl_setopt($ch, CURLOPT_USERAGENT , 'Mozilla/5.0 (Windows; U; Windows NT 5.1; fr; rv:184.108.40.206) Gecko/20090715 Firefox/3.5.1');
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true );
curl_setopt($ch, CURLOPT_COOKIEJAR , "facebookcookies");
curl_setopt($ch, CURLOPT_URL,"https://www.facebook.com/plugins/likebox.php?href=http%3A%2F%2Fwww.facebook.com%2Fstevejobs&width=292&height=258&colorscheme=dark&show_faces=true&border_color&stream=false&header=false");
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLOPT_POST, true );
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);

$html = curl_exec($ch);

//remove everything before <!DOCTYPE
echo preg_replace('/^[^<!]*<!\s*/', '<!', $html);

if (curl_error($ch))
    die(curl_error($ch));

// Get the status code
$status = curl_getinfo($ch, CURLINFO_HTTP_CODE);

curl_close($ch);


How to drop dhcp ip assignated when using clevis/tang on Ubuntu 20.04

Question: I unlock my drive with clevis/tang on an Ubuntu server (NBDE). It works fine, but even if my server is configured to use a static ip in /etc/netplan/01-netcfg.yaml, my network interface also listen on two dhcp ip attributed on the boot process. How to drop it after boot is completed?
I enabled clevis with the following commands:
sudo apt install clevis clevis-systemd clevis-initramfs clevis-luks
sudo clevis luks bind -d /dev/sda3 sss '{"t": 1, "pins": {"tang": [{"url": "http://10.1.1.1:8888"},{"url": "http://10.2.2.2:8888"}]}}'
sudo update-initramfs -u -k 'all'

After rebooting my server, the network interface got 3 ips! My static ip configured in /etc/netplan and two dhcp ips. One of the dhcp ip is used by the clevis process (I see a trace on my tang server). The other seem to be assigned after the clevis process is completed.
I was able to make clevis to drop the dhcp ip it use. I noticed that the script at /usr/share/initramfs-tools/scripts/local-bottom/clevis was different than the one in the clevis git repository. I added the line iface=$(basename "$iface") after if [ -e "$iface" ]; then.
But I'm still stuck with one useless dhcp ip on my interface. When I do a netplan apply, systemd-networkd even refresh the dhcp lease as you can the in the following log extract:
Oct 22 12:04:56 testserver systemd[1]: Reloading.
Oct 22 12:04:56 testserver systemd[1]: /lib/systemd/system/dbus.socket:5: ListenStream= references a path below legacy directory /var/run/, updating /var/run/dbus/system_bus_socket → /run/dbus/system_bus_socket; please update the unit file accordingly.
Oct 22 12:04:56 testserver systemd[1]: systemd-networkd-wait-online.service: Succeeded.
Oct 22 12:04:56 testserver systemd[1]: Stopped Wait for Network to be Configured.
Oct 22 12:04:56 testserver systemd[1]: Stopping Network Service...
Oct 22 12:04:57 testserver systemd[1]: systemd-networkd.service: Succeeded.
Oct 22 12:04:57 testserver systemd[1]: Stopped Network Service.
Oct 22 12:04:57 testserver systemd[1]: Condition check resulted in OpenVSwitch configuration for cleanup being skipped.
Oct 22 12:04:57 testserver systemd[1]: Starting Network Service...
Oct 22 12:04:57 testserver systemd[1]: Condition check resulted in OpenVSwitch configuration for cleanup being skipped.
Oct 22 12:04:57 testserver systemd-networkd[1711]: eno3: Gained IPv6LL
Oct 22 12:04:57 testserver systemd-networkd[1711]: Enumeration completed
Oct 22 12:04:57 testserver systemd[1]: Started Network Service.
Oct 22 12:04:57 testserver systemd-networkd[1711]: eno3: IPv6 successfully enabled
Oct 22 12:04:57 testserver systemd-networkd[1711]: eno3: DHCPv4 address 10.1.1.71/21 via 10.1.0.1

But I don't use dhcp at all in my netplan configuration!
# This file describes the network interfaces available on your system
# For more information, see netplan(5).
network:
  version: 2
  #renderer: networkd
  ethernets:
    eno3:
      dhcp4: no
      addresses:
      - 10.1.0.99/21
      gateway4: 10.1.0.1
      nameservers:
        addresses:
        - 10.1.0.3
        - 10.1.0.33

When I launch netplan --debug apply, I see that dhcp4 become enabled when the config is merged!? But merged with what? Can be from /run/netplan/eno3.yaml? In that file, I see a dynamic network configuration with dhcp enabled. What does generate that file?
Comment: This return: `BOOT_IMAGE=/vmlinuz-5.4.0-52-generic root=/dev/mapper/vg0-lv--root ro quiet`
Answer: Seem like there is a bug in a clevis script. Edit /usr/share/initramfs-tools/scripts/local-bottom/clevis.
Search:
for iface in /sys/class/net/*; do
    if [ -e "$iface" ]; then
        ip link  set   dev "$iface" down
        ip addr  flush dev "$iface"
        ip route flush dev "$iface"
    fi
done

Replace with:
for iface in /sys/class/net/*; do
    if [ -e "$iface" ]; then
        iface=$(basename "$iface")
        ip link  set   dev "$iface" down
        ip addr  flush dev "$iface"
        ip route flush dev "$iface"

        if [ -f "/run/netplan/${iface}.yaml" ]; then
            rm "/run/netplan/${iface}.yaml"
        fi
    fi
done

Regenerate initramfs with the following command: update-initramfs -u -k 'all' then reboot.
The file /run/netplan/eno3.yaml is gone and all the stall dhcp addresses are also gone from the interface!


Winding number of a polynomial

Question: Consider $f(z) = c_n z^n + ... + c_1 z + c_0$, where $c_n\ne 0$. Let $C_R$ be the circle of radius $R$ centred at the origin, oriented counterclockwise. Prove that the winding number of $f\circ C_R =n $ for $R$ sufficiently large.

My approach:

Parametrize $C_R$ as $\gamma(t) = Re^{it}$. Then
$$\frac{1}{2\pi i}\int_{C_R} \frac{f'(z)}{f(z)}dz=\frac{1}{2\pi i}\int\limits_0^{2\pi} \frac{f'(\gamma(t))\gamma'(t)}{f(\gamma(t))}dt$$
$$=\frac{1}{2\pi }\int\limits_0^{2\pi} \frac{nc_n (Re^{it})^n + ... + c_1 Re^{it}}{c_n (Re^{it})^n+...+c_1Re^{it}+c_0}dt$$
I thought I got stuck here, but now I'm thinking: maybe I should take the limit as $R\to \infty$ of the integral above, take the limit in the integral (since the limit is not in terms of $t$), and then observe that the integrand becomes $ndt$, and so the integral comes to $\frac{2\pi n}{2\pi}=n$?
Would this approach be correct? I think so, because $R$ should go to infinity in order to encompass all possibilities for all zeros of $f(z)$.
Comment: Correct. You can also note that asymptotically (for large $R$), the winding number will be that of the dominant term, which is $z^n$, i.e. a rotation of winding $n$.
Comment: That looks fine, but: haven't you studied yet the (Cauchy's) Argument Principle? Because if you have then the proof, if I'm not mistake, takes one line at most and looks much less messy.
Comment: @DonAntonio By the Argument Principle, we have to "already" know that f has n roots. But this proof is another proof of the Fundamental Theorem of Algebra, where we assume we don't yet know that f has n roots, and deduce it in the end, by the Argument Principle.
Comment: @sequence That wasn't clear from the beginning, and you also wrote "$\,R\;$ should go to infinity to encompass all possibilities for all zeros of $\;f(z)\;$", so I didn't even think of the FTA.
Comment: @DonAntonio I think I wasn't clear enough in my original post. When we let $R\to \infty$ we want to account for all possibilities of "covering" any zeros of $f$, since $f$ is a general polynomial. That's what I should've said.
Answer: By the Argument Principle, directly we get for $\;R\;$ big enough so that all the roots of the polynomial are within the circle $\;|z|=R\;$:
$$\frac1{2\pi i}\oint_{C_R}\frac{f'(z)}{f(z)}dz=n$$
and we're done.
Comment: @sequence, you should have told us in the question that you were trying to prove the FTA.
Comment: By the Argument Principle, we have to "already" know that $f$ has $n$ roots. But this proof is another proof of the Fundamental Theorem of Algebra, where we assume we don't yet know that $f$ has $n$ roots, and deduce it in the end, by the Argument Principle.
Answer: Suppose wlog $c_n =1$.
$$
\int_{|z|=R}\frac{f'(z)}{f(z)}\,dz =
\int_{|z|=R}\left(\frac{f'(z)}{f(z)} - \frac{n}z + \frac{n}z\right)dz =
\int_{|z|=R}\left(\frac{f'(z)}{f(z)} - \frac{n}z\right)dz + 2\pi i n
$$
and for some $M>0$
$$
\left|\int_{|z|=R}\left(\frac{f'(z)}{f(z)} - \frac{n}z\right)dz\right| =
\left|\int_{|z|=R}\frac{zf'(z) - nf(z)}{zf(z)}\,dz\right|\le\frac{MR^{n-1}}{R^{n+1}}2\pi R = \frac{2\pi M}R.
$$

Winding number of a polynomial


dotnetcore 3 web api external login with google GetExternalLoginInfoAsync return null most of the times

Question: I have tried almost all possible solutions available online, but still, am unable to get a working solution. I doing a POC with dotnetcore 3 web API, using GoogleAuthentication.
I have configured the returnUrl in console.google as localhost:5432/Account/ExternalLoginCallback
Whenever I try to hit the API at http://localhost:5432/account/externallogin?provider=Google, It hits the ExternalLogin method and then redirects me to google sign-in page, when I sign in, again I am redirected to ExternalLoginCallback method, but signInManager.GetExternalLoginInfoAsync() mostly return null.
The most surprising thing is that out of 100 tries there are 2, 3 tries in which I actually get data back from signInManager.GetExternalLoginInfoAsync().
I am totally confused, can you please help me here
The startup.cs looks like this
<code>    public void ConfigureServices(IServiceCollection services)
        {
            ...

            services.AddAuthentication().AddCookie().AddGoogle(options =>
            {
                options.ClientId = "<id>";
                options.ClientSecret = "<secret>";
                options.CallbackPath = new PathString("/Account/ExternalLoginCallback");

            });
            ...
</code>
The AccountController has two methods which looks like this
<code>[HttpGet("ExternalLogin")]
    public IActionResult ExternalLogin(string provider, string returnUrl="/")
    {
        var redirectUrl = Url.Action("ExternalLoginCallback", "Account",
                                    new { ReturnUrl = returnUrl });
        var properties = signInManager.ConfigureExternalAuthenticationProperties(provider, redirectUrl);
        return new ChallengeResult(provider, properties);
    }

[HttpGet("ExternalLoginCallback")]
    public async Task<IActionResult> ExternalLoginCallback(string returnUrl = null, string remoteError = null)
    {
        ExternalLoginInfo info = await signInManager.GetExternalLoginInfoAsync();
        if (info == null)
        {
            return Content("Could not load user info");
        }
       .....

    }
</code>
Comment: did you find solution in this problem? we have the same problem
Comment: I have the same problem. I am confused.
Answer: Google+ based auth deprecation and replacement
ASP.NET Core 2.x
For Microsoft.AspNetCore.Authentication.Google 2.x the mitigation is to replace your existing call to AddGoogle in Startup with:
<code>.AddGoogle(o =>
{
    o.ClientId = Configuration["Authentication:Google:ClientId"];
    o.ClientSecret = Configuration["Authentication:Google:ClientSecret"];
    o.UserInformationEndpoint = "https://www.googleapis.com/oauth2/v2/userinfo";
    o.ClaimActions.Clear();
    o.ClaimActions.MapJsonKey(ClaimTypes.NameIdentifier, "id");
    o.ClaimActions.MapJsonKey(ClaimTypes.Name, "name");
    o.ClaimActions.MapJsonKey(ClaimTypes.GivenName, "given_name");
    o.ClaimActions.MapJsonKey(ClaimTypes.Surname, "family_name");
    o.ClaimActions.MapJsonKey("urn:google:profile", "link");
    o.ClaimActions.MapJsonKey(ClaimTypes.Email, "email");
});
</code>
Applications should do immediate testing with the mitigation to check for changes in the data format. Expect a fix for this to be included in the February 2.1 and 2.2 patches that incorperates the above reconfiguration as the new defaults. No patch is planned for 2.0 since it has reached end of life.
ASP.NET Core 3.0 Preview
The mitigation given for 2.x can also be used for the current 3.0 preview. In future 3.0 previews we're considering removing the Microsoft.AspNetCore.Authentication.Google package and directing users to Microsoft.AspNetCore.Authentication.OpenIdConnect instead. We'll follow up with the final plan. Here's how to replace AddGoogle with AddOpenIdConnect in Startup. This replacement can be used with ASP.NET Core 2.0 and later and can be adapted for 1.x as needed.
<code>.AddOpenIdConnect("Google", o =>
{
    o.ClientId = Configuration["Authentication:Google:ClientId"];
    o.ClientSecret = Configuration["Authentication:Google:ClientSecret"];
    o.Authority = "https://accounts.google.com";
    o.ResponseType = OpenIdConnectResponseType.Code;
    o.CallbackPath = "/signin-google"; // Or register the default "/sigin-oidc"
    o.Scope.Add("email");
});
JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear();
</code>