500 Internal server error em arquivos PHP

Question: Toda vez que executo um arquivo PHP no servidor ele retorna (no header) um erro 500.
Isso só acontece com arquivos PHP...
Comandos como echo e phpinfo() só com strings funcionam (testei com echo 'teste';). Mas se eu passo a usar códigos mais complexos, tipo incluir arrays e etc, ele já não funciona e da aquele erro.
Pensei que poderia ser um erro no meu script, mas funciona em localhost...
A saida para ls -l nas pasta public_html é a seguinte:
drwxr-xr-x 3 root root 4096 Jan 28 06:50 app
drwxr-xr-x 2 root root 4096 Jan 28 06:50 css
drwxr-xr-x 2 root root 4096 Jan 28 06:50 fonts
drwxr-xr-x 5 root root 4096 Jan 28 06:52 img
-rwxr-xr-x 1 root root  859 Jan 28 06:50 index.php
drwxr-xr-x 2 root root 4096 Jan 28 06:52 js

Desde já, obrigado.
@Edit:
Segue meu script completo.
<?php

ini_set('display_errors', true);
error_reporting(E_ALL);

/*
 *  0 = confirmado
 *  1 = talvez
 *  2 = não vai
 */

$convidados = [
    'Cieli' => [0,15],
    'Carlinhos' => [0,30],
    'Daianna' => [1,0],
    'Renato' => [0,20],
    'Ana' => [3,0],
    'Larissa' => [0,20],
    'Debora' => [0,30],
    'Dani' => [0,0],
    'Suelen' => [1,0],
    'Vitor' => [1,0],
    'Felipe' => [1,0],
    'Luany' => [1,0],
    'Sandra' => [1,0],
    'Halysson' => [1,0],
    'Karina' => [3,0],
    'Mariana' => [3,0],
    'Wanessa' => [0,30],
    'Matheus' => [1,20],
    'Mauricio' => [3,0],
    'Mayara' => [1,20],
    'Lukas' => [1,0],
    'Leticia' => [1,0],
    'Geord' => [1,0],
    'Zé' => [3,0],
    'Luana' => [1,0],
    'Keity' => [0,20],
    'Werinton' => [0,20]
];

ksort($convidados);

$confirmed       = '';
$not_confirmed   = '';
$awaiting        = '';
$total           = [];
$total_confirmed = 0;

foreach ($convidados as $key => $value) {
    $total[] = $convidados[$key][1];

    if( $convidados[$key][0] === 0 ) {
        $total_confirmed += 1;
    }
}

?>

<!DOCTYPE html>

        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <title>Site</title>

        <meta name="viewport" content="width=device-width, initial-scale=1">

        <link rel="stylesheet" href="css/normalize.css">
        <link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css">
        <link href='http://fonts.googleapis.com/css?family=Slabo+27px' rel='stylesheet' type='text/css'>
        <link rel="stylesheet" href="css/main.css">

                Site

Tabela de confirmados

                    Legenda: (<?php echo $confirmed; ?>) Confirmado, (<?php echo $awaiting; ?>) Aguardando confirmação, (<?php echo $not_confirmed; ?>) Não confirmado

                        Convidado
                        Confirmado
                        Valor

                <?php
                    foreach ($convidados as $key => $value) {
                        echo
                            '

                                ' . $key . '
                                ' . ($convidados[$key][0] === 0 ? $confirmed : ($convidados[$key][0] === 1 ? $awaiting : $not_confirmed)) . '
                                R$' . number_format($convidados[$key][1], 2, ',', '.') . '

                            ';
                    }
                ?>

                        Total de confirmados: <?php echo $total_confirmed; ?>
                        Total arrecadado: R$<?php echo number_format(array_sum($total), 2, ',', '.'); ?>

Comment: Não, nenhum erro. No site, fica a página em branco, em localhost, funciona perfeito. A versão do localhost é 5.5.9, e no site é 5.3.3
Comment: Tem uma porrada de logs de erros, a maioria ou relacionada a arquivos não encontrados (provavelmente de testes de scripts), outros em relação a função Date(), uma log mais antiga com isso "script not found or unable to stat: /var/www/cgi-bin/test-cgi" e a mais recente relacionada ao CGI é essa: "client sent HTTP/1.1 request without hostname (see RFC2616 section 14.23): /tmUnblock.cgi"
Comment: No seus arquivos de teste, adicione essas duas linhas para exibir os erros no host de produção: `ini_set('display_errors', true); error_reporting(E_ALL);`. Tela em branco ou erro 500 é certeza de erro no código.
Comment: Já estava usando... Veja o script acima; Não seria erro no código tentei criar um array e dar um echo nele através do indice, o que funciona em localhost, mas no server não funciona.
Comment: Apareceu o erro? qual a versão do php dos dois servidores?
Comment: Já verificou os logs do apache? Existe algum error_log no diretório atual do script?
Comment: Sabe me dizer onde fica o diretório de logs? O servidor usar o Centos...
Comment: Logs no CentOS fica no `/var/logs/httpd`. Acredito que possa ser um erro no CGI, se você estiver usando CGI.
Answer: A sintaxe abreviada de arrays está disponável a partir do php5.4, como o seu host de produção utiliza uma versão inferior(5.3.3) comparada ao localhost(5.5.9) o seguinte erro é gerado:

syntax error, unexpected '[' in

Para corrigir isso é necessário converter para a sintaxe antiga, isso pode ser com um replace da sua IDE/editor de texto copie o trecho do array, depois substitua [ por array( e ] por ) não esqueça de $total quem também é um array.
Sintaxe php5.4
$convidados = [
    'Cieli' => [0,15],
    'Carlinhos' => [0,30]
];

Sintaxe para versões anteriores:
$convidados = array(
    'Cieli' => array(0,15),
    'Carlinhos' => array(0,30)
);

No exemplo(sandbox) é possível executar o código em diferentes versões do php. Veja seu código convertido rodando no phpfiddle onde a versão do php é a 5.3.29.
Comment: Também pensei que pudesse ser isso. E inclusive já realizei os testes com essa sintaxe. Mas ainda continuo recebendo este erro no console... Veja uma screenshot do console: http://i.imgur.com/L6nwCuD.png
(+1 Pela dica do array, não sabia..)


Choosing a statistical method to measure differences in age groups while accounting for sex

Question: I am looking at one kind of measurement in 4 groups Young males, young females, senior males, senior females. Whereas I am mainly concerned at looking at the differences between young and old, I don't want sex as a confounding factor which is why I added in the additional sex groups and basically doubled my sample size (no previous studies to say if it is different with age in the species I am researching). I am pretty new to statistics and am not sure how to analyse this as I was originally going to do a student's unpaired T-Test but now I have added the additional two groups to separate the sexes.
Additionally, some of the patients I am using may have underlying health issues that impact the measurement I am taking. I know this in advance (so for example I might know that 2 of the 12 senior females may have a health problem that changes the measurement), but unfortunately I cannot choose a different group of patients. Is there a way to account for these in advance? Or to note which ones may have values indicative of health problems and treat them as outliers later.
So without changing the outline of the project, if I am mainly comparing differences in this measurement between two age groups, while also taking into account sex, what statistical test should I use?
Thank you
Comment: This is an RBD. where the sexis your block. so an anova would suffice
Comment: By analyzing age **groups** and not continuous age, the result will be highly inefficient and possibly misleading.  See https://discourse.datamethods.org/t/categorizing-continuous-variables.  There is great heterogeneity within an age "group".
Comment: @FrankHarrell I was originally looking between the two, but there is a large age gap I am missing as for this initial study I am only looking at two age groups (1-3 and 10+ in animals where lifespan is only max 15 years). The question I am trying to answer is just if there is a difference between the two age groups and if there is my next study would be using animals with continuous age to see where that change may occur. Our hypothesis is that said change happens before the age of ten so there should be significant differences between the two vastly different groups- would you still be wary?
Comment: You can have age gaps and still get a much better analysis by using exact age.
Comment: @FrankHarrell Okay thank you! If all I need to do is change how I analyse the data from these two age groups I will look into analysing them as continuous data rather than groups- would that change the method I analyse it or could I still do a linear regression but specify exact ages instead of young adult or senior?
Comment: Yes, a linear model.  Or an ordinal model for continuous Y: https://fharrell.com/post/rpo
Answer: This would be a linear regression. Your measurement is the outcome (called "Y"), sex, and any other variable (such as the other health conditions you mentioned) are the predictors (called "X" variables). Variables other than age would also be called "covariates". This would allow you to test the relationship between age and your outcome, while adjusting for sex and health conditions.


Describing $\Bbb{Z}$ in set notation

Question: I'm trying to describe $\Bbb{Z}$ in set notation in terms of  $\Bbb{N}$ and $0$.  Does this look right?  I know $\Bbb{Z}$ is all positives, negatives, and zero, but does that work on $\Bbb{N}$?

ℤ={x∈ℕ|x≥0 and x≤0}
Comment: You have just described either the empty set or $\{0\}$, depending on whether or not you take $0 \in \mathbb N$. What you wrote can be read as "The set of all $x$ in $\mathbb N$ such that $x$ is greater than or equal to zero and $x$ is less than or equal to zero. Clearly, the only integer satisfying this is zero, which may or may not be natural, depending on how you define the natural numbers. Try perhaps instead $\mathbb Z = \mathbb N \cup \{-x \mid x \in \mathbb N\} \cup \{0\}$.
Comment: Presumably you mean $\Bbb N = \{1,2,3,\dots\}$.  At any rate, be careful with your notation: which $x \in \Bbb N$ satisfy $x \leq 0$?
Comment: The only way I've seen $\mathbb{Z}$ described in terms of $\mathbb{N}$ is through equivalence classes of $\mathbb{N}$. But again this was in the context of trying to construct the integers
Answer: No, this suggestion is not good.
$\Bbb Z$ is a superset of $\Bbb N$. This means that it has more elements. Whenever you define a set as $\{x\in\Bbb N\mid \ldots\}$ you effectively require the defined set to be a subset of $\Bbb N$.
Moreover, if $x\leq 0$ and $x\geq 0$, then it is necessarily the case that $x=0$. Therefore you have defined $\{0\}$.
HINT: Recall that $x\in\Bbb Z$ if and only if $|x|\in\Bbb N$.
Comment: That looks as if $\sqrt{2}\in\mathbb{Z}$
Comment: I didn't like it either, but I'm struggling how to define $\Bbb{Z}$ in terms of $\Bbb{N}$ and $0$.  Would this work:

ℤ={x∈ℤ| |x|∈N or x=0}

The text doesn't state if N includes 0 or not
Comment: @westhe32nd: Well, yes, but it would be circular. If you have $\Bbb Z$, why not defined it as $\{x\in\Bbb Z\mid x=x\}$? I suppose that you are looking to define $\Bbb Z$ inside a larger set than itself.
Comment: Ah!  Dumb mistake on my part.  If I replaced Z with N, and kept everything else that would work?
Comment: @westhe32nd: No. Read my answer again. In particular the second sentence. Perhaps review again what does it mean when we write $\{x\in X\mid\varphi(x)\}$.

Describing $\Bbb{Z}$ in set notation


How to appropriately reduce data size or take a representative sample from it?

Question: I have a spreadsheet file with around 150,000 pairs (x,y). I wish to work with a smaller file, i.e., with less data, so my exploratory analysis is faster.
What is the appropriate way of resampling, or working (one time only) with this data, so I can obtain a smaller amount of pairs, loosing the "least possible" amount of information or reliability, statistically speaking.
Comment: The right way to do this is to load it into software like R or Python and work with the entire data set. It sounds like a big number, but 300,000 points is not that many. Does something prevent you from using either of those (free!) pieces of software?
Comment: There's no way to assure yourself of getting the same statistics that you would get from the entire data set. The way you (probably) get close is by taking a large random sample.
Comment: Currently, all we can advise is simple random sampling. If you could elaborate what kind of analyses / estimates you are interested in, and what kind of data this is, then a more detailed answer might be possible. Even then, likely the answer will be "take as much as you can, as randomly as you can"
Comment: I understand this is desirable, in fact I plan to do this later (learn R). Nonetheless, me and my team don't have that specific knowledge so far, and we have relied on "office" to do our exploratory analysis. In any case, I still wish to know what would be the way to compress any large data (say then 1,000,000,000 pairs), so as not to loose that much reliability and so as to obtain the same statistics (mean, etc.). Today we just cluster rounded data, without knowing this is the best way.
Answer: There are two issues with exploratory analysis on big data

any analysis that shows individual data points (eg a scatterplot) gets harder to understand
computations get slow

With 150,000 you shouldn't really be having the second problem, but you will have the first problem.  With 150,000,000 points you might have both problems.
The second problem can be solved quite well by sampling.  You can begin by taking a simple random sample. If you need to explore in more detail in a small subpopulation (left-handed avocado farmers, say) you might use the whole data set for that subpopulation, or a sample from just that subpopulation.
For the first problem, you can either work with a random sample (often called "thinning") or with some way of aggregating points.  Two useful general-purpose ways to aggregate points in a scatterplot are hexagonal binning and overplotting with partial transparency.  The former makes individual outliers more visible; the latter makes them less  visible.
There's a book Graphics of Large Datasets: Visualising a Million that discusses approaches to data viz when data sets are too big to look at each point individually.
Answer: For whatever it's worth, SAS defaults to 2,000 as a sample size in it's Graph Explore nodes.  I know that this often produces graphs that are not representative in different ways.  (SAS is top-of-the line data mining software.)
If you want a random sample in Excel, add a new column, put =rand() in the first cell, copy the cell down to the bottom; select all the data (all rows/columns), sort on the new column (direction doesn't matter), and select how ever many rows you want from the top going down.
I can't imagine trying to do exploratory analysis with Excel.  Maybe there are functions I'm not aware of.  How is it easier to find the standard deviation of 1,000 rows rather than the whole set?  It's the same number of key strokes.
I would work with the whole data set.


Acceptance by final state PDA and acceptance by empty stack .

Question: Let $P$ be a non-deterministic push-down automaton (NPDA) with exactly one state, $q$, and exactly one symbol, $Z$, in its stack alphabet. State $q$ is both the starting as well as the accepting state of the PDA. The stack is initialized with one $Z$ before the start of the operation of the PDA. Let the input alphabet of the PDA be $\Sigma$. Let $L(P)$ be the language accepted by the PDA by reading a string and reaching its accepting state. Let $N(P)$ be the language accepted by the PDA by reading a string and emptying its stack.
Which of the following statements is TRUE?

$L(P)$ is necessarily $\Sigma*$ but $N(P)$ is not necessarily $\Sigma*$.
$N(P)$ is necessarily $\Sigma*$ but $L(P)$ is not necessarily $\Sigma*$.
Both $L(P)$ and $N(P)$ are necessarily $\Sigma*$.
Neither $L(P)$ nor $N(P)$ are necessarily $\Sigma*$.

According to me both the languages should be equivalent and so accordingly both $L(P)$ and $N(P)$ are necessarily $\Sigma*$.
Answer: HINT: What if $\delta$, the transition relation (or transition function, if that's how your PDAs are defined), is empty?
Comment: @user123: That's correct if it accepts by empty stack; if it accepts by final state, it will accept the empty word.
Comment: So that means we will have  a PDA which will not accept anything right ?


"Chain Rule" for Finite Difference Operator

Question: I am trying to prove using difference calculus the following formula;
$$\Delta(a+bx)^{(n)}=bn(a+bx)^{(n-1)}$$
which is akin to the chain rule for continuous Calculus.  Here we have that
$$x^{(n)}=x(x-1)...(x-n+1)$$
and
$$\Delta f(x)=f(x+1)-f(x)$$
It seemed daunting at first so I tried small values; $a=3, b=2$.  Looking at the relationship with actual values would help generate an idea how the general proof would look.  So I started;
$$\begin{eqnarray*}\Delta(3+2x)^{(n)}&=&[3+2(x+1)]^{(n)}-(3+2x)^{(n)}\\&=&(5+2x)^{(n)}-(3+2x)^{(n)}\\&=&(2x+5)(2x+4)(2x+3)^{(n-2)}-(2x+3)^{(n-2)}(2x+5-n)(2x+4-n)\\&=&(2x+3)^{(n-2)}[(2x+5)(2x+4)-(2x+5-n)(2x+4-n)]\\&=&(2x+3)^{(n-2)}[n(2x+5)+n(2x+4)-n^2]\\&=&n(2x+3)^{(n-2)}[(2x+5)+(2x+4)-n]\\&=&n(2x+3)^{(n-2)}(4x+9-n)
\end{eqnarray*}$$
This last couple of steps is escaping me.  I can't really factor a 2 without ending up with a $1/2$n.  I know that if I can manipulate the last term into something close to $2(2x+3-(n-2))$ then this should give me what I need, but this expanded is $$(4x+6-2n+4)=4x+10-2n=4x+9-n+(1-n)$$ and so I'm missing a $(1-n)$.
DId I screw up some algebra?
EDIT;  @ancientmathematician, you were right, and my definition of $p(x)^{(n)}$ was incorrect, and is defined as
$$p(x)^{(n)}=p(x)p(x-1)...p(x-n+1)$$
which I'm sure will change things around.  I will go through the algebra shortly and If I solve it i will answer my own question, or someone else can write it up and I'll upvote it.
Comment: What does the $^{(n)}$ mean?
Comment: @ancientmathematician, see my edit above, $p(x)^{(n)}$ is defined differently than above and is defined in my edit above.
Comment: So the book I'm working out of states that the statement $f(x)^{(n)}$ is DEFINED to be $$f(x)^{(n)}=f(x)f(x-1)f(x-2)...f(x-n+1)$$ So i guess this is defined this way for a reason. I haven't had time to go through the algebra, but given this change, I thnk it must work out...
Comment: $$x^{(n)}=x(x-1)...(x-n+1)$$  Its also known as the falling factorial, and there are a few different notations I've seen.
Comment: I( think you have to say what $p(x)^{(n)}$ means.
Comment: Ok so there is just one thing I don't get. You try to get the RHS to be something $^{(n-1)}$, and instead of $n-1$ you make a $n-2$ appear artificially. Why?
Comment: Well, I noticed that they had $n-2$ factors that were equal, so I figured to start with what I had and try to manipulate the last term so that I could adjust it afterward and multiply by that last factor and change to $(n-1)$
Comment: I see. But this number of equal terms is not always going to be so close to $n-1$, it is here only because you chose $2$ and $3$.
Comment: I see what your saying.  I just noticed I was so close, and so I'm thinking I made an algebra mistake above...  and @ancientmathematician, I think that $$p(x)^{(n)}=p(x)[p(x)-1]...[p(x)-(n-1)]$$
Comment: I think this is effectively Proposition 1(1) of section 2 of this: https://ijpam.eu/contents/2014-96-2/3/3.pdf. But it would be nice just to sort out the algebra here.
Comment: @littleO intuitively, i thought my original definition and your statement above  made the most sense in terms of the "factorial" as a product of successively decreasing terms, but we were wrong...
Comment: @Eleven-Eleven Thanks. What book are you reading, by the way?
Comment: I picked it up at the library to help supplement Bernoulli polynomial research , and it's a nice introduction to difference equations.  It's called "An Introduction to the Calculus of Finite Differences and Difference Equations" by Kenneth S. Miller.   It's old, published in 60, but its a good intro.
Comment: Thanks, @Eleven-Eleven, I thought that was how it used to be!
Answer: As you mentioned, the algebra works out when using the definition you gave in the edit.
Let $h(x) = f(x)^{(n)} = f(x)f(x-1)\cdots f(x-n+1)$. Then
\begin{align}
\Delta h(x) &= f(x+1) f(x) f(x-1) \cdots f(x-n+2) - f(x)f(x-1)\cdots f(x-n+1) \\
&= f(x) f(x-1) \cdots f(x-n+2)(f(x+1) - f(x-n+1)) \\
&= (f(x+1) - f(x-n+1)) f(x)^{(n-1)}.
\end{align}
In the special case that $f(x) = a + bx$, we have
\begin{align}
f(x+1) - f(x-n+1) &= a + bx + b - (a + bx - (n-1) b) \\
&= nb.
\end{align}
So we find that
$$
\Delta h(x) = nb (a + bx)^{(n-1)}.
$$
Comment: Once I saw the real definition of $f(x)^{(n)}$ i knew this would work out.  Thanks for the proof.


Redirecting old file URLs (no pattern)

Question: running Drupal 7.65.
Our previous website manager moved us from Drupal 6 to Drupal 7 and cleaned up the file structure on our server.
While all the files that are now on our website have clean and organised URLs, and all general URLs on our website are now clean, Google still has indexed our old URLs.
e.g.:

old: domain.com/program-name
new: domain.com/programname

and

old: domain.com/sites/default/files/documents/owl-final-final3.pdf
new:
  domain.com/sites/default/files/folder1/folder2/owlguide.pdf

So if someone googles 'program name' or googles for our 'owl guide', the Google result takes them to the old URLs (broken links) rather than the new URLs.
Is there a way I can redirect these broken links to e.g. a search page on our website, rather than the "404 page not found" page?
For some of the old URLs to our pages (e.g. /program-name rather than /programname) I've been able to set up URL aliases to redirect people but don't know how I can do so for the files when there are so many that I wouldn't be able to work out.
Sorry if I haven't used the right words, I'm not a web developer! I looked into Pathologic but don't think it addresses the problem we're having...
Answer: Goto http://YOURSITE/admin/config/system/site-information and under "ERROR PAGES
" change "Default 404 (not found) page" to your search page. In this way, Drupal will redirect all 404 pages to the page that you have provided.

Redirecting old file URLs (no pattern)


How to use PrimeReact's Button component?

Question: I am trying out the javascript map method whilst building a simple calculator.
I am using a list for each row of the calculator and mapping it to a table cell and a prime react button inside it.
I am however getting weird results in the browser.
My code in the component is below and I have screenshotted the output.enter image description here

import React, { Component } from 'react'
import {Button} from 'primereact/button'

class Calculator extends Component {

  constructor(props) {
    super(props);
    this.state = {

    }
  }

  render() {
    const values1 = ["7", "8", "9", "/"]
    const values2 = ["4", "5", "6", "x"]
    const values3 = ["1", "2", "3", "-"]
    const values4 = ["0", ".", "+", "="]
    const valuesList1 = values1.map(value => <Button>{value}</Button>	)
    const valuesList2 = values2.map(value => <Button>{value}</Button>	)
    const valuesList3 = values3.map(value => <Button>{value}</Button>	)
    const valuesList4 = values4.map(value => <Button>{value}</Button>	)

    return (

                {valuesList1}

                {valuesList2}

                {valuesList3}

                {valuesList4}

    );
  }

}

export default Calculator;
Answer: It seems the problem may be coming from the <Button/> component as it renders additional text that seems to be its className within it.
I see you are using the PrimeReact library for the button and according to their documentation, you should enter the button's text via the label prop.
Try changing your code to the following:
import React, { Component } from 'react'
import {Button} from 'primereact/button'

class Calculator extends Component {

  constructor(props) {
    super(props);
    this.state = {

    }
  }

  render() {
    const values1 = ["7", "8", "9", "/"]
    const values2 = ["4", "5", "6", "x"]
    const values3 = ["1", "2", "3", "-"]
    const values4 = ["0", ".", "+", "="]
    const valuesList1 = values1.map(value => <Button label={value} />	)
    const valuesList2 = values2.map(value => <Button label={value} />	)
    const valuesList3 = values3.map(value => <Button label={value} />	)
    const valuesList4 = values4.map(value => <Button label={value} />	)

    return (

                {valuesList1}

                {valuesList2}

                {valuesList3}

                {valuesList4}

    );
  }

}

export default Calculator;

Hope this helps
Comment: Worked thanks man! Ill be sure to keep an eye on the documentation next time!


limit of this function

Question: let be the function $ ( \epsilon x +1)^{1/\epsilon}=f(x) $, i know that in the limit
$ \epsilon \to 0 $ then $f(x)=e^{x}$ , however i would like to know what happens if i have the function
$ ( \epsilon x +a)^{1/\epsilon}=f(x) $, in the cases $ a >1$ , $a<1$
in the first case  if $a>1 $ and 'x' is positive the function is $f(x)=\infty$ , for the other case with $ a<1$ i believe that $ f(x)=0$ , but i am not sure.
Answer: You are correct. For a constant $a\in \mathbb{R}^+$ such that $a<1$, we have $\lim_{\epsilon\rightarrow 0} ( \epsilon x +a)^{1/\epsilon} = 0,\forall x\in\mathbb{R}$ because this is trivially true for $x=0$ and any $0\neq x\in \mathbb{R}$ we have that $$\epsilon < \frac{1-a}{2|x|}\implies 0 < ( \epsilon x +a)^{1/\epsilon} < ( a + \frac{1-a}{2})^{1/\epsilon}$$ and since $a + \frac{1-a}{2} < 1$ we have $\lim_{\epsilon\rightarrow 0}( a + \frac{1-a}{2})^{1/\epsilon} = 0$ so the desired result follows from squeeze theorem, as we can neglect all $\epsilon \geq \frac{1-a}{2|x|}$ when we take the limit.
Answer: A simple way to do this is this one.
$$
f_a(x) = (\varepsilon x + a)^{1/\varepsilon} = a^{1/\varepsilon}  \cdot (\varepsilon(x/a) + 1)^{1/\varepsilon}.
$$
For the case $a = 1$, you know that the limit exists and no factor $a^{1/\varepsilon}$ appears. It gives you $f_1(x) = e^x$. Now this show that for $a > 0$,
$$
f_a(x) = \left( \lim_{\varepsilon \to 0} \, a^{1/\varepsilon} \right) e^{x/a} = \left( \lim_{y \to \infty} \, a^y \right) e^{x/a}.
$$
Since the limit in $y$ is well known to be $0$ if $0 < a < 1$ and $\infty$ if $a > 1$, you have your desired result.
Hope that helps,

limit of this function


How can i get token number from notify url in Laravel?

Question: I am using citruspay Payment gateway in my project, when return url hit the page
than  TokenMismatchException in VerifyCsrfToken.php line 53: error show.
How can i match token .
route.php
Route::POST('ideas/paymentResponse',function(){
    return View::make('ideas.paymentDone');
});

payment.php
 <form  method="post" action="https://sandbox.citruspay.com/qwer">

         <input type="hidden" id="merchantTxnId" name="merchantTxnId" value="<?php echo $merchantTxnId; ?>" />

         <input type="hidden" id="orderAmount" name="orderAmount" value="<?php echo $orderAmount; ?>" />
          <input type="hidden" name="_token" id="_token" value="{{ csrf_token() }}">

         <input type="hidden" id="currency" name="currency" value="<?php $currency ?>" />
         <input type="hidden" name="returnUrl" value="http://local.ideabazaar.com/ideas/paymentResponse" />
         <input type="hidden" id="notifyUrl" name="notifyUrl" value="http://local.ideabazaar.com/ideas/paidNotify" />
         <input type="hidden" id="secSignature" name="secSignature" value="<?php echo $securitySignature ?>" />
         <input type="Submit" class="redBtn" value="Pay Now"/>

paymentResponse.php
@extends('layouts.home')
@section('content')

   <?php
    set_include_path('../lib'.PATH_SEPARATOR.get_include_path());
    //Replace this with your secret key from the citrus panel
    $secret_key = "***************";
{{ csrf_token() }}
    $data = "";
    $flag = "true";
    if(isset($_POST['TxId'])) {
        $txnid = $_POST['TxId'];
        $data .= $txnid;
    }
     if(isset($_POST['TxStatus'])) {
        $txnstatus = $_POST['TxStatus'];
        $data .= $txnstatus;
     }
     if(isset($_POST['amount'])) {
        $amount = $_POST['amount'];
        $data .= $amount;
     }
     if(isset($_POST['pgTxnNo'])) {
        $pgtxnno = $_POST['pgTxnNo'];
        $data .= $pgtxnno;
     }
     if(isset($_POST['issuerRefNo'])) {
        $issuerrefno = $_POST['issuerRefNo'];
        $data .= $issuerrefno;
     }
     if(isset($_POST['authIdCode'])) {
        $authidcode = $_POST['authIdCode'];
        $data .= $authidcode;
     }
     if(isset($_POST['firstName'])) {
        $firstName = $_POST['firstName'];
        $data .= $firstName;
     }
     if(isset($_POST['lastName'])) {
        $lastName = $_POST['lastName'];
        $data .= $lastName;
     }
     if(isset($_POST['pgRespCode'])) {
        $pgrespcode = $_POST['pgRespCode'];
        $data .= $pgrespcode;
     }
     if(isset($_POST['addressZip'])) {
        $pincode = $_POST['addressZip'];
        $data .= $pincode;
     }
     if(isset($_POST['signature'])) {
        $signature = $_POST['signature'];
     }

         $respSignature = hash_hmac('sha1', $data, $secret_key);
     if($signature != "" && strcmp($signature, $respSignature) != 0) {
        $flag = "false";
     }
    ?>

        <meta HTTP-EQUIV="Content-Type" CONTENT="text/html;CHARSET=iso-8859-1">

        <?php
        if ($flag == "true") {
        ?>
        Your Unique Transaction/Order Id : <?php echo $txnid ?>
        Transaction Status : <?php echo $txnstatus ?>
        <?php } else { ?>
        Citrus Response Signature and Our (Merchant) Signature Mis-Mactch
        <?php } ?>

@stop

Please help
Answer: You have to insert a hidden input with the _token and later get that value as you do to get the other form fields in your ajax post.
<input type="hidden" name="_token" value="{{ csrf_token() }}" />

On your view you can set an object with the _token

Comment: Thanks Rahautos.But my response come from payment gateway site, than how i can  match session token and post token?
Answer: If your payment gateway allows to specify a custom callback URL per request you could set the callback URL to include the current CSFR token. Something like this:
$callbackUrl = url('ideas/paymentResponse?_token=' . csrf_token());

If you can't customize the callback URL per request, the only option you have left is disabling CSFR protection for your callback URL. Something like this
<?php

namespace App\Http\Middleware;

use Illuminate\Foundation\Http\Middleware\VerifyCsrfToken as BaseVerifier;

class VerifyCsrfToken extends BaseVerifier
{
    /**
    * The URIs that should be excluded from CSRF verification.
    *
    * @var array
    */
    protected $except = [
        'ideas/paymentResponse',
    ];
}

Comment: Thanks Javi. I skip the  csrf token  particular  route.


Determining the rank of a $4 \times 5$ matrix whos null space is three dimensional

Question:
What is the the rank of a $4 \times 5$ matrix whose null space is three dimensional?

Wouldn't this mean that I would have something like
$\begin{bmatrix}1&0&0&0&0\\0&1&0&0&0\\0&0&1&0&0\\0&0&0&1&0\end{bmatrix}$
So wouldn't it's rank = (the # of pivot columns) - the null space dimension? so rank $= 4 - 3 = 1$?
Comment: Are you familiar with the rank-nullity theorem?
Comment: Well, a $4\times 5$ matrix defines a map from $\mathbb{R}^5$ to $\mathbb{R}^4$. So rank plus nullity equals $5$.
Comment: Just because the column space is generated by five columns does **not** mean that these columns form a **basis** for the column space. Review the notion of "dimension".
Comment: I've heard it @carmichael561 . Would that mean  that the $rank = $ (#ofPivotColumns) - (null space dimension) => 4 - 3 = 1?
Comment: The rank-nullity theorem says that given a linear map $T:\mathbb{R}^n\to\mathbb{R}^m$, the rank of $T$ plus the dimension of its nullspace is equal to $n$. What are $n$ and $m$ for a $4\times 5$ matrix?
Comment: So then (1 + 3)? So its rank is 1!
Comment: Oh I see. **rank** of $A$ is just the dimension of the column space of $A$ so it's just $5$ because $A$ has $5$ columns correct?
Comment: The space $\mathbb{R}^n$ has dimension $n$. **Every** basis for $\mathbb{R}^n$ consists of $n$ vectors, so why do you say that @AlexProvost I'm confused.
Comment: I made a typo. the rank should be = $4$
Comment: $\mathbb{R}^n$ is generated by $10000000$ vectors if you want, but its dimension is nonetheless $n$.
Comment: So in this case my rank would be $2$ then correct? @AlexProvost
Comment: Yes, total number of columns minus nullity.
Comment: Oh I see what you're saying. You're saying just because I have 5 columns , doesn't mean that I'm going to have a number in each column correct? So it could be different
Comment: I'm saying that, generally, the five columns won't be linearly independent, and so they won't form a basis. The pivots give you a linearly independent subset of columns that still generate the column space (i.e., a basis).
Comment: And by "review the notion of dimension", I meant: what is the dimension of a space in terms of spanning and linearly independent subsets?
Answer: The rank-nullity theorem states that for a matrix $A$
$$
\DeclareMathOperator{rank}{rank}\rank(A)+\DeclareMathOperator{nullity}{nullity}\nullity(A)=\#\text{ columns  of }A
$$
The rank of $A$ is the dimension of the column space of $A$ and $\nullity(A)$ is the dimension of the null space of $A$.
Your question asks for the rank of a $4\times 5$ matrix $A$ whose null space is three-dimensional. The rank-nullity theorem immediately implies
$$
\rank(A)=\#\text{ columns of }A-\nullity(A)=5-3=2
$$
The example you give is
$$
A =
\left[\begin{array}{rrrrr}
1 & 0 & 0 & 0 & 0 \\
0 & 1 & 0 & 0 & 0 \\
0 & 0 & 1 & 0 & 0 \\
0 & 0 & 0 & 1 & 0
\end{array}\right]
$$
This matrix has $\rank(A)=4$ and thus $\nullity(A)=4-3=1$. It is thus not a relevant example of your problem.
A relevant example would be
$$
A =
\left[\begin{array}{rrrrr}
1 & 0 & 0 & 0 & 0 \\
0 & 1 & 0 & 0 & 0 \\
0 & 0 & 0 & 0 & 0 \\
0 & 0 & 0 & 0 & 0
\end{array}\right]
$$
This matrix has nullity three and thus has rank two.
Comment: I am so confused. I thought the rank was the number of pivot columns as alex said below me. Also, how is a 4x5 matrix not a relevant example?
Comment: Oh I see what you mean now, there could be numbers in the 5th column.
Comment: I think a relevant example would be S = {[1,5,0,2,0],[0,1,2,3,0],[0,0,0,0,0],[0,0,0,0,0]}, where S is the set of row vectors of some matrix A.
Answer: The number of pivot columns is the rank: row-reducing gives you pivots, which in turn gives you a basis for the column space. In terms of matrices, the rank-nullity theorem says that the total number of columns is equal to the sum of the nullity and the rank.
You seem to be confusing the total number of columns with the dimension of the column space. Take for example the $1 \times 2$ matrix $\begin{pmatrix}1 & 1 \end{pmatrix}$. Evidently the total number of columns is $2$, but these columns are linearly dependent. A basis for the column space consists of a single column $\begin{pmatrix}1 \end{pmatrix}$, and hence the rank = dimension of column space = $1$.


upload files in MVC4

Question: I'm creating a website in MVC4 C#, which allow you to upload files to a folder inside the project's folder,
For some reason the controller can't find the uploaded file. The "db.music.Add(newsong)" doesn't add the song path and name to the DB. here are the View,Controller and Model of the project.
thanks for your help!

Index.cshtml - VIEW
@{
ViewBag.Title = "Index";
}

Your Music

<form action="" method="post" enctype="multipart/form-data">
    <input type="file" name="file" id="file" >
    <input type="submit" />

MusicController.cs - CONTROLLER
[HttpPost]
public ActionResult Index(HttpPostedFileBase file)
{

   if (file.ContentLength > 0)
       {
            var fileName = Path.GetFileName(file.FileName);
            MVPDB db = new MVPDB();
            UploadMusic newsong = new UploadMusic();
            newsong.userId = 11;
            newsong.songName = file.FileName.ToString();
            newsong.songPath = Path.GetFileName(file.FileName).ToString();

            db.music.Add(newsong);
            db.SaveChanges();

            var path = Path.Combine(Server.MapPath("~/UserFiles/"), fileName);
            file.SaveAs(path);
        }

            return RedirectToAction("Index");
        }

Music.cs - MODEL
namespace MVP.Models
{
public class Music
    {
        [Key]
        public int userId { get; set; }
        public string songName { get; set; }
        public string songPath { get; set; }

    }
public class UploadMusic
    {
        [Required]
        public int userId { get; set; }
        [Required]
        public string songName { get; set; }
        [Required]
        public string songPath { get; set; }

    }
}

Comment: What does "can't find the uploaded file" mean?
Answer: Your form doesn't contains action. Try this
@using (Html.BeginForm("Index", "Music", FormMethod.Post, new { enctype = "multipart/form-data" }))

Comment: Thanks Jason, but I don't know where to put this code (I'm new on MVC4) can you please give me another hand?
Comment: http://www.codeproject.com/Articles/38970/Implementing-HTTP-File-Upload-with-ASP-NET-MVC    this post may help. Just change it to Razor view.

upload files in MVC4


Export to CSV file and open in browser

Question: I am stuck with an issue where I need to export data to a .csv file, but not store the file in file system - instead I need to simply open the file in browser.
I have written the below code to write data to .csv file:
FileWriter myWriter = new FileWriter("output.csv");
myWriter.append(EmployeeCode);
myWriter.append(',');
myWriter.append(Band);
myWriter.append('\n');
response.setHeader("Content-Disposition", "attachment; filename=output.csv");
response.setContentType("application/ms-excel");
response.setCharacterEncoding("UTF-8");

I am able to open a .csv file but it is empty. My data does not get populated into it.
Please suggest what am I doing wrong.
Comment: at the end add `myWriter.flush();myWriter.close();` & while writing print the same data on screen `System.out.println(EmployeeCode + "==" + Band);` and see actually you are getting data or not.
Comment: can you add at the end `myWriter.flush();myWriter.close();` and let me know what you get?
Comment: Fahim,
Yes I am getting the data printed using Sys out.
Comment: @user179516 we should close the file writers to read from the streams at the end :)
Answer: FileWriter writes the content in the output.csv file, not on the response output stream. You should do something like:
OutputStream out = response.getOutputStream();

To get the response output stream.
And write the content in the out stream, something like:
response.setContentType("application/ms-excel"); // or you can use text/csv
response.setHeader("Content-Disposition", "attachment; filename=output.csv");
try {
    // Write the header line
    OutputStream out = response.getOutputStream();
    String header = "EmployeeCode, Band\n";
    out.write(header.getBytes());
    // Write the content
    String line=new String(EmployeeCode+","+Band+"\n");
    out.write(line.toString().getBytes());
    out.flush();
} catch (Exception e) {
   log.error(e);
}

Export to CSV file and open in browser


Seria preciso ter outra linguagem de programação para se criar o assembler?

Question: Seria preciso ter outra linguagem de programação para se criar o assembler? Se sim, qual? Se não, o que poderia fazer para começar?
Sei que conforme os anos, logo após os cartões perfurados, surgiu a linguagem assembly. Mas, a linguagem de programação Assembly e seu compilador Assembler também foi programada com outra linguagem de programação? Se sim, qual seria?
Comment: Obrigada! E pessoal, desculpa pelas premissas erradas. É que quando ia corrigir já tinha enviado rs.
Comment: Alguma das respostas resolveu sua dúvida? Acha que pode aceitar uma delas? Veja o [tour] como fazer isso, se ainda não o fez. Você ajudaria a comunidade identificando qual foi a melhor solução para você. Pode aceitar apenas uma delas. Mas pode votar em qualquer pergunta ou resposta que achar útil no site todo;
Answer: Há premissas erradas na pergunta. Assembly (ênfase no maiúsculo) existe antes dos cartões perfurados que na verdade é só uma entrada de dados. Assembler não é um compilador, embora algumas pessoas acham que sim. Ele até é uma forma de compilador, mas não é completo, por isso é considerado apenas um montador, como o nome diz.
Tem perguntas que ajudam entender melhor isso e sobre a primeira linguagem de programação:

Como um computador entende o código binário?
A primeira linguagem de programação
Como é desenvolvida uma linguagem de programação?
Como é feito um compilador?
O que caracteriza uma linguagem de programação?
O que é assembler?

A linguagem de máquina é o código binário que a máquina entende. Ela até pode ser ser escrita fora da máquina, mas é raro quem faça. Ela não precisa ser transformada.
O Assembly é um texto "compreensível" por humanos. O Assembly existe fora da máquina, depois de entrada no computador precisa de uma transformação, pelo assembler. Há uma relação de 1 para 1 entre o código Assembly e o código de máquina.
O assembler é um mecanismo de tradução do Assembly para o código de máquina, portanto ele é um software. Sendo assim, ele precisa ser desenvolvido em alguma linguagem. O primeiro certamente foi escrito em código de máquina. Daí pra frente foi possível, mas não necessariamente foi feito assim, esse e outros assemblers foram usados para escrever qualquer tipo de software, incluindo compiladores e outros assemblers. Hoje é possível usar uma linguagem de alto nível para escrever um assembler.
Então respondendo estritamente a pergunta feita, sim, hoje em dia é possível escrever um assembler com qualquer linguagem de programação. Na década de 40 foi necessário usar a linguagem de máquina.
Assembly é uma linguagem de programação, portanto ela é apenas uma especificação.
Programe binário aqui.
Coloquei no GitHub para referência futura.
Answer: Luana, um programa compilado são códigos em formato suportado pela arquitetura do processador - Os processadores da intel por exemplo seguem a arquitetura CISC - Cada arquitetura tem um conjunto de comandos próprios. Segue um link com os opcodes do processador z80, um bom processador para aprender: Opcodes z80
Um compilador na verdade, transforma suas linhas de código em uma série de opcodes equivalentes. Já o assembly são os próprios opcodes, por exemplo:
ld a, #1800  //Carrega o valor na posição de memória #1800 para o registrador a
adc a, #1802 //Soma o valor em a com o valor na posição #1802
ld #1804, a  // Grava o valor de a na posição #1804 da memória

Isto seria equivalente, mais ou menos a x = y + z;
O Assembler só seria responsável então por transformar isso em binário.
Espero que tenha respondido sua pergunta de forma clara.
Answer: Se você estivesse criando agora um novo processador e não tivesse outra máquina disponível, você teria que escrever o primeiro assembler para ele em código de máquina direto em um disco, fita, cartões ou mesmo memória. E provavelmente, esse assembler teria o mínimo de recursos necessários para você conseguir escrever uma próxima versão com mais recursos em assembly ou em uma linguagem de mais alto nivel.
Como hoje em dia dispomos de diversas linguagens de todos os níveis você pode escolher a linguagem que é mais apropriada para gerar o assembler, e o C costuma ser a primeira melhor opção.
Comment: Se estivesse criando o primeiro computador do mundo não existiria disco, fira, cartões, nem memória. Durante mais de uma década só existiram assemblers e muitos já não eram tão simples assim. A maioria dos assemblers puros ainda são escritos em Assembly e código de máquina.


Do I have a misconception about probability?

Question: I have come across this text recently. I was confused, asked a friend, she was also not certain. Can you explain please? What author is talking about here? I don't understand.   Is the problem with the phrase "on average"?

Innumerable misconceptions about probability. For example, suppose I
toss a fair coin 100 times. On every "heads", I take one step to the
north. On every "tails", I take one step to the south. After the 100th
step, how far away am I, on average, from where I started? (Most kids
– and more than a few teachers – say "zero" ... which is not the right
answer.)

In a way it is pointless to talk about misconceptions, when you don't explain the misconceptions...
Source: https://www.av8n.com/physics/pedagogy.htm
Section 4.2 Miscellaneous Misconceptions, item number 5
Comment: @Masacroso No.  We are not talking about the expected *location* after $n$ steps, we are talking the average *distance*.  At step 2, for example, you could be 2 steps away (TT or HH), or you could be at your starting location (HT or TH).  All four outcomes are equally likely, hence the expected distance is $(2+2+0+0)/4 = 1$ unit from the starting location.  More generally, after $n$ steps, there is a non-zero chance of being somewhere other than the start, hence a non-zero (positive) expected distance from the start.
Comment: "Do I have a misconception about probability?" - probably ;-)
Comment: If the question asked for the expected position then the common misconception would be correct. I would classify the "misconception" as a misinterpretation of the problem.
Comment: The distance from where you start is the absolute difference.  That is, if you are moving on the number line, and you are at $-3$, the distance from $0$ is $3$.  Hence the answer is clearly not $0$ here.
Comment: I think "how far away am I, on average" is a colloquial phrasing that's reasonable to interpret as meaning the second thing, and not the first thing. But I don't like using it as a "gotcha" when the first possible meaning is there to confuse things.
Comment: What an irritating bit of math writing. It's not "probability" that misconception is about, it's a confusion between "signed displacements" and "distances".  And if ever an English sentence could have a smug look on its face, that last sentence would have one.
Comment: To be honest, I don't know if this qualifies as a "misconception". The wrong answer doesn't arise from some misbelief or some inadequate conceptualization of probability, but simply from not paying attention to the wording of the question and/or from the question(er) not placing more emphasis on what's being asked of you. The misconception aspect of it would be more related to what people expect the average distance vs average location to be (as in, do they expect them to be the same or different, and why).
Comment: Oh, I see. Thank you for the clarification @Xander
Comment: I agree with you that the phrase "on average" is problematic here, although I think the popular misconception would not vanish with a more careful phrasing. "Considering the distribution over endpoints of random walks, how far is the average of that distribution from the origin?" Zero. "Considering the distribution over distances of random walk endpoints from the origin, what is the average of that distribution?" Assuming 'average' here is the mean, nonzero, as explained in various answers. (Although the mode of the distribution is zero -- no individual distance will be more common than zero.)
Comment: "In a way it is pointless to talk about misconceptions, when you don't explain the misconceptions."  The linked page contains, in section 4, a very long list of "misconceptions".  None of them are explained.  A few have references.  These are listed as misconceptions held by *professionals*, hence one might expect that the intended audience would be capable of using the Google for details.
Comment: I didn't see any missconception here: the expected distance from the origin will be zero as far as the probability of heads and tails is the same, that is, $1/2$
Comment: I suspect that the fundamental misconception the author is trying to point to is that people will often conflate "f(average of x)" and "average of f(x)", for arbitrary function f. (In this case, f(x) = abs(x))  There are likely better examples that the author could have chosen.
Comment: It is a classic case of imprecise English that initially suggests mathematical precision (with a positive or negative value measured Northwards for the distance moved) and yet flips over to the imprecise choice of North or South (distance 'far away' from origin). Our brains fail to spot the subtle mind shift and try harder to fit the discussion to our mistaken axioms. Most paradoxes use the same trick (Monty Hall)
Comment: Interesting puzzle that I'd be sure to get wrong. But I do see a problem with the phrase "on average" in this case. Think about it. After the 100th step, you are where you are, period. There is no "average" about it. It's like saying, after I take the subway uptown two stops and downtown 3 stops, how far away, on average, am I from my original stop? You just are where you are, which is an absolute distance from where you started. Seems to me that is thrown in to make it a trick question.
Comment: Related: https://math.stackexchange.com/questions/103142/expected-value-of-random-walk/
Comment: Or does the author have a misconception (or no conception at all) of the Coriolis effect?
Comment: I like the question, though to be fair on the source page, it does state that "there are so many misconceptions that it would be impossible to list them all, let alone analyze them", and "To a first approximation, with isolated exceptions, the best policy is to teach the correct concepts and move on."
Comment: @screwtop Quite so, and the page is directed at teachers, who are presumed to understand, at the latest when they read "which is not the right answer".
Answer: Since the distance can't be negative, the average distance is strictly greater than zero when at least once you don't land on zero.
Let's say you land 2 steps above zero on the first try and 2 steps beneath zero on the second try. Then on average you will have thrown heads and tails equally many times, but the average distance from zero is 2.
How you can see that is as follows: suppose you start with a variable $x$ which is initially 0 and every time you throw heads, you add 1, and every time you throw tails, you subtract 1.
Then the average value of $x$ after 100 throws is 0, since they expect you to throw as many heads as tails on average.
But the average distance is the average value of $|x|$ after 100 throws. Throwing a lot of heads once in one "run" and throwing a lot of tails in another "run" cancels in the average value, but adds to the average distance.
Comment: I would add to the answer: This is not really a misconception of probabilities, this is mostly a misunderstanding of "distance" vs "location" in the question. It is a little like a trick question like "what is heavier a ton of feathers or a ton of lead"
Comment: But in the text, it says, "how far away am I, on average, from where I started" not "how far have I travelled", which I would translate to the expected location, in absolute value. I would take the absolute value of the average, not the average of the absolute value
Comment: @Falco, you are right that the probability of position to be $0$ is the biggest, but it's not true that the probability that distance is $0$ is the biggest. The probability that the distance is $0$ is $\frac 1{2^{100}}\binom{100}{50} \approx 0.0796$, while the probability that the distance is $2$ is $2\cdot\frac 1{2^{100}}\binom{100}{49}\approx 0.1561$. Intuitively, probability that we get $50$ heads is approximately the same as the probability that we get $51$ or $49$ heads, so the probability that the distance is $2$ is approximately double the probability that the distance will be $0$.
Comment: @AnderBiguri: Not necessarily - whether you're two steps north, or two steps south, of your starting location, you're precisely 2 steps away from it. (If you were two steps due _east_ of your start point, you'd still be 2 steps away, not zero!) But you're right that it's a matter of how the English description is interpreted in mathematical terms.
Comment: @AntiHeadshot, that's not how expected value works. It's like saying that expected value of normal distribution $\mathcal N(\mu,\sigma^2)$ can't be $\mu$ since the probability that $\mu$ occurs exactly is $0$.
Comment: I agree that the misconception isn't about probabilities at all, but is one which *Denker himself* shares with anyone else who is labouring under it—namely, that the phrase "how far away am I, on average, from where I started?" is completely unambiguous. Denker's misconception is that it *must be* interpreted as synonymous with "what is my expected distance from where I started?" rather than "what is my expected location, relative to where I started?", which is probably the way that those who think the answer is zero interpret it.
Comment: @Falco I would argue it is not. The Average result is not 0 steps, because the only way you are 0 steps from the start is, if you tossed exactly 50 heads and 50 tails. Which is not that common.
Comment: @AnderBiguri I think it's more that there's yet a third thing you could say which is "what is my average position". That's distinct from both "how far am I on average from where I started" and "how far I have traveled on average".
Comment: @Ennar I just want to say the question is not about the average distance while tossing the coin, it is about the average result of doing this experiment multiple times. And thus only exactly 50 heads an 50 tails will end up in 0 steps while all the other cases will increase the average.
Comment: If someone were to ask me the question, my *suspicion* would be they meant it to be interpreted in the way that Denker does.  But the ambiguity highlighted by Ander Biguri's comment is also sufficiently obvious that I'd certainly want to clarify the question before I attempted to answer it.
Comment: @AntiHeadshot, ok, I misunderstood the point you are trying to make.
Comment: @AntiHeadshot in contrast - 50 heads and 50 tails is the most likely single scenario, if you paint a curve of the chance of finishing at each individual location, it would be a bell curve around zero. And this is the intuitive answer - if I had to bet on any single location to win, I would bet on zero. The same for distance - if I had do bet on a single most likely distance it would be zero. Zero is the most likely result for location and distance.
Comment: @plm it's just a language thing. If I ask someone "how far I am from home" I don't expect them to give me a large positive number after going around the world and being back in my sofa. I don't thing it's unambiguous, otherwise there would net be as much discussion there is here hehe.
Comment: The whole catch lies in how different results are summed up to get the "average distance" and distance ignoring direction aka the negative sign.
Comment: Other viewpoint: variance is $E\left[(X-\mu)^2\right]$ where $E$ stands for expected value and $\mu$ for the expected value of $X$ (meaning average). Another type of measure for variance could be $E\left[|X-\mu|\right]$, the average distance between values and the expected value. The reason we don't use that is because squaring is much easier for a computer than taken abs and $x^2$ is continuous everywhere so easier to describe mathematically. (It's just another norm) The average distance expresses (almost) the same as variance: bigger means more spread out data. 0 means no variation of data
Comment: @AnderBiguri expected location/position = "where am i on average ?" = "what is my average position ?" ; expected distance = "how far am i on average?" (from where i started). This distance is just the absolute value of your walk after 100 steps, so you take the expectation of this. "Absolute value of the average [position]", which is $0$, is just not what is asked (for instance, again, the random variable "position" can be negative while the rv "distance" cannot). The original text is written unambiguously.
Comment: @AnderBiguri , from your remark i think you are not understanding what is done here. If you are in your sofa then your distance from home is 0, regardless of whether you have gone "around the world". Same for the random walk, if its final position is O (to distinguish from distance $0$) then its distance from O is $0$, regardless how far it travelled. And if i ask you a distance you wont give me a negative number. When you are averaging you are not averaging $|S_i|$ over the intermediate steps: you are averaging $|S_{100}|$ over $2^{100}$ full paths, not intermediate steps. -See my answer too.
Comment: @plm I do get it, just pointing out why the misconception arises
Comment: @AnderBiguri, ok, thank you. I just wanted to underline that the formulation is really totally unambiguous. And to be honest, when i read the question at first i thought there was a mistake in the "misconception", i really thought that we were supposed to compute the expected position; so it is a matter preconditioned or automatic thought.
Answer: The average distance (in steps) from where you started is approximately $\sqrt{\frac{200}{\pi}}\approx 7.978845608$ and as the number of steps $N$ tends to infinity is asymptotic to $\sqrt{\frac{2N}{\pi}}$.
The "misconception" here is a confusion between the expectation of $S_N=\sum_{i=1}^NX_i$ with $X_i$ independent random variables taking values $\{-1,1\}$ with equal probabilities $\frac{1}{2}$, and the expectation of $|S_N|$; i think this confusion is highly prevalent because we instinctively visualize position and its average, rather than distance, especially because here the symmetry of the random walk draws us to the simple "symmetric" value, $0=-0$. There is another closely related value, simpler to calculate and in some ways more natural: the squareroot of the expectation of $S_N^2$, that is the standard deviation $\sigma$ of $S_N$, as $ES_N=0$.
There are $2^N$ possible paths after N steps, each with probability $2^{-N}$, thus as noted in other answers since all values of the random variable $|S_N|$ are nonnegative, it suffices to find one that is positive to prove that the average distance $E|S_N|>0$. You may take the path $\omega=(1,1,1,...,1,1)$, "all steps to the north": the final distance from where you started is $N$ which contributes $\frac{N}{2^N}$ to the expectation, so $E|S_N|\geq\frac{N}{2^N}>0$.
Hölder's inequality implies that the variance $\sigma^2_{S_N}=ES_N^2\geq (E|S_N|)^2$; and actually $ES_N^2=N$ (by independence of the $X_i$ and $\sigma_{X_i}^2=1$) while as $N\rightarrow\infty$, $(E|S_N|)^2\sim\frac{2N}{\pi}<N$.
The exact formula -whose proof you can find in https://mathworld.wolfram.com/RandomWalk1-Dimensional.html - for $E|S_N|$ is $\frac{(N-1)!!}{(N-2)!!}$, for $N$ even, and $\frac{N!!}{(N-1)!!}$ for $N$ odd. And both formulas have the same asymptotic, given above. As commented by Džuris, the average distance increases only when taking an odd-numbered step -see my reply for a direct proof, not relying on the exact formula, which is not trivial to arrive at.
A decimal approximation of the value (rather than of the asymptotic estimate given at the beginning of this answer) is $E|S_{100}|\approx 7.95892373871787614981270502421704614$, and of course the standard deviation of $S_{100}$ is $10$.
Comment: Hi @galaxy-- , you can find the derivation of the exact formula in the link to Mathworld i gave above, it uses the (Legendre) multiplication formula for the Gamma function. Then you have a quotient of Gamma functions with a factor $\frac{2}{\sqrt{\pi}}$ whence you get the estimate either with an asymptotic expansion of Gamma functions or via Stirling's formula. I do not think there is a name for the asymptotic but it is related to "projection constants", as you may find in the references -eg https://www.ams.org/journals/tran/1960-095-03/S0002-9947-1960-0114110-9/S0002-9947-1960-0114110-9.pdf.
Comment: Wow, so the even numbered steps don't change the expected distance. Makes sense when you think a bit, but it surprised me!
Comment: @plm: thank you very much for your detailed answer.
Comment: The asymptotic $\sqrt{\frac{2N}{\pi}}$ is also the mean of the corresponding [half-normal distribution](https://en.wikipedia.org/wiki/Half-normal_distribution) with scale parameter $\sqrt{N}$, related to the central limit theorem applied to the signed distance
Comment: @Džuris thank you, good remark, i should have highlighted it. This follows from the explicit formula, but we can see it directly: note that if after $N$ steps you stand at $0$ then you can only increase your distance from it at the next step, but if after $N$ steps you stand away from $0$ then you have as much probability to get closer to it as to get farther from it. Now we can only come back to $0$ after an even number of steps $N$, thus $E|S_{N+1}|>E|S_N|$ only for even $N$.
Comment: @plm: could you please tell the name of the asymptotic estimate which you used at the beginning? I would like to look up how it is derived. Thanks
Comment: @Henry, yes, thank you. I thought about adding it a couple of times, and got lazy.  ^^   It is thus also the expectation of the absolute value of standard brownian motion (starting at $0$) up to any real time $N$.
Answer: I suspect it comes from the following plausible-sounding but flawed reasoning:
(1) the average final position is the starting point (correct)
(2) so the distance from the starting point to the average final position is zero (correct)
(3) and average distance equals distance to the average (incorrect! the former is actually a much more complicated thing, in this case, than the latter, and they are not equal)
(4) therefore, the average final distance is zero (incorrect)
Comment: Yes, I think this is the key point. It is a very common error to think that it doesn't matter at what point they take an average, and completely fail to notice that the answer they get is unreasonable. I think you would get a decent amount of people who know that the distance can't be negative and yet are happy with an argument that the average is 0, not realising that would imply it is *always* 0.
Answer:
Is the problem with the phrase "on average"?

Perhaps. You might also be jumping to conclusions about what's being asked. The question says:
After the 100th step, how far away am I, on average, from where I started?
I'm sure you know that to calculate an average, you add all the samples  and divide the total by the number of samples. Since the coin is fair, your intuition might tell you that since heads and tails occur with equal frequency, they should cancel each other out and the average distance from the starting point will be zero. However, if you think about all the possible outcomes that you could get from tossing the coin 100 times, the only ones that result in a distance of 0 steps from the start are the ones where there are exactly 50 heads and 50 tails. All the outcomes with more heads than tails or vice versa put you some distance greater than 0 steps from the start, so the average distance has to be more than 0 steps.
Here's a table with all the possible outcomes for just 4 coin tosses, along with their average distance from the start:

As you can see, if you toss a coin 4 times and take 1 step north on heads and 1 step south on tails, on average you'll end up 1.5 steps from the start.
Comment: As a non-mathematician, I appreciate the clarity and the use of a concrete example to highlight the misconception.
Answer: I think the idea here is that most people believe that since you are throwing coin a "large" number of time ($100$ is not large by the way), the heads and tails should "average out" and we should thus be close to the initial point, and that the distance to initial point is $0$.
However, the problem is that this is not how it turns out. What is true is that the ratio between the distance to origin and the total distance walked is trending to $0$ as the number of coin tosses increases. However the average distance to the origin (which can take all values from $0$ to $100$ in our case), is then not $0$.
Answer:
Flip two coins and walk a mile north for each heads, and a mile south for each tails.
How much is your average cab-fare home?

Phrased this way, we know the answer isn't "zero" because no cabby is going to pay you for walking south instead of north.  Doing the math, a quarter of the time you end up 2-miles north, a quarter of the time you end up 2-miles south, and the other half the times you've already made it home; altogether that amounts to 1-mile worth of cab-fare on average.  That's not so hard, right?
So what's with the stupid "How far away am I, on average, from where I started?... (Zero is wrong...)" wording?  If they didn't want to know 'where' I end up on average, they should have asked 'how far'... umm, I mean... well, that's just annoying now isn't it.

And that's why it was worded that way!  The lesson isn't supposed to be "And now class, we define a single pedantic definition of what 'How far away?' is supposed to mean!" but rather the lesson is that everyday language can sometimes be vague and/or imprecise.
Or at least, that's the usual place where I see this example: in distance-versus-displacement pedagogy.
Connecting this example to "misunderstanding probability" is somewhat unusual, but it's not entirely incorrect either.  In one way it illustrates how, just because you can crunch numbers and output a statistic doesn't necessarily mean that you have actually produced the useful data that you think you wanted.
How so? Well, we've determined the average displacement and average distance for this example: on average you end up back where you started, but on average you spend 1-mile worth of cab-fare.  If we didn't just work through the math and know exactly what each of those two statistics signified and how they do/don't relate, we might have looked at those numbers and thought... "Why am I paying a cabby for 1-miles on average when I'm 0-miles from home on average?" or even worse "Why on Earth am I paying somebody to drive me 1-mile away from home!?".  Both conclusions are total nonsense and we know why (having done all that the math above) but these kinds of conclusions get made quite easily.  Knowing that calculating average cab-fare required the average-distance statistic (rather than assuming that average-displacement was the 'same thing') was vital to understanding the whole situation.
Similarly, problems involving combinatorics, probabilities, and statistics will rely on a chain of logical steps being accounted for properly.  What if we hadn't properly accounted for TH and HT separately? We would have thought our average cab ride was (2+0+2)/3=1.33-miles long!  Probability problems can be notoriously tricky for new students precisely because it can be hard to properly account for every possibility when you barely know what adding versus multiplying probabilities means and you're just winging it.
Answer: We can model taking a step to north or south as discrete random variable
$X_n\sim\begin{pmatrix}-1 & 1\\ \frac 12 & \frac 12\end{pmatrix}$. We can then look at random variable $S_n = X_1+X_2+\ldots + X_n$ which will tell us our position after $n$ coin tosses.
If you look at $E(S_n)$, then it is indeed $0$ because $E(X_i) = 0$ and expected value is linear. However, if we want to look at distance from the origin, we should look at random variable $|S_n|$ instead.
Let me assume that $n$ is even, since in the original question we have $n = 100$. The case when $n$ is odd is dealt with similarly. The reason that we consider parity is because $S_n$ is the sum of $n$ odd numbers, so the parity of $S_n$ is the same as $n$. We can look at the probability that $S_n = 2k$, $k = -n/2, -n/2 + 1, \ldots, n/2$. This will happen exactly when there are $n/2+k$ coin tosses that result in heads and $n/2-k$ coin tosses that result in tails. Thus, the probability is
$$P(S_n = 2k) = \frac 1{2^n}\binom n{n/2+k}.$$
The expected value of $S_n$ is then
$$E(S_n) = \sum_{k=-n/2}^{n/2}\frac 1{2^n}\binom n{n/2+k}\cdot 2k$$ which we can confirm is $0$ by noting that $\binom n{n/2+k} = \binom n{n/2-k}$, so $2k$ and $-2k$ occur equally likely.
The expected value of $|S_n|$, on the other hand is
$$E(|S_n|) = \sum_{k=-n/2}^{n/2}\frac 1{2^n}\binom n{n/2+k}\cdot |2k|$$ which is strictly greater than $0$ since $\frac 1{2^n}\binom n{n/2+k}\cdot |2k|>0$ for all $k\neq 0$, and is $0$ for $k = 0$.
Plugging some values of $n$ in software, we get $E(|S_2|) = 1$ (which you can check by hand to convince yourself of the formula), $E(|S_4|) = 1.5$ and $E(|S_{100}|)\approx 7.96.$
I would say the point of the exercise is to understand the difference between $|E(X)|$ and $E(|X|)$, which are not the same in general. In fact $|E(X)|\leq E(|X|)$ is an instance of triangle inequality.

The reason that you don't answer to the question "how far am I from home on average" by looking at $S_n$, its expected value and taking absolute value of that is, intuitively, the same reason no one would say the following: "Yesterday I walked two kilometers north from home and today I walked two kilometers south from home. On average, I was at home." One would instead say: "Yesterday I walked two kilometers north from home and today I walked two kilometers south from home. On average, I walked two kilometers from home."
Comment: You can replace $1/2^n$ with $p^{n-2k} (1-p)^{2k}$ if you want a generalized version of the above with a skewed coin with probability $p\in(0,1)$ for heads.
Answer: Not right, but perhaps thinking of it this way will help you grasp the problem — you might think of this as where the most people end up, versus the average difference.
Suppose that 98 out of 100 end back where they started, and 1 person was 1 step north, 1 person was 1 step south.  That's still 2% of the total being off, making the average distance be .02 steps.  And despite the fair toss, out of a hundred you're not going to end up with 98 of them back on zero.
Answer: The question tries to be kind to the reader by using non-technical language. "How far way am I?", is intended as "what is my positive distance from?", or "how far must I still walk?" or some technical equivalent involving $L_1$ norms. A non-technical reader can easily misinterpret it as "How far North am I?", so the kindness was misplaced. The reader was just confused. There are reasons why professionals use precisely-defined language, and there are many pitfalls involved in communicating with non-professionals
Answer: Here is my approach.
Let $X_1,...,X_{100}$ be independent random variables that possess a uniform distribution on $\{-1,1\}$
You're looking to find the expected value of $|X_1+\dots+X_{100}|$.
Put $Y_j=\frac{1}{2}(X_j+1)$. Then $Y_j\sim \text{Bernoulli}(0.5)$ and it follows that $$\mathbb{E}(|X_1+\dots +X_{100}|)=\mathbb{E}\left(|2Y-100|\right)$$
where $$Y=Y_1+\dots+Y_{100}\sim \text{Binom}(100,0.5)$$ Indeed, with the law of the unconscious statistician, the expected value equals $$\sum_{k=0}^{100}|2k-100|{100 \choose k}(0.5)^{100}$$ which is around $7.96$
Answer: Okay the question, citation might be incomplete right away.
There are two possibilities in the problem given. One possibility is the mainly discussed one given for the fair coins. The second one, and evidently asked for one is that of the positions taken in the experiment.
Now look detailed into the experiment.
The fair coin is thrown and shows a result.
Take for example a step to the north.
What had been possible before the fair coin is tossed are two results. A step to the north or a step to the south.
Each is by the fair coin equally possible.
In the second step the conditions change. We get of course the fair possibility for each again in the succession of the two independent tosses.
We could stand two steps to the north or south or again where we started. These three results are equally possible so each one has the possibility $\frac{1}{3}$ and we did step a distance different only in one of the results. The case we did not move has the distance zero. In the two other cases we are two steps away. Since the decision is based on the fair coin we use the possibilities for the paths are each equal.
This get more complicated after the third toss. We now get the cases we made three step in one direction, only two times. So our intermediate results has grown again. We now have four results and each one is equally probable. The change is that we do not only ignore negative values in the evaluation of the distance, we get paths that lead to the same position. One step the north, one step to the south and again to the north is still one step to the north altogether.
Mind again the even step place are not taken in the odd steps situation. We change from $\{-2,0,2\}$ to $\{-3,-1,1,3\}$ in the set of taken positions. The distances taken are $\{1,3\}$. These are more possible from the probability at the moment of evaluation than in the step before. We have again $\frac{1}{2}=0.5$ If the paths are considered we have now a bigger weight on each.
Probability changes each time the situation in which the probability is consider does change. So the question is for averages. We see from our results, so where we stand after even and odd numbers of tosses is each symmetric to the place we started is north and south remain different.
This for the human accessible statics heuristics for the posed problem.
A professional answer is:
To calculate the average distance from where you started after taking 100 steps based on the coin toss, we can use the concept of expected value in probability.
Let's analyze the situation step by step:
On every "heads," you take one step to the north.
On every "tails," you take one step to the south.
Since the coin is fair, the probability of getting "heads" or "tails" is 0.5 (50%) for each toss.
After 100 steps, the net distance you move to the north is the number of heads minus the number of tails. Let's call this difference "D."
The expected value of "D" is the average value we expect to obtain after performing the experiment multiple times. Since the coin tosses are independent and fair, the expected value of "D" is zero. This is because, over a large number of trials, you would expect to have an equal number of heads and tails, leading to a net displacement of zero.
However, we want to find the average distance from where you started, which is the absolute value of "D." The absolute value is used because the distance is always positive, regardless of whether you moved north or south.
As a result, after 100 steps, on average, you would be exactly the same distance away from where you started, which is 0 units.
Remember that this result is based on the assumption of a fair coin and an equal number of steps in both directions (north and south).
To analyze the statistics of this problem, we can consider the random variable "X," which represents the net distance you move after 100 steps. As we discussed earlier, "X" will be the difference between the number of heads and the number of tails.
Let's break down the statistics step-by-step:

Probability distribution of a single step:

The probability of getting "heads" (moving north) on a single toss is P(Heads) = 0.5.
The probability of getting "tails" (moving south) on a single toss is P(Tails) = 0.5.

Probability distribution of "X" after 100 steps:

The probability distribution of "X" will follow a binomial distribution since we have 100 independent Bernoulli trials (coin tosses) with a probability of success (P(Heads)) equal to 0.5.
The probability mass function (PMF) of the binomial distribution is given by:
P(X = k) = C(n, k) * (P(Heads))^k * (1 - P(Heads))^(n - k),
where C(n, k) is the binomial coefficient, given by C(n, k) = n! / (k! * (n - k)!).

Expected value (mean) of "X":

The expected value of "X" is the mean distance you would be from where you started after 100 steps.
For a binomial distribution with parameters n and p, the expected value is given by n * p, where n is the number of trials (100 steps) and p is the probability of success (P(Heads)).

Therefore, the expected value of "X" is E(X) = 100 * 0.5 = 50.

Variance of "X":

The variance of "X" represents the spread or dispersion of the net distance.
For a binomial distribution with parameters n and p, the variance is given by n * p * (1 - p).

Therefore, the variance of "X" is Var(X) = 100 * 0.5 * (1 - 0.5) = 25.

Standard deviation of "X":

The standard deviation of "X" is the square root of the variance.

Therefore, the standard deviation of "X" is SD(X) = sqrt(25) = 5.

So, the statistics of the problem are as follows:

Expected value (mean) of "X": 50
Variance of "X": 25
Standard deviation of "X": 5

This means that, on average, you would be 50 units away from where you started after 100 steps, with a spread of 5 units in either direction due to the variability caused by the random coin tosses.
This for sure enhanced the number of professional definitions used. This makes the problem really harder and excuse many of the person allegedly accused in the supporting gossip of the question. I think this is worth this proper scientific answer despite it is lengthy.
Since my perceptions and understandings of the question is different to most of the others given here. I start now my concept for an answer:
There are several possible misconceptions that people might have when considering this problem:
Misinterpreting the expected value: One common misconception is to assume that the expected value of 50 means you will end up exactly 50 units away from the starting point after 100 steps. However, the expected value represents the average value over many trials. In reality, you could end up closer or farther away from the starting point in any single run of 100 steps.
Believing the average distance is always zero: Some people might think that, since there are an equal number of steps in each direction (north and south) due to the fair coin, the average distance should be zero. However, this overlooks the fact that the distance is measured as an absolute value, so the final distance is always positive.
Expecting a linear relationship between steps and distance: Another misconception might involve assuming that the average distance increases linearly with the number of steps taken. For example, doubling the number of steps would double the average distance. In reality, the average distance is determined by the expected value (in this case, 50) and doesn't scale linearly with the number of steps.
Thinking that the standard deviation is the distance you'll end up: The standard deviation of 5 might be misinterpreted as the maximum distance you could end up from the starting point. However, the standard deviation represents the spread of the net distance values (positive and negative) around the expected value (50), but it doesn't determine the farthest distance you might reach in any single run.
Assuming the average distance will converge to zero with more steps: Some might believe that if you increase the number of steps (e.g., to 1,000 or 10,000), the average distance would converge to zero. While it's true that the expected value of "X" will scale linearly with the number of steps, it doesn't mean the average distance will always get closer to zero. Due to the spread caused by the random coin tosses, the average distance will likely oscillate around 0.
Expecting a normal distribution of distances: A common misconception might involve assuming that the distribution of distances after 100 steps will be approximately normal (bell-shaped). However, in this case, the distribution follows a binomial distribution, which can have a different shape, especially for a relatively small number of steps like 100.
To overcome these misconceptions, it's essential to understand the concepts of expected value, probability distributions, and the distinction between average (expected value) and individual outcomes. Probability problems can be counterintuitive, and sometimes our intuition might not align with the actual mathematical results. Analyzing the statistics and the underlying probability distributions can help clarify any misconceptions.
Comment: "We could stand two steps to the north or south or again where we started. These three results are equally possible so each one has the possibility $1\over 3$" This is incorrect: the probabilities are $.25$, $.25$, $.5$ (think about the four possible pairs of coin outcomes).


Is tossing a die in 10 consequent days an ergodic process?

Question: IT maybe an elementary question but I'm totally new to the concept. In Wikipedia, ergodicity is defined as follows:

In statistics, the term describes a random process for which the time
  average of one sequence of events is the same as the ensemble average.

Suppose that we have thrown a die one time in 10 consequent days and gotten these results:
$\{5,5,1,5,4,1,2,3,5,5\}$
If we consider $(X_i)_{1\le i\le10}$ the random process for this experiment, in the $i$th day we have 6 possible values for random variable $X_i$ each with probablilty $\frac{1}{6}$ so:  $$ensemble\;average=\frac{1+2+3+4+5+6}{6}=\frac{21}{6}=3.5$$
but for temporal average base on this single realization we have:$$temporal\;average=\frac{36}{10}=3.6$$
so tossing a die for 10 subsequent days is not an ergodic random process. But if $number\;of\;days\to\infty$ then $temporal\;average\to 3.5$ so tossing a die for an infinite subsequent days is an ergodic process.
1-Is my conclusion true?
2-Is my understanding for ensemble average, temporal average and ergodicity right?
If yes give me an example of an ergodic and a nonergodic continuous random processes and Compute their ensemble and temporal averages?
If no tell me how should I compute ensemble and temporal averages? should I consider all $6^{10}$ possible realizations when computing temporal average?
Comment: If you have not done it yet, I suggest you read https://en.wikipedia.org/wiki/Ergodic_process . Beyond formulas, what's important about ergodicity is: "a stochastic process is said to be ergodic if its statistical properties (such as its mean and variance) can be deduced from a single, sufficiently long sample (realization) of the process".
Answer: Ergodicity is a concept based on the limit of the temporal average. So, based on a small number of experiments you cannot infer that the process is not ergodic.
In the case of independent experiments it can be easily shown what the relationship of the temporal average and the ensemble average. In your case
$$\text{temporal average}=\frac{36}{10}=\frac{5}{10}5+\frac{2}{10}1+\frac1{10}4+\frac1{10}3+\frac1{10}2=3.6$$
Here, say, $\frac5{10}$ is the relative frequency of the outcome $5$. If the number of experiments is large (the temporal length of the experiment is high). Then the estimates of the relative frequencies are good.
It is clear that in the case of independent experiments the temporal average has to tend to the ensemble average. Also, if the estimates of the ensemble probabilities are poor then the temporal average is also poor. Which does not mean the the process is not ergodic.


What is retired out in cricket?

Question: I have seen a match score card, where Mitali Raj (India) was shown retd out.
What is "retired out" in cricket? When is a player declared retired out?
Answer: This is very clearly covered by Law 2.9:

Batsman retiring
A batsman may retire at any time during his innings when the ball is dead. The umpires, before allowing play to proceed shall be informed of the reason for a batsman retiring.
(a) If a batsman retires because of illness, injury or any other unavoidable cause, he is entitled to resume his innings subject to (c) below. If for any reason he does not do so, his innings is to be recorded as 'Retired - not out'.
(b) If a batsman retires for any reason other than as in (a) above, he may resume his innings only with the consent of the opposing captain. If for any reason he does not resume his innings it is to be recorded as 'Retired - out'.

As the Cricbuzz scorecard you've linked to indicates, this was a bit of a strange situation in that the Indian Women continued to bat after reaching their target of 107 runs - basically at this point it had turned into a practice match, so a couple of the Indian women retired to let the rest of the team have a go.
Comment: Spot on. Just one addition to that - under the [new laws](https://www.lords.org/mcc/laws-of-cricket/new-code-of-laws-october-2017/), a batsman who is removed from the field for offensive behaviour will also be recorded "Retired - out" (I'm a little surprised they didn't create a new category of dismissal to record that. "Retired - a**hole" isn't something a batsman would want on his record after all!). Those laws will come into effect on 1 Oct 2017.

What is retired out in cricket?


Joomla 1.7: change meta tags from system plugin

Question: Joomla version 1.7
Plugin enabled in admin part
Plugin code:
<?php
// no direct access
defined('_JEXEC') or die;

jimport('joomla.plugin.plugin');

class plgSystemMetatags extends JPlugin
{
    public function __construct(&$subject, $config)
    {
        parent::__construct($subject, $config);
    }

    public function onBeforeRender()
    {
        $document =& JFactory::getDocument();
        $document->setMetaData('keywords', 'test keywords');
    }
}

But this doesn't work
Meta description renders value, which set in global configuration
plugin xml file
<?xml version="1.0" encoding="utf-8"?>
<extension version="1.7" type="plugin" group="system" method="upgrade" client="site">
    <name>System - Metatags</name>
    <author>Joomla! Project</author>
    <creationDate>November 2005</creationDate>
    <copyright>Copyright (C) 2005 - 2011 Open Source Matters. All rights reserved.</copyright>
    <license>GNU General Public License version 2 or later; see LICENSE.txt</license>
    <authorEmail>firstname.lastname@example.com</authorEmail>
    <authorUrl>www.joomla.org</authorUrl>
    <version>1.7.0</version>
    <description></description>

    <files>
        <filename plugin="metatags">metatags.php</filename>
        <filename>index.html</filename>
    </files>

</extension>

Answer: use onBeforeRender instead of onAfterRender.
When onAfterRender event is triggered the output of the application is already available in the response buffer.
Comment: Thanks, but i just figured out, that Joomla  doesn't even executes my plugin. It is enabled in system.
Comment: But still, you need to use onBeforeRender
Comment: I change event to onBeforeRender  - nothing, even when i put wrong construction into that file - no any errors. It doesn't executes at all.
Comment: enable the debug mode and set error reporting to maximum in Global configuration. Let me know if any warning or error is there.
Comment: Nothing! standart Profile Information, memory usage & queries list
Comment: onAfterDispatch helped, onBeforeRender  - doesn't not react. Thanks for help


run an exe on access of folder

Question: I have a share folder ,which i want to grant access permission to few people only at certain times.i.e. while they try to access the folder ,i should be able to either allow or deny based on my wish.In short its run time access control ,not the static access control already present in windows.
Is there a provision to hook a exe as such?
I prefer to do it in C# .net
Answer: So to accomplish such a task i would use the ACL from NTFS. Yes it is 'hardcoded' and can't be changed while someone access a file. But you can write a windows service which will change the ACL dynamically based on whatever you like.
So write a program that changes the ACL and windows does the rest. Some examples for doing such a task in C# can be found with a little google search:

http://weblogs.asp.net/cumpsd/archive/2004/02/08/69403.aspx
http://blog.crowe.co.nz/blog/archive/2007/08/25/c---An-example-of-setting-NTFS-Directory--File.aspx
...

Update
To grant or deny a permission you need a rule set. These rules can be checked within your application and this sets the NTFS permissions. What is missing?
Maybe you don't have this easy method to get an event about 'user is accessing file/folder foo, what should i do?'. But you can generate each second (if you like) or depending on a event (file/folder created, copied, deleted, renamed; specific date/time reached) a new rule set and just burn it down into ACL. Finished.
Update (again)
@Ravisha: But when do you know the rules if you grant or deny the access? These rules are defined beforehand.
You say the user X has access only from 8am to 15pm or only if file y exists (or something special is written into file y). For all these rules you have to write a program and this program doesn't evaluate the rules if you got the event 'x is trying to access y'. Instead you check the rules on a regular basis (e.g. once per minute) or some other event (file rules.config has been changed). And then you alter the NTFS permissions according to your rules.
Maybe this isn't the perfect solution. But the easiest one you can accomplish within windows. If you really like to do it the hard way, you can maybe take a look into File System Filter Drivers. But this is a hard task and far away from managed code.
Comment: This is to set the user permission on the go,this is half the answer:)
Actual requirement is to grant or deny permission
Comment: @Oliver
Suppose person X  tries to access my folder,i should be able to either grant him or deny the permission.In the example what you sent it explains how to set the permissions,but main part is to get the event which is raised when person X access my folder.
Comment: Oliver,If you have noticed ,the question itself is about run time permission not static permissions.
Comment: @Ravisha: As already explained in my last paragraph, the only way for that would be File System Filter Drivers and that's a hard way to go. And the far easier way would be to change the static permissions at runtime like explained above.
Answer: The access control is checked when a user tries to perform a file operation on a file in the folder, so you should not need to have any additional run-time checks.
Also, Windows doesn't include a "hook" facility to allow or deny access to a folder by running a program when access is attemped.
Answer: If a rootkit can do it, so can you. But I don't think you want to go there.
Why not put all you documents into some kind of file, with an extension that you control. If you doubleclick the file a winzip/explorer/... like interface will give access to the files in the cabinet, but only if you wish.
Answer: You can probably include an autorun.inf file that will run your app on folder open and close explorer window/ navigate up when someone is not allowed to enter. For details look Here

run an exe on access of folder


unusable-partial-specialization error with Clang by default

Question: I am just programming with C++ templates, but Clang gave me an error by default.
The code below:
#include <type_traits>
#include <utility>

template <int... vals>
struct int_seq {};

template <typename>
struct pop_back;

template <int... vals, int val>
struct pop_back<int_seq<vals..., val>>
    : std::enable_if<true, std::pair<std::integral_constant<int, val>, int_seq<vals...>>> {};

Can be compiled successfully with GCC and MSVC. But Clang will give an -Wunusable-partial-specialization error:
$ clang++ -std=c++17 -c main.cpp
error: class template partial specialization contains template parameters that cannot be deduced; this partial specialization will never be used [-Wunusable-partial-specialization]

However, if we specify the -Wno-unusable-partial-specialization option, it can be compiled successfully:
$ clang++ -std=c++17 -c main.cpp -Wno-unusable-partial-specialization

Diff view in godbolt:
https://gcc.godbolt.org/z/sd6MW5MTT
So which behavior is correct?
Comment: Does it do "the right thing" when you compile it with `-Wno-unusable-partial-specialization`? Can you add a usage example to the question too?
Comment: Looks like IFNDR as you're not using the template. Once you use it, it will become ill-formed.
Answer:
So which behavior is correct?

The program is ill-formed as per temp.class.spec.match#3 as the template parameter cannot be deduced:

If the template arguments of a partial specialization cannot be deduced because of the structure of its template-parameter-list and the template-id, the program is ill-formed.
[Example 3 :
template <int I, int J> struct A {};
template <int I> struct A {}; // error

end example]

(emphasis mine)

Note that if you don't actually use the template then the program is ill-formed no diagnostic required. But once you start using it, it will be ill-formed and a diagnostic should be issued in that case. Here is a demo that actually uses the template and makes the program ill-formed.


If we change the infinite series (or power series) so we are adding two terms at a time, is this still the same as the original series?

Question: I would like to ask about the second equality in this proof:

So the only difference between these two series, is that we are adding two terms at a time and I can actually imagine situation where the left hand side fails to converge but the right hand side converges using some alternating series.
For that reason, I would like to ask when are we allowed to change a series (or power series) like this and why is it ok in this specific case?
Answer: Your instinct is right that you can start with a convergent series (like the left-hand side) and then proceed to group the terms two at a time (like the right-hand side), but not the other way around.
The convergence of $\sum_{n=0}^\infty a_n$, by definition, means that the limit of its partial sums $s_N = \lim_{N\to\infty} \sum_{n=0}^N a_n$ exists. The regrouped series converges, again by definition, precisely when the limit of its partial sums $t_N = \lim_{N\to\infty} \sum_{n=0}^N (a_{2n}+a_{2n+1})$ converges. But $t_N = s_{2N+1}$ is a subsequence of a convergent sequence, so it converges to the same limit.
As for the failure in the other direction, you're right that there are simple alternating counterexamples like $\sum_{n=0}^\infty (-1)^n$.
Comment: You answer the original question (good!). But I am not quite sure why the OP didn't ask about the next equality, the one justified by Th. 7.95(a). In general that's the step that needs care when we try to split up series.


Referencing Sprites/ Objects stored in an array

Question: After an object has been added to an array via push(), how can you reference the x or y value of it? For example:
var Test:Sprite = new Sprite();
Test.graphics.beginFill(0x000000);
Test.graphics.drawRect(0,0,10,10);
testHolder.addChildAt(genericBlock,0);

Comment: sorry, missed the adding of the test array out.
Answer: The x and y values of any object stored in an array can be accessed via:
var myArray = new Array();
myArray.push(testSprite1); // First object 'pushed' into array at position 0
myArray.push(testSprite2); // Second object 'pushed' into array at position 1

myArray[0].x = 50; // testSprite1.x = 50
myArray[1].x = 100; // testSprite2.x = 100;

// To referece..
trace(myArray[0].x, myArray[1].x); // Outputs: 50 100

This is a great tutorial to learn how to implement arrays and manipulate all/single elements held within them:
http://www.republicofcode.com/tutorials/flash/as3arrays/
Comment: Might I suggest that you cast the array elements, for example Sprite(myArray[0]).x as Actionscript-3 is a strongly typed language.


Fields from different content types in a single page

Question: Using field permissions i have set 10 fields from various content types (articles, page, etc) to private.
While the rest of the fields is filled by the user, the publisher needs verify and fill those 10 fields to publish the content.
Is it possible to get all these fields in a single page so the publisher don't have to go to the individual content types to fill those fields.
Comment: Hello, and welcome to Drupal Answers. I am not clear why you put those fields on different content types. Would not creating a content type with all the needed fields be easier?
Comment: I have set some fields from each content type(there are like 3 content types) for the publisher to enter before publishing the content. so he has to visit every content type for entering the values and set it to published. I was looking for a way to show all the fields the publisher has to enter in a single page.
Answer: My first thought would be to rethink your publishing workflow.
Having that said, I would try to create a view which takes content from all content types. Instead of showing the content, show the appropriate fields and create a filter so only unpublished content is shown...
Comment: A view doesn't allow to edit fields; it just allows to show a list of nodes. I agree with rethinking the publishing workflow, though.
Comment: isn't it logical for a role to be able to fill in all their assigned fields from different content types with ease... guaranteed only they have those field permissions. There should be something may be am using the wrong words. :( and  thanks for your replies :)
Answer: If you can't restructure your publishing flow as kiamlaluno said (preferred method!), then another option would be to write a custom module to programmatically retrieve the info from each field and display them for the publisher's review in a form, then store the publisher's revisions in each field. See these pages for more info, Drupal API and another SO thread