How do you prove the mean is the best estimator?

Question: sorry if this wastes your time but I am not a mathematician. I do like numbers though.
After reading a problem where you were shown a set of X numbers, and asked how would you predict the next one, I learnt about the average.
By plotting I realize that the average is a number that will always be between the max and the min but also that is the number whose differences to all the sample will by smallest possible (at least in the case of picking up a single number).
I tried to write some math representing this but I have no real idea how to prove it.
I imagine that this could be proved by contradiction: any other number gives rise to a larger difference. But I couldnt get anywhere.
Would you give me some hints, or pointers as to what kind of ideas do you need to prove it?
Comment: Hi: $\bar{x}$ has this nice property but only when the loss function is the distance squared. When the loss function is such, then $\bar{x}$ minimizes the sum of all of the (distance squared) values in the sample. but if you used say, sum of absolute values of distance, as the loss function, then the estimator with this property would be the median. So, the estimator depends on the loss function used.
Comment: Oh, and to prove it ( since that what you asked ) take $\sum_{i=1}^{n} (x_{i} - c)^2$ and solve for the $c$ that minimizes the sum by taking the first derivative and setting it to zero. you should get $\bar{x}$.
Answer: Suppose we have some numbers $x_1, x_2, \ldots, x_n$. By shuffling them around we can assume that they are ordered such that $x_1 \leq x_2 \leq \ldots \leq x_n$.
The mean of these numbers is given by
$$
\bar{x} = \frac{1}{n} \sum_{i=1}^n x_i.
$$
It is easy to prove that $\bar{x}$ lies between the smallest number $x_1$ and the largest $x_n$ since
$$
x_1 = \frac{1}{n} \sum_{i=1}^n x_1 \leq \frac{1}{n}\sum_{i=1}^n x_i \leq \frac{1}{n}\sum_{i=1}^n x_n = x_n.
$$
As you mention, $\bar{x}$ is a number with small distance to each individual point.
The precise way in which this is true, is that  $\bar{x}$ minimizes the expression
$$
\sum_{i=1}^n (x_i - \bar{x})^2.
$$
One way to prove this, is to note that this expression is a quadratic in the variable $\bar{x}$, so it's unique minimum will be at the point where its derivative is zero. Setting the derivative to zero gives
$$
-2\sum_{i=1}^n x_i+2n\bar{x}=0,
$$
so that we indeed find that
$$
\bar{x} = \frac{1}{n} \sum_{i=1}^n x_i.
$$
Edit: In response to your comment, indeed it turns out that $\bar{x}$ minimizes the squared differences $\sum_{i=1}^n (x_i - \bar{x})^2$ instead of $\sum_{i=1}^n |x_i - \bar{x}|$, which you might have initially expected. It turns out that the minimizer of $\sum_{i=1}^n |x_i - \bar{x}|$ is the median, which you have probably heard of. After some searching, I found this answer which gives a precise argument that the median minimizes this expression. It turns out, however, that the median is often non-unique.
For example, in the case of two numbers $x_1 < x_2$, any $\bar{x} \in [x_1,x_2]$ minimizes $\sum_{i=1}^2 |x_i - \bar{x}|$. The fact that the squared differences always have a unique, easily expressible minimizer is convenient, but which measure is appropriate depends on the application.
It might also be helpful to know that in the context of machine learning, the sum of the squared differences is called the $\ell^2$-loss and the sum of the absolute value differences the $\ell^1$-loss.
Comment: Why did you pick that up to minimize? The distance to a point is $d = x-x'$  isnt it? why not minimizing that sum? Oh, this can not be minimized I think..? But why the squared, just simplicity?
Comment: By the way, thanks for the answer, it is clean, creative and understandable.
Comment: I wonder if there is any other way, more visual / geometrical / common sensical rather than purely analytical.
Comment: @MahNeh Thank you! Expanded my answer a little bit. It might also be helpful to think of examples, that is, sequences of numbers $x_1, \ldots, x_n$ where the mean doesn't minimize the absolute value differences and where the median doesn't minimize the squared differences.
Comment: Dang this is good. I love maths sometimes. Still don't fully understand but I'll keep coming back to the answer. Hope you don't mind that I asked a follow up question to check whether there is any geometrical way, something that does not include "minimizing" which I find difficult to imagine.
Comment: @MahNeh to get some geometrical intuition, I would just try to think of some examples. For example, why the median for two points $x_1<x_2$ is not unique, but why the mean is (it has to do with that squaring the differences 'punishes' large differences), or what happens when we have a couple of points fairly close and then one far outlier.


Standardisation in Naive Bayes?

Question: Is it possible that the accuracy of Naive Bayes remain the same even after applying Standardisation . I have applied 2 Standardisation techniques :

Min Max Scaling ( which squishes the range from 0-1 )
Standard Scaling ( which makes the mean=0 and standard deviation =1 )

My implementation is correct as I checked for the range , mean and standard deviation after Standardising . However , the accuracies I obtain are exactly the same . Is this possible or is there some kind of error with my implementation ?
Comment: Are you writing your own Naive Bayes algorithm, or are you using a package in R or Python or another software?
Comment: The Naive Bayes algorithm I'm taking from Python's Sklearn implementation . However , the standardisation part , I'm implementing on my own .
Comment: sklearn has nice and convenient transformers for both standardization and minmax. I recommed using them whenever possible
Answer: I assume you are using Gaussian, not Multinomial/Binomial Naive Bayes?
For Gaussian Naive Bayes, the estimator learns the mean and standard deviation of each feature (per class). At prediction time the probability of a value being in a class is a function of the distance from the center of the distribution. The function used is Probability Density Function (PDF), of a Normal/Gaussian distribution. And the Normal PDF is just a Standard Normal distribution (0 mean, unit variance) that is scaled by variance and shifted by mean. So a value which is at mean+(0.5*std) has the same probability.
With standardization the mean and stddev changes, but probabilities stay exactly the same, and thus classification results. In essence Gaussian Naive Bayes performs standardization internally.

Standardisation in Naive Bayes?


Solving a functional equation in CDF's of probability distributions

Question: Reading a paper I've come across the following functional equation for unknown CDF's $F_1, F_2$ of centered probability distributions $\mu_1, \mu_2$ with variance $1$: $$F^{-1}(G_2(x+y)) = F_1^{-1}(G_1(x))+ F_2^{-1}(G_1(y))\qquad \text{for all} \ (x,y) \in \mathbb{R}^2$$
where $G_i$ is the CDF of a centered gaussian with Variance $i$ and $F$ is the CDF of the convolution $\mu_1 \ast \mu_2$. The unique solution is actually $F_1 = F_2 = G_1$ but I've not been able to proof that. I (think I) can show that $F_1 = F_2$: $$F_1^{-1}(G_1(x))+ F_2^{-1}(G_1(y)) = F^{-1}(G_2(x+y)) = F^{-1}(G_2(y+x)) = F_1^{-1}(G_1(y))+ F_2^{-1}(G_1(x))$$ so
$$F_1^{-1}(G_1(x)) - F_2^{-1}(G_1(x)) = F_1^{-1}(G_1(y)) - F_2^{-1}(G_1(y))$$
which means, that $F_1^{-1}(G_1(x)) - F_2^{-1}(G_1(x))$ is constant, since the right-hand side does not depend on $x$. If the difference was not $0$ then either $\mu_1$ or $\mu_2$ is not centered since, $\mathbb{E}[\mu_i] = \int_0^1 F_i^{-1}(y)dy$, so $F_1 = F_2$.
Is this argument correct? How can I proceed to show uniqueness of solution?
You can find the paper here - the functional equation is part of the proof of Theorem 2 on page 49.
Answer: $$F^{-1}(G_2(x+y)) = F_1^{-1}(G_1(x))+ F_2^{-1}(G_1(y))$$
$$\text{let } h_1(x)=\int_0^tF_1^{-1}(G_1(xt))dt $$
$$\text{let } h_2(y)=\int_0^tF_2^{-1}(G_1(yt))dt $$
$$\text{let } h(x+y)=\int_0^tF^{-1}(G_1(xt+yt))dt $$
$$ \text{it is easily seen that $h_i(x)=\frac{\int_0^xF_i^{-1}(G_1(u))du}{x}$} \text{  ,it is continuous}$$
$$h_1(x)+h_2(y)=h(x+y) \text{ holds everywhere}$$
$$h_1(x)+h_2(0)=h(x)$$
$$h_1(0)+h_2(x)=h(x)$$
$$h_1(x)+h_2(0)=h_1(0)+h_2(x)$$
$$\text{The derivative: } h_1'(x)=h_2'(x)$$
$$xh_1'(x)+h_1(x)=F_1^{-1}(G_1(x))$$
$$xh_2'(x)+h_2(x)=F_2^{-1}(G_1(x))$$
The equations imply $$h_1(x)-h_2(x) \text{ is constant}$$
$$F_1^{-1}(G_1(x))-F_2^{-1}(G_1(x)) \text{ is constant}$$
$$h(x)-h_1(x) \text{ is constant}$$
$$h(x)-h_2(x) \text{ is constant}$$
Answer: Getting a (big) hint from a professor I was able to solve the equation:
In the following we'll write $h:=F^{-1} \circ G_2$, $f:=F_1^{-1} \circ G_1$, $g:=F_2^{-1} \circ G_2$.
Inserting $(x,0)$ and $(0,x)$ in the equation yields
$$f(x) + g(0) = h(x+0)=h(0+x) = f(0) + g(x)$$
therefore
$$f(x) = h(x) - g(0)\quad \text{and} \quad g(x) = h(x) - f(0)$$
Reinserting this in the function equation, we find
$$h(x+y) = h(x) - g(0) + h(y) - f(0) = h(x) + h(y) - h(0)$$
Hence $\phi(x):=h(x)-h(0)$ satisfies Cauchy's functional equation
$$\phi(x+y)=h(x+y)-h(0) = h(x) + h(y) - h(0) - h(0) = \phi(x) + \phi(y)$$
which only admits one monotone solution, $\phi(x) = ax$. From here, using that $\mu$ and $\nu$ are centered with variance on we can show that $a=1$, $h(0)=0$ and finally $h=f=g=id_\mathbb{R}$, arriving at the desired conclusion.
Comment: You are inserting values into equation that holds almost everywhere which has to be justified.
Comment: @ibnAbu I checked, and the paper actually requires the equation to be satisfied for all $x,y \in \mathbb{R}$. I'll edit this in my question!


Condition on closures implies discreteness of topology.

Question: I'm supposed to prove that if $(X, \tau)$ is a topological space such that $\overline{A \cap B} = \overline{A} \cap \overline{B}$ for all $A,B \subset X$, then $\tau$ is the discrete topology.
My first ideas were to try proving that $\{x\}$ is open for all $x \in X$, or proving that $A$ is closed, whichever $A \subset X$ is. I would show some work, but I couldn't manage anything so far. I mean, looking at extreme cases using $A$ or $B$ equal to $\{x\}, X \setminus \{x\}, X$ or $\varnothing$ didn't gave me anything useful.
Can someone give me ideas? Thanks.
Answer: For some $x \in X$ suppose that $X - \{x\}$ is not closed.  Then clearly $\overline{X - \{x\}} = X$.  Then we have that
$$
\emptyset \;\; =\;\; \overline{ \{x\} \cap (X - \{x\})} \;\; =\;\; \overline{\{x\}} \cap \overline{X - \{x\}} \;\; =\;\; \overline{\{x\}} \cap X
$$
but this is a contradiction.  Therefore we must have that $X - \{x\}$ is closed.
Comment: Oh, thinking of $\overline{X\setminus \{x\}}$ as the $\subseteq$-smaller closed set containing it really makes it clear. I'll be sure to remember that, thanks.


Render Error Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined

Question: I am trying to import an image on react-native, from the assets folder,(contains all the images). However the images are not compiling when I export them on the IOS-simulator. I think it is important to add that my assets file (that contains all the images), is a read-only file. I've attached an image on the bottom of what the assets-folder looks like on my end. In addition to that picture, I have also attached screenshots of the two errors I am experiencing with the IOS-simulator.
Thank You for your time!
Now, for better clarity here is my code:
import React from 'react';

import  { ImageBackround, StyleSheet, View, Image, Text} from 'react-native';

function WelcomeScreen(props){
    return(
        <>
        <ImageBackround
        style={styles.background}
        source={require('./assets/icon.png')}
        >
        <View style={styles.logoContainer}>

        <Image style={styles.logo} source={require('./assets/favicon.png')}/>
        <Text> Sell what you dont need!</Text>
        </View>
        <View style ={styles.registerButton}></View>
        < View style= {styles.loginButton}></View>
        </ImageBackround>
        </>
    )
}
const styles = StyleSheet.create({
    background: {
        flex:1,
        alignItems: "center" ,

    },
    loginButton: {
        width: "100%",
        height: 70,
        backgroundColor: "#4ecdc4",

    },
    logo: {
        width: 100,
        height: 100,

    },
    logoContainer: {
        position: "absolute",
        top: 70,
        alignItems:"center",

    },
    registerButton: {
        width: "100%",
        height: 70,
        backgroundColor: "#4ecdc4"
    },
});

export default WelcomeScreen;

Here Ive attached in order, the image of the assets file, and the 2 errors that the Ios-simulator is giving me:
Answer: Can you try creating a file inside assets which exports all images and call it from your WelcomeScreen.
create index.js file inside assets folder like this
export const Images ={
   adaptive:require('./adaptive.png'),
   favicon:require('./favicon.png'),
   icon:require('./icon.png'),
   splash:require('./splash.png')
}

and change your WelcomeScreen like this
import React from 'react';
import  { ImageBackround, StyleSheet, View, Image, Text} from 'react-native';
import {Images} from './assets';

function WelcomeScreen(props){
    return(
        <>
        <ImageBackround
        style={styles.background}
        source={Images.icon}
        >
        <View style={styles.logoContainer}>

        <Image style={styles.logo} source={Images.favicon}/>
        <Text> Sell what you dont need!</Text>
        </View>
        <View style ={styles.registerButton}></View>
        < View style= {styles.loginButton}></View>
        </ImageBackround>
        </>
    )
}
const styles = StyleSheet.create({
    background: {
        flex:1,
        alignItems: "center" ,

    },
    loginButton: {
        width: "100%",
        height: 70,
        backgroundColor: "#4ecdc4",

    },
    logo: {
        width: 100,
        height: 100,

    },
    logoContainer: {
        position: "absolute",
        top: 70,
        alignItems:"center",

    },
    registerButton: {
        width: "100%",
        height: 70,
        backgroundColor: "#4ecdc4"
    },
});

export default WelcomeScreen;

Comment: I did that, however now it is stuck on the splash screen(white blank screen).
Comment: can you show me your navigation file and root screen
Comment: I re-launched my project and am still experiencing the same error. So, i dont have a blank screen issue anymore. Where would i find the navigation file and root screen? Thanks for your fast response time, appreciate it
Comment: The error on VS-code.
It says this:

This error is located at:
    in WelcomeScreen (created by App)
    in App (created by ExpoRoot)
    in ExpoRoot
    in RCTView (created by View)
    in View (created by AppContainer)
    in DevAppContainer (created by AppContainer)
    in RCTView (created by View)
    in View (created by AppContainer)
    in AppContainer.
Comment: You have only welcome screen?
No navigation setup?
Comment: I haven't made a navigation component, because i'm currently following Mosh hamedani's react-native course, and he didn't make one either.
Comment: If i do create one, you think the problem will be solved?
Comment: No, error is not because of not using navigation. I just asked for clarifying.
So you have only welcome screen.
Can you share your project structure like you showed your assets folder above and also updated WelcomeScreen which caused error.
Comment: Sounds good, I just updated the post. Its the 4th picture
Comment: Oh so this is an expo project.
Sorry I don't have much experience in expo.
Here is reference to folder structure of expo project : [expo-folder-and-file-structure](https://ckmobile.medium.com/expo-folder-and-file-structure-872661bdf339)
Try updating your code like that.
Good Luck.
Comment: Yeah, this project is an expo project.


Change UITextField behavior

Question: What is the best way to disable UITextField's 'return' keyboard key if input area does not contain any text? UITextField with enablesReturnKeyAutomatically property set to YES enables return key even if there are only spaces entered, but I'd like it to enable return key only when the text is not empty. any suggestions?
Comment: You may want to look into `UITextFieldDelegate` methods.
Answer: I don't know how you'd override the text input trait behaviour, but you could use the text field delegate method textField:shouldChangeCharactersInRange:replacementString: to prevent the user being able to enter spaces into an otherwise blank string. This would prevent any whitespace text being added, so the return key should not be enabled.
If you're not bothered about the return key actually being enabled, you could use textFieldShouldReturn:, again one of the text field delegate methods.
Answer: I would do something like the following

Create an extension to String and add a trim method (it will become handy in other scenarios too that's why I suggest an extension.
public func trim() -> String {
  return  stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet())
}

Make your class a delegate of UITextFieldDelegate and add the following fuction
func textFieldDidChange(textField: UITextField) {
  textField.text = textField.text.trim()
}

Set the delegate of your UITextField to self.

Change UITextField behavior


If $A$ is not a regular language and $B$ is a regular language and $B \neq \varnothing$, does $AB$ is not regular language?

Question: I am trying to proof that
$L = \{ 0^11^2...0^{n-1}1^n0^{n-1}...1^20^1\}$ where $n >= 0$ is not a regular language.
So my method is to put
$S = 0^11^2...0^{n-1}$
$W = S1^nS^R$
And then proof $S^R$ is not a regular language using pumping lemma. But as my understanding goes, the closure property is for regular language only and not the other way around. So From above I've got that
$S$ and $S^R$ is not a regular language. But $1^n$ is a regular language. So how to proof that $W$ is not a regular language?
Comment: Note: If $A=\{\,0^p\mid p\text{ prime}\,\}$ and $B=0^*$, then $AB$ is regular
Comment: You can't write $W = S1^nS^R$, since that would allow for, say, $01100011000110$. If you write it as a concatenation of languages like this, you cannot control the value of $n$ between the two definitions.
Comment: Why don't you apply the pumping lemma to $L$?
Comment: How exactly? (Normally I work with $W = XYZ$ and X = $a^i$, $Y = a^j$ but in this case, the variable is at the centre and I don't know how to prove). It would be so kind if you could give me a hint. Thanks.

Also from the first comment, I just notice that. Thank you.
Comment: For the title question: consider the counterexample $A = \{ 0^m 1^n \mid m \ge n \}$ and $B = 1^*$.  Then $AB = 0^* 1^*$ is regular.
Answer: Okay, I have asked my senior for help
So what he told is
Let $L = \{ 0^11^2...0^{n-1}1^n0^{n-1}...1^20^1\}$.
Given $W = XYZ$ for $\forall W\in L$
We got $|W| = n^2$. For arbitrary Y, $1\le|Y|\le n$
Consider $n^2 \lt n^2 + 1 \le |XY^2Z| \le n^2 + n < n^2 + 2n < (n + 1)^2$
So $n^2 < |XY^2Z| < (n+1)^2$
Thus proving $XY^2Z \notin L$.
From pumping lemma we can conclude that $L$ is not regular.


python3 not working in virtual environment

Question: First I installed anaconda 2 and created virtual environment with python 2.7 and it's working fine.
But I created another environment with python 3 and in this environment inside jupyter notebook and there is kernel error.
Is there any problem in creating two environment with different python version??How can I solve it?
(First environment is still working fine)
this is what prompt showing
this is jupyter error
Comment: Please, follow [this guide](https://stackoverflow.com/help/how-to-ask) to ask a good question. Show us the error, explain what did you try to solve it, etc.
Answer: Yes you can make different virtual environments for different versions of Python. you  should create your environments using the command:
conda create -n yourenvname1 python=2.7 anaconda

and the other environment by typing the command
conda create -n yourenvname2 python=3.7 anaconda

Be sure to activate whichever environment you wish to use. In the above lines enter whichever version of python you have.


Como relacionar duas tabelas diferentes dentro de uma PROCEDURE? PLSQL

Question: Preciso criar uma procedure (em PL-SQL) que seja de marcar_Agendamentos, nelas vou incluir informações como data, paciente e também o id_médico responsável e o id_especialidade, o que venho quebrando a cabeça é que gostaria de desenvolver uma condição onde fosse possível verificar se o id_medico inserido e id_especialidade é o que retorna na tabela médicos, onde tem o id,nome e a área em que cada médico atende, evitando que na hora de inserir os dados a pessoa troque e coloque uma outra especialidade para o médico.
Está sendo bem difícil , já procurei soluções sem sucesso e também já tentei as minhas mas sem sucesso.
Comment: Poderia pegar a especialidade através da tabela médico e da relação médico -> especialidade. Assim na tabela agendado basta ter uma fk para médico.
Answer: Acho que você poderia usar cursores pra trazer as informações que vc quer destas tabelas. Caso o retorno do cursor seja diferente de nulo, por exemplo, você terá as informações que precisa e com a certeza que eles estão nas respectivas tabelas.
Por exemplo:
Table medicos:
-id_medico
-id_especialidade

Seu cursor seria algo como:
cursor get_info_doc (id_doc medicos.id_medico%type, id_esp medicos.id_especialidade) is
 select * from medicos where id_medico = id_doc and id_especialidade = id_esp;

Aí na sua verificação seria tipo:
if get_info_doc%NOTFOUND then
...
else
...
end if;

Talvez dê pra adaptar algo pra vc com isso, espero ter ajudado.


How to use MAPE with auto.arima model?

Question: The code below gets a: error in mean(abs((y_true - y_pred)/y_true)) :
argument "y_true" is missing, with no default
I've seen MAPE used on forecasts. Can one use this and similar methods on models? Or is there some other R package that would work?
Edit 1: Seems lke MAPE wants a forecast. While my arima:
> class(arima)
[1] "forecast_ARIMA" "ARIMA"          "Arima"

might be a forecast MAPE does not work. Using summary, i get:
Training set error measures:
                      ME     RMSE      MAE          MPE
Training set 0.003245791 1.473989 1.051721 -0.001574146
                  MAPE      MASE         ACF1
Training set 0.5306977 0.9908161 -0.001193281

Doing a ??MAP gets me nine packages (with many different names for methods ans parameters). This is confusing. Is there any doc on which types of objects work with what?
Original code:
symbols <- c("SPY","EFA", "IJS", "EEM","AGG")
prices <- getSymbols(symbols,
               src = 'yahoo',
               from = "2012-12-31",
               to = "2017-12-31",
               auto.assign = TRUE,
               warnings = FALSE)

ts<-SPY$SPY.Close
autoplot(ts)
arima = auto.arima(ts)
library(MLmetrics)
MAPE(arima)

Answer: MAPE is just a calculation. The functions from MLmetrics might not be specifically designed for time series, but if you give the MLmetrocs::MAPE function the true and predicted values, you will get the desired mean absolute percent error for the predictions made by your ARIMA model.
Note that MAPE, despite what seems to be a nice interpretation, has some problem that are worth knowing.
Since it is fine to use the function from MLmetrics, you do not have to write your own MAPE function. However, if you have defined the y_true and y_pred variables in your code, you seem to have given the right calculation (though it seems you have not defined y_true anywhere, which would explain your error).
Comment: nice link. thanks.

How to use MAPE with auto.arima model?


PHP to do what ImageMagick does

Question: I need to find some PHP code to essentially do what the ImageMagick command ">compare -metric AE -fuzz 10% image1.png image2.png output.png" does.  I have found the http://www.phpied.com/image-diff/ code and it does well, but I really need the -fuzz capabilities to filter out the insignificant differences and it would be nice to have the -metric flag functionality to spit out the difference count, but I would think that is pretty easy to add.
Reason for this is that I can't install ImageMagick on my web server so I need standalone code or libraries.
Any suggestions on code or places to look?
Thanks
Comment: So you can or cannot install ImageMagick binaries? If they're available, making a system call to ImageMagick executables is the easiest...
Comment: ImageMagick is not installed on my webserver and I do not have rights to install it.  I would do it that way if I could but no go.
Answer: What's wrong with the ImageMagick functions of PHP?
Comment: Not a thing, I just dont have ImageMagick at my disposal.
Comment: If it's because you're with a shared host and don't have shell access, I'd be looking for an alternative host if they're not providing default access to such an integral library and especially if they are unwilling to install it upon request. Re-writing any of ImageMagick's functions in PHP  is going to take a **lot** more time/effort than moving to (or offloading this task) to another server with `imagick` or `imagemagick`.

PHP to do what ImageMagick does


How to change a MySQL database to UTC?

Question: I'm on Windows 7 and I'm a bit new to this database stuff. I tried searching on Google for how to change the timezone from my system to UTC but the documents are somewhat advanced and I'm not too sure how to change this field.
Comment: This question is related to windows 7 configuration, not to mysql at all.
Comment: @zerkm: Could it be possible to change the configuration only for the database (so the SQL works in UTC mode), while retaining the time zone of the system?
Answer: In your my.ini file, under the [mysqld] section, add the following line:
default-time-zone = '+00:00'

Restart the server.
You could also set it at runtime from the command line with
mysql> SET GLOBAL time_zone = '+00:00';

The documentation from MySql

How to change a MySQL database to UTC?


Problem setting up Sendmail's SMTP authentification - doesn't accept login

Question: I have no idea what's wrong with this, but for some reason I can't get my email program (Thunderbird) to send mail via Sendmail. There seems to be virtually no help on the subject on the web.
Here's what's going on:
I can receive email just fine. I can send email through PHP. But when I try to set up the SMTP in Thunderbird, I get a variety of errors. My goal is to be able to use port 25 or 465 with SSL. I found a site that explains how to set up a certificate with Sendmail to get that to work, but I haven't done that yet, so for now I'm just using port 465 with no encryption. I've got it to the point that it asks for a password, but it won't accept it. I'm using the same username/password I use to login to the server. How do I make Sendmail accept my login?
Here's how I've got Sendmail configured (copied from the M4 config file):
DAEMON_OPTIONS(`Name=MTA,Port=25')
DAEMON_OPTIONS(`Name=SMTPS,Port=465,Modifiers=a')
I need to be able to:
Send email over port 25 or 465 (SSL), but ONLY with my username & password.
Can anyone help????
Thanks!
Grant
--------------------
PS- I'm still kindof a beginner with Sendmail, especially its config file, so if you could explain exactly how to do whatever I need to do, it would be greatly appreciated.
Answer: Port 465 requires SSL encryption, your client will not be able to use it without encryption. You can setup SMTP authentication on the default port 25 without encryption (but that exposes your login details).
Here is info to get you going https://devhen.wordpress.com/2006/05/01/howto-sendmail-smtp-auth/
Comment: I tried adding the lines mentioned in the link, but it still doesn't work. Here's a link to my M4 file, maybe it'll help:

http://prudlow.com/files/m4.txt

Note: I tried adding the certificates my imap server in an attempt to get SSL working, but that didn't work either. Still, 1st priority is getting authentication working; it's still either rejecting my password or timing out. :/
Comment: What errors are you seeing in your log files.


Google APIs vs Google Play Services, Why we need Google APIs now?

Question: We used to use Google APIs SDK to use functionality like Google Maps, which is now available in Google Play Services Library.
So do we still need to create our android project with Google APIs, or can use simply android?
Comment: you need google api's and get the key for connecting to the google servers such as for google maps v3
Comment: isn't the latest native maps API is v2 and not v3?
https://developers.google.com/maps/documentation/android/

Also I guess its part of Play Services? no really get what you mean here.
Comment: ya sorry i mentioned about the javascript version. you can use simply any android version i have used it and it's working fine. however you will need to import the `google play services library` and include it.
Answer: if you are using maps v2 then no you do not need google API's you just need to import google play services
Comment: Then why there is a Google APIs SDK available to download?
Comment: google api's is not just maps there are other things in the API too (most if not all are deprecated) but in order to use all the new stuff you need google play services which all devices do not have. so if you made an app and want it to work on a device that does not have the play store then you are stuck using the old google api's


Extension of $*$-representation from an algebraic corner of a $*$-algebra

Question: Let $B$ be a $*$-algebra and $A\subseteq B$ a $*$-subalgebra. Let $p\in B$ be a projection such that
$$pBp=A.$$
Suppose we have a $*$-homomorphism $\phi:A\rightarrow\mathcal{B}(H)$, where $H$ is some Hilbert space.
Question: Can $\phi$ be extended to a $*$-homomorphism $\phi':B\rightarrow\mathcal{B}(H)$?
Answer: Not necessarily. Let $B= M_{2\times 2}(\Bbb C)$ and let $p=\begin{pmatrix}1&0\\0&0\end{pmatrix}$. Then $A$ are those matrices where only the $11$ component is non-zero. Let $\varphi: A\to \mathcal B(\Bbb C)=\Bbb C$ be the map sending such a matrix to its only non-zero component. This is a $*$-algebra morphism.
There can be no extension of this, because no $M_{2\times 2}(\Bbb C)$ admits no characters (meaning no $*$-algebra morphisms into $\Bbb C$). If you denote with $\varphi_{ij}$ the image of the matrix with a $1$ on the $ij$ component and else $0$ of such an extension, you have $(\varphi_{12})^2=0=(\varphi_{21})^2$ since this is an algebra morphism, implying $\varphi_{12}=\varphi_{21}=0$. But $\begin{pmatrix}0& 1\\ 1&0\end{pmatrix}$ is invertible, so either $\varphi_{12}+\varphi_{21}$ is invertible (not possible) or $\varphi$ is the zero morphism.
Comment: Thanks for your answer. I wonder if the answer would be different if we only allow $H$ to be infinite-dimensional?
Comment: Yes, take the same $A,B$ and let $H=\ell^2$ and $\varphi_{11}=\mathrm{id}$. You must have $(\varphi_{12})^2=0=(\varphi_{21})^2 $ but $\varphi_{12}\varphi_{21}=\varphi_{11}=\mathrm{id}$. This cannot happen as $\varphi_{21}$ must have a kernel.
Comment: A scenario where you can always extend is if $pBp$ is an ideal in $B$. This would be implied for example by $pB=Bp$, ie $p$ normalising $B$.


Discrete Random Variable measure theoretic

Question: I'm reading a book on measure foundations for probability theory.
On a page, after defining r.v. as measurable functions, speaking of the probability distribution associated with the r.v., the authors define a r.v. like this:
$X(\omega)=a$, with probability p.
$X(\omega)=b$, with probability (1-p).
This doesn't seem like a proper definition, since 'with prob. p' could be translated into '$P(X^{-1}(B))=p$, when $a\in B$ '. So, we're defining $X$ with itself, but not in a consistent way I think...
Is there a way to define it without itself?
Any help would be appreciated.
Comment: What is $B'$? You can say nothing about its measure unless you define it.
Comment: @iiivooo $B \in \mathbf{B}(\mathbb{R})$, and by the way, I like your user name. ;)
Comment: In that case $P(X^{-1}(B))=1-p$ if $b \in B$ and zero otherwise. Please see my answer for details.
Comment: could you add a source for this?
Comment: @user190080 http://www.amazon.co.uk/Integral-Probability-Springer-Undergraduate-Mathematics/dp/1852337818/ref=sr_1_1?s=books&ie=UTF8&qid=1445442191&sr=1-1&keywords=measure+integral+and+probability
Answer: $X(\omega)=a$ with probability $p$ means, that $X(\omega)=a$ for all $\omega \in \Omega_a$, such that $P(\Omega_a)=p$. Similarly you define $X(\omega)=b$ for all $\omega \in \Omega_b$, such that $P(\Omega_b)=1-p$. Now we can see, that we defined r.v. $X$ on set of measure 1 (the intersection of $\Omega_a$ and $\Omega_b$ is clearly empty if $a \neq b$). Therefore it is proper definition of r.v.
Edit:
To defined $\Omega_a$ and $\Omega_b$ first you have to define $\Omega$ and $P$. Since you did not do it, I define the space $\Omega$ having just two elements  $\Omega=\{\omega_a,\omega_b\}$ and $P(\omega_a)=p$ and $P(\omega_b)=1-p$ and then I define $X(\omega_a)=a$ and $X(\omega_b)=b$.
But you must accept, that this concept with space $\Omega$ is abstract, and in dealing with r.v. you do not need to know (in fact you do not care) about what $\Omega_a$ is exactly, you just need to know its measure.
Also to your example:
$$P(X^{-1}(B))=P(\{\omega \in \Omega :X(\omega) \in B\}$$
so we immediately see, that for borel $B$ we have 4 cases:
$P(X^{-1}(B))=1$ if both $a,b \in B$,
$P(X^{-1}(B))=p$ if $a \in B$ and $b \notin B$,
$P(X^{-1}(B))=1-p$ if $a \notin B$ and $b \in B$,
$P(X^{-1}(B))=0$ if both $a,b \notin B$.
Comment: $P: \Omega \rightarrow [0,1]$, but $B \subset $ range of $X$, not the domain...
Comment: Sorry my notation could confuse you so I changed it, hope it is clear now.
Comment: Thanks for your answer. I'm learning this, so I still have some doubts on your answer: 1) if $p=1-p$ the sets$\Omega_a, \Omega_b$ could intersect, right? Also, by $\Omega_a, \Omega_b$ do you mean any set that $P(\Omega_a)=p$ and $P(\Omega_b)=1-p$, or the whole collection of subsets where the equalities are true? Because from how you write it seems as if you're saying that $\Omega_a \cup \Omega_b=\Omega$
Comment: No, $\Omega_a$ and $\Omega_b$ are two fixed sets (fixed in definition of r.v.). However for dealing with r.v. the only desired information you need about them is their measure. Also if $\omega$ is in both, than you have $a=X(\omega)=b$, which is contradiction with $a \neq b$ therefore their intersection is empty. Also $P(\Omega_a \cup \Omega_b)=1$, so $X$ is defined on set of measure 1. There could be some elements outside both sets, but you can define $X$ on them as you want, since their measure is zero.
Comment: ok. I think I'm getting there. =)  so they are fixed sets, but when $p=1-p$ they are not defined in a unique way only by their measure... So, how would you define those omega sets in this case?
Comment: I'll edit the answer.
Comment: Let us [continue this discussion in chat](http://chat.stackexchange.com/rooms/30552/discussion-between-an-old-man-in-the-sea-and-iiivooo).


Find a function whose first partial with respect to $x$ does not exist.

Question: I'm having a difficult time understanding what it means for a first partial derivative of a function to exist. I was wondering if someone could come up with an example of a function defined in the $xy$-plane whose first partial with respect to $x$ does not exist, and show this using the definition of derivative?
Answer: Hint: Find a function $g: \mathbb R \to \mathbb R$ whose derivative doesn't exist somewhere, and then define $f(x,y)=g(x).$
Answer: How about $f(x,y)=\ln x$?  The partial derivative $\frac{\partial}{\partial x}f(x,y)=\frac1x$  at $(0,y)$ doesn't exist.
Comment: Yes.  I guess you could also consider something like $f(x,y)=\mid x\mid$, with a "sharp point".
Comment: Thanks for the input. I think that I was most confused about figuring out if a partial derivative exits when the denominator is nonzero. Since I assume one would then have to check to see that the left and right hand limits of $f_x$ agree, right?


Django Filewrapper memory error serving big files, how to stream

Question: I have code like this:
@login_required
def download_file(request):
    content_type = "application/octet-stream"
    download_name = os.path.join(DATA_ROOT, "video.avi")

    with open(download_name, "rb") as f:
        wrapper = FileWrapper(f, 8192)
        response = HttpResponse(wrapper, content_type=content_type)
    response['Content-Disposition'] = 'attachment; filename=blabla.avi'
    response['Content-Length'] = os.path.getsize(download_name)
    # response['Content-Length'] = _file.size
    return response

It seems that it works. However, If I download bigger file (~600MB for example) my memory consumption increase by this 600MB. After few such a downloads my server throws:

Internal Server Error: /download/ Traceback (most recent call last):
  File
  "/home/matous/.local/lib/python3.5/site-packages/django/core/handlers/exception.py",
  line 35, in inner
      response = get_response(request)   File "/home/matous/.local/lib/python3.5/site-packages/django/core/handlers/base.py",
  line 128, in _get_response
      response = self.process_exception_by_middleware(e, request)   File "/home/matous/.local/lib/python3.5/site-packages/django/core/handlers/base.py",
  line 126, in _get_response
      response = wrapped_callback(request, *callback_args, **callback_kwargs)   File "/home/matous/.local/lib/python3.5/site-packages/django/contrib/auth/decorators.py",
  line 21, in _wrapped_view
      return view_func(request, *args, **kwargs)   File "/media/matous/89104d3d-fa52-4b14-9c5d-9ec54ceebebb/home/matous/phd/emoapp/emoapp/mainapp/views.py",
  line 118, in download_file
      response = HttpResponse(wrapper, content_type=content_type)   File "/home/matous/.local/lib/python3.5/site-packages/django/http/response.py",
  line 285, in init
      self.content = content   File "/home/matous/.local/lib/python3.5/site-packages/django/http/response.py",
  line 308, in content
      content = b''.join(self.make_bytes(chunk) for chunk in value) MemoryError

What I am doing wrong? Is it possible to configure it somehow to stream it the piece by piece from hard-drive without this insane memory storage?
Note: I know that big files should not be served by Django, but I am looking for simple approach that allows to verify user access rights for any served file.
Answer: Try to use StreamingHttpResponse instead, that will help, it is exactly what you are looking for.
Is it possible to configure it somehow to stream it the piece by piece from hard-drive without this insane memory storage?
import os
from django.http import StreamingHttpResponse
from django.core.servers.basehttp import FileWrapper #django <=1.8
from wsgiref.util import FileWrapper #django >1.8

@login_required
def download_file(request):
   file_path = os.path.join(DATA_ROOT, "video.avi")
   filename = os.path.basename(file_path)
   chunk_size = 8192
   response = StreamingHttpResponse(
       FileWrapper(open(file_path, 'rb'), chunk_size),
       content_type="application/octet-stream"
   )
   response['Content-Length'] = os.path.getsize(file_path)
   response['Content-Disposition'] = "attachment; filename=%s" % filename
   return response

This will stream your file in chunks without loading it in memory; alternatively, you can use FileResponse,

which is a subclass of StreamingHttpResponse optimized for binary
  files.


Recommendations for beginner piano pieces that make equal use of both hands

Question: There are more demands on my right hand for much of what I play, and am beginning to notice a difference between my hands when playing e.g. scales.
I would like to play more pieces that make equal usage of both hands. For example, Bach's Minuet in A Minor does a pretty good job. I think many of Bach's inventions also make equal usage—but, right now, they're above my level.
Does anyone have any recommendations?
Answer: The Bach Minuet in A Minor comes from the Anna Magdalena Notebook (Wikipedia), which contains many pieces of a similar level. Many, if not all, of those pieces are available at IMSLP.
You could also try the collection, Introduction to Classics to Moderns, edited by Denes Agay. It contains pieces from the pre-Baroque through the mid-twentieth century, all of which use both hands equally (except the very first song). The pieces are placed in approximate order of difficulty.


How can I strip symbols from my executable when using Clang and the LLVM ELF ld.LLD linker?

Question: I am building with Clang 9.0.0 and linking with the ld.lld linker
clang++.exe -Wall -fexceptions -m64 -O3 -Xclang -flto-visibility-public-std -std=c++2a -flto=thin  -c
  I:\Cpp\hello_boost\hello_codeblocks_world\hello_codeblocks_world.cpp -o obj\release\hello_codeblocks_world.o

clang++.exe  -o bin\release\hello_codeblocks_world.exe obj\release\hello_codeblocks_world.o  -m64 -fuse-ld=lld --strip-all

but, unlike when using the usual GCC linker LD, this option (--strip-all or -s) is not recognized
clang++: error: unsupported option '--strip-all' (or similarly with -s)

Can anyone suggest what I should be doing to strip symbols?
(My release-mode  hello_world.exe size is 15 kb for GC but 230 kB for Clang :-( and this is likely to have some adverse effects for no benefit).
Is this not an option for ld.lld  ?
Thanks
Answer: You might want to use:
-Xlinker --strip-all
You can use this to supply system-specific linker options that GCC does not recognize (gcc manual)
https://gcc.gnu.org/onlinedocs/gcc/Link-Options.html


Number of solutions of $x^2 \equiv 1 \pmod{2^rq}$

Question: I need to show that the number of solutions of
$$x^2 \equiv 1 \pmod{2^rq}, (2^rq) \in \mathbb{N}$$
is $2^{s+t}$ where $s$ = #distinct prime divisors of $q$ and $t$ = 0,1,2 according as $r\le1$, $r=2$, $r\ge3$.
So far I've been able to prove show this for: $x^2 \equiv 1 \pmod{2^r}$
I'm having trouble seeing what happens taken mod ($2^r$ q) Thanks for any help!
Comment: I think you can just apply chinese remainder theorem?
Comment: The solutions modulo $2^rq$ correspond to tuples of solutions, one for each prime divisor $q_i$ of $2^rq,$ modulo $q_i^{r_i}$ where $q_i^{r_i}||2^rq.$
Comment: I was thinking chinese remainder theorem a while back in my thought process..but don't know how this would allow me to determine the number of distinct solution?
Comment: I'm very sorry, but I just don't see this
Comment: @MargretButton, I'm sorry I thought q was prime.
Comment: I still think we may be able to apply the CRT, but I'm struggling with it.
Comment: You can Apply CRT with use of the following results: http://math.stackexchange.com/questions/55223/how-many-solutions-are-there-to-x2-equiv-1-pmod2a-when-a-geq-3, http://math.stackexchange.com/questions/29344/solving-x2-equiv-1-pmodp-ell
Comment: @JavaMan yes, I've proved both of those. Thanks though!
Answer: We must assume $q$ is odd (the statement certainly isn't true if $q$ is a power of $2$).
Note that if $m_1, m_2, \ldots, m_k$ are relatively prime, $x$ is a solution of $x^2 \equiv 1 \mod m_1 m_2 \ldots m_k$ iff $x^2 \equiv 1 \mod m_1$, $x^2 \equiv 1 \mod m_2,\ \ldots x^2 \equiv 1 \mod m_k$.  If $S_j = \{x \in {\mathbb Z}_{m_j}: x^2 \equiv 1 \mod m_j\}$, then
$x$ is a solution of $x^2 \equiv 1 \mod m_1 \ldots m_j$ iff $x \in S_j \mod m_j$ for each $j$.  By CRT the number of such solutions in ${\mathbb Z}_{m_1 \ldots m_k}$ is
$|S_1| |S_2| \ldots |S_k|$: each one corresponds to choosing one member $x_1$ of $S_1$, one member $x_2$ of $S_2$, etc, and then taking $x$ so $x \equiv x_1 \mod m_1$, $x \equiv x_2 \mod m_2$, etc.  So you just have to see how many solutions there are mod $2^r$ (which you have already done) and mod $p^m$ if $p$ is an odd prime.  For the latter,
note that $x^2 - 1 = (x-1)(x+1)$, and $x-1$ and $x+1$ can't both be divisible by $p$.
Comment: Much appreciated!


Diagonalizabilty of ad(adjoint map)?

Question: let $\mathsf{g}$ be a finite dimensional lie algebra and $\xi\in\mathsf{g}$.

Under which conditions the adjoint map $ad_\xi :\mathsf{g}\longrightarrow \mathsf{g}$ is diagonalizable?
  what about in infinite dimentional case?
Answer: The conditions for a linear map $ad(x)$ to be diagonalizable are the same as for any endomorphism of a (finite)-dimensional vector space. In a given Lie algebra, some adjoint operators are diagonalizable, others not. For $\mathfrak{sl}_2(K)$ for example,
with standard basis $x,y,h$, the operator $ad(h)$ is diagonalizable, whereas $ad(x)$ and $ad(y)$ are not.
For a semisimple Lie algebra, there is a unique decomposition of a given element $x$ as
$x=s+n$ such that $ad(s)$ is diagonalizable, $ad(n)$ is nilpotent, $[s,n]=0$, and
$ad(x)=ad(s)+ad(n)$. This decomposition, the Jordan-Chevalley decomposition also holds for some classes of infinite-dimensional Lie algebras, e.g., see here.
Comment: thank you Dietrich, perfect answer. well done

Diagonalizabilty of ad(adjoint map)?


Bind_param() Output

Question: I want to expand a query in a foreach loop. I'm doing it without bind_param(), which causes errors, probably because my values include commas which i do not want to remove.
I want to Insert multiple rows with one Query. Is there a Way to use bind_param() in this context?
Code now looks like:
<code>$finalquery = "INSERT INTO mytable (a,b) VALUES";
foreach($xml->entry) {
    $abc_a = $xml->schema;
    $abc_b = $xml->schema->a;
    if($count == 1){
         $finalquery .= "($abc_a,$abc_b)"
    }else($count == 1){
         $finalquery .= ",($abc_a,$abc_b)"
    }
    //COUNT UP
}
$result = $mysqli->query($finalquery) or die ("ERROR: ($finalquery)");
</code>
Answer: Just keep in mind that when building a query like this, This way i am inserting multiple rows in my single table.
<code>$values = array();
foreach ($_POST as $key => $value) {
    $qvalue = mysql_real_escape_string($value);
    $values[] = "($field1, $field2, $field3, $qvalue)"; // quoted value, not the raw value
}

$query_values = implode(',', $values);

$query = "INSERT INTO tablename(field1, field2, field3, field4) VALUES $query_values";
$result = mysql_query($query, $connection);
</code>
Comment: First of all: thanks for you answer.
so the query would be something like:
"Insert into tablename(field1, field2, field3, field4) values (abc,def,ghi,jk),(acb,fed,ghgi,ik),(...,...,...,..)" right?

Problem is, that my values have commas and i need to keep them. I thought that i could use bind_param() but i don't know how to use it for inserting multiple rows.

Bind_param() Output


Algorithm for retrieving all the permutations (randomized) for a vector sequence 1...N with only unique values

Question: Here is the problem: I have a vector of $N$ elements long (containing only unique values from $1...N$).

I am searching for an algorithm to obtain all the (randomized) combinations possible, where each value can only appear once.

That is for instance the following vectors in case $N=3$.
$(1, 2, 3)$
$(1, 3, 2)$
$(2, 1, 3)$
$(2, 3, 1)$
$(3, 1, 2)$
$(3, 2, 1)$
Any more?
Follow up questions:

Is there a way to filter out rules that seem to be systematic, for example the vector $(1,2,3,4)$, as I am only searching for randomized combinations.
How many combinations are there possible? Is it 100x100?
Is there a built-in Matlab function available for this?
Comment: What do you call a **randomized** combination? (actually, permutation, see my answer below) I can imagine taking a random permutation (see [Knuth shuffle](https://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle)), but not *filtering* random permutations...
Answer: These are not combinations but permutations. There are $n!$ permutations of $(1,2,\cdots,n)$, with $n!=1\cdot2\cdots n$.
There is a very simple algorithm to get them, one at a time, in lexicographic order (that is, the order you use in your example).
Start with a permutation $(a_1,a_2,\cdots,a_n)$, we want the next one in lexicographic order.

Find the smallest index $i$ such that the sequence $(a_i,a_{i+1},\cdots,a_n)$ is decreasing.
If $i=1$, you are done, because the whole permutation is decreasing, and it's the last.
Reverse this sequence $(a_i,a_{i+1},\cdots,a_n)$, so that it's now increasing.
Exchange $a_{i-1}$ with $a_j$, where $j$ is the smallest index, such that $j\geq i$ and $a_j>a_{i-1}$. You have then the next permutation.

See RosettaCode for several implementations. For Matlab, you have the perms function.
You will find this algorithm and other ones in Knuth's TAOCP volume 4 fasc. 2. The whole volume 4 is about combinatorial algorithms.


private keyword when calling methods

Question: This is a piece of code that I have that I'm testing right now, and I noticed that when I change public to private on the getInfo() method in Person, both Student().printPerson() & Person().printPerson() print out "Person". However, when it's public, "Student" is displayed. Can someone explain this? Why is it that the private modifier disallows access to the getInfo method from Student?
        new Student().printPerson();
        new Person().printPerson();
      }
    }

    class Student extends Person {
        public Student(){
        System.out.println("student invoked")   ;
        }

      public String getInfo() {
        return "Student";
      }
    }

    class Person {
     public Person(){

    System.out.println("person invoked");

     }
        private String getInfo() {
        return "Person";
      }

      public void printPerson() {
        System.out.println(getInfo());
      }

Answer: public (or protected) method in Java are always virtual.
This means that if a derived class overrides the method, calls made through the base class will call the derived class (if the object is actually an instance of the derived class).
When your base method is public, this happens, and calling it from printPerson() calls the overriding derived version.
When it's private, it is not virtual, so calls from the base class always call the base version (since it doesn't know about the derived class' method).
Comment: thanks a lot, this cleared it up. I have another question: if I left the private modifier but wanted instead to access the Student class's getInfo(), how would I do that?
Comment: Use an `abstract` (or virtual) method with a different name.

private keyword when calling methods


What physical effects cause ageing/worn guitar strings to change their tone?

Question: Guitar strings wear out over time and are prone to oxidation due to sweat. As a result, they change their tone usually sounding more "bright" when they are new and "dull" when aged.
There's been a question on this site that goes into what changes happen to the strings i.e. that they oxidate and grease starts to settle in:
Why does the quality of the sound of guitar strings decay over time?
However, no one has gone into how grease and oxidation changes the vibration characteristics of a string. In particular, I'd assume that it changes the way that a string is able to produce overtones.
I've heard strings would change their stiffness, but haven't seen a scientific comparison between the stiffness properties of new and worn properties anywhere. Does oxidation change the stiffness of a string too? How does stiffness affect the overtones generated by the string?
Also, it'd be interesting to know why changing strings is so particularly relevant on the guitar but seems to be less relevant on e.g. the Piano (to be honest, I've never heard of a string change on a Piano).
Comment: Have you considered contacting one of the large string manufacturers? They may just brush you aside with marketing guff, but if you phrase a polite question well someone technical might take the time to reply since passionate people often like talking about their field to those genuinely interested.
Comment: Piano strings rarely get touched, so grease, acids etc. won't be affecting them like they do on guitar strings. MeaningfulUsername's answer seemed fine.
Comment: It sounds like you should devise an experiment, or send it in to Mythbusters.
Comment: I've definitely heard of people changing strings on a piano, but it *is* much more rare, and also tends to accompany refinishing/refurbishing the entire instrument.
Comment: Piano strings also break and must be replaced then, especially with heavy use.
Comment: Anecdotally, some joker once squirted me & my Rikki with HP Sauce during a gig. The strings went dull in seconds.
Answer: One effect that is relevant for the wear on metal cored strings is work-hardening -- the repeated bending of the string through use causes microscopic changes in the crystalline structure of the strand of steel, affecting its stiffness and ultimately leading to breakage.  Similar to bending a paper clip back and forth until it breaks.  This affects the tone because string stiffness leads to inharmonicities and wave dispersion in the string motion.  There are inharmonicities even in fresh strings, but they change as the stiffness of the string changes.
I'm also not 100% convinced that "oxidation" is a significant effect, but if it were it would go something like this: the patches of oxidized metal on the strings are stiff (inelastic), so they to affect the ability of the string to freely bend back and forth, and thus affect the sustain and overtone characteristics of the string in a manner similar to the work-hardening referred to in the previous paragraph.
A third effect is the build up of fatty/gummy gunk (oils from your skin mixed with dust from the air), either on the surface of the string or in the grooves of the wound strings.  This has the effect of adding additional internal friction to the string (sort of like smearing a slinky with Vaseline), resulting in less sustain.  This makes the notes seem like a pitched "thud" instead of having ringing sustain.
I'm not sure how (or if) these considerations apply to non-metallic strings.
Answer: I believe the effects are:

The oil & muck from your fingers getting into the string :"A third effect is the build up of fatty/gummy gunk (oils from your skin mixed with dust from the air), either on the surface of the string or in the grooves of the wound strings. This has the effect of adding additional internal friction to the string (sort of like smearing a slinky with Vaseline), " - credit Dave's answer for that. This affects the wound strings (nylon or steel) far more than the unwound ones, although it can collect under the thinner strings too.
Work-hardeining of the string which will affect the stiffness of the metal. Work-hardening occurs when metal is bent to and fro repeatedly. This happens as the string vibrates, notably at the bridge (especially when you bend a string). The metal becomes brittle and eventually will break. I don't believe this will affect the tension in the string but it may affect the tone. Nylon strings don't seem to suffer from the same effect although nylon itself does harden after a while, but this can take a much longer time.
Lastly and also significant is oxidation. This affects all the strings but in my experience it affects thinner (unwound) string more. Acid in your sweat sets on the strings and the metal rusts. This is why unwound steel stings go a bit black after a while. Eventually bits of the metal in the string actually rust away, and the string gets thinner - but it'll do this usually unevenly giving rise to problems with intonation (you just can't get the string in tune anymore). Obviously the thinner the string gets, the more chance of it breaking. This doesn't affect nylon strings at all, but the windings of wound nylon strings may suffer a similar effect. The inner part of a nylon string is ... nylon, so it won't end up breaking, just sounding strange.

This last effect will differ depending on who plays the guitar. Some people have VERY acid sweat, others not to. I have experience of this : my fingers don't rust guitar strings too much; they last quite a while but for me the work hardening effect is what makes them break in the end. However I have lent a gutar to a friend for a weekly jam and been amazed how, week by week, the strings literally went ginger with rust. He says all his guitars do that as he seems to have very acid sweat.
You can prevent some of this taking hold, to an extent, by wiping down the strings after playing so that the moisture from your hands doens't sit on the string. It'll also help get rid of the oily muck.
Comment: I wonder if rusting strings is what makes old strings feel "sharp" to me
Comment: @WayneWerner Could be - I've noticed that too. I guess it maight not be so much that the string is thinning out, but it becomes a bit rought and uneven?


Stripe: How can I create a non-renewable subscription plan?

Question: We would like to have a yearly plan for our service, but legally we cannot automatically-renew our customer's yearly plan. We need to communicate with our customers in a timely manner within the weeks leading up to the end of their yearly plan so that they will manually purchase another year. (this is a legal thing). So we need some method of setting up a Stripe subscription plan that will either not auto-renew, or that we can cancel via API when we're informed via a webhook that their subscription's year is about to end.
Has anyone had any luck with any creative ways of setting up a non-renewable yearly subscription plan with Stripe? Trying to avoid needing to setup a cron job that hits Stripe everyday to find subscriptions that need to be cancelled.
After contacting Stripe support, there's not an "official" way to do so.
One thought I had was to setup a custom subscription plan of 10 days with a 355 day trial period. That way I could set a webhook to trigger based on the customer.subscription.trial_will_end event.
I'm doing this with the node.js Stripe module.
Answer: Well, you could set up a $0.00 subscription, and then a listener for invoice.created webhook, and use that to trigger a flow where you inform the user that their invoice is due, and direct them to a page where they can 'approve' the payment.  When they approve it, you could then just create a good old fashioned Charge to collect the money.
Basically, use Stripe as your cron job, and do the actual Charge creation separately.


High disk time on SQL Server

Question: We have a dedicated SQL Server 2008 R2 Enterprise Edition.
The setup is:

D: (data files) - stored on local ssd disks (not the same disks as log files) (raid 10)
E: (log files) - stored on local ssd disks (not the same disks as data files) (raid 1)
F: (transaction log backup) - stored remote on a SAN

Today we moved our log files to new disks (from F: to E:). From a shared volume (F:(SAN)) to dedicated local disks (E:).
What then happend was that the "disk time", "avg. transfer time" and "avg disk write queue length" increased on the volume where we have the data files (D:) (not on the volume where the log files are located).
The data volume and log volume does not share disks, however they share the same controller card.
"Disk idle time" is low for all volumes.
One thought is ofcourse that the controller card might be overloaded. But, we need more ideas on where the problem might be.
UPDATE:
The RAID controller is DELL PERC H700 (512 MB cache). The server is a DELL R910.
We have about 2500 transactions / sec during peak hours.
The "disk time"-counter has been at 100% since we moved the log files (even during low traffic time).
The "disk idle time" however is about 98-99% for D: (data files) and E: (log files)
We have write back cache enabled for booth the data disks and the log disks.
The wait stats looks like this:
<code>wait_type                     wait_time_s
---------                     -----------
BROKER_TASK_STOP               1283336.21
FT_IFTS_SCHEDULER_IDLE_WAIT     101357.47
PAGELATCH_EX                     89712.72
BROKER_TRANSMITTER               75894.76
XE_TIMER_EVENT                   38778.35
REQUEST_FOR_DEADLOCK_SEARCH      38770.35
SQLTRACE_INCREMENTAL_FLUSH_SLEEP 38767.03
FT_IFTSHC_MUTEX                  38759.14
LOGMGR_QUEUE                     38632.87
CHECKPOINT_QUEUE                 38382.63
BROKER_EVENTHANDLER              35082.42
XE_DISPATCHER_WAIT               34396.31
DISPATCHER_QUEUE_SEMAPHORE       33578.68
</code>
Comment: Big ouch here. This is REALLY haryd to say. Can you share more info? LIke: What time are we talking about, what card, what backplane, what throughput etc. - and do contact MS PSS and open a ticket.
Comment: If you move the log files back to the local drive do the times go back down to the previous levels?  I'm just wondering if you had two things change.
Comment: What aboout disc access times? THose are the only interesting ones. I.e. "ms/read" and "ms/write". The rest (other disc performance counters) are hard to evaluate.
Answer: After some more research (checking waits and running the site with peak traffic), the "problem" described above was actually not a problem.
The problem appeared when we removed a bottleneck (the old log storage). So when we got faster disks for the tranaction logs the data disks could handle more transactions / sec and therefore the queue length increased.
It also explain why disk idle time was good.
The "disk time"-counter seems to be  pretty much useless for a fast disk system (using cache etc).

High disk time on SQL Server


Finding the 19th derivative of $\frac{x-1}{e^x}$ using taylor series

Question: Full context: The problem is multiple choice and originally asks to find the 19th derivative which I prefer to do by Taylor Series. My method get's the answer (after plugging in $x=0$) but it is a bit unsatisfying since it relies on there being multiple choice options and I am wondering if there is a less multiple choice-y way to do the question under time pressure.
I took
$$f(x)=e^{-x}(x-1)=\sum_{n=0}^{\infty}\frac{1}{n!}(-x)^{n+1}-\sum_{n=0}^{\infty}\frac{1}{n!}(-x)^{n}$$
A taylor series centered at zero. Then we can equate
$$
\frac{f^{(n)}(0)}{n!}=a_n\Rightarrow \frac{f^{(19)}(0)}{19!}=\frac{1}{18!}+\frac{1}{19!}\Rightarrow f^{(19)}(0)=20
$$
Then plugging in, only one solution satisfies $f^{(19)}(0)=20$: $(20-x)e^{-x}$.
I am wondering: Is there a more sound way to find a closed form solution? I tend to not be great at looking for a pattern, especially under pressure, so if that is your method please explain how you go about seeing a pattern quickly after a couple of computations.
Comment: My previous (now deleted) comments were incorrect: I made a calculation mistake and misunderstood the question a bit; apologies. To answer the question: unfortunately, I dont think there is a great way to do this other than to 'recognize the pattern' after taking a few derivatives. That being said, it seems like such a question should only be asked in multiple choice format and if it is multiple choice, I think you used the best method for reasoning through it if you prefer not trying to guess at patterns. This seems like something that would be on the GRE for example which is multiple choice.
Comment: fair enough, thank you for clarifying. And that is where it came from :)
Answer: I think this  maybe useful for you
$$y=e^{-x}(x-1)$$
$$y'=-e^{-x}(x-1)+e^{-x}=-y+e^{-x}$$
$$y''=-y'-e^{-x}=y-2e^{-x}$$
if you continue, you will get the following equation for nth derivative
$$y^n=(-1)^{n}y+(-1)^{n+1}*n*e^{-x}$$
Comment: This is an excellent answer and exactly what I was looking for, a method for "seeing" the pattern
Answer: Hint: By the quotient rule
\begin{align*}
f'(x) &= \frac{(1)e^{x} - e^x(x-1)}{e^{2x}}\\
&=e^{-x} - \frac{(x-1)}{e^x}\\
&=e^{-x} - f(x)
\end{align*}
If you want to be rigorous, you can use induction to finish this off! However, its clear from this point that
$$f^n(x) = (-1)^{n+1}ne^{-x} + (-1)^nf(x)$$
(which gives your answer for $n=19$).
Hope this helps.
Comment: this was also great, I am sorry I saw the other one first. Upvoted!


Autocorrelation differences

Question: Though I know the key definition of autocorrelation. How can I define the difference of autocorrelation in case of simple regression model and multiple regression model?
Answer: "Difference of autocorrelation" doesn't make sense. Did you mean "autocorrelation of difference" ? You might want to look at http://www.autobox.com/pdfs/regvsbox-old.pdf as an introduction to "regression versus time series" suggesting a way to integrate both memory(arima) and regression (x) effects. You might want to find Mr. Chitra Baniya in Katmandu , Nepal [Central Department of Botany, Tribhuvan University] as he might be of help to you as you pursue this subject.

Autocorrelation differences


How can I extract the correct hyper-plane from sklearn.svm's LinearSVC

Question: I'm not certain I understand how sklearn's Linear SVC works. I had assumed that it would find an optimal hyper-plane to divide one class from another.
I tried to recover the separating hyper-plane from the following example in  the docs (https://scikit-learn.org/stable/modules/generated/sklearn.svm.LinearSVC.html#sklearn.svm.LinearSVC.score):
from sklearn.svm import LinearSVC
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.datasets import make_classification
X, y = make_classification(n_features=4, random_state=0)

clf = make_pipeline(StandardScaler(), LinearSVC(random_state=0, tol=1e-5))
clf.fit(X, y)
clf.score(X, y)

and, found the score was 0.93
I then tried to extract the dividing hyper-plane and recover this result. I did it the following way:
A = clf.named_steps['linearsvc'].coef_
b = clf.named_steps['linearsvc'].intercept_
C = np.dot(A,X.transpose()) + b
C = C[0,:] # This gives C the shape of y

I then tried to rescale C so that all positive responses correspond to +1 and all negative responses correspond to 0. This was to make C match y. I did this as follows, renaming C as y_calc:
y_calc = (C > 0).astype(np.int)
clf.score(X, y_calc)

I expected to get a perfect score by using y_calc as the 2nd argument to clf.score. I did not. The score I got was 0.96.
This doesn't make sense. I eventually found that if I added a margin, I could get the perfect score I expected:
C1 = C + 2.5e-1
y_calc = (C1 > 0).astype(np.int)
clf.score(X, y_calc)

I don't understand this. I found 2.5e-1 by guessing. I don't see where it came from. The specified tolerance in LinearSVC was 1e-5, not 2.5e-1.
Why did I need to add 2.5e-1 to C, in order to get the classifications from clf.score mach those calculated directly from the SVC calculated hyper-plane?

I think the issue lies in the use of StandardScaler() within make_pipeline. Possibly, I need to extract the standard scaling.
Answer: Yes .... The issue was standard scaling. I needed to rescale X, by subtracting the component-wise mean (mu=np.mean(X, axis=0)) and dividing by the component-wise std (sigma = np.sqrt(np.var(X, axis=0)) to recover the correct result.
It should be noted that in their code the authors of sklearn.svm are careful to avoid divide by zero errors, deal with issues involving sparse/non-sparse matrices and update incremental statistics using the following reference:
"The algorithm for incremental mean and std is given in Equation 1.5a,b
        in Chan, Tony F., Gene H. Golub, and Randall J. LeVeque. "Algorithms
        for computing the sample variance: Analysis and recommendations."
        The American Statistician 37.3 (1983): 242-247:"

I did not need to be so careful for my quick sanity check. Using the following rescaling was all that was needed to correctly use the Linear SVM's hyper-plane:
mu = np.mean(X, axis=0)
sigma_2 = np.var(X, axis=0)
sigma = np.sqrt(sigma_2) #Slightly too slavish in mimicing sklearn's calculations
                         # Could've just calc'ed np.std directly
Xscale = (X-mu)/sigma
Cscale = np.dot(A,Xscale.transpose()) + b
Cscale = Cscale[0,:]
y_calc = (Cscale  > 0).astype(np.int)
clf.score(X,y_calc)


Is binomial coefficient $\binom{n}{t}$ increasing in $t$

Question: Let $t\geq \alpha n$ be an integer. I want to know whether there exists a nice lower bound for $\binom{n}{t}$. I know that the following is true
$\binom{n}{\alpha n} \geq \frac{1}{2\sqrt{n}}2^{h(\alpha)n}$, where $h(\alpha) = -\alpha\log{\alpha} - (1-\alpha)\log(1-\alpha)$ is the Binary entropy function . For a proof of this please see The exponential complexity of satisfiability problems
.
Answer: The binomial coefficient ${n \choose t}$ is not monotone in $t$, it increases when $t$ varies from $0$ to $\lfloor \frac{n}2\rfloor$, then we have
$${n \choose \lfloor \frac{n}2\rfloor} =  {n \choose \lceil \frac{n}2\rceil},$$
and finally it decreases when $t$ varies from $\lceil \frac{n}2\rceil$ to $n$. More specifically, it is symmetric with ${n \choose t} = {n \choose n-t}$.
A proof of this symmetry follows immediately from the the definition
$${n \choose t} = \frac{n!}{t!(n-t)!},$$
and the monotonicity behavior also follows from this, using the recurrence relation
$${n \choose t+1} = {n \choose t} \frac{n-t}{t+1}.$$
So if $t=n$, then ${n \choose t}=1$ and this is the only lower bound you can have if you don't have additional restrictions on $t$ (from above).


Stuck on proof of Thm 8.4 in Baby Rudin.

Question: Theorem 8.3: Given a double sequence $\{a_{ij}\}$ ,$i=1,2,3,\cdots$,$j=1,2,3,\cdots$, suppose that
$$\sum_{j=1}^\infty|a_{ij}|=b_i\ \ \ (i=1,2,3,\cdots)$$
and $\sum b_i$ converges. Then
$$\sum_{i=1}^\infty\sum_{j=1}^\infty a_{ij}=\sum_{j=1}^\infty\sum_{i=1}^\infty a_{ij}.$$
Theorem 8.4: Suppose
$$f(x)=\sum_{n=0}^\infty c_n x^n$$
the series converging in $|x|<R$. If $-R<a<R$, then f can be expanded in a power series about the point $x=a$ which converges in $|x-a|<R-|a|$, and
$$f(x)=\sum_{n=0}^\infty\frac{f^{(n)}(a)}{n!}(x-a)^n\ \ \ (|x-a|<R-|a|)$$
Proof we have
$$f(x)=\sum_{n=0}^\infty c_n[(x-a)+a]^n$$
$$=\sum_{n=0}^\infty c_n\sum_{m=0}^n\Big{(}^n_m\Big{)}a^{n-m}(x-a)^m$$
$$=\sum_{m=0}^{\infty}\Big{[}\sum_{n=m}^\infty\Big{(}_m^n\Big{)}c_na^{n-m}\Big{]}(x-a)^m$$
This is the desired expansion about the point $x=a$. to prove its validity, we have to justify the change which was made in order of summation. Theorem 8.3 show that this is permissible if
$$\sum_{n=0}^\infty\sum_{m=0}^n\Big{|}c_n\Big{(}_m^n\Big{)}a^{n-m}(x-a)^m\Big{|}$$
converge.
Why does theorem 8.3 shows that this is permissible if
$$\sum_{n=0}^\infty\sum_{m=0}^n\Big{|}c_n\Big{(}_m^n\Big{)}a^{n-m}(x-a)^m\Big{|}$$
converge?
Comment: I don't have the book: can you post the whole exercise and the theorem in question? (Maybe about changing order of summing)
Comment: We want to derive thm 8.4 using thm 8.3
Comment: I'm not squinting or stretching the image for that. Edit your post to write it in MathJax. https://math.meta.stackexchange.com/q/5020/171839
Answer: Consider:
$$\sum_{n=0}^\infty c_n\sum_{m=0}^n {n\choose m}a^{n-m}(x-a)^m = \sum_{n=0}^\infty \sum_{m=0}^n{n\choose m}c_na^{n-m}(x-a)^m$$
and since:
$$\sum_{m=0}^n\Bigg|{n\choose m}c_na^{n-m}(x-a)^m\Bigg|<\infty$$
because it is a finite sum, you can apply Theorem 8.3 by considering the remaining terms of the sum to be zero. Thus you can permute the sums (being careful with the indexing).
Comment: Is this method reasonable? Let $s(n-m):=\Big{\{}_{0\ \ \ n<m}^{1\ \ \ n \geq m}$ and $\sum_{n=0}^\infty c_n\sum_{m=0}^n\Big{(}^n_m\Big{)}a^{n-m}(x-a)^m$$=\sum_{n=0}^\infty\sum_{m=0}^\infty c_ns(n-m)\Big{(}^n_m\Big{)}a^{n-m}(x-a)^m$
Comment: and use theorem 8.3
Comment: You have to be careful because if $n<m$ the combination (or binomial coefficient) ${n\choose m}$ is not well defined. If you want to take this approach, try defining $a_{n,m} = c_na^{n-m}(x-a)^m$ for $n\geq m$ and $a_{n,m} = 0$ for $n<m$.
Comment: I apologize, I missed a combination when defining $a_{n,m}$.


Restore Exchange 2003 database to disk on a server not running Exchange

Question: I need to restore an Exchange 2003 database to disk on a server that is not running Microsoft Exchange, would that be possible? or would Backup Exec only restore to a server running Exchange?
If it is not possible, how can i restore the database to the production Exchange server without overwriting the production database?
The purpose of the restore is to retrieve a mailbox that had some messages deleted.
The backup software is Backup Exec 2010 R2 running on Windows Server 2008 R2 64bit, backing up to magnetic tape.
Granular Recovery Technology is not being used for backup, just throwing that in.
Comment: Are you sure the e-mails are actually deleted? Most administrators set a retention policy when installing Exchange so e-mails are not deleted for ~30 days. This allows you to open outlook and undelete items during the retention period.
Comment: @ZeroSubnet, Exchange data is in basically a big database file.  You can't really do anything with the database.  Generally with Exchange you must follow a special procedure to restore, but the procedure you partly depends on how you are performing the backups.  There are a couple tools that will read the database files directly, but those tools also come with software to extract the raw database files directly from common backup archives.  You and the Exchange Admin should probably be **coordinating the restore**.
Comment: So you restore the database files, without Exchange installed how are you planning getting stuff out of the database?
Comment: I will leave that to the Exchange admin. My thought was to do a file level restore so I don't run the risk of overwriting any production database on the production Exchange server
Comment: BackupExec doesn't perform a file level backup of the Exchange mailbox databases or the public folder databases (nor does it for SQL databases). It uses what it calls an "active file exlusion" to exclude the Exchange mailbox database files (the *.edb files). You'll need to use the RSG method as Zoredache states in his answer.
Comment: Ok, considering how sensetive the situation is to data loss on a production server, I will have to ask this. Does Backup Exec or Exchange "know" to put the store being restored into the Recovery Storage Group instead of the production storage group?
Comment: Agree with Zoredache, I have also used Ontrack PowerControls. The tool is amazing, I also had good experience with Stellar Toolkit for Exchange. But Ontrack PowerControls is best!!
Answer: It sounds like you are looking for instructions on how to use the Recovery Storage Group.

This article describes the new Recovery Store Group feature in
  Exchange Server 2003. By using the Recovery Storage Group feature, you
  can mount a second copy of an Exchange mailbox store (database) on the
  same computer as the original mailbox store, or on any other Exchange
  computer that is in the same administrative group. You can use the
  Recovery Storage Group feature to recover mailbox data without having
  to install and to configure a separate Exchange recovery computer.

I am not sure which version of Backup Exec you are running, but this article may have the directions you need.
How to prepare Exchange 2003 so that a Recovery Storage Group Restore can be performed
Comment: So the restore can't be done to disk on just any server. A recovery storage group needs to be created on the Exchange server and that will allow for restoring an older copy of the database from backup, without the risk of overwriting the live database.
Comment: I am not saying it can't be done, just that what you are asking is probably not what you want/need.  [Ontrack PowerControls](http://www.krollontrack.com/software/powercontrols/) can work with a database directly, but it is somewhat expensive.
Answer: Basically Exchange Server data have lots of database file. You can't easily do anything. so You must follow a special procedure to restore and coordination with Administrator for restore exchange.

NTBackup is in-build tools and found in the Start to Accessories to System Tools then Backup.
Open NTBackup click the 'Restore and Manage Media' tab. Backup files
display in the left panel. Chose Option:

Overwrite the original copy of the database.
Or Restore to alternate database

Select recent backup file then choose Alternate Location where you
store.
Complete the Selection process then Start Restore and after complete Finish.


ProgressDialog gets dismissed when button is pressed

Question: I have a "please wait" ProgressDialog that includes a button, the problem is that when the button is clicked the dialog is dismissed (it disappears), how can I make the dialog stay on the screen?
    // Please wait dialog
private void showWaitDialog() {
    prgDialg = new ProgressDialog(context);
    prgDialg.setTitle("Working...");
    prgDialg.setMessage("Please wait.");
    prgDialg.setCancelable(false);
    prgDialg.setButton("Do something", myListener);
    prgDialg.show();
}

// Click listener
public OnClickListener myListener = new OnClickListener(){

    @Override
    public void onClick(DialogInterface dialog, int which) {
        textViev1.setText("xxx");
    }

Comment: Why do you need a button in progress dialog?
Comment: @NareshR Not true, you can easily use a **`ProgressDialog`** with a `setButton` to create a cancel button. However, you need to set the `onClickListener` after the `ProgressDialog` has been rendered.
Comment: By definition, if you use a built in button on a Dialog, it will dismiss the dialog. If you want to have more interaction with the Dialog, you will need to add a View to it containing the buttons etc that you want.
Comment: @NareshR For example, a **Cancel** button.
Comment: possible duplicate of [Prevent ProgressDialog from getting dismissed by onClick](http://stackoverflow.com/questions/18579030/prevent-progressdialog-from-getting-dismissed-by-onclick)
Comment: @JoshPinter For that you need to create a custom dialog using DialogFragment and place the ProgressBar and Cancel Button.
Answer: Try this
prgDialg.setButton("Do something", new DialogInterface.OnClickListener()
    {
        public void onClick(DialogInterface dialog, int which)
        {
            // Use either finish() or return() to either close the activity or just the dialog
            return;
        }
    });

Comment: Unfortunately, you can't prevent the `ProgressDialog` from closing using this method, regardless of what you put in the `onClickListener`. You need to set the `onClickListener` after the `ProgressDialog` has been shown.
Comment: @JoshPinter, This actually helped me. Thank you.
Comment: @Mann You bet. Check out this answer for an example: http://stackoverflow.com/a/24843394/293280
Answer:

prgDialg.setButton("Do something", myListener);
    the above method setButton(CharSequence text, DialogInterface.OnClickListener listener) is deprecated.

you can use
private void showWaitDialog() {
    prgDialg = new ProgressDialog(this);
    prgDialg.setTitle("Working...");
    prgDialg.setMessage("Please wait.");
    prgDialg.setCancelable(false);
    prgDialg.setButton(DialogInterface.BUTTON_NEUTRAL, "Do something", this);
    prgDialg.show();
}

@Override
public void cancel() {

}

@Override
public void dismiss() {

}

Comment: This still dismisses the `ProgressDialog` when the button is clicked.
Answer: private void showWaitDialog() {
    prgDialg = new ProgressDialog(context);
    prgDialg.setTitle("Working...");
    prgDialg.setMessage("Please wait.");
    prgDialg.setCancelable(false);
    prgDialg.setNeutralButton("Do Something", new View.OnClickListener() {

    @Override
    public void onClick(DialogInterface dialog, int which) {
                textViev1.setText("xxx");
    }
    });
    prgDialg.show();
}

Comment: I don't have `setNeutralButton` available. Where'd you get that from?


Using Flow for browser apps

Question: I want to use Flow (the static type checker for JavaScript by Facebook) for browser apps. How do you get Flow to follow the other .js files which are being used by a given .js file? In Node.js, the use of the require function makes Flow follow other modules and check for type errors, and I want a similar functionality for browser apps too.
Say I have a Classroom.js file which uses a module Student.js. When I run Flow, it will throw the error identifier Student Unknown global name.
Answer: Facebook uses browserify to do this in their Flux Chat example. Browserify inlines the require statements in node-style JavaScript to produce code that can be run in the browser.
Here are the relevant bits of their package.json:
{
  "scripts": {
    "build": "NODE_ENV=production browserify . | uglifyjs -cm > js/bundle.min.js",
  },
  "browserify": {
    "transform": [
      ["reactify", { "stripTypes": true }],
      "envify"
    ]
  }
}

Answer: I have run into this problem myself, just now.
As you have a single, simple dependency (Classroom --> Student, this link contains a workaround that might help in your case.  http://flowtype.org/docs/third-party.html
It says, create a new directory, put an "interface file" inside (this is basically a stub. pick any name for the file), and include everything with
flow check --lib /abs/path/to/my/interfacefiledir/ Classroom.js

For more complex scenarios, like secondary dependencies, third-party-libraries (like including jQuery with its full API), I don't have a strategy.
I think the facebook-flow team has put "add more interface files" on their to-do list. http://flowtype.org/docs/coming-soon.html#_

Using Flow for browser apps


Bounds of integration

Question: A little bit rusty on the topic of surface integrals and perhaps some basic calculus after a while. A little help would be appreciated
Find the volume of the solid under the surface $$z=3x^{2}+y^{2}
$$ and above the region bounded by $$y=x$$ and $$y^{2}-y=x.$$
The main problem I'm facing is with the parabola. I've found the parabola to cut the y-intercept at $y=0$ and $y=1$. However, this does not square with the solutions I am looking at.
Any help is appreciated.
Comment: It is helpful to draw pictures for these types of problems. You need to visualize how these surfaces intersect one another in order to find the bounds of your integrals.
Comment: @AlexG. I did but not exactly sure what am I missing.
Clearly, the parabola intercept the y-axis at y=0 and y=1. The equation y=x is just the straight line.
I want the area bounded within this region.
But clearly, when I attempt to determine the point of intersection, I arrived at y=0 which is a contradiction so something is wrong somewhere.
Comment: I think you are missing that these are surfaces in three dimensional space, not just lines and parabolas. $y=x$ is a plane, and $y^2-y=x$ is a "parabola-shaped cylinder" or whatever you would call it. You need to see not only how these two intersect, but how they intersect with $z=3x^2+y^2$ as well.
Comment: @AlexG. I don't believe that we need to consider the "sides" of the plane $x=y$ and parabolic cylinder $x=y^2-y$.  The volume under the surface $z=3x^2+y^2$.  We need not see how they intersect with the surface of interest.
Answer: It might be easier here to view the region in the $x-y$ plane, which comprises the domain for the integral, having $y$ playing the role of the independent variable and having $x$ as a function of $y$.
The region in the $x-y$ plane is bounded from $x=y^2-y$ to $x=y$ as $y$ goes from $0$ to $2$.
Therefore, the volume integral is
$$V=\int_0^2\int_{y^2-y}^y(3x^2+y^2)dx\,dy$$
Can you finish?
Comment: Of course, trivial. Thank you!
Comment: @Mathematicing You're welcome!!  My pleasure.

Bounds of integration


Is setting an attribute to null the same as not setting it in Terraform configuration?

Question: I was looking at the code of terraform VPC module and found
resource "aws_subnet" "public" {
   vpc_id     = aws_vpc_ipv4_cidr_block_association.secondary_cidr.vpc_id
   cidr_block = "188.8.131.52/24"
   availability_zone = null
}

availability_zone attribute is optional based on the docs of AWS provider.
Is setting availability_zone to null is the same as not listing it all? For example, this is the same way to write the following configuration:
resource "aws_subnet" "in_secondary_cidr" {
  vpc_id     = aws_vpc_ipv4_cidr_block_association.secondary_cidr.vpc_id
  cidr_block = "126.96.36.199/24"
}

I've never seen it before. Seems like it's a popular way to declare an optional variable in a module:
variable "private_subnet_assign_ipv6_address_on_creation" {
  description = "Assign IPv6 address on private subnet, must be disabled to change IPv6 CIDRs. This is the IPv6 equivalent of map_public_ip_on_launch"
  type        = bool
  default     = null
}

Answer: Yes, if you use null is the same as not listing it all. From docs:

a value that represents absence or omission. If you set an argument of a resource to null, Terraform behaves as though you had completely omitted it — it will use the argument's default value if it has one, or raise an error if the argument is mandatory. null is most useful in conditional expressions, so you can dynamically omit an argument if a condition isn't met.


DIV só ficar clicável se o RADIO estiver marcado

Question: Gostaria que meu <button id="bottaaoPA">Comprar</button> só ficasse clicável se o radio estivesse marcado.
Código:

$(function(){

  var contador = 0;

  $('.pa').click(function(){

    if(contador === 0)
    {
      $(this).addClass("select");
      $(this).hasClass("selectB");
      $("#bottaaoPA").css("display","block");
      $("#bottaaoPB").css("display","none");
      $("#bottaaoPC").css("display","none");
      contador = 1;
    }
    else
    {
      $(this).removeClass("select");
      $("#bottaaoPA").css("display","none"); //apenas para teste
      contador = 0;
    }
  });
});
$(function(){
  $("#bottaaoPA").click(function(){
    if($("input[name='bbt']").prop( "checked" ) &&
       $("input[name='resp'").prop( "checked" ))
    {
      alert("Dois marcados");
    }
  });
});

<form action="">

<input type="radio" class="radio" id="radio1" name="bbt" value="bbt">Li e concordo com o Regulamento Geral BBT.

<input type="radio" class="radio" id="radio2" name="resp" value="resp">Li e concordo com o Termo de Isenção de Responsabilidade do evento.

Baixe aqui a Ficha de Inscrição/Ficha Médica para a sua inscrição do evento.

</form>
<button id="bottaaoPA" disabled="disabled">Comprar</button>
Answer: Ficaria assim com a div:

$(function(){
  $("#bottaaoPA").off("click");

  $("#bottaaoPA").click(function(){
    if($("input[name='bbt']").prop( "checked" ) &&
       $("input[name='resp'").prop( "checked" ))
    {
      alert("Dois marcados");
    }

  });
  $("input[name='bbt']").click(function(){
    verifica();
  });
  $("input[name='resp']").click(function(){
    verifica();
  });

  function verifica()
  {
    if($("input[name='bbt']").prop( "checked" ) &&
       $("input[name='resp'").prop( "checked" ))
    {
      $("#bottaaoPA").on("click");
      return true;
    }
    else
    {
      return false;
    }
  }
});

<form action="">

<input type="radio" name="bbt" value="bbt">Li e concordo com o Regulamento Geral BBT.

<input type="radio" name="resp" value="resp">Li e concordo com o Termo de Isenção de Responsabilidade do evento.

Baixe aqui a Ficha de Inscrição/Ficha Médica para a sua inscrição do evento.

</form>

Comprar

Ou pode ser (mas o bottaaaoPA deve ser um botão pois div não tem atributo disabled):

$(function(){
  $("input[name='bbt']").change(function(){
    verifica();
  });
  $("input[name='resp']").change(function(){
    verifica();
  });
  $("#bottaaoPA").click(function(){
    alert("teste");
  });

  function verifica()
  {
    if($("input[name='bbt']").prop( "checked" ) &&
       $("input[name='resp'").prop( "checked" ))
    {
      $("#bottaaoPA").prop("disabled", false);
      return true;
    }
    else
    {
      return false;
    }
  }
});

<form action="">

<input type="radio" name="bbt" value="bbt">Li e concordo com o Regulamento Geral BBT.

<input type="radio" name="resp" value="resp">Li e concordo com o Termo de Isenção de Responsabilidade do evento.

Baixe aqui a Ficha de Inscrição/Ficha Médica para a sua inscrição do evento.

</form>
<button id="bottaaoPA" disabled>Comprar</button>
Comment: Completei a resposta usando a `div`, com a função `on` e `off` do `jquery`. Agora com a div também funciona, só será clicável se os dois checkbox forem marcados.
Comment: Amigo não foi... ainda com 1 marcado da para aperta no botão :/
Comment: Aqui funciona perfeitamente, aperte em Executar trecho de código e verá. para ele não fazer nada quando apenas um radio estiver marcado basta apagar os `else if` e `else` que ele só fará algo se ambos tiverem marcado.
Comment: @Ivcs eu tirei so deixei o IF mas mesmo assim ele fica clicavel
Comment: Para deixar clicável ou não é só usando botão amigo, coloquei o jeito usando botão na resposta.
Comment: Sim ele ja esta assim com o disable mas se eu marca 1 ele ja fica clicável :/
Comment: Mano você está fazendo algo errado então, olhe na resposta no segundo `Executar trecho de código` só ativará o botão se os dois estiverem marcado.
Comment: Opaaa, agora foi descobri meu erro obrigado :)
Answer:

$(document).ready(function() {
  $(".radio").click(function() {
    if($("#radio1").is(":checked") && $("#radio2").is(":checked")) {
      $("#bottaaoPA").removeAttr("disabled");
    }
  });
});

<form action="">

<input type="radio" class="radio" id="radio1" name="bbt" value="bbt">Li e concordo com o Regulamento Geral BBT.

<input type="radio" class="radio" id="radio2" name="resp" value="resp">Li e concordo com o Termo de Isenção de Responsabilidade do evento.

Baixe aqui a Ficha de Inscrição/Ficha Médica para a sua inscrição do evento.

</form>
<button id="bottaaoPA" disabled="disabled">Comprar</button>
Comment: Ele deu mais ou menos certo. pois preciso que o botão só fique ON se os 2 RADIO estiverem selecionados e não só um!
Comment: @kaiquemix você não especificou isso na sua pergunta. Mas, de qualquer forma, já editei minha resposta.
Comment: não foi, apertando 1 ele ainda da para apertar
Comment: @kaiquemix aqui funcionou corretamente. Você está fazendo algo errado.
Comment: Vou atualizar o meu la em cima apra você da uma olhada Igor
Comment: editei, poderia dar uma olhada


Atypical intersection of algebraic varieties

Question: We know that if $X, Y\subset \mathbb{A}^n$ are irreducible closed subvarieties and we assume that $X\cap Y$ is non empty, then each irreducible component of $X\cap Y$ has dimension at least $\dim{X}+\dim{Y}- n$. But when talking about unlikely (atypical) intersections we move to the other side of the inequality:
In Umberto Zannier's book "Some Problems of Unlikely Intersections in Arithmetic and Geometry", in the very first pages we study the motivation to this field:

Why would we expect the opposite of the above theorem?
Thanks in advance.
Comment: In addition to the answer, one may note that by the moving lemma of intersection theory, it is always possible to find a cycle $Z$ on the space, which is rationally equivalent to $X$ and whose components intersect $Y$ in varieties of dimension $r+s-n$. So up to deformation (in some sense), this is the situation of intersection theory.
Answer: Note that this is not completely the opposite of the theorem you quoted. The part

in particular to be empty if $r+s<n$.

is exactly a consequence of your theorem, when the intersection takes place in $\mathbb A^n$ (and similar theorems hold in $\mathbb P^n$). So the question is: Why do we expect $\dim X \cap Y = r+s-n$ in the "general case"?
I think one motivation comes from linear algebra. If $r+s \geq n$, then two subspaces $V_1, V_2 \subset V$ of dimensions $r,s$ have an intersection of dimension $r+s-n$ if and only if $V_1 + V_2 = V$. But $r+s$ "general" vectors will generate $V$.
A less basic motivation might come from differential topology. Two manifolds $X,Y  \subset Z$ are said to intersect transversely in a point $p \in X \cap Y$, if and only if their tangent spaces in $p$ generate the tangent space of $Z$, i.e.
$$T_pX + T_pY = T_pZ.$$
Here you see the connection to the linear algebra case. Now there are important transversality theorems in differential topology, that you can always move the manifolds in such a way that they intersect transversely in every intersection point. So transverse intersections are the generic case also for manifolds.
Comment: Oh I see! so apparently I misunderstood the "atypical" part. Thank you!


syntax error, unexpected '{' at token "{"

Question: So somewhere in this pile of code I am getting the above error (as seen in title) and I have spent a great deal of time trying to figure out why.
<code>vec4 calcPointLight(PointLight pointLight, vec3 normal);
 {
  vec3 lightDirection = worldPos0 - pointLight.position;
  float distanceToPoint = length(lightDirection);
  lightDirection = normalize(lightDirection);

  vec4 color = calcLight(pointLight.base, lightDirection, normal);

  float attenuation = pointLight.atten.constant +
                      pointLight.atten.linear * distanceToPoint +
                      pointLight.atten.exponent * distanceToPoint *  distanceToPoint +
                      0.0001;
</code>
return color / attenuation;
 }
Answer: Get rid of the semicolon at the end of the first line.
Side note: you should really mention what language you're working with at the very least.


Dynamic product catalogues

Question: So, I work at a web development agency and we recently decided to give our custom CMS up and start developing with Drupal. Currently, I am developing a wholesale product website. What I need to do is to create some product catalogs without using commerce since we do not need the purchase, checkout and payment features and I thought that using the built-in Content, Taxonomy and Views features we can get our job done.
I have created the product categories in Taxonomy. The main (root) categories are main Taxonomy objects and the subcategories are terms.
I created a custom Content type called: products. In this type I have the following form fields: Product Code, Name, Image, Description and a list field to choose the Terms I would like the product to be displayed in.
I would appreciate some help in order to set the whole structure up as I am still heavily influenced by the custom CMS we used to work on that had similar content management with Joomla!
In conclusion, I would like to:

Set a sidebar menu up that contains the categories and the subcategories as a tree. I would also like the menu to be updated if any changes occur in the taxonomy (e.g I add a term in taxonomy and it shows up on the menu).
Set the structure so that when someone clicks on a category that does NOT contain products but subcategories, gets the list of the categories bellow the active one.

I am really looking forward to your answers and I'd like to thank you in advance.
Answer: Personally instead if all Vocabularies are part of same "Tree" they should be in one "vocabulary" and current items should be displayed as parent terms -> children terms tree structure
1. regarding first bullet point

https://www.drupal.org/project/taxonomy_menu <- allows adding
taxonomy items to any menu of your choice
https://www.drupal.org/project/taxonomy_menu_block <- creates a block
in sidebar with list of your terms of selected vocabulary with
options such as "Count" that is updated on cron run
taxonomy_manager <-  I use to mess around with the order of things or
importing lots of terms it really speeds up the process if you would
need to move taxonomies from different vocabularies into one :)
Google it as I cannot post more then 2 links :)

2. regarding second bullet point
For that you would need to create "Taxonomy view" instead of content view and set it up so that the categories would be displayed for example: (cant post example as not enough rep)
Answer: You're definitely going to want to leverage Views for this. You'll make a view to display all of your taxonomy terms in a block, and put it in the appropriate region in your theme. Views will keep that block updated automatically as any terms are changed.
You might find a module like Views Tree helpful for your display. And this question is pretty much a duplicate of the second part of your question: "Taxonomy with depth" view
Comment: I will try that today and let you know. It's mainly the fact that I need more experience to completely understand drupal's work flow (which looks brilliant). Thank you.

Dynamic product catalogues


R checking if the same numbers occur in multiple rows of a data frame

Question: I have a data frame, nearest_neighbour, which lists the nearest neighbours of a point. So for point 1, the 1st nearest neighbour is point 2, the second nearest neighbour is point 3, and so on.
What is the quickest way to loop through this and check if 4 points all share the same nearest neighbours?
Eg. Point 1's three nearest neighbours are 2, 3 and 4. Point 2's nearest neighbours are 1, 3 and 4 etc.
  which.1 which.2 which.3
1       2       3       4
2       1       4       3
3       1       4       2
4       3       1       2
5       2       4       6
6       7       5       2

I can do it easily with if statements for just two neighbours:
count <- 0
for (j in 1:length(nearest_neighbour[[1]])){
    if(nearest_neighbour[[1]][nearest_neighbour[[1]][j]] == j){
        count <- count + 1
    }
}

However this method seems silly for more than 2 as there ends up being a lot of if statements.
Answer: Here is a base R method using factor and apply
groups <- factor(apply(cbind(df, seq_len(nrow(df))), 1,
                       function(i) paste(sort(i), collapse="_")))

groups
      1       2       3       4       5       6
1_2_3_4 1_2_3_4 1_2_3_4 1_2_3_4 2_4_5_6 2_5_6_7
Levels: 1_2_3_4 2_4_5_6 2_5_6_7

The inner function sorts a vector and collapses the result into a string separated by underscores. This function is applied to each row of a modified version of the data frame where the current row number (element ID) is added.
Answer: Here is also a base R solution, but with a different approach:
dd <- t(apply(df, 1, function(x) table(factor(x, levels=1:max(df)))))

colSums(dd) >= 4

    1     2     3     4     5     6     7
FALSE  TRUE FALSE  TRUE FALSE FALSE FALSE

So points 2 and 4 appear more (or equal) then 4 times.