How can Java ArrayList change value while passing as argument?

Question: Good Day.
I am pretty sure that this question has been asked before but I couldn't find it.
Basically, how does the below code work:
import java.util.ArrayList;

public class Main{
    public static void main(String[] args) {
        ArrayList<Integer> a = new ArrayList<Integer>();

        a.add(10);

        change(a);

        System.out.println(a.get(0));
    }

    static void change(ArrayList v){
        if(v.size() > 0){
            v.set(0, "Hello");
        }
    }
}

It compiles and also runs successfully, printing "Hello". How could Java replace Integer with String?
I also tried adding in Main:
        a.set(0, 1002);

        for(Integer c: a){
            System.out.print(c + " ");
        }
        System.out.println("");

Once again, very surprising. I thought that maybe somwhow a gets changed to ArrayList<String> but the set method works normally?
Can anyone please explain this to me? Is this undefined behaviour?
Thanks.
Comment: [What is a raw type and why shouldn't we use it?](https://stackoverflow.com/questions/2770321/what-is-a-raw-type-and-why-shouldnt-we-use-it)
Comment: You could do it you you used `Object` as your list type `(e.g. new ArrayList`  But lists of mixed types is not not a good idea and can lead to problems.
Comment: When you compiled this code, you would have got a warning.  That warning was telling you this could happen.
Comment: Java doesn't replace Integer with String. `System.out.println(a.get(0));`Is using [println(Object)](https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/io/PrintStream.html#println(java.lang.Object)) So it doesn't need to cast the String to an Integer. If you tired `Integer b = v.get(0);` you'd get different results.
Answer: Generic types like the <Integer> in your ArrayList are a compile-time concept, this information is lost at runtime. This is known as "type erasure".
You just use ArrayList (without type parameter) in the change method, which means that the compiler will not check for a type, so it's possible to add a String to an Integer List. If you used ArrayList<Integer>, the compiler would complain.
Internally, ArrayList uses a simple array of objects that can hold any type.


Correct y-axis labelling for a Kaplan-Meier figure

Question: Kaplan-Meier curves have been shown with many different names in studies.

Survival
% survival
Survival probability
Survival proportion

Is it okay to use any of them or are there slight differences? Is it a proportion or a probability? Does it depend when CIs are also provided?
Comment: I would go with "survival probability" which seems the most comprehensive and concerns the overall probability of survival in the population. The term "survival proportion" is understable as well but "proportion" is somehow, I guess, tied with the notion of sample (the proportion of success in a sample). I found this subject about the distinction between both terms if you want to take a look: https://stats.stackexchange.com/questions/1525/whats-the-difference-between-a-probability-and-a-proportion
Answer: You might want to distinguish between displays of raw survival data like Kaplan-Meier curves and survival functions predicted from a semiparametric or parametric model. For example, "proportion" might most directly represent raw data while "probability" might represent model predictions. Thanks to @periwinkle for the helpful link about that distinction. Even that distinction gets a bit fuzzy, however, as raw Kaplan-Meier curves are generally presented with modeled confidence limits.
Whichever you choose, make sure that the numeric axis labels agree with the text label. If you use "Percent survival" then the y-axis range should be 0 to 100. If it's "Survival probability" then the range should be 0 to 1.


Java, null pointer exception

Question: I have the following code which i have been refining for a school assignment, but there is a null pointer exception that is driving me crazy.
Here is my code:
public static <AnyType extends Comparable<? super AnyType>>
    void difference(List<AnyType> L1, List<AnyType> L2, List<AnyType> Difference){

        if(L1 == null){
            Difference = null;
        }
        else if(L2 == null || L1.isEmpty() || L2.isEmpty()){
            Difference = L1;
        }
        else{
            Iterator<AnyType> iterator1 =L1.listIterator();
            Iterator<AnyType> iterator2 =L2.listIterator();

            AnyType a = iterator1.next();
            AnyType b = iterator2.next();

            while(a!=null || b!=null){
                int comp = a.compareTo(b);
                if(comp > 0)
                    b =(iterator2.hasNext()) ? iterator2.next(): null;

                else if(comp < 0){
                    Difference.add(a);
                    a = (iterator1.hasNext())? iterator1.next(): null;

                }
                else {
                    a = (iterator1.hasNext())? iterator1.next() : null;
                    b = (iterator2.hasNext())? iterator2.next() : null;
                }
            }
            if(b==null){
                while(a!=null){
                    Difference.add(a);
                    a = iterator1.next();
                }
            }
        }
        System.out.println("Difference Set: " + Arrays.toString(Difference.toArray()));
    }

On the while loop, when a is null the program keeps going into the while and that is not supposed to happen. Can anyone tell me why is this happening?
The data i am using to test is:
List<Integer> list3 = Arrays.asList(1,2);
        List<Integer> list4 =Arrays.asList(5,17);
        List<Integer> listR = new ArrayList<>();

        ListsSets.difference(list3, list4, listR);

after a is null the while is supposed to not be executed again but it somehow happens.
Comment: your using `||` , so only one of them has to be true
Comment: because you have entered 'OR' condition instead of && operator inside the expression used as while condition. So it should enter inside the while loop even if a is null but b is not null
Answer: Use &&, because using || will make your if condition pass if one of them is true. As the result, your code still executing if a not null but b is null.

Java, null pointer exception


Work out the values of a and b (in the below question):

Question: $1^2 = 1$
$1^2 + 2^2 = 5$
$1^2 + 2^2 + 3^2 = 14$
$1^2 + 2^2 + 3^2 + 4^2 = 30$
$1^2 + 2^2 + 3^2 + 4^2 + ...... + n^2 = an^3 + bn^2 + (n/6)$
Work out the values of $a$ and $b$.
Answer: $$\sum_{r=0}^nr^2=\frac{n(n+1)(2n+1)}{6}$$
now you can expand this
Comment: just a question.
Comment: shouldn't r start with 1?
Comment: Possibly yes, although in this context the $r=0$ term is ignored obviously
Answer: By one of the properties of sigma, the last equation can be expressed as $\frac{n(n+1)(2n+1)}{6}$.
This means that the sum of the squares of numbers from $1$ to $n$ can be expressed as $\frac{n(n+1)(2n+1)}{6}$.
Therefore, you just have to make it equal to that and work out the values of $a$ and $b$ by yourself.
To be more clear, you just need to let $an^3+bn^2+\frac{n}{6}= \frac{n(n+1)(2n+1)}{6}$ and solve for $n$.
Comment: What do you mean exactly?
Comment: I edited my answer
Comment: Thanks for the reply. I still have a few doubts though. How will solving for n get the values for a and b? And is it possible to get the values for a and b without using sigma?
Comment: 1^2+2^2+.....+n^2=an^3+bn^2+n/6=n(n+1)(2n+1)6                                             Is it better to understand?In case you are curious about how the formula is made, you can copy and go to this link.

 http://mathforum.org/library/drmath/view/56920.html .
                                                                                This shows you how the formula is achieved.
Answer: Sum of squares of first $n$ natural numbers is given by : $$ \Sigma_{r=1}^nr^2= \frac{n(n+1)(2n+1)}{6}$$
Expanding it: $$\frac13 n^3+\frac 12 n^2+\frac n6$$

So, $$a=\frac 13$$ and $$b=\frac 12$$
Comment: Thanks for the reply, but is it possible to get the values of a and b without using sigma?
Comment: We used sigma to get that expression. Once got that, then just simplify it to form a cubic. And you are done!


How do i search by ID in json file?

Question: so let's say i have this JSON file:
{
  "1": {
    "name": "some random name 1",
    "nickname": "some random nickname 1"
  },
  "2": {
    "name": "some random name 2",
    "nickname": "some random nickname 2"
  }
}

And i need function that searches by ID,("1": / "2": is ID basically) and saves it in variable. (Using Javascript). I just don't know how to do it.
Answer: Why not just standard bracket notation for this...?

var object = {
  "1": {
    "name": "some random name 1",
    "nickname": "some random nickname 1"
  },
  "2": {
    "name": "some random name 2",
    "nickname": "some random nickname 2"
  }
}

console.log(object["1"]);
console.log(object["2"]);

How do i search by ID in json file?


Como -1 pode ser maior que 4?

Question: Como este código pode executar desta forma?
#include <stdio.h>

int main(void) {
    printf("tamanho de um inteiro: %d\n", sizeof(int));
    if(sizeof(int) > -1) {
        printf("4 é maior que -1");
    } else {
        printf("-1 é maior que 4");
    }
    return 0;
}

Saída:
-1 é maior que 4

Intuitivamente -1 deve ser menor que 4 sempre, porque acontece este tipo de "erro"? O computador não é uma máquina que não erra?
Answer: Mesmo que minha mãe e alguns programadores achem que o computador toma suas próprias decisões, ele só é capaz de fazer o que humanos determinam.
Claro que um computador pode produzir resultados errados sem um humano errar usando ele. Mas isso significa que um humano projetou o computador ou pelo menos algum componente dele de forma errada. Ou a especificação determinou que o erro será possível, e quem for utilizar aquele hardware precisa estar ciente disto e tomar as devidas providências para isso não trazer resultados indesejados. Na prática os erros ocorrem mais nos softwares mesmo.
Os programadores cometem muitos erros, frequentemente porque não entendem todos os aspectos do que ele estão fazendo. É normal. Não existe ninguém que sabe tudo de tudo, mesmo que esse tudo seja só sobre desenvolvimento de software.
Esse "problema" específico ocorre por causa da diferença de tipos utilizado do código. Não é muito óbvio mas se procurar na especificação verá que o operador sizeof retorna um valor de tipo unsigned int, mais especificamente um size_t e a comparação no if está sendo feito com um signed int ou simplesmente int. Ou seja, está comparando um tipo que tem sinal com outro que não tem. Por isso há uma conversão implícita do tipo sinalizado para o tipo não sinalizado. Nesta conversão há uma mudança na interpretação do dado.
Sabendo que o retorno do operador usado é um inteiro sem sinal e que o cast implícito ocorre e ainda que um valor negativo quando convertido para um tipo sem sinal começa a contagem do maior inteiro possível e vai reduzindo quanto mais for o negativo - já que ele ignora o bit de sinal como um sinal e o considera como parte do número - fica fácil entender o que está ocorrendo. E o problema é só uma interpretação errada de um humano. O computador fez o que mandaram ele fazer.
Fica mais fácil entender imprimindo o -1 sem sinal:
#include <stdio.h>

int main(void) {
    printf("tamanho de um inteiro: %d\n", sizeof(int));
    printf("-1 com cast: %u\n", -1);
    if(sizeof(int) > -1) {
        printf("4 é maior que -1");
    } else {
        printf("-1 é maior que 4");
    }
    return 0;
}

Então a mensagem deveria ser "4294967295 é maior que 4".
Veja funcionando no ideone. E no repl.it. Também coloquei no GitHub para referência futura.
Algumas pessoas vão aproveitar isso para criticar a conversão implícita. De fato ela é ruim quando espera-se que a linguagem será usada por programadores que não entendem bem todo funcionamento do que ele está usando ou de quem costuma ter desatenções. Mas acho que mais ajuda que atrapalha.
De uma certa forma isso remete ao que eu respondi em outra pergunta. O fato de você não saber o tipo que uma expressão resulta é o real problema do código. Deixar tudo explícito ajudaria a evitar alguns problemas mas deixaria o código mais longo e redundante adicionando um detalhe desnecessário. Ironicamente isso pode ser benéfico em linguagens que tem como alvo programadores que não se preocupam com os detalhes.
Conclusão
Saiba os tipos de toda sub-expressão que está computando. E garanta que está usando os tipos certos. Neste caso se a intenção realmente é comparar o tamanho do tipo com literal inteiro sinalizado, então deve garantir que o resultado de sizeof(int) seja um int através de um cast. Assim:
#include <stdio.h>

int main(void) {
    printf("tamanho de um inteiro: %d\n", (int)sizeof(int));
    if((int)sizeof(int) > -1) printf("4 é maior que -1");
    else printf("-1 é maior que 4");
}

Veja funcionando no ideone. E no repl.it. Também coloquei no GitHub para referência futura.
Este par de pergunta e resposta foi inspirado em uma discussão no Reddit que achei interessante mostrar.
Comment: Realmente interessante.
Obrigado por compartilhar!
Answer: Na verdade sizeof retorna um tipo size_t, devendo ser do tipo unsigned. O problema ocorre na conversão binário signed para binário unsigned, caso o programador não tenha cuidado.
A conversão de um número binário para um inteiro decimal negativo como -1, por exemplo, é feito em C pelo complemento de dois do seu equivalente positivo.
Exemplo de como o computador enxerga um número negativo:
Pega o número 1 -- positivo -- em forma binária com o tamanho de 4 bytes (32 bits, ou 32 dígitos binários):
00000000 00000000 00000000 00000001 -> binário de 1
11111111 11111111 11111111 11111110 -> complemento de um (inverte-se os bits)
                                + 1 -> complemento de dois (soma 1 ao complemento)
___________________________________
11111111 11111111 11111111 11111111 -> complemento de dois equivalendo a -1

O problema ocorre quando o computador trata um número que deveria ser negativo como positivo. Por exemplo, o número decimal -1 acima, tratado como positivo é reconhecido pelo computador como 4294967295 decimal, que obviamente é maior que o número 4 do seu mesmo tipo.
Levando em conta isso, deve-se ter bastante cuidado de como o computador e a linguagem de programação lida com a conversão implícita de tipos. Estude bastante casting para ter certeza de sempre fazê-la de maneira segura.

Como -1 pode ser maior que 4?


Integrate out missing variables in Gaussian Processing?

Question: In https://stats.stackexchange.com/a/103533/83252 @juampa writes

[...] in models like Naive Bayes or Gaussian Processes you would integrate out missing variables, and choose the best option with the remaining variables.

What does (s)he mean by that? How do I use Gaussian Processing Regression on incomplete datasets, "integrating out" the missing variables?
I am mostly interested in a detailed (hopefully step by step, easy to understand) mathematical explanation.
Answer: The linked question is discussing data imputation for the purposes of building a predictive model. What I believe the accepted answer is referring to is using a Gaussian Process as a model for the missing data, conditional on the observed data.
"Integrating out" these missing variables then means marginalising the predictions of the resulting predictive model (the model built using these "imputed" data points) over the distribution of possible values the missing points could take.
I am not confident enough to give you a rigorous mathematical explanation, but I will attempt a verbose, intuitive example since this has been open for a while, and perhaps someone else can expand on it or correct me if I also misunderstand.

Suppose we wish to build a predictive model of some function $f(x,y,z)$, but the process by which we collect data on variable $z$ is messy. So sometimes we will only have access to $x$ and $y$.
In order to build our predictive model, we require $z$. One approach is to attempt to "impute" $z$, given it's previous observations and any covariance structure we believe might be present between $x$, $y$ and $z$: this is where we can use a Gaussian Process.
In this case, we suppose a Gaussian Process models $z$ as a function of $x$ and $y$. To make things a bit easier to read, assume we concatenate $x$ and $y$ into a vector, $r$ (so $r:=[x, y]$). We consequently end up with a set of different $r$ corresponding to all the data points we have collected.
For some of these datapoints, there will not be a corresponding measurement $z$ (as it was corrupted, is missing, or otherwise unavailable). If we refer to these points ($x$ and $y$ measurements missing a particular $z$) as $r^*$, and the missing values as $z^*$, our task is to compute $z^*$ at $r^*$ conditional on $r$ and $z$.
Using a Gaussian Process we can do this as follows:
Let $k$ be some appropriate covariance kernel and $\theta$ its hyperparameters, and let $\mathbf{z}$ be the stacked vector of observed $z$ (so those $z$ measurements we do have). Additionally, I will use the somewhat abusive notation of $k(a,b)$ to represent the covariance matrix obtained by evaluating $k$ pairwise between the elements of $a$ and $b$.
Note:
If you're unfamiliar with how to pick a kernel or how to identify the hyperparameters, I suggest reading some of the introductory material on Gaussian Processes - I won't cover it here in the interest of brevity. I personally like this three part (1,2,3) series by Michael Betancourt.
The predictive distribution of $z^*$ is a multivariate normal distribution conditional on the currently observed values $z$, the points at which they are observed, $r$, the kernel $k$, and the kernel hyperparameters $\theta$:
$p(z^* | r, z, k, \theta) \sim \mathrm{MultiNormal} (\mu_p, \Sigma_p)$
where the "predictive" (or conditional) mean distribution $\mu_p$ is given by:
$\mu_p = k(r^*,r) [k(r, r)]^{-1} \mathbf{z}$
And the predictive covariance matrix $\Sigma$ is:
$\Sigma = k(r^*, r^*) - k(r^*, r) [k(r, r)]^{-1} k(r,r^*)$
Given this model for $p(z^* | r, z, k, \theta)$, we are able to assess the probability of $z^*$ given the observed data and the assumptions we used to select $k$.

Now, suppose we want to use these imputed values of $z^*$ in a predictive model for some other quantity $f(x,y,z)$: It is here we would "integrate out" missing variables.
Since our predictions of $z^*$ are a distribution (a normal distribution, $p(z^*)$, given we have used a Gaussian Process as a model for $z$), we probably want to capture uncertainty in the fact we do not know $z$ at these locations exactly.
Very simply, if we want to make a prediction of $f(x,y,z)$ using $x, y$ and $p(z^*)$, we should account for all the values $z^*$ could be when making this prediction. This amounts to approaching the following integral:
$p(f(x,y,z^*)) = \displaystyle\int f(x,y,z^*) p(z^*) dz^*$
This is usually approached numerically since $f$ rarely permits an analytical treatment (but it might). Typical approaches are quadrature or Monte-Carlo simulation.
The important point is that predictions made using $z^*$ are done so over the distribution of possible $z^*$. This implies these predictions are themselves a distribution, and should be assessed as such to evaluate predictive performance in a robust way,


Proving that two systems of linear equations are equivalent if they have the same solutions

Question: I've just begun to work learn Linear Algebra on my own through Hoffman and Kunze's book and the first problem set already has a question that I can't solve:
Prove that if two homogeneous systems of linear equations in two unknowns have the same solutions, then they are equivalent.
I can't seem to figure out how to prove this without resorting to case work where you account for the cases where one of the coefficients are zero and when both are.
Is there an elegant way to prove in general that when two systems of linear equations have the same solutions, they are equivalent? The converse is obvious enough though.
Definition of equivalence from the text :

Let us say that two systems of linear equations are equivalent if each equation in each system is a linear combination of the equations
  in the other system.
Comment: What's the book's definition of "equivalent"? Usually it simply means having the same set of solutions...
Comment: @Lundmark: here it is probably an equivalence relation on the matrices associated with the equations, defined by some row/column operations. So the thing to prove is that those operations don't change the solution space. Is this what you had in mind, @Herman?
Comment: @Marek: Well, the way Hoffman and Kunze define equivalent is that each equation in one system is a linear combination of equations in the other.
Answer: We have to prove the following: Given any solution set $L\subset{\mathbb R}^2$ then any two homogeneous systems
$$\Sigma: \qquad a_i x+ b_i y=0 \qquad (1\leq i\leq n)$$
having the solution set $L$ can be transformed into each other by means of row operations.
The solution set $L$ can be one of the following:
(i) $\ \{0\}$,
(ii) a one-dimensional subspace $<r>$ with $r=(p,q)\ne 0$,
(iii) all of ${\mathbb R}^2$.
Ad (i): If $0$ is the only solution of $\Sigma$ then not all row vectors $c_i=(a_i,b_i)$ can be multiples of one and the same vector $c\ne0$. So there are two equations $a_1 x+b_1 y=0$, $a_2 x+ b_2 y=0$ in $\Sigma$ with linearly independent row vectors $(a_i, b_i)$, and by means of row operations one can transform these into $\Sigma_0: \ x=0, y=0$. Further row operations will remove all remaining equations from $\Sigma$. We conclude that in this case all systems $\Sigma$ are equivalent to $\Sigma_0$.
Ad (ii): The System $\Sigma$ has to contain at least one equation with $c_i=(a_i,b_i)\ne 0$. We claim that all equations with $c_i\ne 0$ are individually equivalent to $\Sigma_1: \  q x -p y=0$. So in this case any given $\Sigma$ is equivalent to $\Sigma_1$. To prove the claim we may assume $a_i\ne 0$. Now $r\in L$ implies $a_i p+ b_i q=0$, and as $r\ne 0$ we must have $q\ne 0$. This implies $b_i=-a_i p/q$, so multiplying the equation $a_i x+ b_i y=0$ by $q/a_i$ gives $\Sigma_1$.
Ad (iii): This case is trivial. All rows of $\Sigma$ are $0$.
Comment: Yes, I can prove it by breaking it down into the same three cases and showing it for each of them separately. However, it should be possible to prove it generally (two NxM systems have the same solutions iff they are equivalent), in which case proving it case by case doesn't work.
Comment: Any reason for working in two dimensions and writing out all the solution cases? In my mind the general proof is as simple as this: let $W$ be the solution space and $W'$ its orthogonal complement. Define a matrix $C$ that acts as identity on $W'$ and annihilates $W$. Now, by Gauss elimination, both $A$ and $B$ can be brought into this form and therefore are equivalent to $C$ and therefore to each other.
Comment: Well, I'm just beginning to learn Linear Algebra and the exercise in the book only asked to prove it in two dimensions, presumably because you're not expected to be able to prove it in general yet. I don't really understand what an orthogonal complement or even what is meant by "annihilating" a solution space, so I guess I'll refer back to your answer once I get a bit farther in my textbook. Thanks!
Comment: @Christian Blatter I really don't get this although it may be because I am just starting Linear Algebra. I was stuck with the same question as well and I think I came up with a proof yet I don't know if it is wrong or not. can you check it? https://math.stackexchange.com/questions/2844153/verify-my-proof-that-if-two-homogeneous-systems-of-linear-equations-have-the-sam
Answer: Let there be two systems, if the each equation of the second system is a Linear Combination of the first system then every solution of the first system is also the solution of the second system and if each equation of the first system is a Linear Combination of the second system the every solution of the second system is also the solution of the first system.
Now, let us consider the following two homogeneous systems in two unknowns ($x_1, x_2$), the solutions to both the systems are same.
$A_{11}x_1+A_{12}x_2=0  ...  A_{n1}x_1+A_{n2}x_2=0$ and $B_{11}x_1+B_{12}x_2=0  ...  B_{n1}x_1+B_{n2}x_2=0$.
Select scalars $C_1, C_2, ..., C_n$.  Multiply $k^{th}$ equation of the first system by $C_k$ and then add column-wise (so that variable is common) to get the following
$(C_1A_{11}+...+C_nA_{n1})x_1+(C_1A_{12}+...+C_nA_{n2})x_2=0$.
Comparing this equation with all the equations of the second system and also utilising the fact given that both the systems have the same solutions, we get
$C_1A_{11}+...+C_nA_{n1}=B_{11}, B_{21},..., B_{n1}$ and $C_1A_{12}+...+C_nA_{n2}=B_{12}, B_{22},..., B_{n2}$,
which proves that the second system is a Linear Combination the the first system.  Similar way we can show that the first system is a Linear Combination of the second system and thus conclude that both the systems are Equivalent.
Comment: Thank you for your answer, I do not quite get the last step. Could you explain a bit more?
Answer: If equivalence means "that each equation in one system is a linear combination of equations in the other" then the proof is almost trivial by the method of Gauss-Jordan elimination which is an application of Gauss elimination to make a system of equations equivalent to a diagonal form (upper triangular first, then diagonal), arriving at the solution by performing elementary row operations. You can work backwards and start up from solution of your system written as a diagonal matrix and apply a different set of elementary row operations to arrive at different systems of equations which are equivalent since each equation (row of your matrix) of one can be traced back to be written as a linear combination of the other by construction.
Answer: Consider the space of vectors in $\mathbb R^n$.
Then it is known that $m \le n$ vectors of it $\bf v_1, \cdots, \bf v_m$ will span a subspace of at most $\mu \le m$ dimensions.
It is also known that their null-space, i.e. the space spanned by the vectors normal to them, is of dimension $n-\mu$.
The solutions $\bf x$ to the system
$$\bf v_1 \cdot \bf x=0, \; \bf v_2 \cdot \bf x =0, \; \cdots,\; \bf v_m\cdot \bf x =0$$
are in fact all the vectors pertaining to respective the null-space.
If two sets of vectors
$\bf v_1, \cdots, \bf v_m$ and $\bf w_1, \cdots, \bf w_m$ have the same set of null vectors, i.e. the same nullspace,
then the $\bf v$'s and $\bf w$'s span the same subspace, so they share the same base,
can be expressed one as a linear combination of the other. In that sense they are equivalent.
In the other direction, if they are equivalent by spanning the same subspace, then they have the same null-space and
so the same solutions to the homogeneous system.


The "intersection property" of the symmetric difference metric

Question: $\newcommand{\measure}{\operatorname{measure}}$
The symmetric difference between sets can be used to define a pseudo-metric on the set of subsets of a given measure space:
$$d(S,T)=\measure(S\oplus T)$$
This pseudometric has the following property, that can be called "Intersection Property":
If $S$ intersects $T$, then there is a constant $r>0$ such that
every set $S'$ with $d(S',S)<r$ intersects every set $T'$ with $d(T',T)<r$ [where "$S$ intersects $T$" means: $d(S\cap T, \phi)>0$].
Proof: Define $r = d(S\cap T, \phi)/3 = \measure(S\cap T)/3$. By assumption $r>0$. The set $S\cap T$ can be decomposed as follows:
$$S\cap T = $$
$$[(S\setminus S')\cap(T\setminus T')] \cup $$
$$[(S\cap S')\cap(T\setminus T')] \cup $$
$$[(S\setminus S')\cap(T\cap T')] \cup $$
$$[(S\cap S')\cap(T\cap T')]$$
By definition, $S\oplus S' = (S\setminus S')\cup (S'\setminus S)$. Hence:
$$\measure(S\setminus S')\leq \measure(S\oplus S') < r$$
Simlarly:
$$\measure(T\setminus T')\leq \measure(T\oplus T') < r$$
Substituting in the decomposition of $S\cap T = $ gives:
$$\measure[(S\cap S')\cap(T\cap T')] > \measure[S\cap T] - 3r > 0$$
This implies that $S$ intersects $S'$ and $T$ intersects $T'$.
My questions are:
A. Is this proof correct?
B. Is there a formal term for this property of pseudo-metrics, which I called "intersection property"?
NOTE: This property is not true for all pseudo-metrics. For example, it is not true for the pseudo-metric based on the Hausdorff distance.
Answer: A. Almost correct.  At the end you say that $\text{measure}[S\cap T]-3r>0$, but actually it equals zero.  Also at the end, you conclude that $S$ intersects $S'$ and $T$ intersects $T'$, but that's not what you're trying to prove: what you want is that $S'$ intersects $T'$.  Happily, this also follows from the previous line.
B. I don't know of a standard term for this property.  It does, however, follow from the intersection operation being (jointly) continuous at $S\cap T$, which is a pretty standard property.  The property I mean here is that for every $\epsilon>0$ there exists $\delta>0$ such that for any sets $S'$ and $T'$ satisfying $d(S,S')<\delta$ and $d(T,T')<\delta$, we have $d(S\cap T,S'\cap T')<\epsilon$.  This holds for the symmetric difference metric; in fact,
$$ d_\oplus(S\cap T,S'\cap T') \le d_\oplus(S,S')+d_\oplus(T,T') $$
As for the Hausdorff metric, here are a few related results:

Intersection is "upper semicontinuous" for nonempty closed and bounded sets in a metric space.  Precisely: if $A,A',B,B_n$ are nonempty closed and bounded sets in a metric space $X$, and $B_n\to B$ in Hausdorff metric, and $B_n\cap A=A'$ for all $n$, then $B\cap A\supseteq A'$.
The inclusion in part 1 may be strict: for example, take $X=\mathbb{R}$, $A=\{0,1\}$, $A'=\{1\}$, and $B_n=\{\frac1n,1\}$.
Intersection is jointly continuous for closed convex sets in $\mathbb{R}^d$, at points where the intersection has interior.  Precisely: if $K,K_n,L,L_n$ are closed convex sets in $\mathbb{R}^d$, and $K_n\to K$ and $L_n\to L$ in Hausdorff metric, and $\text{int}(K\cap L)\ne\varnothing$, then $K_n\cap L_n\to K\cap L$.
Comment: I changed my mind.  See Theorem 1.8.8 in Schneider's *Convex Bodies: The Brunn–Minkowski Theory*.  (Actually, it looks like his statement is a bit stronger than mine, since it allows the limit sets to be not full-dimensional.)
Comment: (in #2, you probably meant $A'=\{1\}$?)
Comment: @ErelSegalHalevi I sure did!  Fixing it now, thanks.
Comment: About #3: can you give reference? I would like to check whether this fact can be generalized for some families of non-convex sets.
Comment: I don't have a reference, unfortunately, and the proof I know depends heavily on convexity.  I'll add it to the answer.
Comment: Thanks for the detailed answer.


iOS IAP Cannot connect to iTunes Store

Question: I am testing my app in Xcode . witch means it is not officially up loaded to the appstore. so I can't test the real IAP right? I can only test the sandbox IAP before it officially online in APP store,right?
because when I use the real app id to test the IAP. it always give me error like:
<code>_error  NSError *   domain: @"SKErrorDomain" - code:
 @"Cannot connect to iTunes Store"
</code>
I have checked every thing, all fine. and the sandbox test was also worked fine. so the only reason of the error is the app are not officially online in apptore , am I right?
Comment: Are you testing on a real device or the simulator?  You cannot test IAP on the simulator; you must test on a real device
Answer: IAP can be tested only in sandbox mode with sandbox(test) user account in device.
If you are testing IAP in a sandbox mode with real iTunes apple account in the device, then the error Cannot Connect to iTunes Store is shown.
Comment: Thankyou, but what do you mean by "sandbox mode", I think the IAP code is the same except the vertify aip :'https://sandbox.itunes.apple.com/verifyReceipt' and 'https://buy.itunes.apple.com/verifyReceipt ' right? @Hooda
Comment: sandbox mode simply means development(testing) mode.

iOS IAP Cannot connect to iTunes Store


Very simple MySQL SELECT statement causing error

Question: Working out of an SQL book. (Using MySQL Workbench to run queries).
I'm running the following query
SELECT * FROM people;

Which produced the following error:
Error: Error formatting SQL query; empty string given as argument for ! character

I'm not sure what this error means.
For reference, a DESC of the people table is here:
Field               | Type        | Null | Key | Default | Extra

id                  |int(11)      |NO    |PRI  | NULL    | auto_increment
last_name           |varchar(50)  |YES   |     | NULL    |
first_name          |varchar(50)  |YES   |     | NULL    |

Comment: Could be a PEBKAC. "You have to double click on database name in the left panel to become bold."

Cfr https://teamtreehouse.com/forum/error-executing-query
Comment: Duplicate of http://stackoverflow.com/questions/27132697/mysql-error-empty-string-given-as-argument-for-character
Comment: The above query was prefaced by the appropriate `USE` command, but I guess the schema selection got lost somewhere along the way. Why did the `DESC` command still work in this case?
Answer: You probably didn't selecte a database
Comment: Try select it by double click
Comment: The above query was prefaced by the appropriate `USE` command.
Answer: You have to double click on the database in the left panel so that it becomes bold.


Prove that $\|x\|_A$ is a vector norm.

Question: Prove: A is a positive definite symmetric matrix and
$\forall x \in \mathbb{R^n}$ define $||x||_A$ by $||x||_A=\sqrt{x^TAx}$
Show $||x||_A$ is a vector norm.
Comment: I'm not sure what you're trying to prove. As far as I know, something is a vector norm if it satisfies the three axioms of a norm, and the term "vector" is used to contrast "matrix norm".
Answer: First of all, it is not necessarily true that $||x||_A=\sqrt{x_1^2+x_2^2+...+x_n^2}=\sqrt{x^Tx}$ must be satisfied (and in general it won't be for a positive definite $A$).  Also, I have no idea what you could possibly mean by "choose $Ax = x$".
Hint: Note that there must exist an invertible matrix $U$ such that $\|x\|_A^2 = (Ux)^T(Ux)$.  Now, it'll be easy to show that this function satisfies the requirements of a norm.

Prove that $\|x\|_A$ is a vector norm.


How to compute $\frac{d}{dt} \int_{a(t)}^{b(t)} f(x,t) dx$

Question: I want to differentiate $ \int_{a(t)}^{b(t)} f(x,t) dx$ this integral with respect to $t$ $i.e$,
\begin{align}
\frac{d}{dt} \int_{a(t)}^{b(t)} f(x,t) dx
\end{align}
I only know for the case of constant $a,b$. For this case how can i differentiatie?
Answer: Consider the function
$$ F(t, A, B) := \int_A^B f(x,t)\,dx $$
Then the integral in question is $I(t) = F(t, a(t), b(t))$. The chain rule gives
$$ I'(t) = \partial_t F + \partial_A F \cdot a'(t) + \partial_B F \cdot b'(t) $$
Therefore,
$$ I'(t) = \int_a^b \partial_t f(x,t)\, dx - f(a(t),t)a'(t) + f(b(t),t)b'(t) $$
Answer: $$\frac{db(t)}{dt}\times f(b(t),t)-\frac{da(t)}{dt}\times f(a(t),t)+\int_{a(t)}^{b(t)}\frac{\partial f(t,x)}{\partial t} dx$$
For more details , see Leibniz integral rule.


How to config Nginx runs php on sub directories?

Question: I have 2 versions of portfolio website for 2 languages. I put them in 2  dir in the same root dir.
/root/
    |----vi/
    |----en/
    |----index.php

Then I config nginx as below:
server {
    listen 8080;
    server_name 192.168.0.117;

    access_log /u01/projects/company/log/access.log main;
    error_log /u01/projects/company/log/error.log;
    set $rootLocation /u01/projects/company/;

    root $rootLocation;
    index index.php;

    charset utf-8;
    client_max_body_size 100m;

    location ~* /(vi|en)/admin(/|/.*\.php)$ {
       try_files $uri $uri/;
       gzip on;
       index index.php;
       include fastcgi_params;
       fastcgi_pass 127.0.0.1:9000;
       fastcgi_index index.php;
       fastcgi_param SCRIPT_FILENAME $rootLocation$fastcgi_script_name;
    }

    include common.conf;#some fastcgi config
}

Look at location, I have admin/ dir (and run php directly here) for every version. But when I access 192.168.0.117/en/admin/, browser always redirect to 192.168.0.117/en/index.php. What is wrong with this configuration? How to fix it?
Answer: The problem is here:
       try_files $uri $uri/;

By doing this you explicitly told it to redirect to index.php. A trailing / in a try_files means to try the value of the index directive.
In a PHP-FPM location this should instead be:
       try_files $uri =404;


What to do about a sketchy question

Question: lets say someone asks the question
how can i hack a magento site?
i mean not that way, but in a more round-a-bout way
personally this is something in my opinion that should be flagged and removed
is there a way to flag and remove the question
i am specifically referring to this question
Scraping data from Magento without privileged access or trust
which while might be useful, I mean maybe slightly might be useful, seems like a persons way of asking how to scrape a site without permission from the author, which sounds really bad to me
Answer: There aren't a density of these which I've noticed (or they have been flagged & closed by other mods), so we can handle these on a case by case basis.
The question cited seems legit.
Comment: Im just so security conscious with my server, and when i see something like that... something i could answer in like 5 seconds with a simple bash script... something i think anyone with any magento admin experience could handle easily I just get overly cautious
Comment: No harm in that perspective.
Answer: I would in general say close them with reason to broad.
Also add a link to the owasp.org website
For this specific case, still to broad. And its mostly basic knowledge of html parsing.

What to do about a sketchy question


Childbrowser with phonegap on Android?

Question: I can't get the childbrowser to work on Android.
I have followed the instructions on: https://github.com/brycecurtis/phonegap-plugins/tree/master/Android/ChildBrowser/
I have installed Eclipse and all the other stuff needed to compile an
app and all works as it should.
It is running in the emulator and I can also create an apk file.
So now I'm trying to get the childbrowser to work, like below.

I added the childbrowser.java file in my workspace/appname/
src/com/phonegap/plugins/childBrowser/ folder.
And the childbrowser.js file in my workspace/appname/assets/www/
folder.
I have linked to the phonegap.0.9.4.js and the childBrowser.js
files in my index file.
I added this in the manifest file

>     <activity android:name="com.phonegap.DroidGap"
> android:label="@string/app_name">
>             <intent-filter>
>             </intent-filter>
>             </activity>

The link that should open the childbrowser looks like this:

   Open

And it still isn't working? I'm just testing in the emulator as I don't have a android phone here right now, isn't the childbrowser working in the emulator?
Or have I missed something else?
Thanks.
Answer: I use phonegap.0.9.4.js as well and it is working for me. The childBrowser should work after PhoneGap JS throws event 'deviceready'. So I added the following code.
var url="http://www.google.com";

document.addEventListener("deviceready", onDeviceReady, false);

function onDeviceReady() {
    window.plugins.childBrowser.showWebPage(url);
}

Some tips, as I encountered some issues as well:

The javascript file I downloaded is childbrowser.js, all lowercase, not childBrowser.js
Make sure that ChildBrowser.java is compiled in the correct folder. Check eclipse bin folder
For an external web page use http:// in front.
The Javascript is a different for Android and iPhone. For example on Android you do not call ChildBrowser.install(); So example code is also different for iPhone/Android/BlackBerry
Answer: Try using phonegap.0.9.5.js  and let knw if you have any problem.I followed the same link its working fine.
Answer: Check Eclipse's BuildPath.
Some Eclipse versions have a Build Path entry in the context-sensitive right-click on a file/folder, some you have to go to the root folder, right-click and select 'Properties', select 'Java Build Path', then select the 'Source' tab.
Verify your src folder includes 'All', and it and it's subfolders and the ClassBrowser.java file are not Excluded.
Also, create or open the res/xml/plugins.xml file and add this line in source mode:
<plugin name="ChildBrowser" value="com.phonegap.plugins.childBrowser.ChildBrowser" />
Also note Aschwin's tips.
Answer: Change:
a href="#" onClick="window.plugins.childBrowser.showWebPage("thewebpage.html");"

To:
a href="#" onClick="window.plugins.childBrowser.showWebPage('thewebpage.html');"

The double quotes are likely what is keeping it from working. I see this is an old post, but maybe this will help someone else.

Childbrowser with phonegap on Android?


Differentiate of the form $y=AB^x$

Question: Two points $P(2,5)$ and $Q(4,6)$ lies on a curve $y=AB^x$.
Calculate the rate of change at point P.
Using these two points we can determine the curve equation:
$5=AB^2$ and $6=AB^4$
$\frac{AB^2}{AB^4}=\frac{5}{6}$
$B=\sqrt{\frac{6}{5}}$
$A=5\times \frac{5}{6}=\frac{1}{6}$
$y=\frac{1}{6}\left(\sqrt{\frac{6}{5}}\right)^x$
To find the rate of change; $\frac{dy}{dx}$
This is the part I can't do.
$\frac{d}{dx}\frac{1}{6}\left(\sqrt{\frac{6}{5}}\right)^x=?$
Comment: by the way, $A = \frac{25}{6}$; just a small arithmetic error
Answer: HINT:$$y = AB^x$$
$$\implies\frac{dy}{dx} = AB^x\ln(B)$$
[since, $\frac{d}{dx}a^x = a^x\ln(a)$]
Answer: Suppose $y = a^x$. I assume you know that exponential and logarithms are inverses, which means if $\xi > 0$ then $\xi = e^{\ln(\xi)}$. Now, we have
\begin{align}
y &= a^x \\
&= e^{\ln(a^x)} \\
&= e^{x \ln(a)},
\end{align}
the last line is a property of logarithms. Now, remember that $\ln(a)$ is just a constant, so applying the chain rule tells us
\begin{align}
\dfrac{dy}{dx} &= \ln(a) \cdot e^{x \ln(a)} \\
&= \ln(a) \cdot a^x
\end{align}
(Notice how this is almost like $\dfrac{d}{dx}(e^x) = e^x$, except for the constant $\ln(a)$)
Answer: The full explanation of the derivative of $y = a^x$ is $\frac{dy}{dx} = \ln(a)\cdot a^x\cdot \frac{dy}{dx}(x) = \ln(a)\cdot a^x \cdot 1 = \ln(a)\cdot a^x$.
Hence the derivative of $y = a^{x^2}$ is $\frac{dy}{dx} = \ln(a)\cdot a^{x^2}\cdot 2x$
The derivative of $y = AB^x$ is $\frac{dy}{dx} = \ln(B)\cdot AB^x\cdot \frac{dy}{dx}(x) = \ln(B)\cdot AB^x \cdot 1 = \ln(B)\cdot AB^x$.
The derivative of $y = e^x$ is therefore $\frac{dy}{dx} = \ln(e)\cdot e^x\cdot \frac{dy}{dx}(x) = 1\cdot e^x\cdot 1 = e^x$

Differentiate of the form $y=AB^x$


How to choose $\gamma$ parameter in Focal Loss?

Question: I would like to know if exists a rule of thumb to set the $\gamma$ parameter in Focal Loss when we have very imbalanced classes.
The focal loss first appeared in Focal Loss for Dense Object Detection by Tsung-Yi Lin, Priya Goyal, Ross Girshick, Kaiming He, Piotr Dollár
Comment: (for anyone who's stumbled upon this thread) I'm doing some time series anomaly detection and focal loss wasn't working for me until I set gamma=20, so don't shy away from trying super high values, sometimes that's what you need to do!
Answer: The parameter $\gamma$ smoothly adjusts the rate at which easy examples are down-weighted and that is quite dataset and application dependent. In the paper, the focal loss is actually given as: $−\alpha (1 − p_t)^\gamma \log(p_t)$ which is a reformulated view of the standard cross-entropy loss and the class imbalance itself is "controlled" by $\alpha$ rather than $\gamma$.
People often treat the focal loss as a tool to primarily address class imbalance whether it is actually a tool to primarily address information asymmetry during learning; i.e. focal loss can very relevant when training with a balanced set where one of the two classes is easy to distinguish.
But to bring us back: there is no good rule of thumb aside setting $\gamma=2$ (as the paper suggests) and then adjusting it based on our evaluation criteria.
This point highlights the difference between a loss function and an evaluation metric; CV.SE has thread on Loss function and evaluation metric if you want to explore this distinction further but the main point to carry  here is that $\gamma$ (i.e. a hyper-parameter of our loss) needs to be adjust in relation to our evaluation criteria and "on it's own" is often meaningless.
Answer: On page 3, the authors write "we found $\gamma = 2$ to work best in our experiments." This tells us that they chose $\gamma$ experimentally by training models with different values and then choosing the $\gamma$ from the best model. Because this value was chosen experimentally, it may not be the best choice across all modeling tasks or datasets.
You might use $\gamma =2$, with the reasoning that the paper authors found that to be the best value. Alternatively, you can tune $\gamma$ experimentally (assuming you have the resources to do so).


How to set collation for table attribute as utf8_bin in either annotation or application.properties file using Spring Boot

Question: How do I set the collation for table attribute as utf8_bin in either annotation or the application.properties file using Spring Boot?
I have tried many ways but they did not work. Can you help?
I have tried the following ways.
First: Using @Column annotation like this:
@Column(name = "user_id",columnDefinition="VARCHAR(255) COLLATE utf8_bin")

Second:
 @Column(columnDefinition="VARCHAR(255) CHARACTER SET utf8 COLLATE utf8_bin")

Third: Using application.properties file
spring.jpa.properties.hibernate.connection.characterEncoding=utf-8
spring.jpa.properties.hibernate.connection.CharSet=utf-8
spring.jpa.properties.hibernate.connection.useUnicode=true
spring.jpa.properties.hibernate.connection.collationConnection=utf8_bin

Fourth:
spring.datasource.url =jdbc:mysql://localhost:3306/iot_schema?createDatabaseIfNotExist=true&useUnicode=true&connectionCollation=utf8_bin&characterSetResults=utf8

Comment: Have any one come out solution for this issue, as I am facing this issue. Please post your answer.
Answer: Here's a solution inspired by answer to similar question: Set Table character-set/collation using Hibernate Dialect?
Extend the preferred MySQL dialect and override its getTableTypeString() method like this:
public class MySQLCustomDialect extends MySQL8Dialect {
    @Override
    public String getTableTypeString() {
        return " ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin";
    }
}

Set that class to be used in application.properties:
spring.jpa.properties.hibernate.dialect=my.package.MySQLCustomDialect

Here's the generated SQL query:
    create table test_table (
      ...
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin

EDIT 3/2022
As of Hibernate 6 all version specific MySQL dialect classes are deprecated and MySQLDialect should be used instead. By default it sets dialect version to 5.0. That can be fixed by specifying the required version explicitly, for example:
public class MySQL8UnicodeDialect extends MySQLDialect {

    private static final int MY_SQL_DIALECT_VERSION_MAJOR = 8;

    public MySQL8UnicodeDialect() {
        super(DatabaseVersion.make(MY_SQL_DIALECT_VERSION_MAJOR));
    }

    @Override
    public String getTableTypeString() {
        return " ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci";
    }
}

Comment: It was my problem, too. Your solution helped a lot, thanks!


Composite Function Equality

Question: Let f, g be functions$: \mathbb{R} \mapsto \mathbb{R}$ with $f(x)=x^2+ax+b$ with $a,b \in \mathbb{R}$, such that $(f\circ g)=(g\circ f)$.
If the equation $g(x)=x$ has precisely one solution for all $x \in \mathbb{R}$, prove that $(a-1)^2=4b$.
Comment: Does "**only** one solution" mean precisely one, or at most one?
Comment: @DanielFischer You are right. Precisely One. Edited.
Answer: From $f \circ g = g \circ f$ it follows that:
$$ g^2(x) + ag(x) + b = g(x^2 + ax+b)$$
Now we plug into the above equation $x^*$ which is the unique solution of $g(x^*)=x^*$ and we get:
$$g^2(x^*) + ag(x^*) + b = g(x^{*2}+ ax^*+b)$$
and then:
$$ x^{*2} + ax^* + b = g(x^{*2} + ax^* + b) $$
But then $\tilde{x} = x^{*2} + ax^* + b$ also solves the above equation, i.e. $g(\tilde{x})=\tilde{x}$. By uniqueness of the solution we get $\tilde{x} = x^*$. Plugging in again into the definition of $\tilde{x}$ we see that:
$$ x^{*2} + (a-1)x^* + b = 0 $$
Thus the quadratic equation $x^2+(a-1)x+b=0$ has at least one solution, namely $x^*$.
EDIT: Before I claimed that in fact it only has one solution. But as Karl Kronenfeld pointed out in his answer, this is false (in fact the original question is false).
Nevertheless the above steps are still correct and because the quadratic has at least one solution, it follows that $(a-1)^2 \geq 4b$ (but equality does not necessarily hold).
Comment: Yes, $f(x)=x$ may have multiple solutions--just have $g$ map all of them to $x^{\ast}$.
Comment: I don't think you can delete accepted answers. An edit explaining the error is typical, though I am no expert on MSE etiquette.
Comment: Yes, +1 for the statement and proof of the (correct) inequality.
Comment: The key point is that the solution to $g(x)=x$ is unique, while the quadratic equation is actually $f(x)=x$. My arguments above show that from $g(x^*)=x^*$ it follows that $f(x^*)=x^*$. The problem is that this implication does not go into the other direction: So assume there exists another $x^{**} \neq x^*$ with $f(x^{**})=x^{**}$. It then does not follow that $g(x^{**}) = x^{**}$. What actually follows (can be shown) is simply that $g(x^{**}) = x^{**}$ OR $g(x^{**}) = x^{*}$. So for a counterexample you just need $f$ with 2 solutions to $f(x)=x$ and $g$ which maps both to the first solution.
Comment: Gah, I was just taking a walk when I realized that I had screwed up and wanted to build a counterexample , but you beat me to it. What is the etiquette in such cases, do I delete my answer?
Comment: Thank you, I updated my post accordingly.
Comment: Well, you need to have precisely one solution in the quadratic equation, or else there could be two solutions which contradicts the hypothesis of the original question, that $g(x)=x$ has strictly one solution for all $x \in R$.
Comment: No you don't, look at Karl Kronenfeld's counterexample.
Comment: OK, I accept the counterexample. But what is the error in considering that the quadratic has only one solution? Why can it have two (since the solution has to be unique)?
Comment: I would like to add the following to the question and would like to be given a counterexample **with the following taken into consideration**:

$a\neq 0 \text{ and } b\neq 0 \text{ and } g(x)\neq c, c\in \mathbb{R} \text{ and } g(x)\neq x^n, n\in \mathbb{Z}^*$
Answer: This is false. Define $f$ and $g$ by
$$f(x)=x^2+ax \qquad\text{and} \qquad g(x)=0.$$
We have, for all $x$, $f(g(x))=f(0)=0$ and $g(f(x))=0$. Thus, the condition $f\circ g=g\circ f$ holds. Moreover, $g(x)=x$ if and only if $x=0$. So, $g(x)=x$ has a unique solution.
Yet, the coefficient $a$ is arbitrary, so $(a-1)^2$ can certainly take nonzero values, contradicting the claim in the OP.
Comment: @air I would like to add the following to the question and would like to be given a counterexample **with the following taken into consideration**:

$a\neq 0 \text{ and } b\neq 0 \text{ and } g(x)\neq c, c\in \mathbb{R} \text{ and } g(x)\neq x^n, n\in \mathbb{Z}^*$
Comment: @Jason The a,b nonzero condition should have a negligible effect. I suspect a counterexample still exists, even given those conditions on $g$.
Answer: From the equallity, we have
$g^2(x) + ag(x) + b = g(x^2 + ax + b)$
If we have a solution $c$ for $g(x) = x$, so:
$c^2 + ac + b = g(c^2 + ac + b)$
But from the unicity of the solution of $g(x) = x$, we have
$c^2 + ac + b = c \implies c^2 + (a-1)c + b = 0$
If $\Delta < 0$, then there no exist such $c$. If $\Delta > 0$, then we would have other solution different from $c$ to $g(x) = x$. So, $\Delta = (a-1)^2 - 4b = 0$

Composite Function Equality


Cannot access member of a class through object reference

Question: The following code executes without error and prints "In some", which means that the statement
m[0].Invoke(o, args);

invokes the function some which is a member of the foo class, on object o and affects its public variable i. But when we uncomment the last line of the code and try to compile it, it produces an error. Why??
using System;
using System.Reflection;

class foo
{
    public int i;
    public foo(int ii = 0)
    {
        i = ii;
    }
    public void some(int ii)
    {
        i = ii;
        Console.WriteLine("In some ");
    }
}

class main
{
    static public void Main()
    {
        foo f = new foo();
        object o = new foo();

        Type t = typeof(foo);

        object[] args = new object[1];
        args[0] = 9;
        MethodInfo[] m = t.GetMethods();
        m[0].Invoke(o, args);
        //Console.WriteLine(o.i);
    }
}

Answer:
But when we uncomment the last line of the code and try to compile it, it produces an error. Why??

Because you've declared o as System.Object, which doesn't have a variable i defined on it as far as the compiler is concerned.  You'd need to either cast it to the known type, or use reflection to retrieve this value.
For example:
// You can cast here, since you know the type
foo oAsFoo = o as foo;
Console.WriteLine(oAsFoo.i);

Alternatively, use reflection to get the value:
FieldInfo field = t.GetField("i");
Console.WriteLine(field.GetValue(o));

Answer: You need to cast the o too foo in order to execute it.
Console.WriteLine(((foo)o).i)

C# is a statically typed (typed safe) language and only allows type
  safe operations and as there is no public member i of class
  object therefore it is not allowed by the compiler.
Answer: o is of type object which can hold object of any type but instance of object can not access the attributes of assigned class object.
Type casting to its respective class make the public members accessible like this.
Console.WriteLine(((foo)o).i)


Regarding Chapter 11 of Eloquent Javascript 3rd Edition

Question: I'm reading through Chapter 11 of Eloquent Javascript 3rd Edition (link: https://eloquentjavascript.net/11_async.html) and I'm having a hard time getting the following line of code to work:
routeRequest(bigOak, "Church Tower", "note", "Incoming jackdaws!");

The code works in the interactive sandbox, but if I try to run that line of code myself (saved the files https://eloquentjavascript.net/code/chapter/11_async.js & https://eloquentjavascript.net/code/crow-tech.js in a local directory, added the above code snippet to the 11_async.js file and ran "node 11_async.js") it returns an error, "Error: No route to Church Tower". The only way it will work is if i run with some setTimeout:
setTimeout(() => {
  routeRequest(bigOak, "Church Tower", "note", "Incoming jackdaws!");
}, 3000)

This makes sense to me because it takes some time to propagate all the connections, but the chapter/author doesn't describe the need to run with a setTimeout/delay and I am wondering if I'm missing something...
Appreciate any help...
Comment: What is the error?
Comment: Please [edit] your question to include all relevant information and code. Links to off-site services are fine as supplementary information but everything required to understand your question should be here. See [How to create a Minimal, Reproducible Example](https://stackoverflow.com/help/minimal-reproducible-example) (with particular focus on the **minimal**)
Comment: The error is "Error: No route to Church Tower", whereas with the setTimeout i get a successful "Church Tower received note: Incoming jackdaws!" message...
Comment: I'v just come across the same problem running the code on my environment. With delay times somewhere below 1000ms the error occurs again.
Answer: The Eloquent also has a sandbox. Please check the file "crow-tech.js". This has  code that specifically waits for 500ms so that routeRequest, findInStorage, and chicks work only after the network information has propagated.
if (typeof __sandbox != "undefined") {
    __sandbox.handleDeps = false
    __sandbox.notify.onLoad = () => {
      // Kludge to make sure some functions are delayed until the
      // nodes have been running for 500ms, to give them a chance to
      // propagate network information.
      let waitFor = Date.now() + 500
      function wrapWaiting(f) {
        return function(...args) {
          let wait = waitFor - Date.now()
          if (wait <= 0) return f(...args)
          return new Promise(ok => setTimeout(ok, wait)).then(() => f(...args))
        }
      }
      for (let n of ["routeRequest", "findInStorage", "chicks"])
        window[n] = wrapWaiting(window[n])
    }
  }


React v4 navigation

Question: I'm building a web app with React and I'm using React Router v4 for navigation. Basically what I want to do is, on my signup page once the promise is fulfilled (the user signing up) I want the site to go to a new page. What is the best way to accomplish this?
Thanks for your help.
Answer: The best way to do that would be to render a redirect so your code might look like something like this
<code>this.state = {
  redirect: false,
}

onSubmit() {
   Promise().then(res => this.setState({ redirect: true })
}

render() {
  redirect ? <Redirect to="/path" /> : <ShowSignUpForm />
}
</code>
you should take a look at the docs
https://reacttraining.com/react-router/web/api/Redirect
Comment: no problem you should take a loko at the docs react router has got some pretty good ones! Good Luck

React v4 navigation


Github New line missing end of file: Negative consequences

Question: We have a Java code pull request with Swagger. It's missing the new line character in end of YAML file. What are the consequences of not having new line character?
Curious if we should enforce policy at company, too many people are forgetting to do this. Takes lot of time, however researching how it effects our codebase/system.
Answer: The main consequence is regarding git diff: when you are diffing files, not having a newline at the end can result in misleading diffs. Tools like git will show changes in lines that have not fundamentally changed, just because a newline was added.
Not having a newline can sometimes increase the likelihood of encountering merge conflicts.
See more at "What's the significance of the "No newline at end of file" log?".
Other consequences:

Some tools expect a newline at the end of files and may not behave as expected if a newline is missing. That could include text editors, compilers, and others.
Certain YAML parsers may expect files to end with a newline and may throw errors or behave unexpectedly if a newline is missing.

Plus, regarding the code style, not having a newline at the end of a file can sometimes make code less readable, as it can result in the last line of code being "joined" with the command prompt in terminal-based text editors.

You can enforce it:

from the client side:

IDE: integrated development environments (IDEs) and text editors have settings that can be configured to automatically add a newline at the end of files upon saving, which can help to enforce this policy without requiring additional effort from developers. It can be a good practice to encourage developers to configure their development environments to automatically add a newline at the end of files to avoid these potential issues.

content filter driver "smudge", with a *.yaml filter=ensure_newline in the .gitattributes, and local activation of that filter with git config filter."encure_newline".smudge /path/to/your/ensure-newline.sh + git config filter."encure_newline".clean cat: I prefer it to a pre-commit hook which would have a harder time to be limited to *.yaml file, and would only reject the commit (as opposed to add the missing trailing newline).

Regarding the last option, the ensure-newline.sh script would be:
#!/bin/bash

# Check if the file ends with a newline, and if not, add one
if [ "$(tail -c1)" != "" ]; then
    echo ""
fi

# Pass the file contents through unchanged
cat

from the server side

pre-receive hook, to prevent pushing a commit with the wrong content

a GitHub Action, preventing any PR to be merged with the wrong content.

For the pre-receive hook, the script would be:
#!/bin/bash

# Iterate over every ref being pushed
while read oldrev newrev refname; do
  # Get the list of files in the push
  files_in_push=$(git diff --name-only $oldrev $newrev)

  # Check each file in the push
  for file in $files_in_push; do
    # If the file ends with .yaml, check if it ends with a newline
    if [[ $file == *.yaml ]]; then
      file_content=$(git show $newrev:$file)

      # If the file does not end with a newline, reject the push
      if [[ "$file_content" != *"\n" ]]; then
        echo "Rejected push: $file does not end with a newline."
        exit 1
      fi
    fi
  done
done

# If we reached here, all checks passed
exit 0

For the GitHub Action, the .github/workflows/check_newline.yml would be:
name: Check Newline at EOF

on:
  pull_request:
    paths:
      - '**.yaml'

jobs:
  check_newline:
    runs-on: ubuntu-latest

    steps:
      - name: Checkout code
        uses: actions/checkout@v3

      - name: Check Newline at EOF
        run: |
          PR_NUMBER=$(echo $GITHUB_REF | awk 'BEGIN { FS = "/" } ; { print $3 }')
          FILES_CHANGED=$(curl -s -X GET -G https://api.github.com/repos/$GITHUB_REPOSITORY/pulls/$PR_NUMBER/files | jq -r '.[] | .filename')
          for FILE in $FILES_CHANGED; do
            if [[ "$FILE" == *.yaml ]]; then
              if [ "$(tail -c1 "$FILE")" != "" ]; then
                echo "File $FILE does not end with a newline. Please add a newline at the end of this file."
                exit 1
              fi
            fi
          done


Data truncation: Truncated incorrect DOUBLE value:

Question: I have been trying to solve this for hours and I have no idea why this is happening. I keep on getting this error when trying to update one of my "Employees" with my GUI that I made.
com.mysql.jdbc.MysqlDataTruncation: Data truncation: Truncated incorrect DOUBLE value: 'test'

Whenever I click an employee in my TableView, and then change the field of something, I would get that. Here is a picture of my GUI:

Nothing in my data table is a DOUBLE, they all are like this:

I have googled everywhere and it all says it relates to syntax for my SQL query but that looks fine so I do not know why.
Here is the code for my Update button:
public void handleUpdateEmployee(ActionEvent event) {
    String sql = "UPDATE employees set firstName = ?, lastName = ?, gender = ?, age = ?, position = ?, image = ? where employeeNum =?";
    try {
        Integer employeeNum = Integer.valueOf(employeeNumField.getText());
        String firstName = firstNameField.getText();
        String lastName = lastNameField.getText();
        String gender = genderField.getText();
        Integer age = Integer.valueOf(ageField.getText());
        String position = positionField.getText();
        String image = imageField.getText();

        pst = con.prepareStatement(sql);
        pst.setInt(1, employeeNum);
        pst.setString(2, firstName);
        pst.setString(3, lastName);
        pst.setString(4, gender);
        pst.setInt(5, age);
        pst.setString(6, position);
        pst.setString(7, image);

        pst.executeUpdate();
        loadEmployeeData();

    } catch (SQLException e) {
        e.printStackTrace();
    }
}

Would appreciate any help and if you need any more details, let me know!
Answer: You bound your query parameters in the wrong order.  Look closely at the statement and then the updated code which follows:
String sql = "UPDATE employees set firstName = ?, lastName = ?, gender = ?, ";
sql += "age = ?, position = ?, image = ? where employeeNum =?";

pst.setString(1, firstName);  // first parameter (?) in statement
pst.setString(2, lastName);
pst.setString(3, gender);
pst.setInt(4, age);
pst.setString(5, position);
pst.setString(6, image);
pst.setInt(7, employeeNum);   // LAST parameter (?) in statement

Comment: Ah! I feel so stupid. Thank you so much! Everything works now :)


Is there a closed form for the product of odd zetas?

Question: $$\prod_{n=1}^\infty \zeta(2n+1)=\zeta(3)\zeta(5)\cdots$$
I have only managed to prove that this converges due to comparison with Euler's formula for $\zeta(2n)$
Is there a closed form for that product?
Answer: Currently, there is no known closed form. See OEIS A$080730$, along with OEIS A$080729$ and OEIS A$021002$.


recursive automata, or recursion mod 2.

Question: Consider the list of length $m$ $(1,0,\dots 0)$ we call this list $l_1$, we now define a sequence of lists recursively, where $l_1$ is the previous list, and if $l_n$ is the list $(a_1,a_2\dots a_n)$ then $l_{n+1}$ is the list $(a_1+a_2,a_2+a_3, \dots ,a_{n-1}+a_n,a_n+a_1)$ where all of the operations are done in $\mathbb Z_2$. In other words all the numbers in the lists are 1 or 0 and we use the rules $1+0=0+1=1$ and $1+1=0+0=0$.
The question is whether we can calculate what $l_n$ is for arbitrary values of $m$ and $n$.
Thank you very much in advance.
Regards.
Comment: You will actually never return to the list $(1,0,\ldots 0)$. You can show that if you apply this operation to any list, the resulting list will have an even number of $1$s.
Comment: By those rules and for $m=2$ we have $(1,0),(1,1),(0,0),(0,0),...$. Doesn't go back to $(1,0)$. Since $1+0=0+1$ and $1+1=0+0$, replacing all the $1$s with $0$s and vice versa will achieve the same successor.
Comment: oh, that's right, my bad.
Answer: Your problem can be phrased in terms of the addition mod 2 cellular automaton (CA) as follows:
The alphabet is $\mathbb{Z}_2=\{0,1\}$ the integers mod 2, the transformation you apply to the list is the elementary cellular automaton RULE 102 whose rule sums the symbol and its right neighbour. Your list is the finite set of cells on which you apply the CA. As you are doing this cyclically, i.e. summing $a_i$ and $a_{i+1}$ for $1\leq i<m$ and at the very end summing $a_m$ and $a_1$, this corresponds to $m$-periodic boundary configurations, i.e. you start the CA with a periodic configuration of the form $c:=\ldots 0^{m-1}\,1\,0^{m-1}\,1\,0^{m-1}\,1\,0^{m-1}\ldots$
The list $l_n$ is then the $n$th row of the space-time diagram of this CA started with $c$.
Now what you are asking is exactly what the $n$th line of this space-time diagram looks like.
See: http://mathworld.wolfram.com/Rule102.html for some background.
Comment: Also if the length of your list is a power of 2, it is easy to predict what happens. (Think about the Sierpinski triangle or Pascal's triangle mod 2 to understand this.)

recursive automata, or recursion mod 2.


Index of p-subgroup divisible by p implies normalizer index divisible by p

Question:
Show that if $H$ is a $p$-subgroup of $G$ with $p$ dividing $[G:H]$, then $[N_G(H):H]$ is divisible by $p$.

By considering the action of $H$ on $G/H$. I've considered the $\varphi:H\to S_{G/H}$ and tried a lot of things, I just fail to see how the relevance of the normalizer will solve this problem.
Comment: Apparently theres also a way to solve this from the fact that $H$ is contained in a Sylow p-subgroup, and I don't know how this argument proceeds, and would really like to see that approach
Comment: 3(b) on http://www.math.toronto.edu/~herzig/1100-hwk2-oct16.pdf
Comment: @Unit that doesn't have any solutions, why do you give me that website?
Answer: $\newcommand{\Size}[1]{\left\lvert #1 \right\rvert}$$\newcommand{\Set}[1]{\left\{ #1 \right\}}$Consider the action of $H$ by multiplication on the right on the set of cosets
$$
G/H = \Set{ H x : x \in G}.
$$
So $h \in H$ sends the coset $H x$ to the coset $H x h$.
Since $H$ is a (finite) $p$-group, of order $p^{n}$, say, the orbits will be of size a divisor of $p^{n}$. Let $s_{i}$ be the number of orbits of size $p^{i}$, then
$$
\Size{G : H} = \Size{G/H} = \sum_{i=0}^{n} s_{i} p^{i}.
$$
Since $\Size{G : H}$ is divisible by $p$, we obtain that $s_{0}$ is divisible by $p$.
Now you know that there is at least one orbit of size $1$, namely the orbit of the coset $H = H 1$. So $s_{0} > 0$, and since it is divisible by $p$, $s_{0} \ge p$.
Now for all $H x$ such that $H x$ has length $1$ we have $H x H = H x$.
Now show that $x \in N_{G}(H)$. Conversely, show that if $x \in N_{G}(H)$ we have that $H x$ has an orbit of length $1$.
Comment: I assume this approach is to avoid using Sylow's theorems, which give the claim directly?
Comment: In its original  formulation, the problem *required* to use the action of H on the cosets of H.
Comment: how would we use Sylow?
Comment: Ahh, that explains it. @eeserboy By Sylow's theorems $H$ is a proper subgroup of a $p$-subgroup of $G$, and its normalizer will thus contain something extra from this subgroup.
Comment: why does it being a proper subgroup of a p-subgroup of G imply the normalizer of H in G contains something extra from H?
Answer: It's sufficient to assume Z(G) is a subgroup of H and note that Z(G) is non-trivial
Now u can use induction on o(G) and get a simple.proof for finite groups by considering  G/Z(G) and H/Z(G)
Also u can consider X is the set of all conjugates of H. Then G acts in X by conjugation and hence Card(X)= [G:N(H)] now if u assume N(H)=H then H also acts on X and H is an orbit of size 1 there are at least p-1 orbits of size 1 . Thus there exists some conjugate say gHg^-1 not equal to H which is invariant under conjugacy by each element of H thus u get g belongs to N(H) and hence gHg^-1 = H a contradiction


Extract Input parameters from "mxnet" model

Question: I have saved the model using
mx.model.save(model = fit_dl, prefix = "model", iteration = 10)

and loaded later
fit <- mx.model.load(prefix = "model", iteration = 10)

Now, using object fit, I want to extract the input features (column names of train data). How to do that
Answer: Posting for sake of all open source community
As per my email exchange with maintner of mxnet packge, Qiang Kou  replies following
From: Qiang Kou
To: Shiv Onkar Kumar
Sent: Wednesday, 14 June 2017 10:33 PM
Subject: Re: Extract Input parameters from "mxnet" model
Hi, Shiv,
I don't this is possible since we never store this information in the model.
Best,
Qiang Kou


APN is not specified?

Question: iam creating httpConnection ,but when run the application it gives following exception ?
java.io.IOException
APN is not specified ?
Comment: it says Access Point is not specified ,
Comment: What type of connection are you using ? If possible post some code also.
Answer: I think the See the Developer Knowledge Base article: link can solve your problem
http://www.blackberry.com/knowledgecenterpublic/livelink.exe/fetch/2000/348583/800451/800563/What_Is_-_Different_ways_to_make_an_HTTP_or_socket_connection.html?nodeid=826935&vernum=0
also see this sample code
<code>private static String getConnectionString(){
    String connectionString="";
    if(WLANInfo.getWLANState()==WLANInfo.WLAN_STATE_CONNECTED){
        connectionString="?;interface=wifi";
    }

    else if((CoverageInfo.getCoverageStatus() & CoverageInfo.COVERAGE_MDS) == CoverageInfo.COVERAGE_MDS){
         connectionString = "?;&deviceside=false";
    }
    else if((CoverageInfo.getCoverageStatus() & CoverageInfo.COVERAGE_DIRECT)==CoverageInfo.COVERAGE_DIRECT){
        String carrierUid=getCarrierBIBSUid();
        if(carrierUid == null) {
            connectionString = "?;deviceside=true";
        }
        else{
            connectionString = "?;deviceside=false?;connectionUID="+carrierUid + "?;ConnectionType=mds-public";
        }
    }
    else if(CoverageInfo.getCoverageStatus() == CoverageInfo.COVERAGE_NONE) {
            }
        return connectionString;
    }
</code>
Comment: or you can manually set the Apn name, go to Options>Advanced Option>TCP/IP and enter the service provider's apn.it may get by googling or contact your network provider
Comment: Also see http://supportforums.blackberry.com/t5/Java-Development/Networking-API/ta-p/538863 and the ConnectionFactory class.
Answer: More to the point,
http://supportforums.blackberry.com/t5/Java-Development/How-to-get-APN-Settings/td-p/1704995
It is not completely possible to put the APN settings in your url eg. there is no way to get the username and password.

APN is not specified?


Ubuntu Server and Tomcat 6 WebApp SecurityUtil Exception

Question: I am running clean install of Ubuntu Server 9.10 with Tomcat 6 installed from the Ubuntu installation. When I upload a WebApp through the Tomcat Manager and it starts automatically on boot with /etc/init.d/tomcat6 start my Lib Jars in my Web Apps WebContent/WEB-INF/lib throw an exception.
I am using Project ROME for my RSS Feed which works fine on my local tomcat server I test on through Eclipse. However, when I run it on the Ubuntu Tomcat I get a ServletException:
javax.servlet.ServletException: Could not initialize class com.sun.syndication.feed.synd.SyndFeedImpl
    org.apache.catalina.security.SecurityUtil.execute(SecurityUtil.java:294)
    org.apache.catalina.security.SecurityUtil.doAsPrivilege(SecurityUtil.java:162)

I am guessing I need to change one of the files in /etc/tomcat6/policy.d/ which generates the /var/cache/tomcat6/catalina.policy file. But I don't know what to change. Help please!
Answer: Okay, I got something that works.
I edited the /etc/tomcat6/policy.d/01system.policy and added at the bottom:
// Grant WebApps All Permission
grant codeBase "file:/var/lib/tomcat6/webapps/-" {
    permission java.security.AllPermission;
};

This works now, but not sure if its the right thing to do.
Answer: You could disable the security manager for Tomcat as whole.
Edit /etc/default/tomcat6 and set TOMCAT6_SECURITY to no.
TOMCAT6_SECURITY=no

(Make sure the line is uncommented)
Be sure you understand the implications of doing this though.


Finding Constants for a probability density functions given a finite interval

Question: Given the probability density function f(x) with constant K on the interval [a,b], how do you solve the value of K?
Answer: There are two requirements for a probability density function $f(x)$ on the interval $[a,b]$:
1) $f(x) \ge 0$ everywhere on the interval
2) $\int_a^b f(x)\, dx = 1$
Comment: Dear Robert Israel, It is my pleasure to have your comments on my question: http://math.stackexchange.com/questions/1560808/quasiconvex-and-lower-semicontinuous-function


What exactly is a scalar?

Question: Particularly, referring to scalars I am only implying to individual numbers, for this instance, let's take the set R(real numbers).
These numbers do lie of the real line, i.e. the x axis, which is perpendicular to the y-axis, together form the cartesian plane. So, how are they scalar?
For instance, the number 5 can very well be represented by (5, 0) in the plane, which could also imply that it is a position vector.
If so, let u & v be two vectors in the cartesian plane, then what would the dot product u.v imply? How can the value of it be interpreted? It's obviously not just a random number formed by multiplication of two vectors, what is it that the value of the dot product is so significant?
Comment: Possible duplicate of [Why do we use the word "scalar" and not "number" in Linear Algebra?](http://math.stackexchange.com/questions/1834686/why-do-we-use-the-word-scalar-and-not-number-in-linear-algebra)
Comment: In vector analysis, a vector (in the cartesian plane) from origin $O$ [coordinates : $(0,0)$] is defined by a couple of numbers $(a,b)$. A *scalar* is a number (not a point in the plane).
Comment: A scalar is an element of the underlying field of a vector space. Elements of the vector space are ordered tuples of elements in the underlying field. The $0$ in $(5,0)$ carries some information.
Comment: See [Dot product](https://en.wikipedia.org/wiki/Dot_product).
Comment: @MauroALLEGRANZA, Does a number lie on the real line then?
Comment: @MauroALLEGRANZA, what can be the meaning of a dot product? Why is the value of it's result of meaning?
Comment: 2nd time : See [Dot product](https://en.wikipedia.org/wiki/Dot_product) : definition, formulae to compute it, "geometrical" interpretation. the dot product of $\overline v_1$ and $\overline v_2$ is a **number** $n$ that is not the vector with extreme $(n,0)$.
Comment: @mathbeing, What is the actual meaning of a dot product? It just returns a number, right? How does this specific number relate to any one of the vectors?
Comment: See [inner product](http://mathworld.wolfram.com/InnerProduct.html)
Answer: There are two parts to this question: What is a scalar?, and Can we represent them as vectors? I think these both stem from the same confusion.
In math, we don't usually think about things by what they are, but rather by how they act. So, if we are thinking about the vector space $\mathbb{R}^{2}$ (over $\mathbb{R}$), it seems like we can identify the set $\{ (x, 0) : x \in \mathbb{R} \}$ with the real numbers. They act somewhat similarly, but they have an essential difference: multiplication.
To get what I mean by that, think about how we define vector spaces. Ignore the dot product for now, since it is not central to vector spaces, but rather something we tack on at a later point (when talking about Inner Product Spaces).
A vector space has two parts to it: the vectors, and the scalars. The vectors are simply things that we can add together, with some rules to make it work nicely. For scalars, the essential operations are multiplication and scaling (we require addition as well, but that is somewhat irrelevant to their purpose). In essence, scalars are built around the idea that we use them to scale vectors, and being able to multiply them is actually a natural consequence of that (for a vector $u$, and scalars $a, b$, it is nice express scaling by both as scaling by their product: $a \cdot (b \cdot u) = (ab) \cdot u$).
More precisely, we can think of scalars by how they act on vectors: given a scalar $a$, we can think about the function $u \mapsto a \cdot u$ (for vectors $u$) which represents scaling by $a$. Again, with this it is tempting to take a particular vector $u$ and identify each scalar $a$ with $a \cdot u$. They work the same additively, but they lose the essential ability to scale (in other words, multiplication). Furthermore, this is not a unique representation, since we could choose any vector $u$. It is interesting, but it is not all that helpful.
Now, this is particularly tempting with $\mathbb{R}^{2}$ because the identification with the $x$-axis seems natural, but one of the central points of linear algebra is that it really is not. Basically, the particular coordinate systems that we choose are not really a meaningful part of the structure, and so it is just as natural to choose any one to represent $\mathbb{R}$.
This is primarily true since we are talking about vector spaces, however.
If we were to talk about the complex numbers $\mathbb{C}$, it is a different story. Basically, $\mathbb{C}$ is a vector space over $\mathbb{R}$, and looks exactly like $\mathbb{R}^{2}$, but it has an additional structure: multiplication. Since the complex numbers work like the real numbers (we have addition and multiplication), it is possibly to uniquely represent $\mathbb{R}$ a subset of $\mathbb{C}$. We usually write complex numbers in the form $a + bi$ for real numbers $a, b$, which suggests using $a + 0i$ to represent $a$. In fact, this is precisely the right way to do so to get both addition and multiplication to work right.
Lastly, on the dot product, it really is completely different than it first looks. It is not really multiplication on vectors since the result is a scalar. More precisely, it is not multiplication in the way we have for $\mathbb{R}$ and $\mathbb{C}$ (i.e. for fields). There are all sorts of things we can do in $\mathbb{R}$ (like division) that do not make much sense in $\mathbb{R}^{n}$, even with the dot product.
Really, the most important thing to remember when studying vector spaces (and not more complicated structures like inner product spaces) is that we want everything to be independent of the coordinate system (i.e. basis) that we choose. The dot product is problematic because it makes the standard coordinate system special. Identifying the scalars with a particular axis is problematic because it makes that axis special. Vector addition is good since it is coordinate independent (etc).
Comment: The last sentence has a bit that I think would be logical. My very concept of dot product might be wrong.
Answer: There's no such thing as a scalar. But there's a notion of field, and if $k$ is a field, we can speak of the vector spaces over $k$. Sometimes, we've fixed a field $k$, and we're studying vector spaces over it. In this case, we sometimes write "let $a$ denote a scalar" instead of the more formal "let $a$ denote an element of $k$." But that's all it is - a terminological gimmick, no more.
And you're completely correct that $k$ can itself be viewed as a vector space over $k$. This allows us to can say things like "every scalar can be viewed as a vector in a $1$-dimensional vector space" etc.
Comment: @BeshalJaenal, can you be more specific?
Comment: A 'dot' product, or inner product, is just a function $\cdot :V\times V\to F$, where $V$ is the set of vectors and $F$ if the scalar field. When this function is included in the structure of a vector space, then it is called an inner product space. This allows us to deal with things as length of vectors, angles between them and thus orthogonality. So this is just needed for a lot of geometric concepts to make formal sense. The inner product of two vectors $u,v$ could, informally, be interpreted as, how much of $u$ is 'going' in the same direction as $v$. +(same),0(orthogonal),-(near opposite)
Comment: how does the value of a dot product's value relate to any one of the vectors?
Comment: well you see, it's hard to explain. But, taking an instance, the projection formula has (u.v)/(|v|^2), here you see that there is a dot product of u.v, this specific value must represent some specific terminology representing the vector components itself
Comment: I don't know if this would be the perfect analogy but; taking a plank 10" and dividing it by two means that you get 2" planks with 5 quantity. But in the case of dot products, how is a general interpretation possible? We get a number, just a number, which is of significance and it somehow relates to the two vectors in a way, it couldn't be a random number, but how does it do so?
Comment: Nice answer but why saying "there is no such thing as a scalar"? There *are* mathematical objects called "scalar" and, as you write, they are the elements of the underlying field.
Comment: @MoebiusCorzer, well, no-one ever gives a proper definition of this term (let $a$ denote a foo, then $a$ is a *scalar* iff ...). And, I don't think it's possible to give a proper definition of this term. So for me, there really is no such thing as a scalar.
Comment: @goblin There probably is a subtlety I don't get here. Let $V$ be a vector space over the field $k$. A *scalar* is any element of $k$ and a *vector* is any element of $V$.
This sounds perfectly fine to me. I mean, your argument works for the term "vector" as well, which does not seem to bother you.
Comment: @MoebiusCorzer, that's not a proper definition :) And I don't really believe in vectors either, haha
Comment: Ok, I see what you mean and I can understand why it bothers you. Anyway, I think "scalar" is a better term for oral explanations but I agree we should preferably write "Let $a\in k$ (...)" than "Let $a$ be a scalar" :)
Answer: Here's part of the definition of a vector space (taken from here):
"A vector space over a field F is a set V together with two operations that satisfy the eight axioms listed below. Elements of V are commonly called vectors. Elements of F are commonly called scalars."
The two operations are usually called vector addition and scalar multiplication. This is also a generalization of, what is known as, a module. When the set of scalars is not 'only' a ring but actually a field, then it is called a vector space.
The scalars are possibly called so because they 'scale' the vectors, but it's of course just a name. For example, when you multiply an 'ordinary' vector, say $(1,2)$ in $\mathbb{R}^2$, with the scalar $3$, you get $(3,6)$, which has the same direction but a greater magnitude.
So in a vector space, you always have a set of objects called vectors and a set of scalars, obeying a list of axioms. The vector spaces are often referred to as a $K$-vector space, where $K$ is the scalar field. We also just say a real vector space about an $\mathbb{R}$-vector space.
Any field, such as the real numbers, could then be considered a vector space over itself. This would then be a set of vectors ($\mathbb{R}$) with a set of scalars ($\mathbb{R}$), where vector addition is the ordinary addition in $\mathbb{R}$ and scalar multiplication is the ordinary multiplication in $\mathbb{R}$. So the real numbers could of course be called scalars in that sense.

What exactly is a scalar?


Show hidden div using jQuery with LiveValidation Javascript object

Question: I am still pretty new to jQUery and Javascript, so I might be missing something pretty obvious here.
I have a form which I am using LiveValidation on.
My problem is that I want to display a hidden div (and hide a div (id: main) which was already shown on the screen) when the user hits the submit button, and I can't seem to get it to work.  If I submit the form with all of the fields validated, the hidden div never shows.
In a perfect world, I would like to get the hidden div (id: processing_box) to show when all the form elements are validated at form submission, and when they aren't, the hidden div doesn't show.
Does the LiveValidation object attach itself to the onsubmit event?  There's a massvalidate function which I have tried to use, and have been unsuccessful at doing so.
Here is a little snipped of code that I was using to try to accomplish this:

Comment: What are the values homephoneareacode,homephoneprefix, homephonesuffix holds?.
Comment: they hold integers i.e. 555 555 5555.  there are more form elements than just the phone number, I used that as an example.
Comment: Have you checked the value of `areAllValidated` variable?. Is it coming inside the condition?. Is the `div` with that id `#processing_box` present?.
Answer: I've never used LiveValidation, so I don't know if that code works or not. However, try putting alert() after the if statement to see if that code actually runs. If it doesn't run, then reread the livevalidation documentation; you're doing something wrong. Otherwise, it's something wrong with your jQuery code. Instead of show() and hide(), try .css('display','block') and .css('display','none')


Evaluate $\int_{-\pi}^{\pi} \frac{x^2}{1+\sin{x}+\sqrt{1+\sin^2{x}}} \mathop{dx}$

Question: I came across this integral:$$\int_{-\pi}^{\pi} \frac{x^2}{1+\sin{x}+\sqrt{1+\sin^2{x}}} \mathop{dx}$$
I tried $u=x+\pi$
$$\int_{-\pi}^{\pi} \frac{(x+\pi)^2}{1-\sin{x}+\sqrt{1+\sin^2{x}}} \mathop{dx}$$
but had no success.
I also tried $u=-x$:
$$\int_{-\pi}^{\pi} \frac{x^2}{1-\sin{x}+\sqrt{1+\sin^2{x}}} \mathop{dx}$$
Does this help?  Any suggestions.
Answer is $\dfrac{\pi^3}{3}$ by the way.
Comment: what makes you think this has an analytic antiderivative?
Comment: Add those two integrals together
Answer: Rationalizing the denominator makes it much easier to proceed as follows
$$\frac{x^2}{1+\sin{x}+\sqrt{1+\sin^2{x}}}=\frac{(1+\sin x-\sqrt{1+\sin^2x})x^2}{(1+\sin{x}+\sqrt{1+\sin^2{x}})(1+\sin{x}-\sqrt{1+\sin^2{x}})}$$
$$=\frac{(1+\sin{x}-\sqrt{1+\sin^2{x}})x^2}{2\sin x}$$
$$\therefore I=\int_{-\pi}^{\pi}\frac{(1+\sin{x}-\sqrt{1+\sin^2{x}})x^2}{2\sin x}\ dx\tag 1$$
Now, substituting $x=-x$, we get
$$I=-\int_{-\pi}^{\pi}\frac{(1-\sin{x}-\sqrt{1+\sin^2{x}})x^2}{2\sin x}\ dx\tag 2$$
Adding (1) & (2), we get
$$2I=\int_{-\pi}^{\pi} \frac{2x^2\sin x}{2\sin x} \mathop{dx}$$
$$I=\int_{0}^{\pi} x^2dx$$$$=\color{blue}{\frac{\pi^3}{3}}$$


How do i put values of one column in seaborn point plot

Question: i'm graphing a point plot with two columns from a df (['group', 'preds']).  I have another column, ratio that i would like to use as labels above each point, so the viewer can see how the preds correspond to the ratio.  I haven't found anything in the docs that instructs on how to do that.
See example below.  I just need a line or something that adds ratio as a lable.
import matplotlib.pyplot as plt
import seaborn as sns
import pandas as pd

group = [1,2,3,4,5,6,7,8,9,10]
preds = [.57, .64, .66, .68, .70, .71, .72, .75, .77, .86]
ratio = [.06, .07, .1, .23, .56, .66, .77, .88, .89, 1.07]
df = pd.DataFrame(list(zip(group, preds, ratio)), columns = ['group', 'preds', 'ratio'])
df.head()
import matplotlib.pyplot as plt
import seaborn as sns
plt.style.use("fivethirtyeight")
title = 'Base Line Data only Lift Chart'

plt.rcParams['figure.figsize'] = [16,10]
plt.rcParams['figure.dpi'] = 150
#ax = plt.figure(facecolor='w', edgecolor='k')
ax = sns.pointplot(x ='group', y = 'preds', data = df)
ax = plt.title(title)

Answer: You can use ax.text. Note that my ax refers to ax=sns.pointplot(...), not ax=plt.title(...) like you did in your code. I had also included some keyword parameters for you to tweak and explore on your own in ax.text().
Code for plotting
plt.style.use("fivethirtyeight")
title = 'Base Line Data only Lift Chart'

plt.rcParams['figure.figsize'] = [16,10]
plt.rcParams['figure.dpi'] = 150
#ax = plt.figure(facecolor='w', edgecolor='k')
ax = sns.pointplot(x ='group', y = 'preds', data = df)

for x,y,z in zip(group,preds,ratio):
#change f'{z:.2f}' to str(z) if you want something simpler
    ax.text(x-1,y+0.01,f'{z:.2f}',horizontalalignment='center',color='m',weight='light')

plt.title(title)

Output


É possível alterar CSS de um iframe?

Question: Tenho o seguinte iframe do Google Calendar incorporado:

Estou puxando esse iframe de uma agenda do Google, a pergunta é: Consigo alterar o CSS desse iframe?
Preciso alterar cores, fontes, etc. Gostaria de saber se existe alguma possibilidade de fazer isso, ou se alguém conhece outra forma de fazer essas edições no Google Calendar.
Comment: Você quer alterar o interior do `iframe`?
Comment: Cara, por padrão já posso te dizer que não vai conseguir manipular a página "de baixo", nem com css nem com js nem com nada. Isso por motivos de segurança nós somos impedidos. Mas já procurou na documentação do google a respeito?
Comment: @I_like_trains sim...
Comment: Com PHP vc consegue resolver isso. Veja esse artigo com a sua resposta https://www.webdesignerdepot.com/2012/04/integrating-google-calendar-with-your-website/
Comment: @hugocsl já segui os passos desse tutorial, mas parece que o mesmo está desatualizado.
Comment: Vixi, então complicou rss... Vc pode tentar baixar os arquivos pela aba Source do Dev Tools do Chrome e chama-los direto do seu arquivo local na página para ver se funciona. Nunca tentei isso, mas vai que resolve...
Comment: Não da certo :(
Comment: Confere http://sugi.github.io/jquery-gcal-flow/
Answer: Até onde eu saiba, somente tendo acesso ao DOM usando js ex:
var estilo = document.createElement('link');
estilo.rel = 'stylesheet';
estilo.type = 'text/css';
estilo.href = 'caminho/estilo.css';
seuIframe.getElementsByTagName('head')[0].appendChild(estilo);

É possível alterar CSS de um iframe?


To sum all corresponding fields of 2nd column for each occurrence of fields in the first column

Question: $ bpimagelist -l -d 11/01/2013 03:27:13 -e 11/01/2013 03:30:00 | awk '/^IMAGE/ {print $2, $19}'

XXclcnpde148-bak.XX 11808

XXclnXXcXXcde010-bak.XX 26400

XXcwcnpde148-bak.XX 1623072

XXcwcnpde207-bak.XX 672

XXcwcnpde207-bak.XX 672

XXcwcnpde209-bak.XX 672

XXcwcnpde209-bak.XX 672

XXcwcnpde209-bak.XX 672

-
-
-
- and continues

My output has 2 columns, i need an awk linux command to sum all corresponding fields of 2nd column for each occurrence of fields in the first column. Then  print unique values of column 1 and its corresponding sum in column to.
Answer: For the sum of columns 2 with columns 1 as id :
awk '{sum2[$1] += $2}; END{ for (id in sum2) { print id, sum2[id] } }' < input

Here $1 is the id field, $2 is the column 2. We build 1 arrays for summing columns 2. Once we've processed all the lines/records, we iterate through the array keys (id strings), and print the value at that array index.
Comment: Note that `awk '{commands}' file` is more than enough, you don't need the `< file`.
Comment: thanks, below command worked well awk '{a[$1]+=$2} END {for (x in a) print x, a[x]}' file Please let me know how to get the sorted output. sort columnn 1 with corresponding values of column 2. & also sort columnn 2 with corresponding values of column 1
Answer: Try following awk on your result
awk '{a[$1]+=$2} END {for (x in a) print x, a[x]}' file

Output:
XXclnXXcXXcde010-bak.XX 26400
XXcwcnpde207-bak.XX 1344
XXcwcnpde148-bak.XX 1623072
XXclcnpde148-bak.XX 11808
XXcwcnpde209-bak.XX 2016

In-fact you can do the same task in single awk as follows
bpimagelist ... | awk '/^IMAGE/ {a[$2]+=$19} END {for (x in a) print x, a[x]}'

EDIT (as per OP's comment)

how to get the sorted output. sort columnn 1 with corresponding values
  of column 2. & also sort columnn 2 with corresponding values of column
  1

Simplest approach would be to use sort

Sorting on column 1
awk '{a[$1]+=$2} END {for (x in a) print x, a[x]}' file | sort -k1
-k1 is optional since it's default behaviour
Sorting on column 2
awk '{a[$1]+=$2} END {for (x in a) print x, a[x]}' file | sort -n -k2
-n is for numerical sort since 2nd field consists of numbers
Comment: thanks, below command worked well

awk '{a[$1]+=$2} END {for (x in a) print x, a[x]}' file

Please let me know how to get the sorted output.

sort columnn 1 with corresponding values of column 2.
& also sort columnn 2 with corresponding values of column 1.
Comment: @user3016638 Please check EDIT in my answer.
Answer: In Gnu Awk version 4, you can use PROCINFO["sorted_in"] to sort the result. For example:
gawk -f a.awk file

where a.awk is:
{ a[$1]+=$2 }

END {
    print "Sorted on string value of first column:"
    print "---------------------------------------"
    PROCINFO["sorted_in"] = "@ind_str_asc"
    for (i in a) {
        print i, a[i]
    }
    print ""
    print "Sorted on numerical value of second column:"
    print "-------------------------------------------"
    PROCINFO["sorted_in"] = "@val_num_asc"
    for (i in a) {
        print i, a[i]
    }
}

gives output:
Sorted on string value of first column:
---------------------------------------
XXclcnpde148-bak.XX 11808
XXclnXXcXXcde010-bak.XX 26400
XXcwcnpde148-bak.XX 1623072
XXcwcnpde207-bak.XX 1344
XXcwcnpde209-bak.XX 2016

Sorted on numerical value of second column:
-------------------------------------------
XXcwcnpde207-bak.XX 1344
XXcwcnpde209-bak.XX 2016
XXclcnpde148-bak.XX 11808
XXclnXXcXXcde010-bak.XX 26400
XXcwcnpde148-bak.XX 1623072


Problema com link na lista

Question: Estou com um problema quando coloco um link dentro de uma celula da minha lista, por algum motivo a primeira celula fica como eu quero e as demais ficam todas como se fossem o mesmo link. Como pode ver abaixo
inserir a descrição da imagem aqui

            SERVIÇOS DE TORRE COM O DOUGLAS (PHOUSS)

Torre Normal

R$ 10,00

Torre Hard Auto

R$ 20,00

Clique no Icone para fazer o pedido

Torre Hard Manual

R$ 30,00

Torre Hell 10 ★

R$ 30,00

Torre Hell 15 ★

R$ 40,00

Torre Hell 20 ★

R$ 50,00

Comment: Por favor, esclareça seu problema ou forneça detalhes adicionais a fim de destacar exatamente o que você precisa. Da forma como está escrito atualmente é difícil dizer com exatidão o que você está perguntando.
Comment: QUero colocar uma imagem como link dentro de uma celula da minha lista, porem quando faço isso as demais celulas da lista se tornam um link igual da imagem que inseri na primeira celula
Answer: Você esqueceu de adicionar o "", se pretende colocar a imagem como link clicável, deve seguir uma lógica desse tipo
" < im > "
(tire os espaços estranhos dentro das tags)
Comment: Como está escrito atualmente, sua resposta não é clara. Por favor, pode [edit] para adicionar mais detalhes, que ajudarão outras pessoas a entender como isso resolve a pergunta feita. Você pode encontrar mais informações sobre como escrever boas respostas [na Central de Ajuda](/help/how-to-answer).

Problema com link na lista


Drawing histograms and how size of a bar influences probability?

Question: This is a question concerning the width of the bar in a histogram. Let's say we have frequency distribution like this:

As far as I've learned when you define size of the bar for example 0.5, for each integer value you cluster all the points from the interval integer-0.5 and integer+0.5. So, for example if we draw bar around the integer 50 then it represents all the items from 49,8 + all the items from 50 + all the items in aggregate, that is 20+4+3=27 items in that subset. It doesn't necessarily have to be an integer value, but let's simplify it for this purposes!
Question: By taking a random observation from this distribution what is the probability that it will be in range >=50?
The way it's usually pictured is to sum all (elements contained in) bars in histogram from 50 till the end. If that is the case and thing I've previously described is true, then we should not inculde the subset from the 49,5 to get the right probability?
Maybe the error including that small subset is negligible if the size of the population is high, but still what if the size of the population is small?
Or, it is the other way around: To make a histogram, a size of a bar must be such that there is constant frequency around each number (so that you don't include anything around!).
Answer: Histograms are not really meant for such problems. They are nonparametric estimators for the probability density functions. For estimating probabilities, you would use empirical probability distribution function, i.e. just count the number of times $X \ge 50$, and divide by total size of your sample. By doing this you do not need to bother about bin size, because there is none. Using histograms in here would make the result depend on the bin size.
If the only thing that you are given is the histogram and you need to calculate the probability from it, then you can use a number of possible approaches, like rounding the values to the upper bounds of the bins, to the lower bounds, or using interpolation (linear, something smoother etc.), but in each case those are just workarounds that don't give you guarantees for correctness of the result, just a rough approximation. For example, this is that scipy.stats.rv_histogram class does:
class rv_histogram(rv_continuous):

    def __init__(self, histogram, *args, **kwargs):
        self._histogram = histogram
        self._hpdf = np.asarray(histogram[0])
        self._hbins = np.asarray(histogram[1])
        self._hbin_widths = self._hbins[1:] - self._hbins[:-1]
        self._hpdf = self._hpdf / float(np.sum(self._hpdf * self._hbin_widths))
        self._hcdf = np.cumsum(self._hpdf * self._hbin_widths)

    def _cdf(self, x):
        return np.interp(x, self._hbins, self._hcdf)

(The code was simplified by me. I omitted some of the details that are not important for this problem.)