How do I display an array of entities from a controller?

Question: I am new on Drupal 8 , so i have created a service class which return a list of data, 'articles' (node entities), and I call this  service class inside a controller, but no data showing up :
My getArticles() method inside my service:
  public function getArticles(){
    $storage = \Drupal::service('entity_type.manager')->getStorage('node');
    $my_entity_ids = $storage->getQuery()
      ->condition('type', 'article')
      ->condition('status', 1)
      ->execute();
    $my_entities = $storage->loadMultiple($my_entity_ids);
    return $my_entities;
  }

My controller:
public function myPage() {
    $data = \Drupal::service('mymodule.service');
    $dataService = $data->getArticles();
    return $dataService;
  }

My result is a blank white page when I view the path routed to my controller, but I see the following message in my error log:

Recoverable fatal error : Object of class Drupal\node\Entity\Node could not be converted to string dans Drupal\Component\Utility\Xss::filter()'' -----"Warning : strlen() expects parameter 1 to be string, array given dans Drupal\Component\Utility\Unicode::validateUtf8()

Can anyone tell me please why i can't get the articles?
Comment: You have the articles. They are objects with data. You haven't specified how they should be displayed. Your *myPage()* method needs to return a render array. What are you trying to display from the articles?
Comment: Let's say the title of the articles
Comment: For example i want to display the title of articles
Answer: Controllers need to return a render array. Let's imagine you process your articles for render in a new method renderMyPage() which you call from myPage() and pass your array of article objects.
If you're displaying multiple fields from the articles, you're best off building and configuring a view mode and then getting the view mode render array as described in this answer.
function renderMyPage($articleObjects) {
  $view_builder = \Drupal::entityTypeManager()->getViewBuilder('node');

  $articles = [];
  foreach ($articleObjects as $article) {
    $articles[] = $view_builder->view($article, 'my_view_mode_machine_name');
  }

  return $articles;
}

If you want to render a single field from your article, you can get the render array for a field as described in this answer.
function renderMyPage($articleObjects) {
  $articles = [];
  foreach ($articleObjects as $article) {
    // You can pass a view_mode machine name or
    // an array of field configurations to view().
    $articles[] = $article->title->view();
  }

  return $articles;
}

Alternatively you can build your own render array, say to render the title as an h2.
function renderMyPage($articleObjects) {
  $articles = [];
  foreach ($articleObjects as $article) {
    $articles[] = [
      '#type' => 'html_tag',
      '#html_tag' => 'h2',
      '#value' => $article->title->value,
      // The other methods add cache tags automatically, but we need to add
      // cache tags manually here since we're building the array from scratch.
      '#cache' => [
        'tags' => $article->getCacheTags(),
      ],
    ];
  }

  return $articles;
}

Each of these examples returns an $articles array of renderable contents suitable as a return value from your myPage() method.
Comment: Can i render the body of the article also with the title in the third example?
Comment: #value' => $article->body->value, i can render it but i need to render both of them not one ,
Comment: Yes, render arrays can be nested so for each article you'd just have to add an array with two render arrays, one for title and one for body. If you're doing more than the one field you really should make a view mode and render it, or, at a minimum, create your own theme hook to render your content. You really don't want to build complex render arrays in PHP here, the UI will do it for you. There's a lot of information out there on each of those subjects. If you're having trouble with that stuff, please feel free to open a new question.
Comment: okey i will ask a question now about that issue


Find the limit of $\frac{1}{n^2}\sum_{k=1}^n k^2\sin\left(\frac{\theta}{k}\right)$

Question: I am trying to find the limit of
$$\frac{1}{n^2}\sum_{k=1}^n k^2\sin\left(\frac{\theta}{k}\right)\qquad \theta>0$$
as $n\to \infty$. I know that since $x-\frac{x^3}{6}\leq \sin x \leq x$ then
$$\frac{1}{n^2}\sum_{k=1}^n k^2\sin \left( \frac{\theta}{k}\right)\leq \frac{\theta}{n^2}\sum_{k=1}^n k=\theta\frac{(n+1)}{2n}$$
Since the $\lim_{n\to \infty}\theta\frac{(n+1)}{2n}=\frac\theta2$, then we know that
$$\frac{1}{n^2}\sum_{k=1}^n k^2\sin \left( \frac{\theta}{k}\right)\leq \frac \theta2 \qquad n \to \infty$$
Now I concentrate on the other side and, with the same logic, I obtain
$$\frac{\theta}{n^2}\sum_{k=1}^nk -\frac{\theta^3}{6n^2}\sum_{k=1}^n\frac1k\leq\frac{1}{n^2}\sum_{k=1}^n k^2\sin \left( \frac{\theta}{k}\right)$$
How to prove that also the left side tends to $\frac\theta2$? Can you give me a little hint please?
Answer: We have:
$$\frac{\theta}{n^2}\sum_{k=1}^{n} k = \theta\frac{n+1}{2n}= \frac{\theta}{2}+O\left(\frac{1}{n}\right) $$
while:
$$\frac{\theta^3}{6n^2}\sum_{k=1}^{n}\frac{1}{k}=\frac{\theta^3}{6}\cdot\frac{H_n}{n^2}=O\left(\frac{1}{n}\right),$$
since, obviously:
$$H_n = \sum_{k=1}^{n}\frac{1}{k}\leq\sum_{k=1}^{n} 1 = n.$$
Comment: Quite. Since $H_n=O(n)$, then $\frac{H_n}{n^2}=O\left(\frac{1}{n}\right)$.
Comment: Since I am new to this big Oh notation, I know only the basic definition. Do you mind if I ask you to explain briefly how you transformed my notation in this new way? Would you also provide me some reference about it? I discovered this notation in chapter 8 of my Apostol.
Comment: You wrote that $$\frac{\theta^3}{6} \frac{H_n}{n^2}=O\left( \frac 1n \right)$$ because you can ignore the multiplicative constant. Then you know that the harmonic partial sum is lower than 1. Finally, since $$\frac{1}{n^2}=O\left(\frac 1n \right)$$ you conclude that the whole right side is $$O\left(\frac 1n \right)$$ Am I right?
Comment: Ok, so you used $H_n=O(n)$,  $1/n^2=O(1/n^2)$ and the product rule for big Oh notation. Am I right now?


Lambda GroupBy por ano e mês

Question: tenho uma lista de eventos, e gostaria de agrupá-las por ano e mês,
por exemplo
[Ano 2017]
Mês Janeiro
 { Evento 1, Evento 2, Evento 2 }
Mês Fevereiro
 { Evento 3 }
[Ano 2018]
Mês Janeiro
 { Evento 4, Evento 5 }
estou utilizando Lambda no C#, tenho algo parecido com isso já:
var groupLista = listaDeEventos.GroupBy(x => new {x.Data.Year, x.Data.Month})....

Answer: Basicamente, existem duas formas de fazer isso.
A maneira complicada, onde é necessário fazer um agrupamento por ano e outro mês, sendo este segundo dentro do primeiro (ok, nem é tão complicada assim).
E também a maneira fácil, que seria agrupar diretamente por mês e por ano, juntos, ou seja, concatenar mês de ano de uma maneira que eles sejam chaves únicas para o agrupamento.
Se for necessário manter uma hierarquia (evento -> mês -> ano), use a forma complicada. Caso contrário, não vejo porquê não usar a forma mais simples.
O código no final do post tem um exemplo de cada uma das duas formas.
Também é possível fazer um agrupamento "duplo", da forma que você mostrou na pergunta, só pra ilustrar, ficaria desta forma:
var grupo= listaEventos.GroupBy(x => new { x.Data.Year, x.Data.Month })
                       .Select(g => new { Key = g.Key, Itens = g.ToList() });

foreach(var i in grupo1)
{
    WriteLine($"{i.Key.Year} - { i.Key.Month }");

    foreach(var item in i.Itens)
    {
        WriteLine($"\t{item.Nome}");
    }

    WriteLine("\n");
}

using System;
using System.Linq;
using System.Collections.Generic;
using static System.Console;

public class Program
{
    internal static void MetodoFacil()
    {
        var grupo1 = listaEventos.GroupBy(c => c.Data.ToString("MM/yyyy"))
                                  .Select(g => new { Key = g.Key, Itens = g.ToList() });

        foreach(var i in grupo1)
        {
            WriteLine(i.Key);

            foreach(var item in i.Itens)
            {
                WriteLine($"\t{item.Nome}");
            }

            WriteLine("\n");
        }
    }

    internal static void MetodoComplicado()
    {
        var grupo2 = listaEventos.GroupBy(c => c.Data.Year)
                                 .Select(g => new
                                 {
                                     Ano = g.Key,
                                     Meses = g.ToList()
                                              .GroupBy(c => c.Data.ToString("MMMM"))
                                              .Select(grp => new
                                                             {
                                                                 Mes = grp.Key,
                                                                 Eventos = grp.ToList()
                                                             })
                                 });

        foreach(var i in grupo2)
        {
            WriteLine($"Ano: {i.Ano}");

            foreach(var mes in i.Meses)
            {
                WriteLine($"\tMês: {mes.Mes}");

                foreach(var evento in mes.Eventos)
                {
                    WriteLine($"\t\t{evento.Nome}");
                }

                WriteLine("\n");
            }
        }
    }

    public static void Main()
    {
        MetodoFacil();
        MetodoComplicado();
    }

    internal static List<Evento> listaEventos = new List<Evento>
    {
        new Evento { Nome = "Evento 1", Data = new DateTime(2015, 01, 01) },
        new Evento { Nome = "Evento 2", Data = new DateTime(2016, 01, 01) },
        new Evento { Nome = "Evento 3", Data = new DateTime(2016, 01, 22) },
        new Evento { Nome = "Evento 4", Data = new DateTime(2016, 02, 24) },
        new Evento { Nome = "Evento 5", Data = new DateTime(2016, 03, 30) },
        new Evento { Nome = "Evento 6", Data = new DateTime(2016, 04, 04) },
        new Evento { Nome = "Evento 7", Data = new DateTime(2017, 01, 01) },
        new Evento { Nome = "Evento 8", Data = new DateTime(2017, 09, 30) },
        new Evento { Nome = "Evento 9", Data = new DateTime(2018, 05, 12) },
    };
}

public class Evento
{
    public string Nome { get; set; }
    public DateTime Data { get; set; }
}

Veja funcionando no .NET Fiddle | Código no GitHub para referência futura
Answer: Tudo vai depender de como e onde vai utilizar, emitindo em um console application como forma de entedimento o linq é assim:
var items = listaDeEventos.GroupBy(x => new {x.Data.Year, x.Data.Month})
    .Select(x => new
    {
        x.Key,
        Eventos = x.Select(a => new
        {
            a.Evento
        })
    })
    .ToList();

foreach(var item in items)
{
    System.Console.WriteLine("{0} / {1}", item.Key.Year, item.Key.Month);
    foreach(var str in item.Eventos)
    {
        System.Console.WriteLine("{0}", str);
    }
    System.Console.WriteLine("-----------------------------");
}

Saída:

2016 / 1
{ Evento = Event1 }
{ Evento = Event2 }
-----------------------------
2016 / 2
{ Evento = Event3 }
{ Evento = Event4 }
-----------------------------
2016 / 3
{ Evento = Event5 }
-----------------------------

O layout fica a sua maneira, mas, dessa forma fica fácil entender como funciona outra coisa como não foi especificado o nome do campo da descrição eu utilize Evento gerando a lista de Eventos, sendo que esse nome tem que ser o seu da sua consulta.
Um outra maneira para utilizar seria a criação de ViewModel desse novo tipo de dados:
Classe EventosModelView
public class EventosModelView
{
    public int Year { get; set; }
    public int Month { get; set; }
    public string YearAndMonth
    {
        get
        {
            return string.Format("{0} / {1}", Year, Month);
        }
    }
    public IEnumerable<Events> Events { get; set; }
}

IList<EventosModelView> items = listaDeEventos
                .GroupBy(x => new {x.Data.Year, x.Data.Month})
                .Select(x => new EventosModelView
                {
                    Year = x.Key.Year,
                    Month = x.Key.Month,
                    Events = x.Select(s => s)
                })
                .ToList();

foreach(var item in items)
{
    System.Console.WriteLine("{0}", item.YearAndMonth);
    foreach (var str in item.Events)
    {
        System.Console.WriteLine("{0} {1}", str.Evento, str.Data);
    }
    System.Console.WriteLine("-----------------------------");
}

é a forma melhor de passar informações para a View.
Referencias

Introdução a consultas LINQ (C#)
Operações de consulta LINQ básica (C#)
Group by in LINQ
Cláusulas Let, Group By e Order By no LINQ
Understanding the LINQ GroupBy Operator in C#
O que é e como utilizar o padrão View Model em um projeto ASP.NET MVC

Lambda GroupBy por ano e mês


Why isn't the monetary value of the first transaction used in the gamma-gamma spend model?

Question: I've been doing some customer value calculations using the Lifetimes library in python. This library employs the approach found in Fader, Hardie, and Lee's paper on using iso-value curves for customer base analysis. This approach is also implemented in the BTYD (Buy 'Til You Die) package for R.
In this approach, a gamma-gamma spend model is used to estimate the average order value for each customer (gamma distribution) and the average of these average values across all customers (gamma distribution). As a customer makes more purchases, their expected spend moves closer to their observed average and further away from the average of all customers' averages. The derivation is discussed in Hardie's paper, and the intuition is discussed on page 20 of Fader, Hardie, and Lee.
In Fader, Hardie, and Lee (page 20), it is asserted that...

If no repeat purchases are observed... our best guess is that the individual's average transaction value in the future is simply the mean of the overall transaction value distribution

This means that the first purchase that an individual makes is not enough to learn anything about what their average spend might be, and it is totally ignored. In the formulas presented, a single-purchase customer's values are not used because their repeat purchase frequency is 0. It is unclear why the model could not be adjusted to use first purchases, thus including observations from the overwhelming number of single-purchase customers in most data sets. The paper does not intuitively explain why this information is not used. If the overall average is \$50 and a first-time customer spends \$5, it seems reasonable to assume that their average value may be lower than that of most customers, right?
Comment: Useful post. Am also working on solving a similar problem. Can I check why do the `lifetimes` package consider `Average revenue` instead of `Total revenue`? I see for `M` metric in `RFM` analysis, they only consider `average revenue`. why not `Total revenue of each customer`? Wouldn't that be more useful? how does taking average of revenue help?
Answer: I suspect the reason is primarily theoretical, while there may be mathematical implications as well I think these are more pronounced in the BG/NBD model than the Double-Gamma model. Consider that Fader & Hardie's research has built upon work by Ehrenberg, who began with modeling repeat transactions ... well technically it began with modeling customer buying patterns but it takes multiple transactions to generate a pattern.
We see the language in the papers - the initial transaction is seen as 'trial' rather than repeat and is considered to be of a different nature. (see the initial statement of problem in this paper: http://www.brucehardie.com/notes/006/creating_dor_summary_2004-05-04.pdf). It is a different problem to predict initial customer acquisition (in which a success is defined as a trial purchase) than to predict incremental customer transactions from already-acquired customers (in which success is defined as an additional repeat transaction).
Answer: I think it's simply that the customer's transactions are modelled as coming from a gamma distribution with unknown parameters, which have a gamma prior. In this abstract setup, having a single data point in isolation probably offers no information. I've not looked into the maths, but I would guess one data point gives you only information about the error term, and not the parameter of interest (the mean spend).


Estimates for square free integers

Question: I want to estimate $\sum \limits_{n\leq x} \mu^2(n)$ with error term $o(\sqrt{x})$ Given that $\lim \limits_{x \to \infty} \frac{\psi(x)}{x}=1$ or that $\lim \limits_{x \to \infty} \frac{1}{x} \sum\limits_{n\leq x} \mu(x) = 0$
Without PNT i managed to estimate it with error term $O(\sqrt{x})$
My attempt : $\sum \limits_{n\leq x} \mu^2(n) = \sum \limits_{d^2 \leq x} \mu(d) [\frac{x}{d^2}] =  x \sum \limits_{d \leq \sqrt{x}} \frac{\mu(d)}{d^2} + O( |\sum \limits_{n\leq \sqrt{x}} \mu(n)|)  $ and since $M_{\mu} (\sqrt{x}) = o(\sqrt{x})$ it follows that $O( |\sum \limits_{n\leq \sqrt{x}} \mu(n)|)=o(\sqrt{x})$ ,but i don't know how to get error term $o(\sqrt{x})$ form $ x \sum \limits_{d \leq \sqrt{x}} \frac{\mu(d)}{d^2} = \frac{6x}{\pi^2} - x \sum \limits_{d > \sqrt{x}} \frac{\mu(d)}{d^2} $
Comment: Wikipedia only has one unconditional result for the error that's $o\left(\sqrt x\right)$, from Arnold Walfisz, 1963, "Weylsche Exponentialsummen in der neueren Zahlentheorie":

$$
O\left(x^{1/2}\exp\left(-c\frac{(\log x)^{3/5}}{(\log\log x)^{1/5}}\right)\right)\;,
$$

with $c$ a positive constant. The book is available online. It's in German. The proof extends over $4$ pages. If you don't speak German, I could summarize it for you in an answer.
Comment: Your proof is wrong; $$\sum_{d \leq \sqrt{x}} \mu(d) \left\lfloor \frac{x}{d^2}\right\rfloor = x \sum_{d \leq \sqrt{x}} \frac{\mu}{d^2} + \sum_{d \leq \sqrt{x}} \mu(d) \left( \left\lfloor \frac{x}{d^2}\right\rfloor - \frac{x}{d^2}\right).$$ The correct trivial bound on the latter is $O(\sum_{d \leq \sqrt{x}} |\mu(d)|)$, which unfortunately can only be bounded by $O(\sqrt{x})$.
Answer: Since $\bigl\lfloor \frac{x}{d^2}\bigr\rfloor = 0$ for $d > \sqrt{x}$ we can extend the sum giving $Q(x)$ to infinity,
$$Q(x) = \sum_{d = 1}^{\infty} \mu(d)\biggl\lfloor \frac{x}{d^2}\biggr\rfloor = x\sum_{d = 1}^{\infty} \frac{\mu(d)}{d^2} - \sum_{d = 1}^{\infty} \mu(d) \biggl\lbrace \frac{x}{d^2}\biggr\rbrace\,,\tag{1}$$
where $\{u\} = u - \lfloor u\rfloor$ denotes the fractional part.
The first term on the right of $(1)$ is exactly $\frac{6}{\pi^2}\cdot x$, so what we need is to show
$$\sum_{d = 1}^{\infty} \mu(d) \biggl\lbrace \frac{x}{d^2}\biggr\rbrace = o(\sqrt{x})\,.\tag{2}$$
Now the trick is to split the series at a suitable $y < \sqrt{x}$ (where $y$ depends on $x$ of course). For the first part we use the trivial estimate,
$$\sum_{d = 1}^{y} \mu(d) \biggl\lbrace \frac{x}{d^2}\biggr\rbrace = O(y)$$
since $\lvert\mu(d)\rvert$ and fractional parts are bounded by $1$. Thus we must choose $y = o(\sqrt{x})$. The choice $y = \bigl\lfloor \sqrt{\frac{x}{m(x)}}\bigr\rfloor$ where the positive integer $m(x)$ tends to $\infty$ slowly as $x \to \infty$ is convenient.
To estimate the tail series, write $\mu(d) = M(d) - M(d-1)$ and apply summation by parts. If we have a strong enough bound for $M(x)$, we can see that $\sum \lvert M(d+c)\rvert\bigl\lbrace\frac{x}{d^2}\bigr\rbrace$ converges for every constant $c \geqslant 0$, so we can simply split and recombine the series. But with only $M(x) = o(x)$ available, a more cautious summation by parts is needed. For $z > y$ we have
\begin{align}
\sum_{d = y+1}^{z} \bigl(M(d) - M(d-1)\bigr)\biggl\lbrace \frac{x}{d^2}\biggr\rbrace
&= M(z)\biggl\lbrace \frac{x}{(z+1)^2}\biggr\rbrace - M(y)\biggl\lbrace \frac{x}{(y+1)^2}\biggr\rbrace \\
&\qquad + \sum_{d = y+1}^{z} M(d)\biggl(\biggl\lbrace \frac{x}{d^2} \biggr\rbrace - \biggl\lbrace \frac{x}{(d+1)^2}\biggr\rbrace \biggr)\,.
\end{align}
The first term on the right tends to $0$ as $z \to \infty$. In the sum on the right hand side,
$$\biggl\lbrace \frac{x}{d^2} \biggr\rbrace - \biggl\lbrace \frac{x}{(d+1)^2}\biggr\rbrace = \frac{x(2d+1)}{d^2(d+1)^2} - \underbrace{\biggl(\biggl\lfloor \frac{x}{d^2} \biggr\rfloor - \biggl\lfloor \frac{x}{(d+1)^2}\biggr\rfloor\biggr)}_{s(x,d)}\,,$$
where $s(x,d) = 0$, unless there is a positive integer $k$ such that $d = \bigl\lfloor \sqrt{\frac{x}{k}}\bigr\rfloor$, in which case it is $1$ if we choose $y$ not too small, $y > \sqrt[3]{3x}$, roughly equivalent to $m(x) < \sqrt[3]{\frac{x}{9}}$, suffices easily. Thus we can take the limit for $z \to \infty$ and obtain
$$\sum_{d = y+1}^{\infty} \mu(d)\biggl\lbrace \frac{x}{d^2}\biggr\rbrace
= -\sum_{k = 1}^{m(x)-1} M\biggl(\sqrt{\frac{x}{k}}\biggr) - M(y)\biggl\lbrace\frac{x}{(y+1)^2}\biggr\rbrace + \sum_{d = y+1}^{\infty} \frac{xM(d)(2d+1)}{d^2(d+1)^2}\,.$$
With
$$\delta(u) := \sup \: \bigl\{ x^{-1}\lvert M(x)\rvert : x \geqslant u\bigr\}$$
we can then estimate
$$\Biggl\lvert\sum_{k = 1}^{m(x)-1} M\biggl(\sqrt{\frac{x}{k}}\biggr)\Biggr\rvert \leqslant \delta(y)\sqrt{x}\sum_{k = 1}^{m(x)-1} \frac{1}{\sqrt{k}} \leqslant \delta(y)\sqrt{x}(2\sqrt{m(x)}+1)\,,$$
$\bigl\lvert M(y)\bigl\lbrace\frac{x}{(y+1)^2}\bigr\rbrace\bigr\rvert \leqslant y$ trivially, and
$$\Biggl\lvert \sum_{d = y+1}^{\infty} \frac{xM(d)(2d+1)}{d^2(d+1)^2} \Biggr\rvert
\leqslant 2\delta(y)x \sum_{d = y+1}^{\infty} \frac{1}{d(d+1)} < 2\delta(y)\sqrt{x}\cdot \sqrt{m(x)}\,.$$
Thus to prove the $o(\sqrt{x})$ error term we need to choose $m(x)$ (tending to $\infty$ with $x$) in such a way that
$$\lim_{x \to \infty} \sqrt{m(x)}\delta\biggl(\biggl\lfloor \sqrt{\frac{x}{m(x)}}\biggr\rfloor\biggr) = 0\,.$$
We can do that: Choose a strictly increasing sequence $(\eta_k)$ in $[1,+\infty)$ such that $\delta(\eta_k) \leqslant \frac{1}{k}$. Put $\xi_k = k(\eta_k + 1)^2$ and $m(x) = k$ for $\xi_k \leqslant x < \xi_{k+1}$ (and $m(x) = 1$ for $x < \xi_1$). Clearly $m(x) \to \infty$ for $x\to \infty$, and for $\xi_k \leqslant x < \xi_{k+1}$ we have, using the monotonicity of $\delta$,
\begin{align}
\sqrt{m(x)}\delta\biggl(\biggl\lfloor \sqrt{\frac{x}{m(x)}}\biggr\rfloor\biggr)
&= \sqrt{k}\delta\biggl(\biggl\lfloor \sqrt{\frac{x}{k}}\biggr\rfloor\biggr) \\
&\leqslant \sqrt{k}\delta\biggl(\sqrt{\frac{x}{k}}-1\biggr) \\
&\leqslant \sqrt{k} \delta\biggl(\sqrt{\frac{\xi_k}{k}} - 1\biggr) \\
&= \sqrt{k} \delta\bigl(\sqrt{(\eta_k+1)^2} - 1\bigr) \\
&= \sqrt{k}\delta(\eta_k) \\
&\leqslant \frac{1}{\sqrt{k}}\,.
\end{align}
With explicit bounds for $\delta$ one can obtain explicit bounds for the error term. If we have a bound of the type
$$\delta(x) = O\bigl(\exp\bigl(-c(\log x)^{\alpha}\bigr)\bigr)$$
with $c > 0$ and $0 <\alpha < 1$ — the exponent $\alpha = \frac{1}{2}$ corresponds to de la Vallée Poussin's zero-free region from 1899, the error term of Walfisz (not quite the same form, but similar enough) corresponds to that of Vinogradov/Korobov from 1958 — we can choose
$$m(x) \approx \exp\bigl(b(\log x)^{\alpha}\bigr)$$
with an appropriate $0 < b < c$. Then $y = O\bigl(\sqrt{x}\,\exp(-b/2(\log x)^{\alpha})\bigr)$, and
$$\log \sqrt{\frac{x}{m(x)}} \sim \frac{1}{2}\log x\biggl(1 - \frac{b}{(\log x)^{1-\alpha}}\biggr) \sim \frac{1}{2}\log x\,.$$
For every $0 < c' < c$ we therefore have
$$\sqrt{m(x)}\delta\biggl(\biggl\lfloor \sqrt{\frac{x}{m(x)}}\biggr\rfloor\biggr) = O\biggl(\exp\biggl(-\biggl(\frac{c'}{2^{\alpha}} - \frac{b}{2}\biggr)(\log x)^{\alpha}\biggr)\biggr)\,.$$
The choice $b = c'\cdot 2^{-\alpha}$ yields
$$Q(x) = \frac{6}{\pi^2}x + O\bigl(\sqrt{x}\,\exp\bigl(-b/2(\log x)^{\alpha}\bigr)\bigr)\,.$$
If we have a considerably stronger bound for $\delta$, say $\delta(x) = O(x^{-\beta})$ (meaning $\zeta(s)$ has no zeros with real part  $> 1-\beta$), the loss in the strength of the error term becomes more obvious. We get the best order if we choose $m(x)$ such that
$$\frac{1}{\sqrt{m(x)}} \asymp \sqrt{m(x)}\delta\biggl(\sqrt{\frac{x}{m(x)}}\biggr)$$
(that's also the case for bounds of the previous type), which occurs for
$$m(x) \asymp x^{\beta/(2+\beta)}$$
and leads to an error bound of $O(x^{1/(2+\beta)})$ rather than the $\frac{1-\beta}{2}$ exponent one might hope for because $\zeta(s)/\zeta(2s)$ has no poles except at $1$ with real part $> \frac{1-\beta}{2}$.

Estimates for square free integers


Why am I getting a NoMethodError for an attribute that exists in my model?

Question: This is the error I get:
ContactPostalcardsController#skip (NoMethodError) "undefined method `status=' for #<ContactPostalcard:0x2b21433d64b0>"

This is the code calling it and trying to assign a value to the status attribute for ContactPostalcard (the Model):
  def skip

    @contact_postalcard = ContactPostalcard.new(params[:contact_postalcard])
    @contact_postalcard.contact_id = params[:contact_id]
    @contact_postalcard.postalcard_id = params[:postalcard_id]

    @contact_postalcard.status = "skipped"
    @contact_postalcard.date_sent = Date.today
    @contact_postalcard.date_created = Date.today

    if @contact_postalcard.save
      render :text => 'This email was skipped!'

    end
  end

This is the Model referred. Note the "annotate" output shows status as an attribute:
class ContactPostalcard < ActiveRecord::Base
  attr_accessible :title, :contact_id, :postal_id, :postalcard_id, :message, :campaign_id, :date_sent, :status

  belongs_to :contact
  belongs_to :postalcard

  alias_attribute :body, :message
  alias_attribute :subject, :title

  named_scope :nosugar, :conditions => { :sugarcrm => false }

  def company_name
    contact = Contact.find_by_id(self.contact_id)

    return contact.company_name

  end

  def asset
    Postalcard.find_by_id(self.postalcard_id)
  end

  def asset_class
    Postalcard.find_by_id(self.postalcard_id).class.name
  end

end

# == Schema Information
#
# Table name: contact_postalcards
#
#  id            :integer         not null, primary key
#  title         :string(255)
#  contact_id    :integer
#  postalcard_id :integer
#  message       :text
#  campaign_id   :integer
#  date_sent     :datetime
#  created_at    :datetime
#  updated_at    :datetime
#  postal_id     :integer
#  sugarcrm      :boolean         default(FALSE)
#  status        :string(255)
#

I am unclear as to why I keep getting an 'undefined method' -- I have added the status attribute (it had been missing before but used a migration and then raked), so need some help...thank you.
Answer: Have you restarted your Rails application since you ran your migration? If you're running in production mode, Rails caches your classes until you restart it, and since status wasn't an attribute before the migration, Rails wouldn't have added accessor methods for it, which would explain why status= is undefined.
Comment: although this was just part of the problem, it was something I needed to lead to the ultimate solution and as a practice altogether.


How to find a general formula for any number sequence? $19,25,45,87,159$

Question: Suppose I have the following number series : 19,25,45,87,159
I want to build a formula for the nth term of the series.
Please help me with some algorithm which would solve my problem.
I tried to construct a generating function but i failed.
Comment: Declare that the full sequence is $$19,25,45,87,159,0,0,0,0,0,\ldots$$ and you can write down a simple formula involving Iverson brackets or Kronecker deltas.
Comment: To restate (what I think is) @HenningMakholm's comment, questions of this form are ambiguous. There are many sequences starting that way, so you haven't given enough information for us to know which you have in mind. Presumably you want a "simple" such sequence, but in general simplicity is subjective (in this particular case Macrophage gives a defensible candidate).
Comment: 19, 25, 45, 87, 159, 269, 425, 635, 907, 1249, 1669, 2175, 2775, 3477, 4289, 5219, 0, 0, 0, 0, 0, ...
Comment: @Henning Makholm The full sequence is 19, 25, 45, 87, 159, 269, 425, 635, 907, 1249, 1669, 2175, 2775, 3477, 4289, 5219.
Comment: Can You show me the steps please?
Comment: Maybe, a polynomial !!!.
Comment: @David: there is no way to tell what the next term will be with any certainty, if the only information we have is the numbers in certain terms of the sequence.    Do you have some other information that would help tell what the next entries are?
Comment: $4/3 x^3 − x^2 − 1/3 x + 19$ is a good candidate.
Comment: @David I expanded my comment into [this](https://math.stackexchange.com/a/2771771), which has some suggestions for improving questions like this.
Answer: There is a general approach called "Lagrange polynomial" which ensures that there exists a polynomial of finite degree that passes all given finite plots $(x_i, y_i)$ (with distinct $x_i$s). Thus, we can set a polynomial $f$ for a given sequence $\{a_i\}_1^n$ that matches $f(i) = a_i$ for $i=1,2,\cdots,n$.
The strategy is not difficult. Let \begin{equation}p(x) = (x-1)\cdots(x-n)\end{equation} and $\displaystyle{p_i(x)= \frac{p(x)}{(x-i)}}$. If $i \neq j$, then $p_i(j)=0$. So, for $\displaystyle{q_i(x)=a_i\frac{p_i(x)}{p_i(i)}}$, $q_i(i)=a_i$ and $q_i(j)=0$. Thus, $\displaystyle{L(x) = \sum_1^n q_i(x)}$ is a desired polynomial.
For more details:
https://en.m.wikipedia.org/wiki/Lagrange_polynomial
Comment: The terms may not be in the form of a polynomial evaluated at positive integers...
Comment: Which terms do you point out? Lagrange polynomial may not be the best generating function for fitting a given sequence.
Comment: I mean the general term, it may not be that prescribed by the polynomial. As we can only fit with finite many terms.
Comment: Oh, I understood what you meant by.
Answer: Hint:
$$a_1=19$$
$$a_2=a_1+2\cdot3=25$$
$$a_3=a_2+4\cdot5=45$$
$$a_4=a_3+6\cdot7=87$$
$$a_5=a_4+8\cdot9=159$$
The recurrence formula is given by
$$a_{n+1}=a_n+2n\cdot(2n+1)=a_n+4n^2+2n,n>1$$
Now you can proceed to find a direct formula for $a_n$
The following terms are:$$19, 25, 45, 87, 159, 269, 425, 635, 907, 1249, 1669, 2175, 2775, 3477, 4289, 5219...$$
Speaking of a general algorithm, I don't think there is one. To show this, let's take the square root of any nonsquare number, $\sqrt7=2.6457513 $ for example...
And then we construct a sequence in which $a_n$ is nth digit after the decimal point. How can we ever extrapolate a general formula in reverse if we don't know that we are taking square root of 7 in the first place?
Also, as David said, for any finite sequence you can have infinitely many different closed-form formulas which give all the correct values you have, but diverge later on. That defies a general formula when you can only observe finite many terms of an unknown sequence.
Comment: Nice Argument, but for any finite sequence you can have infinitely many different closed-form formulas which give all the correct values you have, but diverge later on.
Comment: I got this from computer: a(n) = 1/3 (4 n^3 - 3 n^2 - n + 57)
Comment: Thank you for the answer, but my question was to find an algorithm for any such sequence.
Comment: That cubic term makes sense! But I don't think there is an algorithm for any arbitrary sequence...
Comment: Okay let me ask a new question regarding that topic. By the way, dont you think that interpolation would work for any arbitary sequence?
Comment: No, see my proposed counterexample.
Comment: Half-facetious answer: run _all_ algorithms until you find one that matches the sequence that you have. Slightly less facetious answer: once you have enough terms of your sequence; you can find the simplest Turing Machine that reproduces the terms of it - which will often be shorter than the sequence itself, if your sequence is actually coming from an algorithmic source - and then continue running that TM to find the rest of the sequence.
Comment: @StevenStadnicki That's interesting. But I'm not sure how you find the simplest Turing Machine. But obviously, speaking of "all" algorithm is unrealistic :D
Comment: @David Aha, I also just realized that, will add it to the main answer.
Comment: @Macrophage This isn't necessarily meant to be a _practical_ approach (and in fact, finding _the_ simplest Turing Machine that produces a given sequence is recursively unsolvable because it lets you solve the halting problem).  But the core notion, that of 'minimum description length' of a sequence, is an actual practical notion, and you can find a lot of information under that name.


What does mean the index "[0]" in the end of the filter function or in any kind of function that It is added?

Question: What does mean the index "[0]" in the end of the filter function or in any kind of function that It is added? For example let's say that I am importing a JSON data from a file, so I added this code
<Home dish={this.state.dishes.filter((dish) => dish.featured)[0]} />

As you can see It has added the [0] in the end, what does it mean? It is used for what? If it is something that could be added in many functions, and not just in the filter function, for what is used then?
Comment: The first result of the array returned by filter.  filter always returns an array of all matches.  Honestly, I don't understand why people use filter instead of just find even when they don't need to support IE
Comment: Does this answer your question? [What does this symbol mean in JavaScript?](https://stackoverflow.com/questions/9549780/what-does-this-symbol-mean-in-javascript)
Answer: It takes the first item of the result array.
A better approach is to use Array#find instead of Array#filter.
<Home dish={this.state.dishes.find((dish) => dish.featured)} />

Answer: That means to get the first item in the array and return it.
That statement is basically just saying "filter all dishes in the state and return all that are 'featured' and return the first item in the array"


How do I show that $Y=2\sqrt{X_1X_2}\sim$Gamma$(2p,1)$?

Question: Suppose that $X_1\sim \operatorname{Gamma}(p,1)$ and independently, $X_2\sim \operatorname{Gamma}(p+1/2,1)$. Show that $Y=2\sqrt{X_1X_2}\sim\operatorname{Gamma}(2p,1)$.
This problem followed a section on bivariate transformations, so I made attempts to solve this problem using that method. However, I was getting an integral that does not properly integrate, as was my professor.
I also attempted to use CDFs and mgfs, but I was not able to make any progress. How would you solve this problem?
Comment: Possible duplicate of [product of two gamma random variables](https://stats.stackexchange.com/questions/325275/product-of-two-gamma-random-variables)
Comment: @Xi'an: Hence your awesome answer (+1).
Comment: The relationship between $p$ and $q=p+1/2$ is special: I believe that when $q\ne p\pm1/2,$ $\sqrt{X_1X_2}$ is not a multiple of any Gamma distribution.  Following the analysis in @Xi'an's answer, it looks like the result has a density proportional to a power of $z$ times a Bessel $K$ function, reducing to a multiple of $e^{-z}$ only when $|q-p|=1/2.$
Comment: @Xi'an I remember reading about this property years ago and have been hunting for the reference, because I cannot readily formulate an intuitive explanation.  There are some very closely related results in the exercises to Chapter 16 of Kendall & Stuart Volume 1 (the chapter on distributions related to the Normal).
Comment: If bivariate transformations are in the next chapter, I'd suggest looking at other methods for this. Maybe start by exploring distributions of $\sqrt{}$ of gamma and product of gammas. // Simulated this for $p=2$ and it works fine, so I don't doubt it's true. I'll continue comment in Answer format to show simulation.
Comment: Please show your work. Also add the `self-study` tag and read the tag wiki.
Comment: @whuber: exactly. I actually tried first with two Gamma Ga(p,1) variates, having misred the question, and got stuck with a Bessel K. I wonder if there is a simple explanation to this property and to the specificity of the pair $(p,p\pm 1/2)$.
Answer: If $X$ is a Gamma $\mathcal G(p,1)$ variate, its density is
$$f_X(x)= \frac{x^{p-1}}{(p-1)!}e^{-x}\mathbb I_{\mathbb R^*_+}(x)$$
Therefore, the probability density of $Y_1=\sqrt{X_1}$ is
$$f_{Y_1}(y)=\frac{y^{2(p-1)}}{(p-1)!}e^{-y^2}\mathbb I_{\mathbb R^*_+}(y)\times\overbrace{\left|\frac{\text{d}x}{\text{d}y}\right|}^{\text{Jacobian}}
=2y\times\frac{y^{2(p-1)}}{(p-1)!}e^{-y^2}\mathbb I_{\mathbb R^*_+}(y)
=\frac{2y^{2p-1}}{(p-1)!}e^{-y^2}\mathbb I_{\mathbb R^*_+}(y)$$
And the probability density of $Y_2=\sqrt{X_2}$ is
$$f_{Y_2}(y)=\frac{2y^{\overbrace{2p+1-1}^{2p}}}{\Gamma(p+1/2)}e^{-y^2}\mathbb I_{\mathbb R^*_+}(y)$$
Hence the joint density of $(Y_1,Y_2)$ is
$$g(y_1,y_2)=\frac{4y_1^{2p-1}y_2^{2p}}{(p-1)!\Gamma(p+1/2)}e^{-y_1^2-y_2^2}\mathbb I_{\mathbb R^*_+}(y_1)\mathbb I_{\mathbb R^*_+}(y_1)$$
Considering the change of variables from $(y_1,y_2)$ to $(z=y_1y_2,y_2)$, the joint density of $(Z,Y_2)$ is
$$h(z,y_2)=g(z/y_2,y_2)\overbrace{\left|\frac{\text{d}(y_1,y_2)}{\text{d}(z,y_2)}\right|}^{\text{Jacobian}}=g(z/y_2,y_2)\left|\frac{\text{d}y_1}{\text{d}z}\right|=g(z/y_2,y_2)y_2^{-1}$$
and the density of $Z$ is the marginal
\begin{align*}
f_Z(z) &= \int_0^\infty g(z/y_2,y_2)y_2^{-1}\,\text{d}y_2\\
       &=\int_0^\infty \frac{4z^{2p-1}y_2^{2p-(2p-1)}}{(p-1)!\Gamma(p+1/2)}e^{-z^2y_2^{-2}-y_2^2}y_2^{-1}\,\text{d}y_2\\
       &= \frac{4z^{2p-1}}{(p-1)!\Gamma(p+1/2)}\int_0^\infty e^{-z^2y_2^{-2}-y_2^2}\,\text{d}y_2\\
       &= \frac{4z^{2p-1}}{(p-1)!\Gamma(p+1/2)} \frac{\sqrt{\pi}}{2}e^{-2z}
\end{align*}
[the last integral is formula 3.325 in Gradshteyn & Ryzhik, 2007]
Hence the density of $S=2Z$ is
$$f_S(s)=\frac{\sqrt{\pi}2^{1-2p}s^{2p-1}}{(p-1)!\Gamma(p+1/2)}e^{-s}=\frac{s^{2p-1}}{\Gamma(2p)}e^{-s}$$
[where the constant simplifies by the Legendre duplication formula]
Comment: Wow. This is a beautiful solution, very well explained. Thank you so much for your help.
Comment: @Edison: this is very standard, just playing by the book, apply a change of variables and integrate out the extra component ($y_2$ in this case).
Comment: Thank you! Would you know how to solve this problem with mgfs?
Comment: With mgfs, you need first find the mgf of $\sqrt{X_i}$ which is not straightforward.
Answer: I think the moment generating function approach works fine, but easier if we consider MGF of $\ln Y$.
Assuming of course $\mathsf{Gamma}(p,1)$ refers to shape $p$ parameterization, i.e. with density $$f(x)=\frac{e^{-x}x^{p-1}}{\Gamma(p)}\mathbf1_{x>0}$$ with $p>0$ as in @Xi'an's answer.
We have
\begin{align}
E\left[e^{t\ln Y}\right]&=E\left[Y^t\right]
\\&=2^tE\left[X_1^{t/2}\right]E\left[X_2^{t/2}\right]
\end{align}
For $t>-2p$ where $p>0$, clearly
$$E\left[X_1^{t/2}\right]=\frac{\Gamma\left(p+\frac t2\right)}{\Gamma(p)}$$
And $$E\left[X_2^{t/2}\right]=\frac{\Gamma\left(p+\frac t2+\frac12\right)}{\Gamma\left(p+\frac12\right)}$$
Using Legendre's duplication formula,
\begin{align}
E\left[e^{t\ln Y}\right]&=2^t\cdot \frac{\Gamma(2p+t)\sqrt\pi/2^{2p+t-1}}{\Gamma(2p)\sqrt\pi/2^{2p-1}}
\\&=\frac{\Gamma(2p+t)}{\Gamma(2p)}
\end{align}
This is the MGF of the logarithm of a $\mathsf{Gamma}(2p,1)$ distribution evaluated at $t$ (or simply the $t$th order raw moment about $0$) where $t\in (-2p,\infty)$. As the MGF exists in an open interval containing $0$, we can conclude that $Y\sim \mathsf{Gamma}(2p,1)$ by uniqueness theorem of MGF.  In effect we see that this Gamma distribution is uniquely determined by its moments.
Answer: ... Comment continued: R code for the simple simulation is as shown
below. Unfortunately, the simulation gives no clue how to work the
problem. (See @Xi'an's Answer.)
<code>set.seed(1023)
p = 2;  m = 10^6
x1 = rgamma(m,p,1);  x2 = rgamma(m,p+.5,1)
y = 2*sqrt(x1*x2)
hist(y, br=60, prob=T, col="skyblue2")
 curve(dgamma(x,2*p,1), add=T, col="red", n=10001)
</code>
Comment: Thank you for providing the visualization. This is extremely helpful!


Prove: $e^x$ is transcendental over the polynomials with coefficients in $\mathbb{R}$

Question: I have to prove the following for my math study:

Prove: $e^x$ is transcendental over the polynomials with coefficients in $\mathbb{R}$.

So far, I've done this:
It's enough to prove that if $a_n(x),\dots,a_1(x), a_0(x)$ are polynomials with coefficients in $\mathbb{R}$ such that $a_n(x)e^{nx} + a_{n-1}(x)e^{(n - 1)x} + \dots + a_1(x)e^x + a_0(x) = 0$, then $a_i(x) = 0$ $\forall i$
To prove this I assumed that $\exists i : a_i(x) \neq 0$. Then take the smallest $n$ such that $a_n(x)e^{nx} + a_{n-1}(x)e^{(n - 1)x} + ... + a_1(x)e^x + a_0(x) = 0$.
I don't know how I have to complete the proof from here. Could you explain it to me?
Answer: Clearly, as $n>0$,
$$
\lim_{x\to-\infty}-a_0(x)=
\lim_{x\to-\infty}
\bigl(a_n(x)e^{nx} + a_{n-1}(x)e^{(n - 1)x} + ... + a_1(x)e^x\bigr)=
0
$$
So…
(Note: the only needed property is $\lim_{x\to-\infty}x^he^{kx}=0$ for $h\ge0$, $k>0$.)
Answer: You can do it, well, by using calculus.
Suppose
$$\sum_{i=0}^{n}a_i(x)e^{ix}=0$$
with $n$ being smallest possible, i.e. $a_n(x)\neq 0$.
In particular,
$$\lim_{x\rightarrow \infty}a_n(x) \neq 0.$$
Then it follows that for any $\alpha \in \mathbb{R},$
$$\lim_{x \rightarrow \infty} \frac{\sum_{i=0}^{n}a_i(x)e^{ix}}{e^{\alpha x}}=0.$$
Also, for positive $\alpha$ and any polynomial $a(x)$, we have
$$\lim_{x\rightarrow  \infty}\frac{a(x)}{e^{\alpha x}}=0.$$
Putting $\alpha=n$, one has that
$$0 \neq \lim_{x \rightarrow \infty}a_n(x)=\lim_{x \rightarrow \infty} \frac{\sum_{i=0}^{n}a_i(x)e^{ix}}{e^{\alpha x}}=0,$$
a contradiction.
Comment: All limits should be $x\to \infty$ rather than $n \to \infty$.
Comment: @Teddy: thanks, corrected.
Comment: Thanks for the answer! is there also a way to do this without limits? with derivatives for example?
Answer: An approach not using limits. Let $f(x) = \sum_{k=0}^n a_k(x)e^{kx}$ and call $a_0$ the lowest coefficient. Then $f'(x)$ has a similar form and only the the degree of the lowest coefficient decreases, other coefficients remain of the same degree. Take the derivative repeatedly until the lowest coefficient vanishes.
The same approach also works for the difference operator $(\Delta f)(x)=f(x+1)-f(x)$.
Comment: @ WimC Ok, I do understand what you mean. So if I say that the degree of the lowest coefficient is m, then that coefficient vanishes when I take the (m +1)th derative. But what contradiction should I get from that?
Comment: I do not understand what you are trying to say in your last sentence. I am supposed to get a contradiction from this, right?
Comment: If $a_0=0$ you can factor out $e^x$ and get a combination of degree one less.
Comment: Oh and then n was not the smallest degree. So that is the contradiction, right?


WSO2 ESB doesn't have security options for services

Question: I'm trying to deploy this example:
http://wso2.com/library/articles/2012/08/securing-sts-security-token-service-kerberos/
I'm doing in the version of the ESB 4.9.0. The problem I'm facing is that I can't find the security options for the echo proxy service.
Could you help me? Thanks in advance.
Answer: Enabling security for services via the UI was removed from ESB 4.9.0. This is removed from other service hosting supported middleware of WSO2 such as Data Services server and Application Server. Now the recommended way of securing the services is via the WSO2 Developer Studio. See the following webinar.
http://wso2.com/library/webinars/2015/12/how-to-secure-your-enterprise-services-with-wso2-esb-4.9/
And also the following documentation.
https://docs.wso2.com/display/ESB490/Applying+Security+to+a+Proxy+Service
Comment: Thanks for your time and your answer, I was lost!!


does asymptotic normality imply convergence of expectations?

Question: Suppose $\sqrt{n}(X_n-\mu)\to N(0,\sigma^2)$. I know this implies $X_n\to \mu$ in probability. Does it imply $E(X_n)\to \mu$? I heard about a converse to the lindebergh CLT (but couldn't find it on wikipedia), and was thinking that the lindebergh condition might be close to uniform integrability. I don't know if this works though, or if there is a simpler way.
Answer: No, it does not.  It does not even imply that $E[X_n]$ exists.
[This is basically another way of writing @JohnL's answer]
First, suppose $X_n=Z_n+Y_n$ where $Z_n\sim N(0,1/n)$ and $Y_n$ is $n$ with probability $1/n$ and 0 otherwise. Note that $X_n=Z_n$ with probability $(n-1)/n$.
Let $\mu=0$. We have
$$\sqrt{n}(X_n-\mu)\stackrel{d}{\to} N(0,1)$$
Indeed,for any $t$,
$P(\sqrt{n}(X_n-\mu)<t)$ and $P(\sqrt{n}Z_n<t)$ differ by at most $1/n$,  and $\sqrt{n}Z_n\sim N(0,1)$, so the cdf of $\sqrt{n}(X_n-\mu)$  converges pointwise to the CDF of $\sqrt{n}Z_n$, which is the standard Normal CDF, and we have the required convergence in distribution (with $\sigma^2=1$)
However, $E[X_n]=E[Z_n]+E[Y_n]=0+1$ for all $n$, so $E[X_n]$ does not converge to $\mu$.
If we took $Y_n=n^2$ instead of $n$ with probability $1/n$, we would have $E[X_n]=n\to\infty$.  And if $Y_n$ was sampled from a Cauchy distribution with probability $1/n$, $E[X_n]$ would not exist for any finite $n$.
Answer: Let $\Phi(x)$ denote the standard normal distribution function.
Suppose $\sqrt{n} X_n$ has the distribution function:
$\Phi(x)$ if $x<n$
$\Phi(n)$ if $n \le x<\frac{\sqrt{n}}{1-\Phi(n)}$
$1$ if $x \ge \frac{\sqrt{n}}{1-\Phi(n)}$
Then, $\sqrt{n}X_n\rightarrow N(0,1)$.
Also, since $P\left[\sqrt{n}X_n=\frac{\sqrt{n}}{1-\Phi(n)} \right]=1-\Phi(n)$,
we have:
$E[\sqrt{n}X_n]=\int_{-\infty}^{n}x\phi(x)dx+\frac{\sqrt{n}}{1-\Phi(n)}P\left[\sqrt{n}X_n=\frac{\sqrt{n}}{1-\Phi(n)} \right]=-\frac{e^{-\frac{n^2}{2}}}{\sqrt{2 \pi}}+\sqrt{n}$.
Thus, $E[X_n]=\frac{1}{\sqrt{n}}E[\sqrt{n}X_n]\rightarrow 1$
Comment: You might start off your answer with 'No', or something to that effect.


$X_n\to 0$ in probability implies $E[f(X_n)]\to f(0)$ for $f$ uniformly cts and bounded

Question: Let $f$ be a uniformly continuous and bounded function.  I've shown that if $X_n\to 0$ in probability, then $f(X_n)\to f(0)$ in probability as well.  Now I want to say that $$\lim_{n\to\infty} E(f(X_n))=\lim_{n\to\infty}\int_{\Omega}f(X_n)dP=\int_{\Omega}\lim_{n\to\infty}f(X_n)dP=\int_{\Omega}f(0)dP=f(0).$$
The second equality should hold from DCT since $f$ is bounded.  However, the third equality is where I'm unsure if I'm using the fact that $f(X_n)$ converges to $f(0)$ in probability, because it looks like I'm using almost everywhere convergence which isn't implied by convergence in probability.  Can someone please help clear this up?
edit: I've solved the problem a different way by splitting up the integral over where the difference between $f(X_n)$ and $f(0)$ is bigger/less than some epsilon, but I'm just curious if I can do it the way above.
Answer: Recall the following two statements:

Lemma 1 (subsequence principle): A sequence $(a_n)_{n \in \mathbb{N}}$ converges to a limit $a$ if, and only if, any subsequence of $(a_n)_{n \in \mathbb{N}}$ contains a further subsequence which converges to $a$.
Lemma 2: If $Y_n \to Y$ in probability, then there exists a subsequence $(Y_{n(k)})_{k \in \mathbb{N}}$ which converges almost surely to $Y$.

Take any subsequence $(X_{n(k)})_{k \in \mathbb{N}}$ of $(X_n)_{n \in \mathbb{N}}$. By Lemma 2, there exists a subsequence $(X_{n_{k_\ell}})_{\ell \in \mathbb{N}}$ which converges almost surely to $0$. Using the argument explained in the opening question, we find
$$\lim_{\ell \to \infty} \mathbb{E}(f(X_{n_{k_{\ell}}})) = f(0).$$
Obviously, the limit $f(0)$ does not depend on the chosen subsequence. Applying the subsequence principle, we conclude that $\mathbb{E}(f(X_n))$ converges to $f(0)$.
Answer: The dominated convergence theorem holds when the almost convergence is replaced by convergence in probability. Indeed, if $\left(Y_n\right)_{n\geqslant 1}$ to $0$ in probability and $\sup_n\left|Y_n\right|$ is integrable, then for each sub-sequence $\left(Y_{n_k}\right)_{k\geqslant 1}$, we can extract a subsequence $\left(Y_{n'_k}\right)_{k\geqslant 1}$ which converges to $0$ almost surely. By the dominated convergence theorem, we get $\mathbb E\left|Y_{n'_k}\right|\to 0$. In order to deduce the convergence for the whole sequence, argue by contradiction and apply the previous reasoning.


Create schedule task for windows in vb.net

Question: could any one tell me how to create schedule task for windows in vb.net,and how to attach a dll with schedule task.and can we make differnet dll for different function.Could you give me a link or code.
Actully i ahve one windows application which is performing 5 task at a time which are controlled by tick event on a timer .
But now i want to create schedule task for every task.so could you tell me how can i do that.Please give some breif details.
Thanks
Pankaj Pareek.
Answer: This MSDN article describes the steps required for creating a Windows Service: http://msdn.microsoft.com/en-us/library/9k985bc9(VS.80).aspx
The gist of scheduling with a service is to start a timer when the service starts and fire off the actual work of the service when the timer's Tick event is raised.
You can create a separate service for each function, or create a series of timers within one service, each of which does a different task when the appropriate amount of time has elapsed.
If you truly need each of these functions to be in a separate module, you can use MEF or I've done this with the System.Addin pipeline builder, but this is probably more trouble than it is worth -- too much of a learning curve for a simple problem domain.
Answer: Take a look on this snippet:
https://www.aspsnippets.com/Articles/Simple-Windows-Service-that-runs-periodically-and-once-a-day-at-specific-time-using-C-and-VBNet.aspx
I hope it can helps. You can define the interval mode (days, minutes).


Device the file or directory resides on

Question: How to identify the device on which the file or directory resides?
There is a stat module.
Among the results there is a "Device the inode resides on".
How can you map the "Device the inode resides on" to a partition?
Answer: First one need to understand What is the device of inode? and device number in stat command output.
Then, for an example debug output
TASK [debug] *****
ok: [localhost] =>
  result:
    changed: false
    failed: false
    stat:
...
      dev: 2051

there is a Device ID with 2051 decimal but we would need it in HEX. According How can I convert a decimal string to an hexadecimal string? a task like
  - debug:
      msg: "{{ '%#x' % result.stat.dev }}"

would report
TASK [debug] *****
ok: [localhost] =>
  msg: '0x803'

This needs to be split into major (8) and minor (3) device. Maybe start with
"{{ ('%#x' % result.stat.dev).split('x') | last }}"

In an other task it would be necessary to gather the result of
~/test$ ls -al /dev/sd*
brw-rw----. 1 root disk 8,  0 Feb 29 00:01 /dev/sda
brw-rw----. 1 root disk 8,  1 Feb 29 00:01 /dev/sda1
brw-rw----. 1 root disk 8,  2 Feb 29 00:01 /dev/sda2
brw-rw----. 1 root disk 8,  3 Feb 29 00:01 /dev/sda3
brw-rw----. 1 root disk 8,  4 Feb 29 00:01 /dev/sda4
brw-rw----. 1 root disk 8,  5 Feb 29 00:01 /dev/sda5
brw-rw----. 1 root disk 8, 16 Feb 29 00:01 /dev/sdb
brw-rw----. 1 root disk 8, 32 Feb 29 00:01 /dev/sdc
brw-rw----. 1 root disk 8, 33 Feb 29 00:01 /dev/sdc1

and parse it accordingly since ansible_facts.device_links ansible_facts.devices do not collect and hold that kind of information.
Depending on the infrastructure lsblk --output formatted for necessary information only might be easier.
lsblk -o NAME,MAJ:MIN,MOUNTPOINT
NAME   MAJ:MIN MOUNTPOINT
sda      8:0
├─sda1   8:1   /boot/efi
├─sda2   8:2   /boot
├─sda3   8:3   /
├─sda4   8:4   /tmp
└─sda5   8:5   [SWAP]
sdb      8:16  /var/lib/pgsql/16/data
sdc      8:32
└─sdc1   8:33  /var
sr0     11:0

Or according How to get a device/partition name of a file? just
cat /proc/partitions
major minor  #blocks  name

  11        0    1234567 sr0
   8       32   12345678 sdc
   8       33   12345678 sdc1
   8        0  123456789 sda
   8        1     123456 sda1
   8        2     123456 sda2
   8        3   12345678 sda3
   8        4   12345678 sda4
   8        5    1234567 sda5
   8       16    1234567 sdb

From here we can see Major 8 (SCSI) and Minor 3 is /dev/sda3. And "How to find out what's behind the major number?", see in example Linux : Major and Minor device numbers or Major and minor numbers of a partition.
An example task with zero padded fields from text file
  - name: Gather Custom Fact - Partition major minor numbers
    shell:
      cmd: |
        tail -n +3 /proc/partitions | awk '{ printf "%s: %02i%02i\n", $4,$1,$2 }'
    check_mode: false
    changed_when: false
    register: partmajmin

  - debug:
      var: (partmajmin.stdout | from_yaml)

will result into an output of
TASK [debug] *********************
ok: [localhost] =>
  (partmajmin.stdout | from_yaml):
    sda: 0800
    sda1: 0801
    sda2: 0802
    sda3: 0803
    sda4: 0804
    sda5: 0805
    sdb: 0816
    sdc: 0832
    sdc1: 0833
    sr0: 1100

The numbers are accessible as well transformable into integer in example as follow
  - debug:
      var: (partmajmin.stdout | from_yaml).sda3 | int(base=16)

resulting into an output of
TASK [debug] ************************************************
ok: [localhost] =>
  (partmajmin.stdout | from_yaml).sda3 | int(base=16): '2051'

Finally, a task
  - name: Device an inode can reside on
    debug:
      msg: "{{ item.key }}"
    loop: "{{ lookup('dict', (partmajmin.stdout | from_yaml)) }}"
    loop_control:
      label: "{{ item.value | int(base=16) }}"

will report
TASK [Device an inode can reside on] ******
ok: [localhost] => (item=2099) =>
  msg: sdc1
ok: [localhost] => (item=2098) =>
  msg: sdc
ok: [localhost] => (item=2052) =>
  msg: sda4
ok: [localhost] => (item=1100) =>
  msg: sr0
ok: [localhost] => (item=2053) =>
  msg: sda5
ok: [localhost] => (item=2050) =>
  msg: sda2
ok: [localhost] => (item=2048) =>
  msg: sda
ok: [localhost] => (item=2070) =>
  msg: sdb
ok: [localhost] => (item=2049) =>
  msg: sda1
ok: [localhost] => (item=2051) =>
  msg: sda3

Answer: supplement: for a minor number must take the last two digits of the number

File: /path/to/file1
linux stat: device 8/1
ansible device stat: dev: 2049
2049 (DEC) = 801 (HEX) --> 8.01 --> 8/01 (HEX) = 8/1 (DEC)

File: /path/to/file2
linux stat: device 259/2
ansible device stat: dev: 66306
66306 (DEC) = 10302 (HEX) --> 103.02 --> 103/02 (HEX) = 259/2 (DEC)

File: /path/to/file3
linux stat: device 254/1
ansible device stat: dev: 65025
65025 (DEC) = FE01 (HEX) --> FE.01 --> FE/01 (HEX) = 254/1 (DEC)

File: /path/to/file4
linux stat: device 0/45
ansible device stat: dev: 45
45 (DEC) = 2D (HEX) --> 0.2D --> 0/2D (HEX) = 0/45 (DEC)

Device the file or directory resides on


Capturar ações: Scroll Down and Scroll Up

Question: Existe alguma forma em jQuery de capturar os eventos de "ScrollDown" e "ScrollUp"?
Tentei desta maneira:
var lastScrollTop = 0;
$(window).scroll(function(event){
   var st = $(this).scrollTop();
   if (st > lastScrollTop){
      // downscroll code
   } else {
      // upscroll code
   }
   lastScrollTop = st;
});

Mas nela não captura a função de UP e DOWN e sim o scroll qualquer!
E eu queria que assim que o rolamento de mouse fosse acionado a função fosse executada.
Isso é possível ?
Comment: Samir, já agora, esta resposta era o que procurava?
Answer: O código que você colocou faz o que você quer. Não existe nenhuma outra propriedade do evento que seja indicador de direção, tem mesmo que medir.
Se quiser saber especificamente como medir a direção da roda do mouse, aí é possivel tirar das propriedades do evento (dê uma olhada aqui: Como saber a direção do scroll da roda do mouse).
Mas o scroll é mais abrangente é despoletado de outras maneiras e não somente a roda do mouse.
Dê uma olhada aqui para ver o seu código em funcionamento: jsfiddle.net/ayxqg/1/


Handling input form where input field is a component

Question: There is this dynamic form component.

Main.js
import RegistrationItemfrom "./RegistrationItem"
.......
         <Form onSubmit={(e) => {e.preventDefault();}}>
              <RegistrationItem
                inputtype="email"
                inputplaceholder="Email Address*"
                icon={faEnvelope}
              />
              <RegistrationItem
                inputtype="password"
                inputplaceholder="Password*"
                icon={faLock}
              />
             <button onClick={handleLogin()} > Login </Login>
        </Form>

File for input fields with styling and icons add to it.

RegistrationItem.js.
const RegistrationItem = () ={
return(
    <InputGroup className=" mb-4">
      <Input
        type={inputtype}
        name={inputname}
        id={inputid}
        placeholder={inputplaceholder}
        className="border-right-0"
      />
      <InputGroupAddon addonType="append">
        <InputGroupText className="bg-transparent text-primary border-left-0">
          <FontAwesomeIcon className="text-primary" icon={icon} />
        </InputGroupText>
      </InputGroupAddon>
</InputGroup>
)
}

How to implement submit of the form from the Login button <button onClick={handleLogin()} > Login </Login>
Comment: Its in the Main.js component.. The form is in the component but the input field in on another component.
Comment: Looks like you need to implement local state in your form component. And have the inputs update it
Answer: you need to declare state and pass that to your child component and can update the state from child element and when you click on login you can use the state.

below i have shown you how you can declare the state and how you can pass it to your child element and in child element you can use it.
note : i have just passed it in your child component and over ther in argument you can see it so wherever you want to use them you can use it.

  const [registrationTypeValue,setRegistrationTypeValue]=useState("")
             <Form onSubmit={(e) => {e.preventDefault();}}>
                  <RegistrationItem
                    inputtype="email"
                    inputplaceholder="Email Address*"
                    icon={faEnvelope}
                    registrationTypeValue={registrationTypeValue}
                    setRegistrationTypeValue={setRegistrationTypeValue}/>
                  <RegistrationItem
                    inputtype="password"
                    inputplaceholder="Password*"
                    icon={faLock}
                  />
                 <button onClick={handleLogin()} > Login </Login></Form>

    const RegistrationItem = ({registrationTypeValue,setRegistrationTypeValue}) ={
    return(
        <InputGroup className=" mb-4">
          <Input
            type={inputtype}
            name={inputname}
            id={inputid}
            placeholder={inputplaceholder}
            className="border-right-0"
          />
          <InputGroupAddon addonType="append">
            <InputGroupText className="bg-transparent text-primary border-left-0">
              <FontAwesomeIcon className="text-primary" icon={icon} />
            </InputGroupText>
          </InputGroupAddon>
    </InputGroup>
    )
    }

Comment: i just gave an example what you need to do.

create a state
pass it as props to children and use it
Comment: Please add the explanation in the answer itself, not in comments
Comment: sorry bro i missed it
Comment: You can still [edit] and update your answer
Answer: Based on the code given we need two values. One is the email and the other is the password.
So two states needed to be added to the Form element email and password. These values need to be changed based on the change in the input.
So when the form is submitted these values can be used to perform whatever action is needed
The code could be like this if we are using only react and not other form libraries like react hook form
Main.js
import RegistrationItemfrom "./RegistrationItem"
.......
    const [email,setEmail] = useState('');
    const [password,setPasword] = useState('')

     <Form onSubmit={(e) => {e.preventDefault();handleSubmit(email,password,...otherArgs);}}>
          <RegistrationItem
            inputtype="email"
            inputplaceholder="Email Address*"
            icon={faEnvelope}
            value={email}
            setValue={setEmail}
          />
          <RegistrationItem
            inputtype="password"
            inputplaceholder="Password*"
            icon={faLock}
            value={password}
            setValue={setPassword}
          />
         <button type="submit" > Login </button>
    </Form>

RegistrationItem.js
    const RegistrationItem = ({inputtype,inputname,inputid,inputplaceholder,value,setValue,icon}) ={
return(
    <InputGroup className=" mb-4">
      <Input
        type={inputtype}
        name={inputname}
        id={inputid}
        placeholder={inputplaceholder}
        value={value}
        onChange={e=>setValue(e.target.value)}
        className="border-right-0"
      />
      <InputGroupAddon addonType="append">
        <InputGroupText className="bg-transparent text-primary border-left-0">
          <FontAwesomeIcon className="text-primary" icon={icon} />
        </InputGroupText>
      </InputGroupAddon>
</InputGroup>
)
}

Comment: Thanks a lot. Passing functions into compoments to get the value back. This will be helpful in other implementations too.


Does the nontrivial commutants of the Volterra operator admit a strictly continuous spectrum?

Question: Let $H$ be a separable infinite dimensional Hilbert space.
Definition : The spectrum $\sigma(A)$ of $A \in B(H)$, is the set of all $\lambda \in \mathbb{C}$ such that $A - \lambda I$ is not bijective.
It decomposes as follows:
 - Point spectrum: $\sigma_{p}(A) = \{\lambda \in \mathbb{C} : A - \lambda I \text{ not injective}   \}$
 - Continuous spectrum: $\sigma_{c}(A) = \{\lambda \in \mathbb{C} : A - \lambda I \ \text{ injective with a dense nonclosed range}   \}$
 - Residual spectrum: $\sigma_{r}(A) = \{\lambda \in \mathbb{C} : A - \lambda I \ \text{ injective with a nondense range}   \}$
Definition : Let $H= L^{2}[0,1]$ and $V \in B(H)$ the Volterra operator defined as follows :
$$
(V.f)(t)=\int_0^tf(x)dx
$$
Some properties of the Volterra operator $V$ :

$V$ is compact, its spectrum $\sigma(V)=\{0\}$, its norm $\Vert V \Vert = 2/\pi $.
$V$ is nonnormal ($VV^{*} \ne V^{*}V$) with spectrum strictly continuous ($\sigma(V)  = \sigma_{c}(V)$), see here.
The closed invariant subspaces of $V$ are $L^{2}[a,1]$, with $a \in [0,1]$ see Barria 1981.
The commutant $\{ V \}'$ of $V$ is the strongly closed algebra generated by $V$, see Erdos 1982.

Remark : $\forall \lambda \in \mathbb{C}$, $V_{\lambda} := V+\lambda I \in \{ V \}'$ and $\sigma(V_{\lambda}) = \sigma_{c}(V_{\lambda}) = \{ \lambda \}$
Definition : Let $S=\{\lambda_{1}, ... ,\lambda_{r}  \}$ be a finite subset of $\mathbb{C}$ and let $V_{S} \in \{ V \}'$ defined as follows:
$$
V_{S} := (V+\lambda_{1} I).(V+\lambda_{2} I)...(V+\lambda_{r} I)
$$
Preliminary questions :

What is the spectrum of $V_{S}$ ( $S$ or $\{ \prod \lambda_{i} \}$ or anything else) ?
Is it true that  $\sigma(V_{S}) = \sigma_{c}(V_{S}) $ ?

Main question :

Does a nontrivial commutant operator of the Volterra operator admits a strictly
  continuous spectrum
  (i.e. $\mathbb{C} I \not\ni A \in \{ V \}' \Rightarrow \sigma(A) = \sigma_{c}(A)$) ?
Answer: Let me answer the preliminary questions.
1) For commuting bounded operators $A,B$ we have $r(A+B)\leq r(A)+r(B)$ and $r(AB)\leq r(A)r(B),$ where $r$ is the spectral radius. Hence $r(p(V))=0$ for every polynomial $p$ such that $p(0)=0.$ It implies that $\sigma(V_S)=\prod\lambda_i.$
2) It is true.
For any polynomial $p\not\equiv 0,$ the operator $p(V)$ has zero kernel. Indeed, let $p(x)=x^n+a_1 x^{n-1}+\dots+a_n$ and assume that $p(V)\varphi=0.$ Then $Vq(V)\varphi=-a_n\varphi,$ where $p(x)=xq(x)+a_n.$ Since $r(Vq(V))=0,$  we have $a_n=0.$ Since the kernal of $V$ is zero, $q(V)\varphi=0.$ Polynomial $q$ has degree $n-1$ so we can use induction.
Hence $p(V)$ has no eigenvalues for $p\not\equiv const$.
The adjoint to $V$ is $(V^*f)(y) = \int_y^1 \! f(t) \, dt.$ Hence $p(V^*)$ has zero kernel for $p\not\equiv 0$ as well. The formula $Ran\, p(V)^\perp=\ker(\overline p(V^*))$ implies that the range of $p(V)$ is dense for every $p\not\equiv 0,$ that is, residual spectrum of $p(V),$ is empty for all $p.$
As for the main question, I believe that norm-limits of $p_n(V)\in\{V\}'$ satisfy the property. But the strong limits of $p_n(V)$ probably not.
Comment: Because of the "probably not", I still can't accept this answer. @YuriiSavchuk, can you improve this point ?


Module parse failed: Unexpected token - React

Question: i am trying to create a react component as a npm package and was following this link https://medium.com/quick-code/publish-your-own-react-component-as-npm-package-under-5-minutes-8a47f0cb92b9 and I am pretty new to this.
This is the error I am getting when I run npm.start
ERROR in ./src/index.js 6:4
Module parse failed: Unexpected token (6:4)
You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders
|   const { width, height, color, text } = props;
|   return (
>     <div
|       style={{
|         width: width || 100,

I looked online and seems to an issue with webpack.config but I am not sure where it is wrong in mine.
These are my files
webpack.config
var path = require('path');
module.exports = {
  entry: './src/index.js',
  output: {
    path: path.resolve(__dirname, 'build'),
    filename: 'index.js',
    libraryTarget: 'commonjs2'
  },
  module: {
    rules: [
      {
        test: /\.js$/,
        include: path.resolve(__dirname, 'src'),
        exclude: /(node_modules|bower_components|build)/,
        use: {
          loader: 'babel-loader',
          options: {
            presets: ['env']
          }
        }
      }
    ]
  },
  externals: {
    'react': 'commonjs react'
  }
};

.babelrc
    {
    "presets": ["env"],
    "plugins": [
        "transform-object-rest-spread",
        "transform-react-jsx"
    ]
}

src/index.js
import React from "react";

const ReactColorSquare = props => {
  const { width, height, color, text } = props;
  return (

      {text}

  );
};

export default ReactColorSquare;

package.json
{
  "name": "reactnpmpackage",
  "version": "1.0.0",
  "description": "",
  "main": "build/index.js",
  "scripts": {
    "start": "webpack --watch",
    "build": "webpack",
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "react": "^16.13.1",
    "webpack": "^4.43.0"
  },
  "devDependencies": {
    "babel-cli": "^6.26.0",
    "babel-core": "^6.26.3",
    "babel-loader": "^8.1.0",
    "babel-plugin-transform-object-rest-spread": "^6.26.0",
    "babel-plugin-transform-react-jsx": "^6.24.1",
    "babel-preset-env": "^1.7.0",
    "webpack-cli": "^3.3.11"
  }
}

Here is my project structure

Could you please correct where I am getting it wrong..
Answer: Try it with @babel/preset-react.  Do an npm i --save-dev @babel/preset-react, then add it to your .babelrc file:
// .babelrc

{
  "presets": [
    "@babel/preset-env",
    "@babel/preset-react"
  ],
  "plugins": [
    "transform-object-rest-spread",
    "transform-react-jsx"
  ]
}

You might also try changing your libraryTarget to the universal module definition:
libraryTarget: 'umd'

Or add mode: development to your module.exports in the webpack.config.
This solved a similar problem for me a few times.
Comment: Hi thanks for replying, I did not quite understand the first step, where should i run this?
Comment: I did it and it does the same thing. `.babelrc` now looks like this `{
    "presets": [
        "env",
        "@babel/preset-env",
        "@babel/preset-react"
    ],
    "plugins": [
        "transform-object-rest-spread",
        "transform-react-jsx"
    ]
}`
Comment: you would run the `npm install` command in the terminal at the root folder of your project.  Maybe try removing the "transform-react-jsx" plugin, you shouldn't need that if you have the `preset-react` preset
Comment: removed `"transform-react-jsx"` and tried it but the same error.
Comment: in webpack,config, i have `entry: './src/index.js',` is that the right path i have given seeing the folder structure picture I uploaded, it was `build/index.js` i changed to `src/index.js` hope that is right
Comment: You can also try adding `mode: development` to `module.exports` in the webpack config


Parallel translation

Question: I read that for the Lorentz metric defined as
$d(a,b,c,d)=-a^2+b^2+c^2+d^2$
in $R^4$ the parallel translation (corresponding to the Levi-Civita Connection of $d$) agrees with the parallel translation of $\mathbb{R}^{n+1}$.
Could someone explain why?
Answer: In $\mathbb{R}^4$, not in $\mathbb{R}^{n+1}$.
The reason is that this Lorentzian-metrics is flat : there is no curvature.

Parallel translation


Positive model bias but negative percent bias; why?

Question: I'm comparing my training data with some predicted values using the Metrics package in R. When running the bias function, R returns a positive value, yet percent bias on the same data returns a negative value. What's going on?
Here's the data / code
    library(Metrics)

   act<-c(1.9,4.9,9.8,16.7,25.7,37.1,51,67.6,86.9,109.2,134.4,162.7,194.2,229,267.3,308.9,354.2,403.1,455.7,512.1,572.3,636.5,704.8,777.1,853.5,934.2,1019.1,1108.3,1202,1300.1,1402.7,1509.9,1621.8,1738.3,1859.5,1985.5,2120,2250,2390,2540,2690,2850,3010,3170,3340,3520,3700,3890,4080,4280,4480,4690,4910,5130,5350,5590,5820,6070,6320,6570,6830,7100,7370,7650,7940,8230,8520,8830,9140,9450,9770,10100,10440,10780,11120,11480,11840,12200,12580,12960,13340,13740,14140,14540,14960,15380,15800,16240,16680,17120,17580,18040,18510,18980,19460,19950,20450,20950,21460,21980,22500
)
pred<-c(1.97875829108291,4.87441981891739,9.68638775111453,16.5715610019699,25.67930370443,37.1518566832577,51.1247330448926,67.7270981873014,87.0821345330912,109.307391289271,134.515119536896,162.812592953937,194.302414474693,229.082809189018,267.247903784721,308.887992836402,354.089792244055,402.936680124749,455.508925460685,511.883904806941,572.13630736222,636.338328705897,704.55985350469,776.868627492241,853.330419024942,934.009170517296,1018.96714006013,1108.26503352494,1201.96212745776,1300.11638306574,1402.78455159986,1510.02227143699,1621.88415716467,1738.42388097194,1859.6942466494,1985.74725650196,2116.63417147754,2252.40556481493,2393.11136951426,2538.80091993338,2689.52298781326,2845.32581303603,3006.2571294187,3172.36418584602,3343.69376304571,3520.29218630943,3702.20533446276,3889.47864538753,4082.15711839972,4280.28531378638,4483.90734980477,4693.06689744706,4907.80717327391,5128.17093062023,5354.2004494764,5585.93752534835,5823.42345739967,6066.69903617919,6315.80453123726,6570.77967893403,6831.66367074316,7098.49514235406,7371.31216387616,7650.15223144847,7935.05226055761,8226.04858136782,8523.17693636612,8826.47248062599,9135.96978499278,9451.70284249437,9773.70507828014,10102.0093633917,10436.6480326688,10777.6529070933,11125.0553208748,11478.8861535822,11839.1758676215,12205.9545513676,12579.2519682491,12959.0976120921,13345.5207690259,13738.5505862523,14138.2161479844,14544.546558856,14957.5710351056,15377.3190038395,15803.820210675,16237.1048360691,16677.2036206347,17124.1479997485,17577.9702477533,18038.703632058,18506.3825774391,18981.0428408469,19462.7216970188,19951.4581352044,20447.2930673051,20950.2695477306,21460.4330052778,21977.8314873327,22502.515916701
)
    bias(act , pred)

       [1] 1.04888e-05

    percent_bias(act, pred)*100

       [1] -0.02422372

Answer: You have the error defined as:
$$e_i = a_i - p_i$$
Some of those errors are positive (prediction too low), and some of them are negative (prediction too high). On average, they are too low (i.e. the bias is positive).
You then have the percentage error defined as $e_i/a_i$. If you tend to have predictions which are too high when the actual is small (so a large negative percentage error, since all your actuals are positive), and too low when the actual is large (a small positive percentage error), the average of the percentage error can be negative.
In general, the bias depends on the distribution of the $e_i$, but the percentage bias depends on the joint distribution of the $e_i$ and the $a_i$.
Comment: That's great. Thank you


Can $X_1$ and $X_2$ be independent conditioning on $X_1+X_2$?

Question: Suppose that $X_1$ and $X_2$ are independent. I wonder if $X_1$ and $X_2$ conditioning on $X_1+X_2$ can be independent as well.
If $X_1$ and $X_2$ are normally distributed, then the above statement is wrong. I wonder if the statement can be true for some random variables.
Comment: It will be helpful if you type this explicitly mathematically as a theorem.
Answer: $X_1 ~|~ X_1+X_2$ and $X_2 ~|~ X_1+X_2$ are not independent. They are perfectly negatively correlated distributions.
Comment: $X_1 + X_2$ is an instance of a "collider" for $X_1$ and $X_2$.

This is discussed in:  [Day, Felix R., et al.](https://www.cell.com/ajhg/pdf/S0002-9297(15)00514-5.pdf)  "A robust example of collider bias in a genetic association study." The American Journal of Human Genetics 98.2 (2016): 392-393.  See also https://en.wikipedia.org/wiki/Collider_(statistics) .
Comment: They can be independent - see the other answers.
Answer: It's possible if one of them is constant - for example if $X_1$ has a Bernoulli distribution and $X_2$ is always equal to zero.
Comment: OP: _ I wonder if the statement can be true for some random variables_
Comment: @krkeane I don't understand your comment.
Comment: Plural: "random variables", so constant ruled out.
Comment: @krkeane no, a constant random variable is still a random variable. See the "Constant random variable" section on this Wikipedia page: https://en.wikipedia.org/wiki/Degenerate_distribution


Deducing a topology given its continuous functions.

Question: Given a topology $\tau$ for a set $S$, one can easily check if some functions are continuous between some subsets $A,B \subseteq S$, inheriting a topology from $\tau$ to both. My question is if/how I can do the other way around. Choosing the kind of function $f: A \rightarrow B$ that I want to be continuous between $(A, \tau|_A)$ and $(B, \tau|_B)$, how can i construct such $\tau$?
To help understand what I mean, I'll give an example. The continous deformations (not creating holes or glueing point) can be checked to be continuous under the standard topology in $\mathbb{R}$. But suppose I don't know the existence of the standard topology, can I deduce it just by deciding that I want the continuous deformations to be my continuous functions between topological spaces with such topology? If so, there is a "standard method" to deducing such topology?
Answer: For whatever map $f$, the trivial topology is a topology that will make $f$ continuous for any $A,B \subseteq S$. So I don't think that you can recover a specific topology. The trivial topology will always satisfy your requirement.
Comment: Also the discrete topology.
Answer: I mean a really trivial thing could be to choose the discrete topology.
But let me describe a  more common scenario : imagine we have a map $f:A\to B$ (note to define a map all we need is the sets $A,B$). Further imagine we know that we have a topology on $B$, call it $\tau_B$, then
$$
A \overset{f}{\longrightarrow} (B,\tau_B),
$$
now how does one construct a topology on $A$, call it $\tau_A$ so that $f$ is continuous? Well its common to construct it exactly like that i.e
$$
\tau_A:=\{ M\subset A~:~f^{-1}(N)\in \tau_B \},
$$
then for sure $f$ is continuous, i.e this is the coarsest topology one needs for continuity of $f$. $\textbf{Of course}$ one still needs to check $\tau_A$ is a topology, it might not always be!
Comment: The problem is that in the question $\tau_B$ is not given: $\tau_B$ is supposed to be the relative topology induced from $\tau$ that you're looking for.
Comment: Yeah and as I said could go for the discrete topology. The scenario I described is just common, guess its not exactly relevant.


Redirect 301 or RedirectMatch 301 not working for me

Question: So this is my scenario:
I have 1 static IP and 2 servers. 1 server is a web server the other is a mail server. I have a router as a hardware firewall with all the ports are set that require passthrough to internal ip addresses .
If a user types the url http://www.domain.com they see that website. If the user wants to access webmail they type in the url http://mail.domain.com but still see http://www.domain.com
I have set the webmail domain to be accessible via port 8080 on the mail server and if the user types the url http://mail.domain.com:8080 it works no problem but not with http://mail.domain.com.
So this is my issue:
In my httpd.conf I want to setup a Redirect 301 so that when the user types in http://mail.domain.com they get redirected to http://mail.domain.com:8080
I'd prefer not to use .htaccess and keep the directives in the httpd.conf
Thanks...
Answer: There is at least 2 way to do this:

Create 2 virtual host one for www.domain.com and one for mail.domain.com and then put your RedirectMatch directive in the second one.
You could also use the ProxyPass directive in the mail.domain.com virtual host to make it working like a reverse proxy and have mail.domaine.com:80 working directly without redirection
Use mod_rewrite like this to only redirect for the mail.domain.com url with a rule like that
RewriteCond %{HTTP_HOST}  ^mail.domain.com$ [NC]
RewriteRule ^(.*) http://mail.domain.com:8080/$1 [R=301]
with mod_rewrite you can also do a reverse proxy with a rule like (mail.domain.com should resolve to the internal IP)
RewriteCond %{HTTP_HOST}  ^mail.domain.com$ [NC]
RewriteRule ^(.*) http://mail.domain.com:8080/$1 [P]
Answer: You'll need to create a virtual host on your main web server that responds to web requests for the "mail.domain.com" address.  Take a look at the Name-based Virtual Host documentation on the Apache website.  You'll also need a mod_rewrite rule to do the redirection.  Your configuration would look something like this:
<code>NameVirtualHost *:80
<VirtualHost *:80>
  ServerName mail.domain.com
  RewriteEngine On
  RewriteRule (.*) http://mail.domain.com:8080/\1 [R=301,L]
</VirtualHost>
</code>
Comment: Rewrite is useless if a virtualhost is created, RedirectMatch will be probably faster
Comment: what are you talking about radius? Rewrite is perfectly fine in a virtualhost as listed above. The code is a little broken (use $1 not \1) but other than that it's good.


Like a vlookup but in bash to match filenames in a directory against a ref file and return full description

Question: I am aware there isn't a special bash function to do this and we will have to build this with available tools -- e.g. sed, awk, grep, etc.
We dump files into a directory and while their filename looks random, they can be mapped to their full description. For example:
/tmp/abcxyz.csv
/tmp/efgwaz.csv
/tmp/mnostu.csv

In filemapping.dat, we have:
abcxyz, customer_records_abcxyz
efgwaz, routernodes_logs_efgwaz
mnostu, products_campaign

We need to go through each of them in the directory recursively and rename the file with its full description. Final outcome:
/tmp/customer_records_abcxyz.csv
/tmp/routernodes_logs_efgwaz.csv
/tmp/products_campaign_mnostu.csv

I found something similar here but not sure how to work it out at directory level dealing with only one file as the lookup/referece file. Please help. Thanks!
Comment: Show us what you have tried so far ?
Comment: Sure. for i in $(ls -1); do grep "${$i}" /home/sandy/filemapping.dat | cut -f 2 -d","; done

But that does not rename. Not sure what to do after cut. I'm thinking we have to issue a mv command?
Answer: I would try something like this:
sed 's/,/.csv/;s/$/.csv/' filemapping.dat | xargs -n2 mv

Either cd to tmp beforehand, or modify the sed command to include the path name.
The sed commands simply replace the comma and the line end with the string ".csv".
Comment: Thanks for this. Can you elaborate what this sed does, please? I need to make some modifications.


Note Duration Priority?

Question: If a dotted half note precedes a quarter note of the same pitch, is the note held for the duration of the former or latter? Does the following quarter note supersede the dotted half in this case?
Answer: That dotted half note is tracked to a different voice; it basically is like another melodic line played at the same time as the other voice (the way you can tell is if the stems of the noteheads point away from the center of the staff). The dotted half is played for the entire measure, whereas the other notes are all played in sequence starting at the same time that the dotted half does.
In the future, for questions like these, it is invaluable to post the time signature of the piece (which I assume to be 3/4).
Comment: It's poorly written, in that it's supposed to be 3(?) voices. However, it's not easy to show 3 voices when stem options allow 2. The 'middle voice' needs a rest at the beginning of the bar. Unless - it's not 3/4 but 6/4, in which case, it's even more badly written!
Comment: I strongly disagree that the example poorly notated. This sort of figure has been standard in the Western tradition for centuries. Certainly there alternative renderings which that convey the same meaning, but once understood, like anything in traditional Western music notation, the meaning is clear.
Comment: I miss however a quarter rest at the beginning of the bar for the middle voice, which continues with the two quarters of downward stem f (if a treble clef can be assumed).
Comment: It seems to me the two down-stems of the third voice are unnecessary. They seem to be there just to allow the F to be shown as held but in guitar music this can be shown by just using the tie, with no need for a third voice. It's often a matter of taste how these things are notated. The message is clear which is all that matters.
Comment: @PeterJ - had the message been clear, this question wouldn't have appeared!
Comment: I bet the writer just didn't want to take up space writing in that rest. Sucks, but it's common practice. And yes, three voices but weird, right?
Comment: @DeanRansevycz I was in fact very careful not to say that the example was poorly notated. Perhaps you took my "Sucks, but it's common practice" as meaning such? Because if so, that's not what I meant to say.
Comment: Agreed, @user45266; yours are not the comments I'm railing against.
Comment: Oh, sorry. Maybe the reply feature would be useful here* (typing @ and then a user's name to reply to them)*, as I get notified of all comments on my own post, but not the other commenters, who may not have received notice of your remarks.
Comment: @DeanRansevycz - 'once understood....the meaning is clear'. That's true about everything, not just notation! The sole purpose of writing dots is for others to read and thus be able to play what's written. This example is not the best.
Comment: @DeanRansevycz I stand somewhat corrected; apparently Tim somehow saw it :) But it's still a good feature of the site.

Note Duration Priority?


calculate $\int_0^\infty \int_0^\infty e^{-xy} \sin(x) \,dx\, dy$

Question: I want to prove $\int_0^\infty \sin(x) / x \,dx = \frac{\pi}{2}$ using
$$\int_0^\infty \int_0^\infty e^{-xy} \sin(x) \,dx\, dy= \int_0^\infty \int_0^\infty e^{-xy} \sin(x) \,dy\, dx $$
assuming I've proved the integral converges so I can switch integral.
but my trouble is how to calculate $$\tag1\int_0^\infty \int_0^\infty e^{-xy} \sin(x) \,dx\, dy$$I just wrote it in the below form
$$\int_0^\infty \int_0^\infty e^{-xy}\sin x\,dx\,dy = \int_0^\infty \operatorname{Im} \int_0^\infty e^{-xy + ix}\,dx\,dy = \int_0^\infty \operatorname{Im} \frac{1}{y -i}\,dy\\ =\int_0^\infty  \frac{1}{y^2 +1 }\,dy = \frac{\pi}2.
$$
but I'm also looking for another way to calculate this integral $(1)$ , any help is appreciated , thanks!
Comment: "assuming I've proved the integral converges so I can switch integral" - Note that convergence isn't sufficient to interchange the integral, but I'm assuming you just mean to ignore it.  Iirc, the inner integral in $(1)$ can be evaluated by two applications  of integration by parts.
Comment: The command of Maple `int(exp(-x*y)*sin(x), [x = 0 .. infinity, y = 0 .. infinity])` also produces $\frac \pi 2$.
Answer: \begin{align}
& \int_0^\infty \frac{\sin x} x \, dx = \int_0^\infty \left( \sin x \int_0^\infty e^{-xy}\, dy \right) \, dx\\[12pt]
= {} & \int_0^\infty \left( \int_0^\infty e^{-xy} \sin x \,dy\right) \, dx \\[12pt]
= {} & \iint\limits_{x,y\,:\,x\,>\,0,\,y\,>\,0} e^{-xy}\sin x \, d(x,y) \text{ ??} \tag 1
\end{align}
Is the "$=$" on line (1) above true? It is true if
$$
\iint\limits_{x,y\,:\,x\,>\,0,\,y\,>\,0} e^{-xy} \left| \sin x \right| \, d(x,y) <+\infty. \qquad \text{(?)}
$$
That seems less than clear, and questionable since $\displaystyle\int_0^\infty \frac{\left|\sin x\right|} x \, dx = +\infty.$
So we take a somewhat different tack:
\begin{align}
& \int_0^b \frac{\sin x} x \, dx = \int_0^b \left( \sin x \int_0^\infty e^{-xy}\, dy \right) \, dx\\[12pt]
= {} & \int_0^b \left( \int_0^\infty e^{-xy} \sin x \,dy\right) \, dx \\[12pt]
= {} & \iint\limits_{x,y\,:\, x\,>\,0,\ \& \\ 0\,<\,y\,<\,b} e^{-xy}\sin x \, d(x,y) \\
& \text{(For the moment I'll leave it as an exercise} \\
& \phantom{\text{(}} \text{that the integral of the corresponding} \\
& \phantom{\text{(}} \text{absolute value is finite.)} \\[12pt]
= {} & \int_0^\infty \left( \int_0^b e^{-xy} \sin x \, dx \right) \,dy
\end{align}
The inside integral calls for integration by parts twice, leading back to the same integral, thus yielding an algebraic equation in which the unknown to be solved for is the integral.
$$
\int_0^b e^{-xy} \Big( \sin x \, dx \Big) = \int u\,dv = \cdots
$$
If I'm not mistaken, integrating by parts twice yields
$$
\int_0^b e^{-xy} \sin x \, dx = \Big(\cdots\cdots\Big) - y^2 \int_0^b e^{-xy} \sin x \,dx
$$
where $\displaystyle\Big(\cdots\cdots\Big)\to0$ as $b\to+\infty,$
so that
$$
\int_0^b e^{-xy} \sin x \, dx \to \frac 1 {1+y^2} \text{ as } b\to+\infty.
$$
So finally we evaluate $\displaystyle \int_0^\infty \frac{dy}{1+y^2} = \frac \pi 2.$
Answer: For the inner integral, there is a different approach.
Let's find a general formula for integrals of this form.
$$I= \int e^{ax}\sin(bx)\ \mathrm{d} x $$
Integrating by parts two times,
$$I=\dfrac{ e^{ax}\sin(bx)}{a}-\dfrac{b\cos(bx)e^{ax}}{a^2}-\dfrac{b^2}{a^2}\underbrace{\int e^{ax}\sin(bx)\ \mathrm{d}x}_{I} \\ I= \dfrac{e^{ax}(a\sin(bx)-b\cos(bx))}{a^2+b^2}$$
So,
$$\begin{align} \int_0^{\infty} e^{-yx}\sin(x)\ \mathrm{d}x &= \left. \dfrac{e^{-yx}(-y\sin(x)-\cos(x))}{y^2+1}\right|_0^{\infty} \\ &= \dfrac{1}{y^2+1}\end{align} $$
The rest can be evaluated just like you did.
Answer: I liked your approach. You can write, alternatively
\begin{align}\displaystyle\int_0^\infty\displaystyle\int_0^\infty e^{-xy}\sin x\,\mathrm dx\mathrm dy&=\displaystyle\int_0^\infty \frac{1}{x^2+1}\mathrm dx\quad{(1)}\\&=\dfrac{\pi}{2}\end{align}
$(1)-$ We have used the known result to evaluate the inner integral that the Laplace transform of $\sin(\omega t)$ is $\frac{\omega}{s^2+\omega^2}$, therefore $\int_0^\infty \sin(t)e^{-at}\mathrm dt=\frac{1}{a^2+1}$.


Which sport has the most players?

Question: Which widely-played sport has the most active players globally?
By widely-played, I mean played in at least ten countries.
By players, I mean both professional and amateur players who play in an organised competition.
Comment: How do you define "play it". Recreationally; apart of a team in a league; once a year?
Comment: Are you asking for team sports or team and individual players/sports?
Comment: Right comment up for you. Both: pro and amateur
Comment: I've had a go at narrowing it and making it more concise. Let me know if I've changed the question too much.
Comment: @Don_Biglia Right comment up also for you. Both: team and individual sports
Answer: This list appears to be quite a definitive list and is more or less where I'd expect it to be in terms of the top 10.
Stating Soccer as the most played and (mainly because of the massive player numbers on the sub-continent) Cricket at number 2.
Comment: That's a good find, but it looks like the list is ranking number of fans (determined by which sports are the most watched), not number of players.  Although, the two stats are probably correlated somewhat.
Comment: This image https://twitter.com/Amazing_Maps/status/630470784205619200/photo/1 confirm that football is the sport with the most spectator with the large majority so it is also the sport with more players
Answer: Baseball. What else could it be?
Comment: Could you provide some references for this answer? It seems unlikely to me to be true given the limited geographic distribution of baseball - how many Chinese and Indians play baseball?

Which sport has the most players?


Expectation and variance of the posterior distribution example: seeking elaboration on normalising constant

Question: I have the following example:

Assume that we have an observation $Y$ from a Binomial distribution with parameter $n = 20$ and success probability $p: [Y \sim \mathrm{Bin}(20, p)]$.
Further assume that we observed $y = 12$ and want to make inference about the value of $p$ using  Zellner's prior, i.e., we want to use the following PDF as prior for $p$: $[f(p) = c p^p (1-p)^{(1-p)}]$, where $c$ is such that $\int_0^1 f(p) \ dp = 1$. We can determine this constant by numeric integration in R:
integrand <- function(p) p^p * (1-p)^(1-p)
res <- integrate(integrand, lower=0, upper=1)
res
(c <- 1/res$val)

It then continues as follows:

Given that we have observed $y = 12$, the likelihood $L(p \mid y)$ is $[ L(p \mid y) = \binom{20}{12} p^{12} (1 - p)^8]$. The posterior of $p$ is $[f(p \mid y) \propto L(p \mid y) f(p) = \binom{20}{12} p^{12} (1 - p)^8 c p^p (1 - p)^{(1 - p)}]$.

Whence $[f(p \mid y) \propto p^{12 + p} (1 - p)^{9 - p}]$.
Again, we could find the normalising constant for this density by
numerical intergration:
    integrand <- function(p) p^(12+p) * (1-p)^(9-p)
    res1 <- integrate(integrand, lower=0, upper=1)
    res1
    (c1 <- 1/res1$val)
>
> We could also use numerical integration to calculate the posterior
> mean and posterior variance of $p$. The following calculates
> $\mathbb{E}[p \mid y]$, the expectation of the posterior distribution:
>
>     integrand <- function(p) c1 * p * p^(12+p) * (1-p)^(9-p)
>     (resEp <- integrate(integrand, lower=0, upper=1))
>     Ep <- resEp$val

Now we calculate $\mathbb{E}[p^2 \mid y]$, from which we can determine
$\mathrm{Var}[p \mid y] = \mathbb{E}[p^2 \mid y]- (\mathbb{E}[p \mid y])^2$, the variance of the posterior distribution:
integrand <- function(p) c1 * p^2 * p^(12+p) * (1-p)^(9-p)
(resEp2 <- integrate(integrand, lower=0, upper=1))
Ep2 <- resEp2$val
(Varp <- Ep2 - Ep*Ep)

I have only just started learning Bayesian probability, so please be patient with me.
I understand that the $p^{12 + p} \cdot (1 - p)^{9 - p}$ is $f(p \mid y)$ -- the posterior of $p$.
I understand that, in accordance with the formula for the expected value of a continuous random variable $E[X] = \int_\mathbb{R} xf(x)$, we multiply $f(p \mid y)$, which is essentially the density function $f(x)$ in this case, by $p$, which is essentially $x$, the realisations/outcomes/observations of our random variable, since $p$ is the random variable we are trying to find a posterior distribution for, as is in accordance with the Bayesian methodology.
I understand that the normalising constant is used to reduce any probability function to a probability density function between $0$ and $1$.
However, I don't understand the following:

Why is the normalising constant needed here (in general)?
Why do we need to multiply by the normalising constant in the formula for expectation? It has that $\mathbb{E}[p \mid y] = c_1 \cdot p \cdot p^{12 + p} \cdot (1 - p)^{9 - p}$, and, as stated above, I think I understand all of it except for the normalising constant.

I would greatly appreciate it if people could please take take the time to clarify this.
Answer: Unfortunately, you are a little off in several of your beliefs.

$p^{12+p}(1-p)^{9-p}$ is not the posterior of $p$, as it hasn't been normalized to integrate to 1.  It is proportional to the posterior, but without the normalization constant, it is not a probability distribution and cannot be used as such.
The normalizing constant is not there to "reduce any probability [density - I assume this should have been included] function to a probability density function between 0 and 1."  It is there to make the probability density function integrate to exactly 1.  The values of the density function itself need not be $\leq 1$; consider a Uniform distribution over the interval $(0, 1/2)$.  In order to make that integrate to 1, the density $f(x)$ must equal 2 everywhere.

If the posterior density integrates to some number $> 1$, then you are saying "the probability of the parameter taking on a value - any value - is greater than 1", which is ... problematic ... in several respects.  Similarly, if the posterior density integrates to a value $<1$, you are saying "the probability of the parameter taking on a value - any value - is less than 1".  You can see that, too, is problematic in several respects.  For example, what happens if the event "the parameter doesn't take on any value" occurs?
The implications for your specific questions are as follows.  The normalizing constant is there so the distribution integrates to 1.  If you don't multiply by the normalizing constant, you aren't calculating an expected value, you're just calculating an integral; it's not an expected value because you aren't working with a probability distribution, and you're not working with a probability distribution because your function $f(\cdot)$ doesn't integrate to 1.
Comment: Hmmm... maybe I'll hop on over there and edit that... you can see that if you start out with an unnormalized probability function on the integers, for example an unnormalized Poisson distribution, multiplying by the normalization constant won't make it into a probability density function, which is continuous.
Comment: Thank you very much for the elaborate response. You've clarified my confusion, so I think I understand it all now. Side-Note: it was the Wikipedia article on the normalising constant that used the term "probability function": "... to reduce any probability function to a probability density function with total probability of one."


Struggling with C# generic HashSet declaration

Question: I'm trying to declare something like this in C# (note this is NOT correct C# syntax):
enum Color { Red, Yellow, Green, Blue }
type ColorSet HashSet<Color>;                        // #1

void setColors (ColorSet colors = { Red, Green })    // #2
{ ... }

So -- how can I declare a synonym type for HashSet, and how can I define a constant of that type to use e.g. as a function parameter default value?
For #1, a possible approach is an empty wrapper class:
class ColorSet : HashSet<Color> { }

-- but how do I define a constant of that class?
Thanks in advance.
Comment: What is it that you are actually trying to *do* here?
Comment: Marc Gravell: Just as I wrote: I want to use a single type name for the "set of colors" because it is used many times, e.g. as a function parameter. And for defining a default value for the parameter, I'd need a constant definition or a literal.
Comment: the only constant you can use there is `null`.
Answer:
how can I declare a synonym type for HashSet,

You can't; there is no such thing in C#. There is a using alias, but that is per-file.

and how can I define a constant of that type to use e.g. as a function parameter default value?

You can't: a class cannot be a constant (except string literals). You could have a static readonly field somewhere, but it would be mutable.
Answer: You can try this approach:
public enum Color { Red, Yellow, Green, Blue }
public class ColorSet : HashSet<Color> {}

private void setColors(ColorSet colors = null)
{
    if (colors == null)
        colors = new ColorSet {Color.Red, Color.Green};

    ....
}

Note that C# compiler requires method's default parameters to be comile-time defiite, so you can't use any static instance of ColorSet as default parameter for method. Instead assume null is default parameter and in that case use predefined colorset you need in method body.
Answer: You cannot directly set the (not null) default value for reference type for the method, but you can create two methods that act similar:
enum Color { Red, Yellow, Green, Blue }
class ColorSet : HashSet<Color> { }

void setColors(ColorSet colors)
{
    ...
}
void setColors()
{
    setColors(new ColorSet { Color.Red, Color.Green });
}

Comment: Your solution and Andy's are equally useful, I think. :-)


Why is $\lim_{n\to\infty}\binom{n}{i} \frac{1}{n^i} \left (1-\frac{1}{n}\right)^{n-i}=\frac{1}{i!} e^{-1}$?

Question: In my probability script the following equation is used, to show that for $n\to \infty, \displaystyle\binom{n}{\frac{1}{n}}$ converges against the Poisson distribution $Po(1)$.
$$\lim_{n\to\infty} f_X(i) = \lim_{n\to\infty} \frac{n(n-1)...(n-i+1)}{i!}\frac{1}{n^i}\left(1-\frac{1}{n}\right)^{n-i} = \frac{1}{i!}e^{-1}$$
It is clear to me why for a set $i$,  $\lim_{n\to\infty}\left(1-\frac{1}{n}\right)^{n-i} = e^{-1}$. However, I am not sure why the two first fractions result in $\frac{1}{i!}$. I thought that the $n(n-1)...(n-i+1)$ and $n!$ cancel out, but that wouldn't be an equality, at least as far as I know. It could also be that my assumption that $\lim_{n\to\infty}\left(1-\frac{1}{n}\right)^{n-i} = e^{-1}$ in this case.
Comment: use `\left(1\pm\frac{1}{n}\right)` for the output $\left(1\pm\frac{1}{n}\right)$, so the fraction can fit in parentheses nicely and `\displaystyle\binom{n}{\frac{1}{n}}` for the output $\displaystyle\binom{n}{\frac{1}{n}}$.
Comment: https://math.stackexchange.com/q/1795049/321264, https://math.stackexchange.com/q/2280760/321264
Answer: Well, for $i$ fixed, there are $i$ terms in the product $n(n-1)...(n-i+1)$ and so $\dfrac{n(n-1)...(n-i+1)}{n^i}=\prod_{j=0}^{i-1}(\dfrac{n-j}{n})=\prod_{j=0}^{i-1}(1-\dfrac{j}{n})$.
Now $j/n\to0$ as $n\to\infty$ for each $0\leq j\leq i-1$ so $\prod_{j=0}^{i-1}(1-\dfrac{j}{n})\to 1$ and you get the result.
Answer: $$a_n=\binom{n}{i} \frac{1}{n^i} \left (1-\frac{1}{n}\right)^{n-i}$$
$$\log(a_n)=\log (n!)-\log ((n-i)!)-\log (i!)-i\log(n)+(n-i)\log\left (1-\frac{1}{n}\right)$$ Now, for large $n$, use Stirling approximation and Taylor series to get (I skip the simplifications)
$$\log(a_n)=\log \left(\frac{1}{e\, i! }\right)-\frac{i^2-3 i+1}{2 n}+O\left(\frac{1}{n^2}\right)$$
Now, use $a_n=e^{\log(a_n)}$
Answer: $$L=\lim_{n\to \infty} {n \choose k}\frac{1}{n^k}\left(1-\frac{1}{n}\right)^{n-k}$$
$$L=\lim_{n \to \infty} F(n)= \lim_{n \infty} \frac{n(n-1)(n-2)(n-3)...(n-k+1)}{n^k~k!} \lim_{n \to \infty}\left(1-\frac{1}{n}\right)^{-k} \lim_{n \to \infty}\left(1-\frac{1}{n}\right)^{n}$$
$$L= \lim_{n \to \infty} \frac{ (1-1/n)(1-2/n)(1-3/n)...(1-(k-1)/n}{k!}. 1.~ e^{-1}$$
$$\implies L=\frac{e^{-1}}{k!}$$