How to get from $R$ to $R^2$ the hard way

Question: If $r = \frac{S_{X, Y}}{S_X S_Y}$ and $r^2 = \frac{SS_{reg}}{SS_{tot}}$, how do I prove that squaring $r$ really gets me to $r^2$ using those definitions or derivations thereof?
I guess the best way is to start by equating $\left[\frac{\sum{xy} - n\bar{x}\bar{y}}{\sqrt{\sum{x^2} - n\bar{x}^2}\sqrt{\sum{y^2} - n\bar{y}^2}}\right]^2$ and $\frac{\sum{(\hat{y}-\bar{y})^2}}{\sum{(y-\bar{y})^2}}$, but I can't get much past that. How can I further simplify this equation in order to prove that $\left(\frac{S_{X, Y}}{S_X S_Y}\right)^2 = \frac{SS_{reg}}{SS_{tot}}$?
Comment: @Patrick, It's self study. I've been studying ANOVA and the relationships between the $F$ statistic, $r^2$ and $r$ by extension. I'll add the tag, Thanks for the tip!
Comment: What's the reason for this question? If it is a homework or self-study question, the tag "self-study" should be added. (I'm asking because... isn't simply squaring R sufficient?)
Answer: You are missing square roots for $S_X$, $S_Y$ and $SS_{reg}$ should be $\sum(\hat{y}-\overline{y})^2$ but I assume that these are just typos.
Let $y=\alpha+\beta x+\varepsilon$ and let us note that
$$r=\beta\frac{S_X}{S_Y}$$
$$r^2=\beta^2\frac{\overline{x^2}-\overline{x}^2}{\overline{y^2}-\overline{y}^2}$$
On the other hand we have
$$\frac{\sum{(\hat{y}-\overline{y})^2}}{\sum{(y-\bar{y})^2}}=\frac{\overline{\hat{y}^2}-2\overline{y}\overline{\hat{y}}+\overline{y}^2}{\overline{y^2}-2\overline{y}^2+\overline{y}}=\frac{\overline{\hat{y}^2}-\overline{\hat{y}}^2}{\overline{y^2}-\overline{y}^2}$$
since $\overline{y}=\overline{\hat{y}}$ (show it). Now we are left to prove that
$$\beta^2(\overline{x^2}-\overline{x}^2)=\overline{\hat{y}^2}-\overline{\hat{y}}^2$$
which can be done by manipulating the rhs, e.g. using $\overline{\hat{y}}=\hat{\alpha}+\hat{\beta}\overline{x}$.
Comment: Thank you for pointing the typos and providing a solution!
Comment: The key there is that insight that $\bar{y} = \bar{\hat{y}}$, which rings true since $(\bar{x}, \bar{y})$ is the fulcrum of the regression line. Nice catch! ;)


Map iteration race detector in golang map[string]float64

Question: I have a map in golang myMap map[string]float64 which is pre-initialized. I'm trying to iterate over it and run coroutine functions on with keys
for k, v := range myMap {
  go func() {
    f(k,v)
  }()
}

But I'm getting a race detected using go run -race a.go in above which I'm not able to resolve.
I also tried the following but it still gives the same error.
for k, v := range myMap {
  go func(k string) {
    f(k,v)
  }(k)
}

Comment: Create a [mre] showing the actual race.
Answer: In your second example the variable v from the range loop is still being accessed by multiple go routines at the same time causing the race condition.
Instead pass v into the function.
for k, v := range myMap {
    go func(k string, v float64) {
        f(k, v)
    }(k, v)
}

Or alternatively you could just call f using the go keyword.
for k, v := range myMap {
    go f(k, v)
}

Comment: I agree with using a named function. Way too many programmers overuse inline functions / lambdas in my opinion, when they ought to just call a function.


System of diophantine equations $x^2+3y=u^2$, $y^2+3x=v^2$

Question:
Solve the following system of Diophantine equations(the unknowns are positive integers):
  $$
\left\{
\begin{array}{c}
x^2+3y=u^2 \\
y^2+3x=v^2
\end{array}
\right.
$$

I worked as follows:
subtract the two equations to get: $4x^2-4y^2-12(x-y)=9y^2-9x^2\ \implies\ ... (x-y)(13x+13y-12)=0\implies x=y\  or\  13x+13y-12=0$
The first equation has infinite answers and the second has none(since $gcd(13,13)$ does not divide $12$), am I right??
Comment: Shouldn't subtraction give you $x^2 + 3y - y^2 - 3x = u^2 - v^2$?
Comment: @AnHoa Yes you are right,but before that I had deduced that since $u^2-x^2=3y$ so $u-x=3$ and $u+x=y$
Answer: The solution to this system of equations there.   http://www.artofproblemsolving.com/community/c3046h1046718__4
$$\left\{\begin{aligned}&x^2+qy=z^2\\&y^2+qx=v^2\end{aligned}\right.$$
Use this decision.
$$x=2psb^2-a^2p^2$$
$$y=2abp^2-b^2s^2$$
$$q=as(4bp-as)$$
$$z=a^2p^2+2psb^2-abs^2$$
$$v=2abp^2-psa^2+b^2s^2$$
In our case, it is necessary to $b=1$ ; $p=1$ and  $(a,s) - (\pm3;\pm1)$
Answer: $$x^2-y^2-3(x-y)=u^2-v^2$$
$$(x-y)(x+y-3)=(u+v)(u-v)$$
Assuming $u^2-v^2\neq 0$, we have:
$$\dfrac{x-y}{u-v}=\dfrac{u+v}{x+y-3}=\dfrac{r}{s}$$ where $\gcd(r,s)=1$.
$$x-y=\dfrac{r(u-v)}{s}$$
$$x+y=\dfrac{s(u+v)}{r}+3$$
since $x,y$ are integers, and $u,v$ have the same parity, then there exist $p,q$ such that: $$u-v=ps $$ $$ u+v=qr $$
Hence,
$$x-y=pr $$
$$x+y=qs+3 $$
with $$x=\dfrac{qs+pr+3}{2}$$ $$y=\dfrac{qs-pr+3}{2}$$
$$u=\dfrac{qr+ps}{2} $$ $$v=\dfrac{qr-ps}{2} $$ where either $qr$ and $ps$ have the same parity and $pr$ and $qs$ have opposite parity.
Answer: We can without (much) loss of generality assume that $y\le x$. Note that $x^2+3y$ is a perfect square  greater than $x^2$.
Thus we have $x^2+3y\ge (x+1)^2$. But $x^2+3y\lt (x+2)^2$.  It follows that  $3y=2x+1$.
Since $y^2+3x$ is a perfect square, so is $9y^2+27x$, that is, $4x^2+31x+1$.  This has to be a square, so $4x^2+31x+1$ is equal to one of $(2x+1)^2$ or $(2x+2)^2$ and so on up to $(2x+7)^2$, since $(2x+8)^2$ is clearly too big.
The case $(2x+1)^2$ does not work, and neither does $(2x+2)^2$, nor $(2x+3)^2$.  The case $(2x+4)^2$ gives $x=1$. The case $(2x+5)^2$ does not work. The case $(2x+6)^2$ gives $x=5$, which does not work because $y$ is not an integer, and the case $(2x+7)^2$ gives $x=16$.
We conclude that the solutions are $x=1,y=1$, $x=16, y=11$, (and $x=11,y=16$).
Comment: It seems there are other answers for unknowns too,for example: $x=16,y=11,u=17,v=13x=16,y=11,u=17,v=13$... –
Comment: @HamidRezaEbrahimi: My approach used a few more cases than perhaps necessary, but I think things are OK now.


Split lines in GeoPandas

Question: I can find how to split 1 line using geopandas/shapely
def split_line_by_point(line, point, tolerance: float=1.0e-12):
    return split(snap(line, point, tolerance), point)

However I can't figure out how to apply this over an entire geometry column while maintaining other values.
Applying the above function to df.geometry loses a bunch of information
How do split a below linestring so that it 'explodes' maintaining 'type' and 'properties' cols?
{"Feature":'Hi',"ID":1,Linestring([1,1],[2,2],[3,3])},
{"Feature":'bye',"ID":2,Linestring([10,10],[20,20],[30,30])}

To
    {"Feature":'Hi',"ID":1,Linestring([1,1],[2,2])},
    {"Feature":'Hi',"ID":1,Linestring([2,2],[3,3])},
    {"Feature":'bye',"ID":2,Linestring([10,10],[20,20])}
    {"Feature":'bye',"ID":2,Linestring([20,20],[30,30])}

Lines need to be smaller where length > x
Comment: can you define these functions and post a complete code example, ideally a [mre]? what are split, snap, line, point?
Comment: @MichaelDelgado I updated the post to reflect the type of function I need.
Comment: can you show what you've tried and what's not working? what do you mean that it loses a bunch of information? does `df['geometry'] = df.geometry.apply(split_line_by_point); df.explode()` not work? if not, why not? please check out the guide to [ask] - we really need your code and a clear description of what's not working to be able to help. Thanks!
Comment: I tried to solve similar problem in diferent topic.
Splitting whole line_gdf with point_gdf and preserve table:
https://stackoverflow.com/a/78106911/13034952
Answer: This works for me:
import geopandas
from shapely import geometry
from shapely.ops import split, snap

gdf = geopandas.GeoDataFrame([
    {"Feature":'Hi',"ID":1,"geometry": geometry.LineString(([1,1],[2,2],[3,3]))},
    {"Feature":'bye',"ID":2, "geometry": geometry.LineString(([10,10],[20,20],[30,30]))}
])

def split_line_by_point(line, point, tolerance: float=1.0e-12):
    return split(snap(line, point, tolerance), point)

result = (
    gdf
    .assign(geometry=gdf.apply(
        lambda x: split_line_by_point(
            x.geometry,
            geometry.Point(x.geometry.coords[1])
        ), axis=1
    ))
    .explode()
    .reset_index(drop=True)
)

Output:
  Feature  ID                                           geometry
0      Hi   1      LINESTRING (1.00000 1.00000, 2.00000 2.00000)
1      Hi   1      LINESTRING (2.00000 2.00000, 3.00000 3.00000)
2     bye   2  LINESTRING (10.00000 10.00000, 20.00000 20.00000)
3     bye   2  LINESTRING (20.00000 20.00000, 30.00000 30.00000)

Comment: this seems like a nice solution, but for a single point applied over a gdf of lines, if I'm reading correctly? Can you suggest how to tweak it so it could be applied to a gdf of points where each point gets snapped to the nearest linestring in a different gdf? (not all linestrings will get split).  For example, would it run inside of for i,d in gdf_points.iterrows() where point for the function is d.geometry?

Split lines in GeoPandas


Creating a tick system with BC date

Question: My code currently works via after each tick, add 1 to the date, you can see that this then dependant on the month etc will add a month/year when necessary. This is more visual than anything as all game logic will be using the total days system.
However, as you can see there are a multitude of different issues, ie all months are 30 days, and this is alot of code as opposed to a simple DateTime method. However my game is set in 1000 BC and so I cant use the DateTime format. How can I get around this issue?
public Text timeText;

public byte day = 1;
public byte month = 1;
public short year = 1000;

public int totalYears = 1;
public int totalMonths = 1;
public int totalDays = 1;

[Range(0.1f, 5f)]
public float timeSpeed = 1f;
private float elapsedTime = 0;

public bool play = true;

private string[] monthNames = new string[13]
{
    "January",
    "February",
    "March",
    "April",
    "May",
    "June",
    "July",
    "August",
    "September",
    "October",
    "November",
    "December",
    "January"
};

private void Update()
{
    elapsedTime += Time.deltaTime;
    if (elapsedTime >= timeSpeed)
    {
        elapsedTime = 0f;

        AddDay();
        Debug.Log(day + ", " + monthNames[(int)month] + ", " + year.ToString() + " BC");
    }
}

private void AddDay()
{
    totalDays += 1;
    day += 1;

    if (day == 31)
    {
        day = 1;
        AddMonth();
    }
}

private void AddMonth()
{
    totalMonths += 1;
    month += 1;

    if (month == 13)
    {
        month = 1;
        AddYear();
    }
}

private void AddYear()
{
    year -= 1;
    totalYears += 1;
}

public void updateTimeText()
{
    timeText.text = monthNames[(int)month] + ", " + year.ToString() + " BC";
}

EDIT: I was potentially looking to design my own calendar using the following;
public class GameCalendar : MonoBehaviour
{
    public List<Month> months = new List<Month>();

    public void Awake()
    {
        AddMonth(1, "January", 31);
        AddMonth(2, "February", 28);
        AddMonth(3, "March", 31);
        AddMonth(4, "April", 30);
        AddMonth(5, "May", 31);
        AddMonth(6, "June", 30);
        AddMonth(7, "July", 31);
        AddMonth(8, "August", 31);
        AddMonth(9, "September", 30);
        AddMonth(10, "October", 31);
        AddMonth(11, "November", 30);
        AddMonth(12, "December", 31);
    }

    public void AddMonth(byte _monthInt, string _monthName, byte _daysInMonth)
    {
        Month m = new Month();
        m.monthInt = _monthInt;
        m.monthName = _monthName;
        m.daysInMonth = _daysInMonth;
        months.Add(m);
    }
}

[System.Serializable]
public class Month
{
    public byte monthInt;
    public string monthName;
    public byte daysInMonth;
}

Comment: Sounds like you should be making your own date class.
Comment: It's not clear to me [what problem you are trying to solve](https://meta.stackexchange.com/questions/66377/). Note that January, February et al. didn't exist in 1000BC either. Are you trying to create a [proleptic calendar](https://en.wikipedia.org/wiki/Proleptic_Gregorian_calendar)?
Comment: Thank you for your time, and apologies if I was unclear. The question I am asking is similar to how the date/time variables work by holding an int value can be called by a method to convert it into a string dd/mm/yyyy. How can I achieve a similar outcome as opposed to each tick adding a day and a month and a year. How can I just reference the int value of totalDays and convert that to dd/mm/yyyy whilst also taking into consideration the month it is in, so that all months are not initialised to be 30 days.
Comment: So a use case for a discussed above is when an ingame event happens, the event class will store the int of the currentday and the dateOfEvent. Then in the UI similarly as how you would call a TimeDate.ToString() method I could do the same with my dateOfEvent variable
Comment: @BugFinder I thought that this would be case. I am working on it at the moment, just wish there was a simpler work around. Thank you both for your time.
Answer: Use nodatime which supports historic dates and different calendars.

Creating a tick system with BC date


How to compare two or more correlation matrices?

Question: I have $P$ correlation matrices $(n \times  n)$ computed with $P$ sets of $(m \times n)$ data (observed) using the MATLAB function corrcoef.

How do I compare and analyze these $P$ correlation matrices with respect to each other?
What are the tests, methods and/or checkpoints?
Answer: One classical test to compare covariance or correlation matrices is Box's M test. In geometrical sense, it compares average volume of P vector bunches to the volume of their hybrid vector bunch. (Covariance or correlation matrix can be understood as matrix of scalar products therefore constituting a bunch of vectors.) Be aware that the significance level of the test is very sensitive to departures from distributional normality of initial data. I don't know if Matlab has it. Usually the test is computed as part of MANOVA or Discriminant analysis procedures.
Addendum. Departure from normality decreases value of significance level, so if your data are not normal you risk to falsely conclude that the matrices in population differ. If you want to rely on the test of significance the data should be reasonably normal. But you may take interest in the statistic value itself which tells about the degree of difference, or nonhomogeneity, among the matrices. Some programs performing the test print out log determinants for each of the matrices - for you to see which among P matrices are similar and which stand out.
Comment: _[Be aware that the significance level of the test is very sensitive to departures from distributional normality of initial data ]_

So the data from which I am computing the correlation matrices (i.e my observations) should be normally distributed?
Comment: @armundle see addendum please.
Answer: You could perform multiple group structural equation modelling where each dataset represents one group. This would allow you to flexibly explore various constraints (e.g., constrain various correlations across the groups). You could also develop a model of the correlations and then constrain aspects of that model.
You could also check out the metaSEM package in R which is designed for fitting structural equation models on multiple correlation matrices. The author of the package also has several articles (e.g., Cheung, 2008, Cheung and Chan, 2005), where he discusses the models and their implementation.
References

Cheung, M.W.L. (2008). A model for integrating fixed-, random-, and mixed-effects meta-analyses into structural equation modeling. Psychological Methods, 13, 182-202. PDF
Cheung, M.W.L., & Chan, W. (2005). Meta-analytic structural equation modeling: A two-stage approach. Psychological Methods, 10, 40-64.PDF


Dúvida com Javascript Replace

Question: Minha situação: Possuo um input mascarado dessa forma: 0,0000 %. Porém, para conseguir validar como desejo, preciso utilizar um replace, trocando a vírgula por ponto, removendo o % e então tratando o valor desta forma: 0.0000.
Sei que posso utilizar algo como numero.replace(",",".") mas isso só irá trocar a vírgula pelo ponto, e minha validação continuará falhando.
É possível num só replaceou código similar, trocar os caracteres e remover o %?
Apesar do problema já ter sido solucionado, abaixo está a minha resposta ao Sergio:
Na minha validação, posso ter números somente menores ou iguais a 100. Quanto ao formato (string ou number), não sei afirmar com 100% de certeza. Creio que terá que ser number, pois provavelmente este valor será guardado num BD e como string acho que não será muito viável.
Detalhe: Não é recomendável que eu use nada back-end por enquanto. Somente front-end. É mais uma validação client side para não deixar o usuário enviar valores bizarros no post.
Comment: @Sergio aí está, amigo. Obrigado!
Answer: É possível com expressão regular. Não sou mestre no assunto, mas isto parece dar conta:
var re = /^(\d+),(\d+) %$/;
console.log("0,0000 %".replace(re, "$1.$2"));

A expressão regular acima funciona assim:

^: a partir do início da string
(\d+): deve existir um ou mais dígitos; os parênteses são para capturar o que casar com essa parte da expressão
,: seguido de vírgula
(\d+): seguido de um ou mais dígitos (novamente capturados)
%: seguido de espaço e sinal da porcentagem
$: fim da string (ou seja, nada após a porcentagem)

Na segunda parte do replace, os dois grupos capturados com parênteses são referenciados como $1 e $2 respectivamente. Ou seja, $1 são os dígitos antes da vírgula, e $2 são os que vêm depois dela. Montamos uma nova string com esses dois termos, e . no meio em vez de ,.

Considerando sua edição, essa expressão parece insuficiente, pois permite qualquer número, mesmo que maior que 100 (exceto negativos, que você não mencionou mas estou considerando inválidos). Uma expressão mais precisa:
/^(\d{1,2}|100),(\d+) %$/

A parte nova, (\d{1,2}|100), significa que antes da vírgula deve haver dois dígitos quaisquer, ou o valor "100".
Comment: Pronto Victor, acrescentei a explicação e outra opção de expressão regular. Também gosto da sugestão do Sergio.
Comment: Ótimo @bfavaretto! Matou a questão de forma simples! Obrigado!

Ficaria agradecido se pudesse explicar o que o código acima faz exatamente. Valendo um upvote... rs
Comment: Realmente eu devia ter explicado (não só pelo upvote, hehe!). Estou correndo agora, mais tarde complemento ok?
Comment: Sem problemas, valeu!
Comment: Obrigado, muito bem explicado! Apesar da nova correção, a antiga já não me permite sequer valores como `100,0001%`.
Comment: Ambas deveriam permitir isso sim, Victor. É porque ambas exigem um espaço antes do  `%`, como no seu exemplo. Mas você pode remover o espaço, ou usar `(\d+) ?%` para deixá-lo opcional.
Answer: Fica mais uma sugestão para além da boa resposta do @bfavaretto.
Uma vez que tem numeros relativamente pequenos pode usar o parseFloat para converter para Number. Assim basta trocar a , para o parseFloat conseguir trabalhar com o numero:
var string = '0,00123%';
var numero = parseFloat(string.replace(',', '.'));
console.log(numero); // 0.00123
console.log(typeof numero); // number

Exemplo: jsFiddle
Answer:

Se usar um split para quebrar a String e um join para unir, tendo algum caractere ou não como fim, consome menos processamento no browser e é mais rapido que usar uma expressão regular. Um trim no final para remover o espaço vazio.
http://jsfiddle.net/5ax7b2gr/

Dúvida com Javascript Replace


How to show the following cool equality:

Question: I am looking for a proof of the following relationship:
$\newcommand{\ds}[1]{\displaystyle{#1}}$
$$
\frac{\ds{\int_{0}^{\pi}\sin^{n-2}\left(t\right)\,{\rm d}t}}
     {\ds{\int_{0}^{\pi}\sin^{n-3}\left(t\right)\,{\rm d}t}}
     =
     {\ds{\Gamma^{\,2}\left(\left[n - 1\right]/2\right)}
      \over
      \ds{\Gamma\left(n/2\right) \Gamma\left(\left[n - 2\right]/2\right)}},
$$
where $\Gamma$ is the Gamma-function.
But: The proof must only contain things that a person could prove that has just a knowledge of $1$-d calculus (you do not need to show everything, but the things you use should be provable with standard techniques). Especially no Complex Analysis and Functional Analysis.
My problem is, that I do not see any kind of relationship between the left and right-hand side.
Comment: Let $I_K = \int_0^\pi \sin^k t\,dt$. Find a recurrence using integration by parts. Evaluate the base cases.
Comment: are you sure this works? cause I do not see how the gamma function comes into play then
Answer: Let $I_n = \displaystyle \int_{0}^{\frac{\pi}{2}} \sin^n(x) dx$. We then have
$I_n = \displaystyle \int_{0}^{\frac{\pi}{2}} \sin^{n-1}(x) d(-\cos(x)) = -\sin^{n-1}(x) \cos(x) |_{0}^{\frac{\pi}{2}} + \int_{0}^{\frac{\pi}{2}} (n-1) \sin^{n-2}(x) \cos^2(x) dx$
The first expression on the right hand side is zero since $\sin(0) = 0$ and $\cos(\frac{\pi}{2}) = 0$.
Now rewrite $\cos^2(x) = 1 - \sin^2(x)$ to get
$I_n = (n-1) \left(\displaystyle \int_{0}^{\frac{\pi}{2}} \sin^{n-2}(x) dx - \int_{0}^{\frac{\pi}{2}} \sin^{n}(x) dx \right) = (n-1) I_{n-2} - (n-1) I_n$.
Rearranging we get  $n I_n = (n-1) I_{n-2}$, $I_n = \frac{n-1}{n}I_{n-2}$.
Using this recurrence we get
$$I_{2k+1} = \frac{2k}{2k+1}\frac{2k-2}{2k-1} \cdots \frac{2}{3} I_1$$
$$I_{2k} = \frac{2k-1}{2k}\frac{2k-3}{2k-2} \cdots \frac{1}{2} I_0$$
$I_1$ and $I_0$ can be directly evaluated to be $1$ and $\frac{\pi}{2}$ respectively and hence,
$$I_{2k+1} = \frac{2k}{2k+1}\frac{2k-2}{2k-1} \cdots \frac{2}{3} = 4^k \dfrac{(k!)^2}{(2k+1)!}$$
$$I_{2k} = \frac{2k-1}{2k}\frac{2k-3}{2k-2} \cdots \frac{1}{2} \frac{\pi}{2} = \dfrac{(2k)!}{4^k (k!)^2} \dfrac{\pi}2$$
Use this to get what you want.
Comment: The limits of the integral are from $0$ to $\pi$.
Answer: They are called Wallis' integrals, since they were studied by the great British mathematician John Wallis more than $3$ centuries ago. (The first link contains the answer to your question, and more).
Answer: Recalling the $\beta$ function$

$$\beta(x,y) = 2\int_0^{\pi/2}(\sin\theta)^{2x-1}(\cos\theta)^{2y-1}\,d\theta, \qquad \mathrm{Re}(x)>0,\ \mathrm{Re}(y)>0, $$

we can relate your integrals to it. Splitting the integral in the numerator as

$$ I=\int_{0}^{\pi}\sin^{n-2}\left(t\right)\,{\rm d}t= \int_{0}^{\pi/2}\sin^{n-2}\left(t\right)\,{\rm d}t + \int_{\pi/2}^{\pi}\sin^{n-2}\left(t\right)\,{\rm d}t\,= I_1+I_2. $$

Now, $I_1$ can readily related to the $\beta$ function while $I_2$ can be related to the $\beta $ function by using the substitution $x=t+\pi/2$ which results in

$$I_2 =\int_{0}^{\pi/2}\cos^{n-2}\left(t\right)\,{\rm d}t. $$

You can do the same with the other integral. I let you to finish the problem.


CHMMC 2015 Individual Problem 0.1.

Question: I am practicing for the CHMMC, and a lot of the problems are very hard for me...
Question $0.1.$ states:

The following number is the product of the divisors of $n$: $$2^63^3$$What is $n$?
  I did some searching on google and found this, but I don't completely understand it.

Can anyone give some needed formulas, hints, or solutions to help me solve this problem?
Comment: First, prove $n$ must be of the form $2^r3^s$ for some positive integers $r,s$. Then work out the product of the divisors of $2^r3^s$.
Answer: Prime factors of $n$ must be $2$ and $3$.
Factors of $n=2^r3^s$ are of the form of $2^{p}3^{q}$ where $0 \leq p \leq r$, $0 \leq q \leq s$
Hence the product is
$$\large{2^63^3=\prod_{p=0}^r \prod_{q=0}^s2^p3^q=\prod_{p=0}^r 2^{p(s+1)}3^{s(s+1)/2}=3^{\frac{(r+1)(s)(s+1)}{2}}2^\frac{(s+1)(r)(r+1)}{2}}$$
Comparing the power of $2$:
$$(r)(s+1)(r+1)=2(6)=12$$
Comparing the pwoer of $3$:
$$(s)(s+1)(r+1)=2(3)=6$$
$$r=2s$$
$$s(s+1)(2s+1)=6$$
$s=1, r=2$
Hence $n=2^23^1=12$
Comment: Can you explain the notation that looks like the roman numeral II?
Comment: That is the notation for products. $\prod_{i=0}^n a_i= a_0 \times a_1 \times \ldots a_n$
Comment: Oh, so like summation notation but for products instead of sums?
Comment: yup, the corresponding notation for summation would be $\sum$. $\prod$ is for product.

CHMMC 2015 Individual Problem 0.1.


Creating Cumulative Uplift Curve in Time Series CV with Rolling Windows

Question: I'm training a binary classifier using time series cross-validation and a rolling window approach, resulting in $k$ test sets. I want to construct a cumulative uplift curve to evaluate the model.
I've considered simply pooling all the test sets together, but that could result in the same customer appearing $k$ times, which isn't ideal. On the other hand, creating $k$ separate uplift curves would be cumbersome.
I would appreciate any advice or insights on the best practices to handle this issue.
Comment: " separate uplift curves would be cumbersome" unfortunately that is the cleanest thing to do.
Answer: To create a cumulative uplift curve for time series CV with rolling windows, I used the following method:

Divide each day's test set into equal percentiles based on classifier predictions.

Calculate daily uplift for each percentile.

Average the uplifts across days for each percentile.

This gives an averaged cumulative uplift curve without pooling test sets or repeating customers.
However, there are assumptions in my approach. For example, I assume that each day (or window) has roughly the same distribution. I haven't found literature supporting this method, and I welcome feedback on its validity.


Baroque notation question

Question: Here's a snippet from a 1624 facsimile of Juan Arañés' "Libro Segundo de Tonos y Villancicos".

This is a rather syncopated, lively song, with a time signature of C3.
Note values seem to be indicated only by the stems, and my guess is that the filled noteheads indicate duple meter, while the hollow noteheads indicate triple meter.
This works well until the next-to-last measure, which is clearly triple but uses filled noteheads.
Question: Is my guess about filled vs hollow noteheads correct? If so, is the next-to-last measure just an error? (Note also the missing dot in the first measure on the second line).
Comment: @AlbrechtHügli Thanks for the reference to the doctoral dissertation. On page 28 I found this discussing the difficulties of interpreting the printed edition _"... así como relativos al uso
"incorrecto" de los ennegrecimientos de la notación ocasionados por síncopas o
hemiolas en los compases ternarios"_ which I translate as _"... as well as relative to the "incorrect" usage of blackening (i.e. filling-in) of the notation caused by syncopation or hemiolas in ternary (i.e. triple meter) phrases_". So it looks like my guess was correct about the filled note heads.
Comment: I assume this 3/2 time and the rhombic black are whole notes while the dots are quarters and the white notes are half notes. This book may help you further: page 213 ff, 239, 259. https://riunet.upv.es/bitstream/handle/10251/86138/CERVER%c3%93%20-%20Juan%20Ara%c3%b1es%20y%20su%20%22Libro%20segundo%20de%20tonos%20y%20villancicos...%20con%20la%20cifra%20de%20la%20guitarra%20e....pdf?sequence=1&isAllowed=y
Comment: @AlbrechtHügli No, the durations are indicated by the stem vs no stem vs flag. If the stem is 1 beat the no-stem is 2 and the flag is 1/2 beat.
Comment: @AlbrechtHügli If you'll post a summary of the above comments, highlighting the link to the dissertation, as an answer, I'll accept it.  It's more information than I ever though I could find.  I'm grateful for your help.
Comment: Ala vida bona: https://soundcloud.com/albertosanna/a-la-vida-bona. Great music!
Comment: @AlbrechtHügli Here's the [Hesperion XXI version](https://www.youtube.com/watch?v=bkkBUaASKY4)
Comment: and here is the transcription:  http://www2.cpdl.org/wiki/images/5/55/Ws-aran-sar.pdf. and yes, your assumptions are right
Comment: I didn't understand *triple meter* and *duple meter*, but now I'm sure you mean the same as *hemioles* - is this correct? Btw, this is another resource for mensural notation: https://archive.org/details/notationofpolyph00apel
Comment: @AlbrechtHügli  If you will post a summary of your comments as an answer I'll upvote and accept so you can have the +25 rep (assuming you care about reputation :-)
Answer: The concept of having even measures is more modern than Renaissance and Baroque music notation. The melody dictates how the music is divided on the page, not the time signature. Therefore it is very common to find seemingly "incomplete" measures. Composers of that era did not place a new time signature at each change the way we do today.

Baroque notation question


Hibernate & Thread Safety: Is an injected SessionFactory thread safe?

Question: So, I'm using a Hibernate DAO with Spring. My DAO is going to be constructed by the ApplicationContext IOC container, and the SessionFactory is going to be injected by the container (LocalSessionFactoryBean).
Now, this DAO is going to be a singleton, used for all CRUD operations in my program, with a pool of database connections behind it. My concern is about the thread safety of the sessionFactory field.
My understanding of thread safety is that all state fields need to be guarded in a multi-threaded environment. Now, the use of this class will be that Spring will set the SessionFactory upon bean creation, and that factory won't be changed after that. This means that TECHNICALLY it could function safely in a multi-threaded environment, but I feel that's a very risky practice, to just operate on the assumption that the setter method won't be called again.
The thing is, synchronizing the SessionFactory would require all calls to it to be synchronized as well. So the insertPortfolio() method I put in below would need to be synchronized as well, which defeats the purpose of having a pool of available connections to the database, since access will be limited to one thread at a time.
I guess the best solution I can think of is to change this from setter injection to constructor injection, and make the SessionFactory field final. But I'm trying to understand the broader issues at stake here, so I can make good multi-threaded safety decisions with spring in the future.
private SessionFactory sessionFactory;

public HibernatePortfolioDao() {}

public void setSessionFactory(SessionFactory sessionFactory){
    this.sessionFactory = sessionFactory;
}

@Override
public void insertPortfolio(PortfolioModel portfolioModel) {
    sessionFactory.getCurrentSession().save(portfolioModel);
}

Answer: The SessionFactory is thread-safe, and it's initialized only once during application bootstrap. Because you're using Spring, the SessionFactory is represented by LocalSessionFactoryBean.
What you were concerned was properly the Seesion returned by sessionFactory.getCurrentSession() which is bound to the current Thread by HibernateTransactionManager.
Answer: A good place to start looking is at the Class itself:  http://docs.jboss.org/hibernate/core/3.5/api/org/hibernate/SessionFactory.html

The internal state of a SessionFactory is immutable. Once it is created this internal state is set. This internal state includes all of the metadata about Object/Relational Mapping.

This allows it to be shared by multiple threads without worrying about synchronizing it.
Answer: The frameworks implementing SessionFactory have to make their SessionFactories thread safe and concurrent. If you are using a good framework, then the sessionFactory being injected can be considered thread safe. You don't have to worry about a session factory implementation because the documentations asks the implementations be thread safe.
The sessions you get from a session factory are per session/transactions and don't have to be thread safe.
Answer: SessionFactory in hibernate is thread safe.  You should implement it using a singleton mechanism because it resource draining.


Does gcc have a extension overload for std::vector::emplace_back?

Question: According to cppreference, std::vector::emplace_back has only one signature, which is:
template< class... Args >
reference emplace_back( Args&&... args );

And in the description, it says emplace_back is supposed to forward each of its arguments to the constructor of the type in the vector. However, when I tested the following code using gcc 12.2, it successfully compiles:
#include <iostream>
#include <vector>

class Foo
{
public:
    int x;
    int y;
    Foo(int x, int y) : x(x), y(y)
    {}
};

int main()
{
    std::vector<Foo> foos;
    Foo foo(1, 2);
    foos.push_back(std::move(foo));
    foos.emplace_back(foo); // weird
}

(See on compiler explorer)
I expected the line foos.emplace_back(foo); to fail the compilation. It seems as if emplace_back has this overload:
template< class T >
reference emplace_back( T& arg );

which isn't mentioned in the documentation. Am I missing something or is this just a compiler extension?
Comment: `T&&` as forwarding reference can deduced to `T&`
Comment: A **template** `T&&` parameter is a *forwarding reference*, and it is **not** quite the same as a non-template `Foo&&` parameter *rvalue reference* (a "moving" reference).
Answer:
foos.emplace_back(foo); // weird

That's weird indeed! You ask to emplace_back, meaning you're calling the constructor, and you're passing foo to the constructor. Hence, you're calling the copy constructor. push_back would have done the same!
That's an implicitly defined default copy constructor, see cppreference on Copy Constructors:

If no user-defined copy constructors are provided for a class type (struct, class, or union), the compiler will always declare a copy constructor as a non-explicit inline public member of its class.

You didn't define a copy constructor, so the compiler did that for you, as dictated by C++. You can avoid that and make your compilation fail:
class Foo
{
public:
    int x;
    int y;
    Foo(int x, int y) : x(x), y(y)
    {}

    //! Explicitly deleted default copy constructor.
    Foo(const Foo&) = delete;
};

foos.push_back(std::move(foo));

He're you're calling the move constructor. Note that you're using foo after moving from it, that's more or less illegal (you throwing std::move at foo means that foo is no longer supposed to hold any resources.)
Should you really happen to just want to delete the move constructor, same syntax, basically: Foo(Foo&&) = delete;.
Answer: template< class... Args >
reference emplace_back( Args&&... args );

can deduced to something like (with Args = Foo&)
reference emplace_back( Foo& && args[0] );

which collapse to
reference emplace_back( Foo& args[0] );


Uniform convergence on compact sets and limits at infinity

Question: Suppose that we have a sequence of continuous functions $(f_n)_{n \in \mathbb{N}}$,
$f_n: \mathbb{R} \rightarrow \mathbb{R}$,
which converges uniformly on compact sets to a function $f$, and that we have moreover that all that limits $a_n:=\lim_{x \rightarrow \infty} f_n(x)$, as well as $a:= \lim_{x \rightarrow \infty} f$ exist. Can we necessarily conclude that $\lim_{n \rightarrow \infty} a_n=a$?
Comment: Hint: Is $\mathbb{R}^+$ a compact set?
Answer: No. Consider a sequence of function $f_n$ defined as follows: $f_n$ is $1$ on the interval $[-n,n]$, it is zero outside $[-n-1,n+1]$ and continuous on $[-n-1,-n]\cup [n,n+1]$.
For example $$f_n(x)=\left\{\begin{array}{ll} 1 & \text{ for } |x| < n\\
0 & \text{ for } |x|>n+1\\
-x+n+1 &\text{ for } n\leq x\leq n+1\\
x+n+1 &\text{ for } -n-1<x<-n  \end{array}\right.$$
The functions $f_n$ converge to the constant function $1$ on compact sets. Buth with your terminology we have $a_n=0$ forall $n$ and $a=1$.


Probability of $P(X_1 X_2\le 2)$

Question: What is the probability of $P(X_1 X_2\le 2)$. Both variables are independent and each has the probability density function $f(x)=1, 1<x<2$, zero elsewhere. First I would like to assume that the pdf of $f(x_1,x_2) = 1$ by virtue of independence. I am now stuck with this one.
Answer: The basic idea is to integrate like so:
$$\int_{\Bbb R}\int_{x_2\le 2x_1^{-1}}f(x_1,x_2)\,dx_2\,dx_1$$
This gives
$$\int_{1}^2\int_1^{2x_1^{-1}}1\,dx_2\,dx_1$$
$$=\int_1^2 2x_1^{-1}-1\,dx_1$$
$$=\bigg(2\log(x_1)-x_1\bigg|_1^2$$
$$=2\log 2-2-(2\log 1-1)$$

$$=2\log 2-1= \log\left({4\over e}\right)$$

Note
If you draw the picture, you can see that this is the right idea, because the region where the density function is positive and where $X_2\le 2X_1^{-1}$ is exactly the area under the hyperbola $X_1X_2=2$ and above $X_2=1$ and to the right of $X_1=1$, and since the probability you are in a set, $A$ is just
$$\int_A f(x_1,x_2)$$
it's easy to see our computation is the right one.

Probability of $P(X_1 X_2\le 2)$


Alterar string usando parâmetro de função

Question: #include <stdio.h>
#include <stdlib.h>
#include <string.h>
void menu_principal(char* monstro1, char* monstro2){
    int escolha;
    char monstro[20];
    printf("King of Tokyo\n\n");
    printf("Jogador escolha um monstro:\n---------------------------\n");
    printf("1-Godzilla\n2-Feto Gigante Zumbi Nazista\n3-Pac-Man\n4-Blanca\n5-Penha\n6-Nemesis\n\n0-SAIR\n\n");
    do{
        scanf("%d", &escolha);
    }
    while(escolha<0 || escolha>6);
    if(escolha==0){
        exit(0);
    }
    printf("VOCE ESCOLHEU:");
    if(escolha==1){
        char monstro[30]="Godzilla";
        printf("%s\n\n",monstro);
    }
    else if(escolha==2){
        char monstro[30]="Feto Gigante Zumbi Nazista";
        printf("%s\n\n",monstro);
    }
    else if(escolha==3){
        char monstro[30]="Pac-Man";
        printf("%s\n\n",monstro);
    }
    else if(escolha==4){
        char monstro[30]="Blanca";
        printf("%s\n\n",monstro);
    }
    else if(escolha==5){
        char monstro[30]="Penha";
        printf("%s\n\n",monstro);
    }
    else if(escolha==6){
        char monstro[30]="Nemesis";
        printf("%s\n\n",monstro);
    }
    *monstro1=monstro;
}

int main(){
    char monstromain1[30]=".";
    char monstromain2[30]="..";
    menu_principal(monstromain1,monstromain2);
    printf("%s",monstromain1);
    return 0;
}

Eu não estou conseguindo alterar o valor de monstromain1 usando a função. Ao executar eu recebo o erro

main.c:42:14: warning: assignment makes integer from pointer without a cast [-Wint-conversion]
       *monstro1=monstro;
Answer: O código está complicado demais e difícil de ler, isto acaba fazendo ficar difícil de achar o problema e ele é o fato de não estar copiando o texto para a variável que deseja, isto deve ocorrer com strcpy(). Este código não é exatamente seguro, mas para um exercício está bom:
#include <stdio.h>
#include <string.h>

void menu_principal(char *monstro1, char* monstro2){
    printf("King of Tokyo\n\n");
    printf("Jogador escolha um monstro:\n---------------------------\n");
    printf("1-Godzilla\n2-Feto Gigante Zumbi Nazista\n3-Pac-Man\n4-Blanca\n5-Penha\n6-Nemesis\n\n0-SAIR\n\n");
    int escolha;
    do { scanf("%d", &escolha); } while (escolha < 0 || escolha > 6);
    if (escolha == 0) exit(0);
    char *monstros[] = { "", "Godzilla", "Feto Gigante Zumbi Nazista", "Pac-Man", "Blanca", "Penha", "Nemesis" };
    strcpy(monstro1, monstros[escolha]);
    printf("VOCE ESCOLHEU: %s\n\n", monstro1);
}

int main(){
    char monstromain1[30]=".";
    char monstromain2[30]="..";
    menu_principal(monstromain1, monstromain2);
    printf("%s", monstromain1);
}

Veja funcionando no ideone. E no repl.it. Também coloquei no GitHub para referência futura.


Select list preenchido dinamicamente opção selecionada com AngularJs

Question: Preciso trazer um select option com a opção selecionada sendo preenchido dinamicamente.
Tenho em meu controller o preenchimento da lista assim:
$scope.$watch('IdCategoria', function() {
            $http.get("/api/Categoria/GetList", {  }).success(function(response) {
                $scope.categorias = response;
            });
        });

E o meu select está assim:
<select ng-model="newCtrl.IdCategoria" required class="form-control" data-live-search="true" ng-options="c.Value as c.Text for c in categorias">
<option value="">Selecione uma categoria</option>
</select>

Onde o newCtrl.IdCategoria é o campo com o Id da categoria selecionada, no qual o select deveria vir selecionado.
Eu li aqui no Stack que usando o track by deveria funcionar, porem se eu setar track by newCtrl.IdCategoria, tanto na edição quanto no cadastro eu não consigo realizar a seleção de outra opção.
Já tentei também o uso do ng-init, mas também sem sucesso:
ng-init="newCtrl.IdCategoria= newCtrl.categorias[newCtrl.IdCategoria]"
Lembrando que minhas categorias são:
[{"Value":"24","Text":"Categoria 1"},{"Value":"25","Text":"Categoria 2"}]

EDIT1 já testei assim
<select ng-model="newCtrl.IdCategoria" required class="form-control" data-live-search="true">
<option value="">Selecione uma categoria</option>
<option ng-repeat="c in categorias" value="{{c.Value}}">{{c.Text}}</option>
</select>

Comment: Já deu uma olhada na [documentação](https://docs.angularjs.org/api/ng/directive/select)?
Comment: Já sim... não sei se é por causa das informações dinamicas mas não funciona de jeito nenhum.. inclusive já testei usando ng-repeat no options e nada!
Answer: Dentro do seu controller:
$scope.$watch('IdCategoria', function() {
            $http.get("/api/Categoria/GetList", {  })
            .success(function(response) {
                if (response.length > 0) {
                     response.unshift({"Value":"0", "Text":"Selecione uma categoria"});
                   $scope.categorias = {
                                         availableOptions: response,
                                         selectedOption: {
                                             Value: response[0].Value,
                                             Text: response[0].Text
                                        }
                                    };
               }
            });
        });

Depois na view:

   <select name="selecao" class="form-control" id="selecao" required class="form-control" data-live-search="true"
      ng-options="option.Text for option in ctrl.categorias.availableOptions track by option.Value"
      ng-model="ctrl.categorias.selectedOption"></select>

Lembrando que isso só vai rolar se houver uma interação neste elemento  "IdCategoria" que eu não faço ideia do que seja e de onde você está interagindo ele, pois a função $watch é para escutar o elemento, quando ele for alterado:
Veja um exemplo:
angular
  .module('seuApp', [])
  .controller('ACtrl', function ($scope) {
    $scope.collection = [];
  })
  .controller('BCtrl', function ($scope) {
    $scope.$watch('nome.input', function (newValue, oldValue) {
         console.log('escutando elemento, valos novo: ' + newValue);
    });
  });

E na HTML:

          Nome {{key}}: <input ng-model="nome.input" ng-change="doSomething()">

         Olá seu nome é {{ nome.input }}

        <button ng-click="collection.push([])">Incluir nome</button>

Olha o JSFIDDLE (1) e JSFIDDLE (2)
Comment: Bom dia Ivan, então.. não deu certo, pelo seguinte motivo. na linha onde você define o seletedOption[0] indicando que o selecionado é o indice 0 da lista, dai ele trás o primeiro item selecionado ao invés de selecionar o item que veio da base no qual eu informo aqui em meu ng-model='newCtrl.IdCategoria'
Answer: Ivan,
Seu json está vindo o value como um string, verifique se seu IdCategoria é uma string ou um integer, se forem de tipos incompatíveis você terá que ou mudar o seu serviço e trazer os valores dos mesmos tipos, ou mudar na interface, usando um toString ou parseInt, a forma mais correta é mudar o serviço, depois que fizer isso a segunda opção que você tentou value="{{c.Value}}" deverá funcionar.
Vale a pena dar uma olhada também aqui:
https://docs.angularjs.org/api/ng/directive/ngSelected
Answer: Tente isso
<select ng-model="newCtrl.IdCategoria" required class="form-control" data-live-search="true" ng-options="c.Value as c.Text for c in categorias">
<option value="">{{newCtrl.IdCategoria ? newCtrl.IdCategoria : "Selecione uma categoria"}}</option>
</select>

pode dar certo caso o newCtrl.IdCategoria não esteja vazio se vier vazio aparece Selecione uma categoria


Function write.table() is converting my character column to numeric when exporting to excel. How can I prevent this?

Question: I have a dataframe in a similar way:
  Material  c1  c2  c3  c4  c5  c6
1   0111    30  44  24  25  52  27
2   0112    19  70  93  23  68  100
3   1124    22  NA  79  18  133 143
4   2389    79  NA  NA  81  60  NA
5   3480    57  8   95  62  NA  90
6   0134    350 60  50  302 44  4

Here I am forcing as character type, but in my real dataframe it alredy is.
df['Material']=as.character(df['Material'])

sapply(df,mode)

write.table(df, paste(".\\exports\\", "dummy.csv", sep = ""), sep = ";", dec = ",",row.names=F)

The problem is that when I export to excel, my Material column becomes numeric and I loose the 0 in the beginning that is a part of the material code description. My rows get sorted and I would like to have them in the original position. Is there a way of preventing this to happen? To keep my Material column as character when exporting?
In case you want to replicate it, I tried to create a dummy version:
df <- data.frame(Material = c('0111','0112','1124','2389','3480'),
                    actual_202009 = c(30,19,22,79,57),
                    actual_202010 = c(44,70,NA,NA,8),
                    actual_202011 = c(24,93,79,NA,95),
                    pred_202009 = c(25,23,18,81,62),
                    pred_202010 = c(52,68,133,60,NA),
                    pred_202011 = c(27,100,143,NA,90))

Comment: I didn't check, but I guess you'd be better off with using a dedicated package for Excel exporting. E.g. `writexl`or even `openxlsx`. openxlsx might look a bit overwhelming at first, but IMO it's currently the most powerful Excel package for R and shoudl hopefully preserve the properties of your R data.
Comment: just a quick thought, have you tryied to put `'` in front of each value of `Material`? Ex: `'0111`. Then open it with Excel. I do not have time to try it now sry...
Comment: Something like what @Paul suggests, another option is to add a character, export, set the format of the column in excel to text, and then find and remove the character... Not neat (but works)!
Comment: Another option is to save the file as text. I guess this is what you are looking for https://stackoverflow.com/questions/28675279/r-write-dataframe-column-to-csv-having-leading-zeroes
Answer: As mentioned in the comments:
This works.
library(openxlsx)
write.xlsx(df, file = "dummy.xlsx")

Even though the data in your csv has quotes around the Material column, excel likes to think for you and not honour the character quotes. Now you could use libreoffice with calc. This will open the text import option where you can tell it that the first column is text and it will retain the correct format for the Material column.
But the easiest is just to use the above code.


The sequence of functions $f_n = \sin{nx}$ is not uniformly equicontinuous on any compact interval.

Question: The sequence of functions $f_n = \sin{nx}$ is not uniformly equicontinuous on any compact interval.
I already proved that this sequence is not uniformly equicontinuous on $[0,1]$:
Let $f_n(x) = \sin(nx)$ be defined on $[0,1]$. Put $\epsilon = \sin(1)$. Let $\delta >0$. Choose $N \in \mathbb{N}$ such that $\frac{1}{N} < \delta$ and define $x_N = 1/N$ and $y_N = 0$. Then $|x_N-y_N| = 1/N < \delta$ while
$$
|f_N(x_N) - f_N(y_N)| = |\sin(1) - \sin(0)| = |\sin(1)| \geq  \epsilon.
$$
This proves that $\{f_n\}$ is not uniformly equicontinuous on $[0,1]$.
My question is this: is there a way to use the fact that $[0,1]$ is homeomorphic to $[a,b]$ to prove the claim?
Answer: Consider the homeomorphism $f:[0,1]\to[a,b]$ defined by $f(x)=a+x(b-a)$ and consider the sequence $\{\sin(n\cdot f)\}$.
Suppose, $\{y\mapsto\sin(ny)\}$ is equicontinuous family on $[a,b]$. Then given any $\epsilon >0$ we have $\delta>0$ such that, $|\sin(ny_1)-\sin(ny_2)|<\epsilon$ for all $y_1,y_2\in [a,b]$ and for all positive integer $n$.
In particular when, $x_1,x_2\in [0,1]$ with $|x_1-x_2|<\frac{\delta}{b-a}$ we have,  $|f(x_1)-f(x_2)|<\delta$, so that for any positive integer $n$ we have, $\big|\sin\big(nf(x_1)\big)-\sin\big(nf(x_2)\big)\big|<\epsilon$. So that, $\{\sin(n\cdot f)\}$ is a equicontinuous family on $[0,1]$. But you have already proved that it is not possible.
Comment: I am aware of the homeomorphism, but I am more specifically asking how to go about using it.
Comment: Consider the compositions.
Comment: Thanks I will try that.
Comment: Check the solution..


Law convergence and Levy

Question: Let $X_n$ be a random variable that converges weakly to some $X$. In my case $X\sim N(0,1)$ I want to prove that
$E[e^{kX_n}] \to E[e^{kX}]$ for some $k \in \mathbb{N}$.
I've heard that this is a corollary of Levy's theorem but I cannot track down which, mainly because levy's corollary is a slang term. Anyone has any ideas?
Comment: Lévy's continuity theorem gives $\mathbb{E}(e^{i \xi X_n}) \to \mathbb{E}(e^{i \xi X})$ for any $\xi \in \mathbb{R}$.
Answer: You cannot prove such convergence without stronger assumptions; even almost sure convergence does not guarantee it.
E.g. it is enough to assume that $\sup_n E[e^{aX_n}]<\infty$ for some $a>k$ and use de la Vallee-Poussin theorem.

Law convergence and Levy


How can we draw a Blaschke $3$ ellipse?

Question: Today I read the article Ellipses and Finite Blaschke Products by Ulrich Daepp, Pamela Gorkin, and Raymond Mortini.
In there they have proved very nice geometric results about  per-images of  Blaschke products which are fixed at zero of degree $2$ and $3$ on the unit circle.
Also in that paper they proved that the existence of marvelous geometric object called Blaschke $3$-ellipses which is looks like as in below.

Here I want to know about more geometrical properties of per-images of Blaschke  products (similar in the above paper). Is there any?
Also I wonder how we can draw the pictures like Blaschke $3$ ellipses.
How we can find a software to draw a Blaschke $3$ ellipses?
or Can we draw them using a common software (like MATLAB)? How?
My question may be not a good one, but I am very curious about this. Thank you.
Comment: In the paper they state "Using Mathematica, we studied several pictures of the points identified under a finite Blaschke product".
Comment: @Amzoti: Oh.. I have missed it. But I don't have an idea how we can use Mathematica to draw picture like this.
Comment: Mathematica is useful than Matlab in sense of drawing picture.
Answer: Here's how I'd plot your image in Mathematica.
<code>B[a_, b_][z_] := z(z - a)/(1-Conjugate[a]z)(z-b)/(1-Conjugate[b] z);
compPts[a_, b_][lambda_] :=
   Quiet[Solve[B[a, b][z] == lambda, z], Solve::ratnz];
realPts[a_, b_][
   lambda_] := {Re[#], Im[#]} & /@ (z /. compPts[a, b][lambda]);
pic[a_, b_] := Graphics[{
    {Thick, Circle[]},
    {PointSize[Large], Point[{Re[#], Im[#]} & /@ {a, b}]},
    Line /@
     Table[Partition[realPts[a, b][Exp[I*t]], 2, 1, 1], {t, Pi/10,
       2 Pi, Pi/10}]
    }];
pic[0.5, -0.4 + 0.4 I]
</code>

Now, the paper proves (as Theorem 1) that the envelope formed by those lines is exactly the ellipse with equation
$$\left|z-a\right|+\left|z-b\right|=\left|1-\overline{a}{b}\right|.$$
I suppose the geometric properties that you refer to spring forth from that equation.
Comment: @Nilan I rather like Stan Wagon's [Mathematica in Action](http://goo.gl/4CSdLf). The reason is that the book focuses on *mathematics* first, thus, there's always an objective. I find it difficult to learn to program without an objective or project in mind. At some point, you'll want a more general introduction, I think that [Mathematica Programming](http://goo.gl/ag0sV7) is good (and free). Then, you need a good reference so definitely make use of the internal documentation. Finally, [this question](http://goo.gl/RAKjU7) on mathematica.se has plenty more references.
Comment: I used your command and got this wonderful picture. I want to know more about mathematica. As you  think hat is the best reference about this software?

How can we draw a Blaschke $3$ ellipse?


Goodness of fit. How to evaluate if polynomial of order n+1 gives statistically better fit than polynomial of order n?

Question: I fit polynomials with increasing order to some data. What is the best way to evaluate if the additional parameter of polynomial of order n+1 provides a statistically significant better fit than the previous polynomial (order n) with a given confidence level (e.g. 99%)?
So far, I used the F-test in the following way:
$$F = \frac{[rss_n - rss_{n+1}] / (p_{n+1} - p_n)}{rss_{n+1} / (N-p_{n+1})} $$
where n is the order of the polynomial, rss$_n$ is its related Residual Sum of Squares, N is the amount of measurements and p$_n$ is the number of parameters of polynomial of order n. This formula comes from: https://en.wikipedia.org/wiki/F-test#Regression_problems. To give context, in my case p$_{n+1}$-p$_n$ is always equal to 1 and N is typically in the order of a few thousands.
Then I checked if F>F_critical(df$_1$,df$_2$,99%), where df$_1$=p$_{n+1}$ - p$_n$=1 and df$_2$=N-p$_{n+1}$ (df=degrees of freedom). If not, the polynomial of order n+1 does not provide a better fit with 99% confidence and I select the previous polynomial as the best fit.
Is this the way to deal with this problem? Are there other ways to do this (maybe using $\chi^2$)?
I have doubts because in some cases with my data it happens that each polynomial until n=9 keeps providing a better fit with 99% confidence and this seems a bit suspicious (particularly because the fitted polynomial seem fairly similar visually). Here is a figure showing polynomials of order 9 (dark green) and 6 (light green). According to the formula above, each polynomial provides a statistically better fit than the previous with 99% confidence interval. However, I think there's a great deal of overfitting instead.

Data for this test (black dots in the figure) can be downloaded here.
Comment: Your F statistic is a bit strange: (a) the numerator is negative, (b) a nth order polynom has $n+1$ parameters and (c) the denominator usually refers to the bigger model, not to the smaller.
Comment: Hi Michael, thanks for your comments. b) That's right, I rewrote the formula so that this is clear. Note that in my case the difference in models' parameters is always 1 as I compare only 'consecutive' polynomials. c) That was a typo from my side, now corrected. a) If the higher order polynomial provides a worse fit, its rss will be higher, which in turns implies the F-test can be negative?
Comment: Now it is a beauty! RSS will never increase if you add a parameter, so you are safe.
Answer: You are right to be suspicious. That's because there is no way for the F-test to account for overfitting, so as long as the additional polynomial terms improve the in-sample fit even slightly, the null hypothesis of zero improvement will be false. In large data sets, you will very rarely fail to reject this hypothesis, even when the model is grossly overfitted.
By the way, an F test between models that differ by only one term is equivalent to a T test of the hypothesis that the one additional coefficient is zero. That is, you're just doing forward selection on an infinite set of increasingly irrelevant features. Even aside from the issue that you will probably overfit with exploratory polynomial regression, there are good reasons to avoid adding and keeping predictors based on one-at-a-time T testing.
If you genuinely believe that a polynomial is the appropriate model, Long and Trivedi (1991) provide a detailed and lucid review of some misspecification tests.
Comment: Hi @ssdecontrol, thanks for your answer. I'm rather sure that a polynomial will do in my case, I'll check the document you suggest but if you have a pointer to a specific test it would be great.

I'm kind of surprised there is no straightforward test to apply for this actually, but maybe I'm just underestimating the task. For example, another thing I tried was to simply look for convergence of the adjusted R$^2$, although 'convergence' was found empirically via some kind of threshold. This also occasionally led to high order polynomials with no visual difference from lower order ones.
Comment: R-squared, even if adjusted, can only ever give you information about in-sample fit. Out-of-fold R-squared in cross-validation will be much more useful
Comment: Although it's not the question, I'd amplify the warning here about overfitting. Polynomials up to degree 9, even when they fit the observed data well, have typically no interesting or useful substantive interpretation and will go haywire outside the observed range. If goodness of fit to data is the main concern, you will do as well or better with some more localised method, say spline or local polynomial.
Comment: Overfitting is exactly my concern, justified by the fact that I don't visually see a substantial improvement of polynomial of order 9 w.r.t polynomial of order 6 for example. I'm preparing a small test dataset to share and a figure to show this. Using the F-test formula above, I get that n=9 gives a statistically better fit than n=8 (and so on) with 99% confidence interval, but I don't trust this.
Comment: @ssdecontrol, I'm checking the LOOCV and see if I get different results than with the F-test above. Will update the discussion as soon as I have more info.
Comment: @CuriousMind LOOCV is not appropriate here. That's for studying outliers and sensitivity analysis. You should use large folds instead
Comment: I'm not familiar with that and did not find any link. With large folds, do you mean large samples of the original dataset? Like a k-fold with large k?
Comment: @CuriousMind yes
Comment: @CuriousMind sorry, I meant k-fold with _small_ k, so that each fold contains enough data points. One data point (as in leave-one-out) is not enough
Answer: I played around a bit with the data you posted, doing a 2-fold cross-validation with polynomial fits up to order 9. Someone else should check me on if I'm getting the CV procedure right, but I split the data into two groups; ran polynomial fits on each separately; and then took
$ \sum_i \left[ (y^0_i - \hat{y}^1(x^0_i))^2 + (y^1_i - \hat{y}^0(x^1_i))^2 \right] $
as the residual sum of squares. That is, I took the polynomial fit from one group, plugged in the x-values of the other group, and compared it to the y-values of the other group; and vice versa. This quantity itself was minimized for an order 5 polynomial; and the RSS actually increased for the 3,6,7, and 9-degree polynomials. I haven't done a proper F-test comparing, say, order 5 to order 3, but it seems like order 5 should be good enough. Here are the results from a final fit of the whole set to order 5.

I think it speaks to the cross-validation that the 5th-order fits to the whole dataset are similar to the fits from only half the data at a time. Just about every fit I looked at has some weird edge effects, though, so you do probably want to go with a spline fit or something to manage that behavior.

Edit: I revised how I was doing the validation, which should be more in line with the Wikipedia entry. I also started doing F-tests against the last best fit, rather than just the previous order polynomial.  The results...n=9 shows up as the best order every time.  That might actually be your best fit to this data?
I'm posting my code here (in Python) and attaching two new plots. The first one shows the RSS values from each fold and the mean RSS across folds, as a function of polynomial order. The second one just shows the data with the cross-validated polynomial fits for each order.  The 'best' one, based on that new F-Test, is highlighted. Let me know if this helps!
Comment: Hi @Jareth, thanks for your help. I tried this as well but order 9 is still chosen most of the times. I ran the same algorithm a number of times (the folds are generated randomly each time) and still get that as 'preferred' choice while order 5 is chosen very seldomly. The fact that a different polynomial is chosen (although 9 is chosen most often) let me think it depends a lot on how the folds are generated. Have you tried your algorithm multiple times? Does it provide a more stable solution?
Comment: Additionally, I also tried a k-fold with k=5. In this case I divide data into k subsets and I use the first 4 to produce 4 fits using polynomials from n=1 to 9. I then use these fits to generate data at the validation x values (the 5th subset) and calculate the RSS against the validation y values. I repeat this whole procedure k times, which means that for each polynomial I produce 20 RSS estimates. I minimize their sums to select the best polynomial. Still get number 9 most of the times.
Comment: I think this comes down to selection criteria. I did a few runs, and orders 5 and 6 were usually the minimum RSS values with orders 8 and 9 once each. In every case, the order 9 polynomial improves things over the order 8 polynomial based on an F-Test. I think what you need to do is generate an F-test comparing the current polynomial fit to the last best polynomial fit, rather than to the previous order.  I also think that in the 5-fold validation, you produce 1 fit that you test on 4 different independent datasets. Can someone more experienced verify that?
Comment: Hi, I based my algorithm on the description on the wikipedia (https://en.wikipedia.org/wiki/Cross-validation_%28statistics%29#k-fold_cross-validation), which of course might be wrong. It'd be great if anyone could confirm if the method is sound.
I changed slightly the selection criterion for the k-fold algorithm and now orders other than 9 are also chosen (including 5 and 6 relatively often) although there is little consistency between different runs, which is worrying.
Comment: My 2-fold algorithm instead should be like yours (including the selection criterion), but it almost always selects order 9 as the solution (so there must be something different there which I haven't found yet).

Are the subsets in your program completely disjointed? I noticed in my case there is about 30 non-unique elements over about 700 observations used as training sets.
Comment: Is your selection criterion based on the F-Test? What I did was generate the residual sum of squares from predicting the values in group B using the fit from group A. (The groups were disjoint.) The orders I quoted above were the ones that gave minimum RSS values out of all the orders of polynomials. I'd still have order 9 polynomial doing better than order 8, based on the F-test, but it wasn't better than order 5. Looking at the Wiki page, I messed up in my use of the cross-validation. If I get a chance, I'll redo some of it tonight and edit my answer.


How to use Faker to generate titles and real English texts

Question: I have  a table called posts in my database and each record represents a post with title, url and body.
Is it possible to use Faker to generate titles and bodies in English? The body should be actual English text.
I went through the docs and didn't find what I'm looking for.
Comment: If Faker can't do it, find a different tool that does. This sounds like a feature request to Faker. Generating arbitrary English text is non-trivial, which is why Faker emits junk Latin by default. If you want to do this yourself look at a Markov Chain to generate it based on sample text you collect into a corpus for training.
Comment: Why do you want to generate fake "real English posts and text"? For testing and development regular old Lorem works fine. The only reason I can think of for generating fakery is in spam or phishing.
Comment: @AmandaFerrari we may appreciate a sense of humor, but you'll very likely want help again from Tin Man.
Comment: I was able to find a very good dataset with all that I needed :D
Answer: For English texts, why can't you do this?
Faker::Quote.matz
=> "I believe that the purpose of life is, at least in part, to be happy. Based on this belief, Ruby is designed to make programming not only easy but also fun. It allows you to concentrate on the creative side of programming, with less stress."

Or try:
Faker::Hipster.sentences.sample
=> "Cornhole drinking actually pop-up brooklyn williamsburg wayfarers."

For Titles, just do
[Faker::Company.name,  Faker::Company.industry].join(' - ')
=> "Schmitt-Kohler - E-Learning"

But if you really need some random actual sentences you can pull them from random book texts and use this gem to easily grab sentences.
require "tactful_tokenizer"
t = TactfulTokenizer::Model.new
string = `curl http://www.textfiles.com/etext/FICTION/alger-cast-544.txt`;
sentences = t.tokenize_text(string);
sentences.count
=> 6322
sentences.sample

"I'm just staying at a place on Fourteenth Street, but I can't
afford to stay there long, for they charge a dollar a day."


How to tune MCMC with unwieldy posterior

Question: Let's say I have $n$ observations of a random variable, $X_1, \dotsm, X_n \sim \mathcal{N}(0, \sigma^2)$. I also assume $\sigma^2$ has a Gamma(1,1) prior distribution, $\pi(x) = \exp(-x)$.
I'm now attempting to use Metropolis-Hastings to sample from the posterior distribution (which I believe is):
$$f(\sigma | X) \propto \frac{1}{(2\pi\sigma^2)^{n/2}}\exp{-\left( \sigma^2 + \sum\limits_{i=1}^n\frac{X_i^2}{2\sigma^2}\right)}$$
However, for larger $n$, this unnormalized density produces usually either quite small or quite large values, making it difficult to get the Markov chain to mix well.
My question is: in general (and for the MH algorithm), what are my options for attempting to sample with such an unwieldy distribution?
Comment: This is a generalised inverse Gaussian distribution. Not particularly unwieldy. If the issue is numerical (underflows and overflows), then work (a) with log-densities and (b) with differences from the maximal value of the log-density.
Comment: Please see https://stats.stackexchange.com/search?tab=votes&q=log%20underflow%20-neural for threads related to computing with numbers that might overflow or underflow a likelihood or probability.  The current reply by @Xi'an nicely illustrates a standard procedure.
Comment: @Xi'an - does using the log-density not break any of the assumptions of MH or other algorithms used for sampling from densities? And can one just take the exponential of the samples obtained via MH to get transform them back to samples from the original density?
Comment: And good point - I guess by "unwieldy", I meant more unwieldy than most distributions that I've had to deal with. In my case, the $\sum X_i^2$ term is quite large, as is $n$, and it's made for a lot of underflows and overflows
Comment: out of curiosity, why use a gamma prior when inverse gamma is conjugate?  If you desire a gamma variate, why not parameterize the normal in terms of precision?
Answer:
does using the log-density not break any of the assumptions of MH or
  other algorithms used for sampling from densities? And can one just
  take the exponential of the samples obtained via MH to get transform
  them back to samples from the original density?

The issue with underflows and upperflows can be treated through logarithms to some extent, without jeopardising the validity of the Metropolis algorithm. The acceptance step
$$u_t\le\dfrac{f(y_{t})q(y_t,x_{t-1})}{f(x_{t-1})q(x_{t-1},y_t)}$$
can be replaced with
$$\log u_t\le \log\dfrac{f(y_{t})q(y_t,x_{t-1})}{f(x_{t-1})q(x_{t-1},y_t)}$$
and
\begin{align*}
\log\dfrac{f(y_{t})q(y_t,x_{t-1})}{f(x_{t-1})q(x_{t-1},y_t)}
&= \log f(y_{t})-\log f(x_{t-1})+\log q(y_t,x_{t-1})-\log q(x_{t-1},y_t)\\
&= \{\log f(y_{t}) -\max_z \log f(z)\}-\{\log f(x_{t-1})-\max_z \log f(z)\}\\
&\qquad\qquad +\log q(y_t,x_{t-1})-\log q(x_{t-1},y_t)\\
\end{align*}
which assuming $\max_z \log f(z)$ does not produce an overflow means a wider range of values of $y_t$ can be explored.
Here is a (codegolfed) rendition in R:
<code>d<-function(y,x,S=1e6,n=1e4)n*log(y^2/x^2)/2+y^2-x^2+S/y^2/2-S/x^2/2
m<-function(T,y=rnorm(1))ifelse(rep(T>1,T),
   c(y*{d({z<-m(T-1)}[1],y+z[1])<rexp(1)}+z[1],z),y)
</code>
where the exponential generator appears because $-\log(u_t)$ is an exponential variate.


trocar html da li

Question: Tenho um ajax jquery que vai receber o click de um href com uma figura dentro.
Queria fazer com que, apenas durante a execução do ajax a imagem de fundo da li, e não da href fosse trocada e ao termino da operação retornasse ao normal.
Ou seja, o href recebe click,. Mas uma li com uma imagem dentro não é clicável normalmente
Estou fazendo assim:
// JavaScript Document
$(document).ready(function(e) {

  $("a.excluiPlano").click(function() {

      if (confirm('Deseja Excluir este Plano?\nAtenção: Excluindo esse plano, todas as fotos serão excluidas!\nDeseja prosseguir?') ) {

        $.ajax({
            url: "../_requeridos/excluiPlano.php",
            type: 'POST',
            data: {'planoid': $(this).attr('planoid')},
            beforeSend: function() {
              $("a.excluiPlano").html("")
              return false;
            },
            success: function (retorno) {

                if (retorno == 1) {

                    alert('Excluido com sucesso');
                    location.reload();

                } else {

                    alert("Erro na exclusão");

                }

            },
            cache: false,
            /* REMOVIDAS PARA QUE O AJAX ENVIE VARIÁVEIS FORA DO FORM/
            contentType: false,
            processData: false
            */
        });

        return false;

      }

  })

});

Como fazer isso?
HTML + PHP
<?php
      $planos = $planosDao->pesquisaPlanos();

      $planosConta = $planos == NULL ? 0 : count($planos);
?>

Listagem de Planos

 <?php
   if ($planosConta==0) {

       echo $phpUtil->erro ("Sem retornos para esta pesquisa");

    } else {

      $registros = 15;
      $pagina = (isset($_GET['pagina']))? $_GET['pagina'] : 1;
      $numPaginas = ceil($planosConta/$registros);
      $inicio = ($registros * $pagina) - $registros;

      $where = " LIMIT ".$inicio.",".$registros;
      $planos = $planosDao->pesquisaPlanos($where);
?>

NOME

DESCRIÇÃO

EDITAR

EXCLUIR?

 <?php

   $contaLinhas = 0;
   $numreg = 25; // Quantos registros por página vai ser mostrado
   $pagina = isset($_GET["pagina"]) ? $_GET["pagina"] : 1;
   $inicial = ($pagina * $numreg) - $numreg;

   foreach ($planos as $plano) :

     $corLinha = $contaLinhas % 2 == 0 ? "rgb(204,204,204)" : "rgb(255,255,255)";

     $linkEditar = "getIdPlano()."'>";

    $linkExcluir = "getIdPlano().">";

  ?>
     <ul class="listaRegistros" style="background-color:<?php echo $corLinha; ?>">

<?php echo $plano->getNome(); ?>

<?php echo substr($plano->getDescricao(),0,30)." ..."; ?>

<?php echo $linkEditar; ?>

<?php echo $linkExcluir; ?>

 <?php
   $contaLinhas++;
   endforeach;

    //exibe a paginação
    for($i = 1; $i < $numPaginas + 1; $i++) {
        echo "".$i."";
    }
  }
?>

Um exemplo mais simples do que eu quero seria o seguinte:

$(document).ready(function(){
    $('a').click(function(){
        var i = $('a').index(this);
        alert(i);
    });
});

link 1
link 2
link 3

Com esse código eu tenho retornado apenas o elemento a que recebeu o click.
Agora como fazer para ter o html() dele?
Comment: O que você chama de `href` é um elemento ``? Você quer que ao clicar num `` que está dentro de um ``, uma requesição ajax seja feita e durante esse processo (até receber a resposta do servidor) uma imagem seja mostrada num ``?
Comment: Use o `beforeSend` do ajax para mudar pro que quer e o `done` para voltar ao normal
Comment: Vocês viram o código postado? No elemento a tem uma imagem que representa exclusão. O que eu quero é que, durante o processo do ajax, essa imagem mude para uma imagem de loader e após a exclusão/bloqueio (vou fazer nos 2), volte ao normal! Isto é, a imagem de bloqueio. Pois a de exclusão não será mais possível pois o registro já não mais existirá! E sim, usei o beforeSend. Mas mesmo assim todas as imagens mudaram juntas
Answer: Pelo que entendi, o problema está em trocar a imagem de fundo de um li durante a
o processo de requisição AJAX que é executado quando um elemento descendente  receber um click.
Para isso, você pode usar a função css do jQuery e as propriedades beforeSend e complete da função ajax do jQuery - se quiser, veja as documentações aqui para css e aqui para as duas propriedades.

$("a.list__link:not(.list__link--not-clickable)").on("click", function(event) {
   event.preventDefault(); // Impede que o browser execute "normalmente" o evento click de uma âncora

   //var $elem = $(this).closest("li.list__item"); Pega o `li` ascendente
   var $elem = $(this); // ancora que foi clicado
   var url = $(this).attr("href");
  var imgUrl = $(this).attr("data-img-url")
 ajaxCall(url, $elem, imgUrl);
});

function ajaxCall(url, $elem, imgUrl) {

   $.ajax({
    url: url,
   type: 'post',
   beforeSend: function () {
    $elem.css({"background-image":"url("+imgUrl+")"})
   },
   complete: function () {
    $elem.css({ "background-image" : "none" });
   }
  });
}

$("a.list__link.list__link--not-clickable").on("click", function (event) {
   event.preventDefault();
   alert("I'm not clickable."); // apagar isto.
});
a.list__link {
  display: block;
  width: 70%;
  height: 70%;
 text-decoration: none;
  background-color: #aaa;
 background-size: 100% 100%;
}
a.list__link.list__link--not-clickable {
 cursor: default;
}

ul.list {
 list-style-type: none;
}

li.list__item {
 height: 15vh;
 width: 80%;
 border: 1px solid black;
}

Click me - Item 1

Click me - Item 2

Click me - Item 3

Click me - Item 4

Comment: Ainda não é isto. A imagem troca. mas troca de todos a pois todos estão com o mesmo .class. Dificil está sendo pegar o valor do id dele
Comment: Esse feito deveria ocorrer apenas para alguns `a`?
Comment: apenas para o a que foi clicado embora todos tenham a a mesma class. Dá uma reolhada no html fazendo favor
Comment: O imagem deveria ser mostrada no `a` e não no `li`?
Comment: isso, preciso saber então qual desse 'a' foi o clicado
Comment: Alterei a resposta para alterar o `a` quando este for clicado e criei um recurso que os elementos `a` que possuírem a classe `list__link--not-clickable` não possam ser clicados (quando forem clicados uma função será invocada e como ela apenas impede a execução "normal" do click, nada acontecerá).
Comment: descobri que fazendo a = $("a.excluiPlano").index(this);, eu pego o elemento clicado.Agora como pegar a propriedade planoid dele? com attr não funcionou
Comment: Dentro da função invocada pelo evento click, você pode obter o elemento clickado assim `$(this)` porque `this` referenciará o objeto JS do elemento clickado. Para pegar a propriedade dele dentro dessa função: `$(this).attr("planoid")`.
Comment: mas no caso, esse this serão todos que teem a mesma classe. Vou adicionar um exemplo do que eu preciso ao final da pergunta
Comment: O evento click é atribuído a **todos os objetos** selecionados pelo seletores indidicados - ex: $("a.excluiPlano") seleciona todos os elementos``.Mas quando o evento é disparado para um objeto,ouseja,o usuário clica em um link,a função invocada,chamada de *event handler*,é aquela passada como argumento para a`on`-ex: `$("a.excluiPlano").on("click",function () {/* Essa é a event handler */ })` -e dentro dela,a palavra-chave`this`referenciará **apenas o objeto clicado** [Mais sobre this MDN](https://developer.mozilla.org/pt-BR/docs/Web/JavaScript/Reference/Operators/this).
Comment: Por isso, quando um link disparar o evento click, a função vai ser executada só para ele.

trocar html da li


calculate height of paragraph with respect to content [data] in it (number of characters)

Question: paragraph is having fixed width of 300px
and
font-size:20px;
line-height:1.4`
overflow:hidden

I want to find out total height that will be occupied
by paragraph in the UI from the data we have (number of character , font-size ,line-height ,width:300px)
Comment: using jquery height you can find like this $('p.classname').height()
Comment: good try but please read question carefully...i want height w.r.t content in paragrah (number of characters)
Comment: use `.text().length`
Comment: If you want number of character in paragraph ,then you can use $('p').text().length
Comment: i want height  :-)
try how to find out height using length of text
Comment: @shank please check snippet
Answer: use .height()

$(document).ready(function(){
alert("height  => " + $("p").height());
 alert("innerHeight => " + $('p').innerHeight());
})
p{
  font-size:20px;
line-height:1.4`;
overflow:hidden;
  width:300px;
    background-color:red;
  padding:5px;
}

ABC  xyz ABC XYZ ABC XYZ ABC  xyz ABC XYZ ABC XYZ

Comment: dear parth...i dont want height of element...i want height of content in an element...dont make me repeat again n again
Comment: @shank  Both are getting same value. what is problem now? if you have any `padding` or something then it makes diffrence between text height and `p` `height`
Comment: @shank please check i have added padding and you can see difference in height for `.height()` and `innerHeight()`
Answer: You can use ineerHeight or height as per you requirement
$('p').innerHeight();
$('p').height();

Comment: i dont want height of element...i want height of content in an element...please read the question carefully


BIND DNS Server failed

Question: I got this error on Centos. How to solve the problem?
named.service - Berkeley Internet Name Domain (DNS)
Loaded: loaded (/usr/lib/systemd/system/named.service; enabled; vendor preset: disabled)
Active: failed (Result: exit-code) since Wed 2017-07-12 12:01:00 EDT; 15s ago
Process: 4728 ExecStartPre=/bin/bash -c if [ ! "$DISABLE_ZONE_CHECKING" == "yes" ]; then /usr/sbin/named-checkconf -z /etc/named.conf; else echo "Checking of zone files is disabled"; fi (code=exited, status=1/FAILURE)

Jul 12 12:01:00 ns1.ringochat.com bash[4728]: zone ns1.ringochat.com/IN: loaded serial 2013071600
Jul 12 12:01:00 ns1.ringochat.com bash[4728]: zone ns2.ringochat.com/IN: loaded serial 2013071600
Jul 12 12:01:00 ns1.ringochat.com bash[4728]: zone ringochat.com/IN: NS 'ns1.ringochat.com' has no address records (A or AAAA)
Jul 12 12:01:00 ns1.ringochat.com bash[4728]: zone ringochat.com/IN: NS 'ns2.ringochat.com' has no address records (A or AAAA)
Jul 12 12:01:00 ns1.ringochat.com bash[4728]: zone ringochat.com/IN: not loaded due to errors.
Jul 12 12:01:00 ns1.ringochat.com bash[4728]: _default/ringochat.com/IN: bad zone
Jul 12 12:01:00 ns1.ringochat.com systemd[1]: named.service: control process exited, code=exited status=1
Jul 12 12:01:00 ns1.ringochat.com systemd[1]: Failed to start Berkeley Internet Name Domain (DNS).
Jul 12 12:01:00 ns1.ringochat.com systemd[1]: Unit named.service entered failed state.
Jul 12 12:01:00 ns1.ringochat.com systemd[1]: named.service failed.

Comment: Fix your `ringochat.com` zone file.
Answer: The error tells you - you have no A records for your name servers.  This means you are probably hosting your own primary and secondary name servers, so you'll need glue records as well.
Jul 12 12:01:00 ns1.ringochat.com bash[4728]: zone ringochat.com/IN: NS 'ns1.ringochat.com' has no address records (A or AAAA)
Jul 12 12:01:00 ns1.ringochat.com bash[4728]: zone ringochat.com/IN: NS 'ns2.ringochat.com' has no address records (A or AAAA)

In your zone file, you need to add something like
ns1.ringochat.com.  IN   A  192.168.123.231
ns2.ringochat.com.  IN   A  192.168.123.232

and then check the zonefile with
named-checkzone ringochat.com /path/to/zonefile
If it reports loading OK (with maybe a "out of zone info ignored" for your glue record servers) then edit again, increase your serial, and restart bind.

BIND DNS Server failed


require_once(File/Iterator/Autoload.php): failed to open stream: No such file or directory in /usr/lib/php/PHPUnit/Autoload.php on line 64

Question: I am trying to install phpUnit on my MAC 10.8 osx.
However everytime I execute the command phpunit on the terminal, I am getting the following error.:
mkothari-nbook:~ mkothari$ phpunit
PHP Warning:  require_once(File/Iterator/Autoload.php): failed to open stream: No such file or directory in /usr/lib/php/PHPUnit/Autoload.php on line 64
PHP Fatal error:  require_once(): Failed opening required 'File/Iterator/Autoload.php' (include_path='.:/php/includes') in /usr/lib/php/PHPUnit/Autoload.php on line 64
I have tried to update the php.ini file with the following paths but none have given me success with the installation:
include_path=".:/usr/local/php/pear/"
;include_path = ".:/usr/lib/php/pear"
;include_path = ".:/usr/lib/php/PHPUnit"

MY phpunit files are located at this location:
php /usr/lib/php/PHPUnit/Util/GlobalState.php
php /usr/lib/php/PHPUnit/Util/InvalidArgumentHelper.php
php /usr/lib/php/PHPUnit/Util/PHP.php
php /usr/lib/php/PHPUnit/Util/Printer.php
php /usr/lib/php/PHPUnit/Util/String.php
php /usr/lib/php/PHPUnit/Util/Test.php
php /usr/lib/php/PHPUnit/Util/TestSuiteIterator.php
php /usr/lib/php/PHPUnit/Util/Type.php`enter code here`
php /usr/lib/php/PHPUnit/Util/XML.php

Can anyone please help
Comment: One often runs into this error, and to quickly troubleshoot it, follow these steps : https://stackoverflow.com/a/36577021/2873507
Answer: sudo vi which phpunit
After line 38
define('PHPUnit_MAIN_METHOD', 'PHPUnit_TextUI_Command::main');
Add this line
ini_set('include_path', '/usr/lib/php:.');
Comment: For me the appropriate directory to add in place of /usr/lib/php was /opt/local/lib/php, since I use MacPorts.
Comment: There is now a troubleshooting checklist for this frequent error here : https://stackoverflow.com/a/36577021/2873507


How do I find how tall a building is?

Question: How tall is a tower if it casts a shadow 65 ft. long at the same time that a building 160 ft. tall casts a shadow 130 ft. long?
I tried using the hypotenuse formula but didn't get the right answer.
Help.
Comment: Of course, the canonical way of finding the height of a building is to [offer a barometer to the building manager](http://www.snopes.com/college/exam/barometer.asp).
Comment: You need to use similar triangles.
Comment: $\frac{160}{130} = \frac{x}{65}$ so $x = 80$. "You need to use similar triangles."
Comment: Thank you very much, I was using the wrong relationships for the proportion.
Answer: As Arturo said, you need to use similar triangles. Here's a picture to get you started:

The building and its shadow, together with the hypotenuse joining their ends, form a triangle similar to the one formed by the tower and its shadow. You know the lengths of both shadows and the height of the tower; now just use the fact that the large triangle is just a scaled up version of the smaller one: every side has been multiplied by the same amount.
Answer: If $\alpha$ is the angle that the Sun rays make with the Earth, then $\tan \alpha = \frac{h}{s} = \frac{h_1}{s_1}$, where $h,s$ are the height and shadow lengths of the first building and index one stands for the second building. Then, $h = \frac{s}{s_1} h_1 =\frac{65}{130}  160 = 80 ft$.
Answer: Toss a firecracker on to the street from the roof. It will fall at 30 feet per second, the speed of gravity. When it hits the ground the startled pedestrians below will likely swear in surprise. Their swear words will float back up to you at 1100 feet per second, the speed of sound. Therefore the length of time for you to hear swearing after you chuck the firecracker will be:
height/30 seconds + height/1100
=
1100 x height / 33000 + 30 x height / 33000
=
1130 x height / 33000
therefore
the building's height = 33000/1130 x the amount of seconds between when you dropped the cracker and when you heard people swearing at you.
Sometimes maths can be fun. But usually only when it involves things that explode.
Comment: This answer, creative as it may be, requires a lot more information to compute the distance the firecracker would fall in a given amount of time (shape, size, and weight of the firecracker for starters). Not really an answer.
Comment: A reasonable idea, but the distance of fall (ignoring friction) is $16t^2$, not $30t.$
Comment: @Ross. From my youthful pyrotechnic experience, a typical firecracker will reach its terminal velocity quite soon after being tossed off a building, so the linear term for velocity is actually a better answer (though some preliminary experiments should be done to determine the correct coefficient).

How do I find how tall a building is?


Finite Subgroups of $GL(n,\mathbb{C})$

Question: In the Artin's book on Algebra, the author stated a theorem (Ch.9, Thm. 2.2):
"A finite subgroup $G$ of $GL(n,\mathbb{C})$ is conjugate to a subgroup of $U(n)$.
Here, $U(n)$ is the unitary group, i.e. if $\langle \,\,, \rangle$ is the standard Hermitian inner product on $\mathbb{C}^n$ given by
$\langle (x_1,\cdots,x_n),(y_1,\cdots,y_n)\rangle=\sum_{}{x_i\bar{y_i}}$ then $U(n)=\{A\in GL(n,\mathbb{C})  \colon \langle Av,Aw\rangle = \langle v,w\rangle,\forall v,w\in \mathbb{C}^n \}$.
The proof is: there is a $G$-invariant Hermitian inner product $\langle\,\, , \rangle_1$ on $\mathbb{C}^n$, and consider an orthonormal basis $B_1$ w.r.t this form. If $P$ is the matrix of transformation which changes standard basis to $B_1$, then $PGP^{-1}\leq U(n)$
Question: In the last statement in the proof, the author says that $PGP^{-1}$ is subgroup of unitary group; but, this unitary group is corresponding to the Hermitian inner product $\langle \,\,, \rangle_1$, i.e. it is the group of linear transformations which preserves the inner product $\langle \,\,, \rangle_1$. Why $PGP^{-1}$ should be subgroup of $U(n)$ which is the group of linear transformations which "preserves" the standard Hermitian inner product $\langle \,\,,\rangle$ on $\mathbb{C}^n$?
Answer: Preserving the $G$-invariant inner product $\langle , \rangle_1$ implies preserving the original $\langle , \rangle .$ To see this requires knowing how $\langle , \rangle_1$ was constructed (via Weyl's averaging trick.) For $u,v \in \mathbb{C}^n,$ $g\in G,$ and $A \in PGP^{-1},$ we have
$\langle A(gu), A(gv) \rangle_1 = \langle gu, gv \rangle_1 =\langle u, v \rangle_1 =\frac{1}{|G|}   \displaystyle\sum_{g\in G} \langle u , v \rangle = \langle u, v \rangle .$
Comment: The averaging trick surely uses the average $$\frac{1}{|G|} \sum_{g \in G} \langle gu,gv \rangle$$ which is why it ends up $G$-invariant. (Also, it was known long before Weyl in the case of finite groups).
Comment: pithy$\ \ \ \ \ \ \ \ \ $
Answer: To answer the question a slightly different way: choose an orthonormal basis wrt the $G$-invariant Hermitian form $\langle, \rangle_{1}.$ Let this be $\{ u_{i}: 1 \leq i \leq n \}.$
Since the form is $G$-invariant, for any fixed $g \in G,$
we have $\langle gu_{i},gu_{j} \rangle_{1} = \delta_{ij}$ for all $i,j.$ Hence writing the matrix of (the transformation represented by) $g$ with respect to this basis, the columns (and rows) are orthonormal, and the matrix is unitary. So now you have a group of unitary matrices, which is conjugate to the original one via a change of basis matrix.
To answer comment below, which took to long to leave as a comment: It means that if write $gu_{i} = \sum_{j=1}^{n} a_{ij}(g)u_{j},$ where the $a_{ij}(g)$ are complex numbers, then we have for any $r,s$, $$\delta_{rs} = \langle gu_{r},gu_{s} \rangle_{1} = \sum \sum_{p,q= 1}^{n} a_{rp}(g) {\overline a_{sq}(g)} \langle u_{p}, u_{q} \rangle_{1} .$$ But this is $$\sum_{p =1}^{n} a_{rp}(g) { \overline a_{sp}(g)}$$    because $\langle u_{p}, u_{q} \rangle_{1} = \delta_{pq}.$  So what is left is the usual innner product of the rows of the matrix  $[a_{ij}(g)].$
Comment: very simple, and nice..
Comment: in the of $g$ w.r.t. the basic chosen, columns are orthonormal mans "they are orthonormal w.r.t. the inner product $\langle \,,\rangle_1$, isn't it?
Comment: No, see the modified answer. The rows of the matrix are mutually orthogonal and of length $1$, so orthonormal wrt usual hermitian form on $\mathbb{C}^{n}.$Likewise for columns.

Finite Subgroups of $GL(n,\mathbb{C})$


QueryString converted to URL-Encode using NameValueCollection

Question: I am passing an encrypted URL string:
Default.aspx?S3tLlnIKKzE%3d
I want to pass that URL string back into the ASPX page in a variable.
protected string qs = string.Empty;

NameValueCollection qscollstring = HttpContext.Current.Request.QueryString;
qs = qscollstring[0];

Which return :  S3tLlnIKKzE=
The value in qscollstring[0] is correct: S3tLlnIKKzE%3d
I understand the problem is URL-Encoding, but I cannot find a way to keep the string as is.
It seems that assigning the value from qscollstring[0] is: S3tLlnIKKzE%3d
to string changes the value : S3tLlnIKKzE=
I need to to stay: S3tLlnIKKzE%3d
Answer: Use HttpUtility.UrlEncode method to encode the string.
 qs =HttpUtility.UrlEncode(qscollstring[0]);

Answer: You can also pull the value from the Uri of the current URL without having to Encode the value.
Sample:
 Uri u = new Uri("http://localhost.com/default.aspx?S3tLlnIKKzE%3d");
 string q = u.Query;

And part of your page:
 string q = !String.IsNullOrEmpty(Request.Url.Query) && Request.Url.Query.Length > 1 ? Request.Url.Query.Substring(1) : Request.Url.Query;

Answer: Like me if you are searching for the reverse .. use
qs =HttpUtility.UrlDecode("S3tLlnIKKzE%3d");

to get back S3tLlnIKKzE=


Identification from implicit function

Question: Suppose my observed data $y$ and $x$ is generated by the following relationship for each observation $i$:
$$ y_i = h(y_i,\theta) + x_i + \varepsilon_i$$
where $x_i$ is a strictly exogenous variable , $\varepsilon_i$ is an i.i.d. error term and $\theta$ the vector or parameters of interest. Assume that the solution to this equation is unique.
When $h$ is sufficiently simple (e.g. linear), I can manually solve for $y_i$ and consistently estimate $\theta$ with OLS.
However, when $h$ is more involved, e.g., $h(y_i, \theta) = (1+\exp(\theta_1 - \theta_2 y_i)) / \theta_2$, then there is no closed-form solution. It feels tempting to estimate $\theta$ using non-linear least squares:
$$ \arg \min_\theta \sum_i(y_i - h(y_i, \theta) - x_i)^2$$
but there are obvious endogeneity concerns with respect to the right-hand side of this expression.
Is there any instrument that allows dealing with these endogeneity concerns? Or how else is such a non-linear relationship without closed-form solution approached?
Comment: Why not write the relation as $x_i=f(y_i,\theta)+\epsilon_i$ where $\epsilon_i=-\varepsilon_i$ and $f(y_i,\theta)=y_i-h(y_i,\theta)$? That's a standard regression setting, presenting no special problems.
Comment: How is that supposed to help when $x$ is assumed exogenous but $y_i$ is assumed endogenous (if that is indeed what @bonifaz means by "obvious endogeneity concerns")
Comment: $y_i$ is generated by a function of $y_i$ itself? Are you sure that this is correct? $h(y_i, \theta) = y_i - x_i - \varepsilon_i $.
Comment: @Stop "Endogenous" and "exogenous" do not add anything to the model.  If they do, then that needs to be incorporated in the model statement!
Comment: @Tim, yes, that's what I meant with 'implicitly defined'.
Comment: @whuber I struggle to make sense of that comment. Is it because rather than using the words "endogenous"/"exogenous" which you perhaps see as to vague you would prefer a more precise mathematical statement? Or does it reflect some other disagreement with respect to approaching the question?
Comment: @Stop This question begins with the precise mathematical statement of the model.  Except insofar as additional text might explain the symbols, that overrides all else.
Answer: Here is some rough code in R implementing the non-linear two stage least squares estimator under the assumption that $\mathbb E[\epsilon\lvert x] = 0$. Just to see if it works ... it seems to be working up to the point of standard over-underflow issues there might be. But the non-linear two stage least squares estimator should be implemented in most statistical software.
<code>N <- 10000
x <- rnorm(N)
e <- rnorm(N)
x <- c(0,x)
e <- c(0,e)
theta_1 <- 1
theta_2 <- 0.5

# function to solve for y for simulation of data given x and error e
makefunction <- function(x,e)
    {
        g <- function(y)
         {
         out <- y - (1 + exp(theta_1 - theta_2*y)/theta_2) - x - e
           return(out)
         }
      return(g)
    }

y <- rep(NA,N+1)
for (i in 1:(N+1))
    {
        g <- makefunction(x[i],e[i])
        y[i] <- uniroot(g,lower=-100,upper=100)$root
    }

# y is endogenous ... non-zero covariance
cov(y,e)
# x is exogenous
cov(x,e)

# The error-function
r <- function(theta_1,theta_2)
    {
        out <- y - (1 + exp(theta_1 - theta_2*y)/theta_2) - x
        return(out)
    }

# Instruments are function of x
X <- cbind(x,x^2,x^3)
objective <- function(theta)
    {
        a1 <- theta[1]
        a2 <- theta[2]
        out <- rbind(r(a1,a2))%*%X%*%solve(t(X)%*%X)%*%t(X)%*%cbind(r(a1,a2))
        return(out)
    }

optim(c(2,3),objective)
</code>
based on Amemiya (1983) in the Handbook of Econometrics formula (5.10).
I divide with $\theta_2$ within a prentheses instead of outside, but the code still illustrates how the estimator works so I'm not gonna alter it.
The residual function is
$$r(y,x,\theta) = y -h(y,\theta) - x$$
and
$$\mathbb E[r(y,x,\theta)\lvert x]=0$$ implying that
$$\mathbb E[t(x)r(y,x,\theta)]=0$$
for any function $t(x)$. Basically the two stage non linear least squares estimator is as such a general method of moments estimator.
A more recent text is Wooldridge, J.M. (1996) "Estimating systems of equations with different instruments for different equations" in Journal of Econometrics  an article the gist of which is recapitulated in his (2010) Econometric Analysis of Cross Section and Panel Data in the chapter on GMM estimation page 530 - ...
Answer:

Or how else is such a non-linear relationship without closed-form
  solution approached?

For maximum likelihood we want the density of $y$ conditional on $x$ (because this is our sample), $f_{y|x}(y|x)$.
We start with making an assumption on the density of $\varepsilon$ conditional on $x$, $f_{\varepsilon|x}(\varepsilon|x)$.
When the relation is not implicit, say $y = ax + \varepsilon$ the change-of-variables method has a Jacobian determinant equal to unity so we simply have
$$f_{y|x}(y|x) = f_{\varepsilon|x}(y-ax|x)$$
and we can proceed as usual.
But when the relation is implicit we have
$$\varepsilon = y-h(y,\theta)-x \implies \frac{\partial \varepsilon}{\partial y} = 1- \frac{\partial h(y,\theta)}{\partial y}$$
so here, the observation density will be
$$f_{y|x}(y|x) = \left|1- \frac{\partial h(y,\theta)}{\partial y}\right| \cdot f_{\varepsilon|x}(y-h(y,\theta)-x|x)$$

Identification from implicit function


Save UITableView names to array on button action

Question: I want to save the names that are filled in UITableView to an array
var mineSpillere = [String]()

How can I do this on buttonAction?
This is button action for how i add names to tableview:
@IBAction func addButtonAction(sender: AnyObject) {
            mineSpillere.append(namesTextBox.text)
            myTableView.reloadData()
    }

and also here code:
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        var cell:UITableViewCell = self.myTableView.dequeueReusableCellWithIdentifier("cell") as! UITableViewCell

        cell.textLabel!.text = self.mineSpillere[indexPath.row]

        return cell;
    }

That only when I press the "back" button in the application, the names from the UITableView will be saved in an array.
I am going to access these names from another view controller also, so i need them to be saved as an array.
Comment: What names do you mean?  How did they get into the `UITableView`?
Comment: @PhillipMills -  I add them using textbox and button.
Comment: Could you post the code on how you put them into the tableView's cell?
Comment: @StephenFox - Added now!
Comment: So when you press the `back` button you want a copy of `mineSpillere`?
Comment: @StephenFox - When i press back button, i want to save tableview items to array, because i want to access that array from another view controller.
Comment: Okay well seeing as your calling `-reloadData()` on the tableView it would be helpful if we could see your tableView delegate method `func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell` just so we can see exactly how those cells are being set.
Comment: @StephenFox - Added now, take a look :)
Comment: Well seeing as you're setting the tableview cells with the mineSpillere array, I assume the array already has the names. You could use a delegate callback to pass the array when the back button is pressed.
Comment: @StephenFox - what do you mean with "use a delegate callback to pass the array when the back button is pressed"?
Answer: Okay so it looks like you have all the data in the mineSpillere array already as you're using cell.textLabel!.text = self.mineSpillere[indexPath.row] so to get that array back to the first view controller. You could use the following code in the view controller that is being presented when the 'back' button is being pressed:
class FirstViewController: UIViewController,SecondViewControllerDelegate {

    var mineSpillereCopyFromSecondVC = [String]()

    func presentSecondViewController() {
        // Im not sure the class name for you're second view
        // where the tableView is located.
        var secondVC: SecondViewController = SecondViewController();
        secondVC.delegate = self

        // Also not too sure on how you're presenting the `SecondViewController` so I'm goingg to leave that empty.
        // The important part is just above us.
    }

    func passMineSpillere(mineSpillere: [String]) {
        // This class now has the mineSpiller array of name.
        self.mineSpillereCopyFromSecondVC = mineSpillere
    }

}

And then in you SecondViewController where the tableView is located you could add the following code.
import UIKit

protocol SecondViewControllerDelegate {
    func passMineSpillere(mineSpillere:[String])
}

class SecondViewController: UIViewController {

    var delegate: SecondViewControllerDelegate?
    var mineSpillere = [String]()

    // This will be called when the 'back' button is pressed.
    override func viewWillDisappear(animated: Bool) {
        super.viewWillDisappear(animated)

        // Pass the mineSpillere array back to the delegate
        // which is the firstViewController instance.
        self.delegate?.passMineSpillere(self.mineSpillere)
    }

}

Comment: Error at code: "secondVC.delegate = self": - "Cannot assign a value of type "FirstViewController" to a value of type "SecondViewControllerDelegate?"
Comment: You must make sure your FirstViewController conforms to SecondViewControllerDelegate which is done at the declaration of your class.  `class FirstViewController: UIViewController,SecondViewControllerDelegate {`