Convergence in Probability Clarification

Question: The following is from the textbook and I would like to clarify certain things which I am confused about.
Consider a sequence of independent random variables $X_n$ that are uniformly distributed in the interval $[0,1]$, and let
$$Y_n=\min{(X_1,...,X_n)}.$$
The sequence of values of $Y_n$ cannot increase as $n$ increases, and it will occasionally decrease (whenever a value of $X_n$ that is smaller than the preceding values is obtained). Thus, we intuitively expect that $Y_n$ converges to zero. Indeed, for $\epsilon>0$ we have using the independence of the $X_n$,
$$P(|Y_n-0|\geq \epsilon)=P(X_1\geq \epsilon, ... , X_n\geq \epsilon)=P(X_1\geq\epsilon)...P(X_n\geq \epsilon)=(1-\epsilon)^n.$$
Prior to continuing, I am confused about the $0$ in $P(|Y_n-0|\geq \epsilon)$ and how $(1-\epsilon)^n$ was found.
After this I understand the remaining, but would appreciate the clarification of the above. Thank you!
In particular,
$$\lim_{n\to\infty} P(|Y_n-0|\geq \epsilon)=\lim_{n\to\infty} (1-\epsilon)^n=0. $$
Since this is true for every $\epsilon > 0$, we conclude that $Y_n$ converges to zero, in probability.
Answer: You are looking at $|Y_{n}-0|$ because you are attempting to prove that $Y_{n}$ converges to $0$ in probabilty. This means, you must show
$$
\lim_{n\to\infty}P(|Y_{n}-0|\geq \epsilon)=0.
$$
Now, $|Y_{n}-0|\geq\epsilon$ iff $|Y_{n}|\geq \epsilon$ iff $Y_{n}\geq \epsilon  $ since the $X_{i}$'s are uniformly distributed on $[0,1]$ and, hence, positive. Now, $Y_{n}\geq \epsilon$ iff $\min\{X_{1},\ldots, X_{n}\}\geq \epsilon$, which occurs iff each of the $X_{i}$'s for $1\leq i\leq n$ is $\geq\epsilon$. This is how you get
$$
P(|Y_{n}-0|\geq\epsilon)=P(X_{1}\geq \epsilon,\ldots,X_{n}\geq \epsilon).
$$
Now, by independence, $P(X_{1}\geq \epsilon,\ldots,X_{n}\geq \epsilon)=P(X_{1}\geq\epsilon)\cdots P(X_{n}\geq\epsilon)$. Since each $X_{I}$ is uniformly distributed on $[0,1]$, the probability that $X_{i}\geq \epsilon$ is just $\frac{1-\epsilon}{1}=1-\epsilon$. Thus, since this term appears $n$ times, we get
$$
P(X_{1}\geq\epsilon)\cdots P(X_{n}\geq\epsilon)=(1-\epsilon)^{n}.
$$
Therefore,
$$
P(|Y_{n}-0|\geq\epsilon)=(1-\epsilon)^{n}.
$$
Thus, taking the limit, we get
$$
\lim_{n\to\infty}P(|Y_{n}-0|\geq\epsilon)=\lim_{n\to\infty}(1-\epsilon)^{n}=0.
$$
Comment: Thank you for your detailed explanation. I now understand the explanation of $(1-\epsilon)^n$. Could you please justify whether my understanding of the following is correct? The reason we chose $a=0$ is due to the fact that we want to show that the change between $Y_n$ and the true $Y$ as $\lim_{n\to\infty}$ is 0, in other sense they are the same as n goes to infinity? Thank you!
Comment: The statement: $\forall \epsilon>0$, $\lim_{n\to\infty}P(|Y_{n}-Y|\geq\epsilon)=0$ means that $Y_{n}\to Y$ in probability. Since you are showing $Y_{n}\to 0$ in probability, you use $Y=0$.


Ao executar o aplicativo no telemovel a imageView não é visível

Question: <?xml version="1.0" encoding="utf-8"?>

<EditText
    android:id="@+id/editTextEmailEntry"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginStart="87dp"
    android:layout_marginLeft="87dp"
    android:layout_marginEnd="111dp"
    android:layout_marginRight="111dp"
    android:layout_marginBottom="27dp"
    android:autofillHints=""
    android:ems="10"
    android:hint="@string/tEmail"
    android:inputType="textEmailAddress"
    app:layout_constraintBottom_toTopOf="@+id/editTextPasswordEntry"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintHorizontal_bias="0.0"
    app:layout_constraintStart_toStartOf="parent"
    tools:targetApi="o" />

<EditText
    android:id="@+id/editTextPasswordEntry"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginBottom="36dp"
    android:autofillHints=""
    android:ems="10"
    android:hint="@string/tPalavrapasse"
    android:inputType="textPassword"
    app:layout_constraintBottom_toTopOf="@+id/buttonPassRecovery"
    app:layout_constraintEnd_toEndOf="@+id/editTextEmailEntry"
    app:layout_constraintStart_toStartOf="@+id/editTextEmailEntry"
    tools:targetApi="o" />

<Button
    android:id="@+id/buttonProsseguir2"
    android:layout_width="0dp"
    android:layout_height="75dp"
    android:text="@string/bProsseguir"
    android:onClick="TelaSponsers"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent" />

<Button
    android:id="@+id/buttonPassRecovery"
    android:layout_width="174dp"
    android:layout_height="45dp"
    android:text="@string/bEsqueci"
    android:onClick="TelaEsqueci"
    app:layout_constraintBottom_toTopOf="@+id/buttonRegisto"
    app:layout_constraintEnd_toEndOf="@+id/buttonRegisto"
    app:layout_constraintStart_toStartOf="@+id/buttonRegisto" />

<Button
    android:id="@+id/buttonRegisto"
    android:layout_width="174dp"
    android:layout_height="45dp"
    android:layout_marginStart="112dp"
    android:layout_marginLeft="112dp"
    android:layout_marginEnd="125dp"
    android:layout_marginRight="125dp"
    android:layout_marginBottom="38dp"
    android:text="@string/bRegistar"
    android:onClick="TelaRegisto"
    app:layout_constraintBottom_toTopOf="@+id/buttonProsseguir2"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent" />

<ImageView
    android:id="@+id/icon"
    android:layout_width="141dp"
    android:layout_height="141dp"
    android:layout_marginStart="141dp"
    android:layout_marginLeft="141dp"
    android:layout_marginTop="48dp"
    android:layout_marginEnd="142dp"
    android:layout_marginRight="142dp"
    android:contentDescription="@string/icone"
    android:visibility="visible"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    tools:srcCompat="@tools:sample/avatars"
    tools:visibility="visible" />

Answer: Você está usando o atributo tools para colocar a imagem.
Como é explicado na documentação, ao usar este atributo, você está definindo um placeholder para ser exibido somente no preview.
Substitua tools:srcCompat por app:srcCompat que irá funcionar.


Access the 'More...' View Controller of UITabBarController in SWIFT 3

Question: Is there a way to access the 'More...' part of UITabBarController? Since my UITabBarController is not the root, it's being opened by a cell from a navigation-tableview controller, several problems occur (like I cannot see the navigation bar of UIViews attached to UITabBarController, so what I did was to pro grammatically add UIBarButtontems in each UIView controllers. Yet because of this, it 'overwrites' the Edit portion of the 'More...' that enables repositioning of tabs. Any suggestions? Thank you!
Comment: do you have enough rep to add image(s) that explain this problem better?
Answer: You can try from here moreNavigationController... Or you can try to explain better.


Setup on GoDaddy / Addon Domain "403 Forbidden Access Error"

Question: I currently have a working Drupal Commerce site up and running. This site is on a godaddy / cpanel server. This site is on an addon domain and sits in the following server directory:
home/.../public_html/siteX.com

I have the modules / configuration working well and want to use this base code to operate a second Commerce site, primarily to reduce my base code maintenance. (I am fairly new to Drupal and have built two sites for our family's small business. Pretty fun :)
I read a ton about setting up multi-sites that convinced me it would be fairly straightforward. Here's what I have done:

Created a new database on the server. Assigned my "user" to that database with all admin privledges
Created a new directory under the working Drupal Commerce site
home/.../public_html/xxxxx.com/sites/siteY.com
Pointed my "addon" domain to the Document Root above
Copied my default.settings.php into /public_html/xxxxx.com/sites/siteY.com
Renamed to settings.php with the database login information
Set my /siteY.com directory and settings.php to "777" permissions

When I navigate to "siteY.com", I keep getting a 403 error:

Forbidden
  You don't have permission to access / on this server.
  Additionally, a 500 Internal Server Error error was encountered while trying to use an ErrorDocument to handle the request.

If I navigate to "siteY.com/install.php, I get a different permissions error msg:

Internal Server Error
The server encountered an internal error or misconfiguration and was unable to complete your request.
Please contact the server administrator at webmaster@ to inform them of the time this error occurred, and the actions you performed just before this error.
More information about this error may be available in the server error log.
Additionally, a 500 Internal Server Error error was encountered while trying to use an ErrorDocument to handle the request.

Is it an issue to create a multisite from an add-on domain?
What am I missing here?
Should I jump ship and use the "Domain Access" module?
Answer: Solved## Successful installation completed :)
When setting the Directory Root for the "multisite" SiteY.com addon domain, I got it wrong.
Incorrect: home/.../public_html/xxxxx.com/sites/siteY.com

Correct: home/.../public_html/xxxxx.com/

With the correct option, you point to the site that contains the code based you want to pull from, as well as the index.php file.
I don't fully get the mechanics at play here, but am thankful to be on the other side.
Comment: Consider how the site is served - it always comes from index.php, which lives in the root. index.php bootstraps the site, and part of that process involves working out which site it is loading. Once it knows the site then the sites folder comes into play and it loads settings.php from there. (Some details omitted for simplicity).
Answer: After migrating my site from an old hosting account to Linux cPanel hosting with GoDaddy, the site was working temporarily and then suddenly throwing 403 error the next morning. I had not made any changes to the files. After reading Alfred Armstrong's comment below, I checked the Drupal root directory for the index.php file ... somehow it had been changed to index.htm. No idea what happened here unless someone on the GoDaddy side opened and re-saved the file. I renamed to .php and site is up again. Very strange but thanks for pointing me to the solution!


Post an image with HTTPClient but also some parameters on windows phone

Question: I want to do a MultipartFormDataContent request. But I also want to pass a lot of params with it. When I'm just doing a post I do this:
 public async Task<Webservice> inviteMembrs(List<KeyValuePair<string, string>> values)
        {
            String strUrl = String.Format("http://*****.com/nl/webservice/abc123/members/invite");
            var http = new HttpClient();
            var request = new HttpRequestMessage(HttpMethod.Post, new Uri(strUrl));
            request.Content = new HttpFormUrlEncodedContent(values);
            var result = await http.SendRequestAsync(request);
            var data = new Webservice { Status = result.StatusCode };
            if (result.StatusCode == Windows.Web.Http.HttpStatusCode.Ok && result.Content != null)
            {
                data.Data = await result.Content.ReadAsStringAsync();
                Debug.WriteLine(data.Data);
            }
            return data;
        }

This works perfect. But now I also want to pass an image with it.
I found a lot of examples but always without extra params.
Anyone can help?
Answer: Try the following code:
HttpClient httpClient = new HttpClient();

MultipartFormDataContent content = new MultipartFormDataContent();

content.Add(new StringContent(parameter), "name");

content.Add(new StreamContent(stream), "param", "filename");

HttpResponseMessage httpResponseMessage = await httpClient.PostAsync(address, content);

Comment: Do I need to pass all the parameters that way or can I just give the List> values as one param ?
Comment: This way you will post data in multipart-form format https://ru.wikipedia.org/wiki/Multipart/form-data. I think you need to iterate through your collection to post all params


Trying to run a codeigniter app on custom php

Question: I have a CodeIgniter app that I deployed to a server with php 5.2 and my dev box has 5.3, and some stuff doesn't work anymore.  I didn't want to upgrade php and risk the other app on the server having issues.  Anyway I compiled a custom PHP and added the following to a single .conf file in /etc/httpd/conf.d/zcid.conf with all the other conf files.
<code><VirtualHost *:80>
        DocumentRoot /var/www/cid/app
        ServerName sub.example.co.nz
</VirtualHost>

<Directory "/var/www/cid/app">
        authtype Basic
        authname "oh dear how did this get here i am no good with computer"
        authuserfile /path/to/auth
        require valid-user
        RewriteEngine on
        RewriteCond $1 !^(index\.php|robots\.txt|createEvent\.php|/cgi-bin)
        RewriteRule ^(.*)$ /index.php/$1 [L]
        AddHandler custom-php .php
        Action custom-php /cgi-bin/php53.cgi
</Directory>
</code>
In /var/www/cid/app I have the cgi-bin folder and the php53.cgi that I copied from /usr/local/php53/bin/php-cgi
But now when I navigate to the subdomain it says:
The requested URL /cgi-bin/php53.cgi/index.php/ was not found on this server.
And if I try to browse to /cgi-bin it says (what it is supposed to?):
You don't have permission to access /cgi-bin/ on this server.
Quite confused now.  Anyone know what to do here?
Thanks :)
Comment: You're trying to run codeigniter against a cgi connected PHP??? You should really have a look at php-fpm
Answer: Maybe have a look at this thread:
http://codeigniter.com/forums/viewthread/96347/
Answer: chmod 777 cgi-bin
Comment: -1. You should only use `777` if you really need *any* system user to have write access. If your problem is "the Apache user needs access to a directory", create a group with that user in, give that group ownership of that directory and set permissions accordingly.


How do I see that for every point $(x,y,z)$ such that $||(x,y,z) - (0,1,0)|| = 1$ there exist $s \in \mathbb R$ s.t $\gamma(s) = (x,y,z)$?

Question: I've the parametrization of a circle $\gamma(s)=(0,1,0) + \cos(s)(4/5,0,-3/5) + \sin(s)(0,-1,0)$.
I see that the radius is $1$ and that the center is $(0,1,0)$ (this is right?)
How do I see that for every point in space $\mathbb R^3$ of the form $(x,y,z)$ such that $||(x,y,z) - (0,1,0)|| = 1$ there exist $s \in \mathbb R$ s.t $\gamma(s) = (x,y,z)$ ?
That $\gamma(s)$ is included in the circle is easy to see by inspecting $||\gamma(s) - c||$.
Answer: It isn't true. There is no $s$ satisfying $\gamma(s) = (4/5,1,3/5)$.
Comment: So what I have is not a parametrization of a circle?
Comment: Yes, it is a parameterization of a circle. No, the set of points $(x,y,z)$ satisfying $\|(x,y,z) - (0,1,0)\| = 1$ is not a circle.
Comment: How do I see it is a complete circle and not "part of" a circle ?


How to calculate Weibull confidence interval using chi-square distribution?

Question: I have a dataset, which I assume has a weibull distribution :
vec <- c(90, 10, 60, 186, 61, 49, 14, 24, 56, 20, 79, 84,
         44, 59, 29, 118, 25, 156, 310, 76, 26, 44, 23, 62,
         130, 208, 70, 101, 208)

and want to know how to calculate the Confidence Interval for parameters scale and shape using a chi-squared test.
I have calculated alpha(=scale). I also know how to just extract Confidence Interval from the packages such as fitdistrplus. I know the formula for Confidence Interval is
D(a) = 2[log L(a_hat) − log L(a)] ≤ χ2(α)

but I don't know how this formula works. Can somebody help?
Comment: Using the visually similar "$a$" and "$\alpha$" within the same equation is just asking for trouble...
Comment: You are using $\alpha$ for two distinct things in: "2[log L(α.hat) − log L(α)] ≤ χ2(α)"...  On the left of the inequality it's a parameter of the Weibull but on the right it represents an upper-tail quantile (the value such that the probability of the relevant chi-squared variable being to the left of it is at least $1-\alpha$). *DON'T* use the same symbol for two different things. Since $\alpha$ is so entrenched as a convention on the right hand side, I strongly suggest you choose a different symbol (something *other* than $\alpha$) for the scale parameter of the Weibull
Comment: Please see https://stats.stackexchange.com/a/566564/919, which illustrates the basic concept and provides general-purpose `R` code.
Comment: This will be necessary for an answer to be able to respond suitably while still using symbols in a similar way to you. Please fix.
Comment: @Glen_b I fixed it. Thanks for catching that typo. I meant to type ```a```
Answer: All your entries in your dataset contribute to the likelihood function. If you maximize your likelihood function, then you will get the most likely values for your shape and scale parameters.
For that maximum value, the shape and scale can only have one specific value. Any other value will produce a lower value of the likelihood function.
Let's say you lower your likelihood function by a Chi-squared distribution, with 2 degrees of freedom, and a confidence interval of 90% (approx 1.35), then the shape and scale parameters have more "room" to take on a different value.
Basically, by lowering your likelihood function, you enable the shape and scale parameters to be other values, within a certain range.
See also:
https://reliawiki.org/index.php/Confidence_Bounds#Likelihood_Ratio_Confidence_Bounds


Analysis of a function: Showing that Quantum Mechanics violates relativity

Question: Consider the Hilbert space $L^2(\mathbb{R}^d)$ and a self-adjoint, positive operator $H$ (Hamiltonian).
Let $\psi_t$ be a solution to the Schrödinger equation (with $\psi_0$ the initial condition), then consider the function
$$t \mapsto \int_{\mathbb{R}} \overline{f(\boldsymbol{x})} e^{-iHt} \psi_0(\boldsymbol{x}) \ d^dx.$$
Assume that $\psi_o$ is compactly supported in some ball of radius $r>0$ centred at the origin.
I am supposed to be observing how quantum mechanics violates special relativity by showing that the support of $\psi_t$ grows faster than the speed of light, but I'm lost as to where to go with this.
How to proceed? Thanks.
Comment: Surely this is only true if you use a nonrelativistic Hamiltonian?
Comment: What part exactly? We are using a non-relativistic Hamiltonian above, and I am attempting to use this to show that non-relativistic quantum mechanics does indeed violate relativity (even though the name obviously implies it does!)
Comment: You never specified what Hamiltonian you were using... if $H$ is a relativistic Hamiltonian, then I expect causality to be preserved.
Comment: I see, I'm sorry. I should have been more explicit. We are using a non-relativistic Hamiltonian above and showing that causality is indeed not preserved.
Comment: Sections 2.1 of the QFT textbook by Peskin and Schroder discusses this question (and then 2.4 shows how graduating from quantum mech to quantum field theory resolves it). However it is at a physicist's level of rigor, which I doubt will be suitable for your needs. Let me see if I can massage it a bit.
Answer: In Peskin and Schroeder, the argument goes
$$
U(t) = \langle x\mid e^{-i(p^2/2m)t}\mid x_0\rangle\\
 = \int\frac{d^3p}{(2\pi)^3}\langle x\mid e^{-i(p^2/2m)t}\mid p\rangle\langle p\mid x_0\rangle\\
 = \frac{1}{(2\pi)^3}\int dp^3 e^{-i(p^2/2m)t}e^{ip(x-x_0)}\\
=\left(\frac{m}{2\pi i t}\right)^{3/2}e^{im(x-x_0)^2/2t}.
$$
That the propagator does not vanish for space-like separated $x$, $x_0$ implies violation of causality.
So instead of a generic positive Hamiltonian, he's assuming a free nonrelativistic Hamiltonian $H=\frac{p^2}{2m}$. And instead of assuming an initial state that has compact support, I think he's assuming here a Dirac delta function. For a generic function of compact support, I think just insert its Fourier transform, and proceed as above.
Then they talk about the Hamiltonian $H=\sqrt{p^2+m^2}$, and how the problems with this Hamiltonian are the same, via an asymptotic argument through Bessel functions only vaguely alluded to, you wind up with $U(t)\sim e^{-m\sqrt{x^2-t^2}}.$ Note that this shows, contrary to what I said in the comments, using a relativistic Hamiltonian does not enforce causality (but switching from a quantum mechanics to a quantum field theory does).
The general case, with an arbitrary self-adjoint positive Hamiltonian, may proceed similarly, but the details were too vague for me to follow.


Duas ações na mesma View

Question: Possuo uma View onde retorno os dados de um usuário, e necessito chamar uma outra view, para salvar dados, através de um modal.
O problema, é que são duas Views de controllers diferentes, então ao chamar, por meio de uma PartialView eu recebo um erro de declaração.
The model item passed into the dictionary is of type 'PortalRH.DomainModel.Entities.Usuario', but this dictionary requires a model item of type 'PortalRH.DomainModel.Entities.Divergente'.

Minha index:
@model PortalRH.DomainModel.Entities.Usuario

    <button type="button" class="btn btn-primary btn-lg" data-toggle="modal" data-target="#myModal">
        Relatar Divergência
    </button>

                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">×</button>

Modal title

                    @Html.Partial("~/Views/Divergente/Relatar.cshtml")

Pessoal

Documentos

Endereço

Dados Profissionais

                    @Html.Partial("_DadosPessoais")

                    @Html.Partial("_Endereco")

                    @Html.Partial("_DadosProfissionais")

                    @Html.Partial("_Documentos")

© @DateTime.Now.Year - Portal RH - Prefeitura Municipal de Vila Velha

    @Scripts.Render("~/bundles/jquery")
    @Scripts.Render("~/bundles/bootstrap")

A View que preciso chamar através do modal:
@model PortalRH.DomainModel.Entities.Divergente

@using (Html.BeginForm())
{
    @Html.AntiForgeryToken()

    @Html.ValidationSummary(true, "", new { @class = "text-danger" })

            @TempData["Mensagem"]

Dependente(s)

                            CAMPO
                            INFORMAÇÃO CORRETA

                            DADOS PESSOAIS

                            <input type="checkbox" class="cb" data-id="nmMae">
                             Data de Nascimento
                            <input type="text" data-id="nmMae" disabled class="form-control" name="nmMae">

            <input type="submit" value="Create" class="btn btn-default" />

}

Só adicionando, eu possuo as duas páginas funcionando perfeitamente( em cada view separada), necessito apenas que uma apareça em um modal, na mesma página.
A partial, é um model diferente, com a funcionalidade do usuário salvar no banco, alguma divergência em suas informações, para o administrador revisar e alterar, caso esteja correto. As entidades Usuario e Divergente não possuem nenhum relacionamento, preciso apenas mostrar através de um Modal, para deixar a aplicação mais fácil de ser usada pelo usuário.
Só adicionando, eu possuo as duas páginas funcionando perfeitamente( em cada view separada), necessito apenas que uma apareça em um modal, na mesma página.
Estou tentando fazer da forma correta? Ou existe outra maneira de obter o mesmo resultado?
Comment: As informações que serão exibidas em `PartialView` estão em qual `Model`?
Comment: @CiganoMorrisonMendez Editei a pergunta, com os models em suas determinadas Views
Comment: Ainda não entendi. `Index` tem `Divergente` como `Model`. A `Partial` também?
Comment: @CiganoMorrisonMendez Não. A Index possui Usuário como Model, e a partial possui Divergente.
Preciso mostrar as duas na mesma view, apenas para ficar mais fácil do usuário utilizar a aplicação.
Comment: E qual a relação de `Usuario` com `Divergente`, se há alguma?
Comment: @CiganoMorrisonMendez Nenhuma. O que estou querendo fazer é que quando a pessoa clicar no botão **RELATAR DIVERGÊNCIA** abra um *modal* com a view "Divergente", para o usuário poder edita-lá.
Pois do jeito que está, ele é redirecionado para outra página.
Answer: Supondo que a Modal já está devidamente escondida, a seguinte declaração deve resolver:

    @Html.Partial("~/Views/Divergente/Relatar.cshtml", new Divergente())

Atualize seu @Html.BeginForm() de dentro da Modal para receber parâmetros da action do form. Do jeito em que está, o form pode ser preenchido errado.
Não sei para onde irá o formulário, mas vou supor que é a Action Incluir de DivergenteController:
@using (Html.BeginForm("Incluir", "Divergente")) { ... }

Comment: Agora que notei algo curioso, a PartialView dele não utiliza a @model, vai entender.
Comment: Era isso mesmo que estava precisando.
Mas poderia explicar melhor a parte do **@Html.BeginForm()**? Não entendi onde devo alterar.
Comment: O `@Html.BeginForm()` tem algumas sobreescritas, uma delas lhe permite informar o `actionName` e a `controllerName`, no seu caso é interresante informar estes valores para que o formulario seja recebido pelo Action certa.
Comment: @RenilsonAndrade Atualizei a resposta.
Comment: Obrigado. Era exatamente o que precisava
Answer: A sua View está a utilizar uma Model do Tipo PortalRH.DomainModel.Entities.Usuario, porém a sua PartialView está esperando uma Model do Tipo PortalRH.DomainModel.Entities.Divergente.
Como você não especificou a Model a ser passada pela sua View para a PartialView, ele está a passar a sua propria Model para ser compatilhada com a PartialView.
Então tudo que precisa é passar uma Model do tipo PortalRH.DomainModel.Entities.Divergente para a sua PartialView.
Controller
public ActionResult Index(...)
{
    ...
    var divergente = default(Divergente);
    divergente = this.GetDivergente();
    ViewBag.Divergente = divergente;
    ...
}

public Divergente GetDivergente()
{
    ...
}

View
@Html.Partial("~/Views/Divergente/Relatar.cshtml", ViewBag.Divergente as PortalRH.DomainModel.Entities.Divergente);

Comment: Esqueci de comentar que possui um **@model PortalRH.DomainModel.Entities.Usuario** em minha view Index. ela aceita dois *@models*?
Comment: e o **@model PortalRH.DomainModel.Entities.Divergente** eu já possuo em minha partial
Comment: @Renaldo, `@model` é uma declaração do model que a `View`/`PartialView` espera receber. Como na `PartialView` você declarou que iria usar uma Model do tipo `Divergente`, então a sua `View` precisa passar um objeto do tipo `Divergente` como Model para a sua `PartialView`
Comment: Caso o seu objeto `Usuario` possua como propriedade do tipo `Divergente`, você pode chamar a sua `View` da seguinte forma: `@Html.Partial("~/Views/Divergente/Relatar.cshtml", Model.Divergente);`, caso contrario, ainda na sua controle você precisará salvar um objeto `Divergente` na sua `ViewBag`, e utilizar a mesma para chamar a `PartialView`
Comment: Divergente é uma outra classe, onde não possui relacionamento com o Usuário. Apenas preciso mostrar ela em um modal, para ficar mais fácil do usuário utilizar esta funcionalidade
Comment: atualizei a resposta para utilizar uma ViewBag.
Comment: Com esse código, estou recebendo um erro no **this.GetDivergente**, como se não existisse.
Comment: você precisa implementar este método.

Duas ações na mesma View


Disturbing fingertip-scar in playing guitar

Question: My husband likes very much to learn playing guitar. But he has a scar on two fingertips of his left hand. This causes problems in pushing the strings hard enough to the neck of the guitar. (It is not painful in general, but the tissue of the scared fingertip is not as firm as this of the other fingers)
He tried so far:

tape the fingers with sticky tape
change the hands and use a plectrum to avoid fingertip-string contact

But both was not working over time. The sticky tapes start loosing and then disturb, and the hands change is against his natural handing, so learning is quite difficult.
Does someone have experience or a work around for this problem?
Edit: Thank you for the variety of answers! I will encourage him to try finger-protection supply and then report the success.!
I know, it is not the picture you are looking for... But to describe the scar, it is better than nothing. Like I wrote in the comments: But a picture of the fingers would not real help I assume, because there is no visible scar. The skin of the fingertips was cut of by a planer. The skin grow again with no visible unevenness, but the skin itself is more soft and maybe thinner than the "normal" skin. In effect the string cuts more into the skin than on the healthy fingertips, which makes it tricky to push it onto the wood.
Comment: When the action of a guitar is low, the strings don't fight back so much. Make sure it's as low as possible. Thicker strings may help, but that's balanced against them having to be tighter. Not good. So maybe thicker strings, tuned down.
Comment: Action is how far away the strings are from the fretboard. High action means pressing harder to sound notes. Too low, and the strings rattle, or bind on the frets.
Comment: What kind of guitar is he playing? Classic should be more gentle to the left hand!
Comment: @Tom Because his fingers are quite big, he chose a western guitar for its bigger gaps between the strings. The strings are actual part of nylon and part of copper I assume, but I remember he was trying with steel too at some point.
Comment: He can try a dab of super glue on the tips of the fingers in question for an extra layer of protection. Always helps when one is playing on a busted callus... you don't have to reapply as often as tape but, the super glue will rub off onto the strings and more quickly decrease their life span.
Comment: A pic would help.
Comment: The fingers mostly.  But a pic of him playing something that shows finger placement would help too.
Comment: Yes, send a photo of the ends of his fingers and a picture of the guitar.
Comment: I am just beginning to learn myself so I am no expert but what if he tries cutting off the tips of a latex glove and use them as protection?
Answer: Lefty playing righty speaking. Playing the other is a matter of habit that you only have to commit yourself to do at the beginning, however, I would not recommend a righty playing the other way around, at least for the fact that left-handed guitars are not that common… That being said a few things could be attempted:

move to a classic guitar (with wide neck and nylon strings). You said he was playing western guitar which, from what I remembered would normally have steel strings but I am probably mistaken…

lower the gauges of the strings so that the pressure to apply is lower

maybe (not sure about that) let the nails on the left hand to grow just a little bit, not further than the fingertips, in order to have them assisting the fingertip,

try with thin fingertip protections, probably not ideal but might help for the meantime before the skin on the fingertips naturally hardens.

Note that, it is normal as a beginner to have a bit of pain in the fingertips as your fingertips are not used to press hard these thin steel or metal strings.
Comment: Classic guitars will be more adapted to fit nylon strings and the neck is wider which makes it easier to play with big fingers or to have more room to place the finger in order for the scars not to touching. This is [what](https://duckduckgo.com/?t=ffsb&q=fingertip+protection&atb=v232-1&iax=images&ia=images&iai=http%3A%2F%2Fres.cloudinary.com%2Fmfasco-first-aid-supplies%2Fimage%2Fupload%2F7711z.jpg) I was thinking about, I remembered buying some a pharmacy once when cutting myself while cooking (the mandolin slicer is a dangerous instrument…)
Comment: I know he was changing the strings of the western guitar. If it is common with steel strings, then this could be the cause I remember discussions about steel strings. But now the western guitar has nylon and copper strings. Is there an additional reason to change from western to classic guitar? And how would such a fingertip protection would look like?
Answer: Something that could easen the pressure on the fingertips, is to use lighter gauge strings, which could be a good place to start in this scenario.
Western guitars usually utilizes quite heavy steel strings (commonly referred to as > .11).
He could try and go for a set of gauge .08 strings and see how that feels. It should give him some relief on the pressure needed to make the strings "sound".
What @Tom suggests using nylon strings is also an option, but if he's going for more of a country sound, I bet he won't be satisfied with that. My 2 cents.
Comment: "_if he's going for more of a country sound..._" -- Willie Nelson has played nylon strings as long as anyone can remember ;)
Answer: I think a pic would help.  Usually, in my experience, scar tissue is tougher than regular tissue so it's hard for me to understand your post.
Tony Iommi of Black Sabbath lost two of his fingers in a machine shop accident.  He fashioned prosthetics out of wood and put leather on the ends for grip.  I'm not suggesting that for your husband but the fact remains that some type of covering would help.  It sounds like that is what you were trying with the tape.  The problem is tape is going to wear down and the sticky adhesive will mess up the finger board.  You don't want that.
A few options are:

Switch sides.  If he's a righty, play lefty.

Try a different material on the finger tips.  I recall something in the 80s called new skin liquid bandage.  I had a friend who played guitar and if he over played to the point of causing a tear in the skin on the finger tip or pulling it away from the nail he'd hit it with new skin and that would last for a while.  I have never tried it so I' can't say if it is better than tape.  Point is, get creative.

If it doesn't hurt just keep practicing and eventually a callus will form and that may fix the problem naturally.  Even if the callus wears down or softens over time his skin may eventually transform to accommodate his needs.

Depending on where the scar is on the finger attacking at a different angle might fix it.  For example if the scar is on the pad then fret with the finger tip (which is the "proper" classical way to fret).  If the scar is on the tip then try fretting with a flatter finger.  This is not great for open string chords as the flat finger will dampen some strings but a lot of shredders who play electric play on the pad instead of the tip and it works for them.
Comment: I have added a scratch of the location. To get a picture of my husband is not easy -.-
Comment: I try to get a picture. But a picture of the fingers would not real help I assume, because there is no visible scar. The skin of the fingertips was cut of by a planer. The skin grow again with no visible unevenness, but the skin itself is more soft and maybe thinner than the "normal" skin. In effect the string cuts more into the skin than on the healthy fingertips, which makes it tricky to push it onto the wood.
Comment: This is helpful.  How long ago were the fingers cut?  It could just be too fresh.  I would suspect that calluses would help and you just need to take time.  My father plays classical guitar and builds guitars.  He has had similar things happen, not very deep but just the surface layer.  It will be soft and pink for months but eventually toughen up again.
Comment: It happened minimum 20 years ago. So no, i is not fresh. It it was not only the surface, but the whole skin layer, but the bone not visible.
Comment: On the tip or on the pad?
Answer: I recently took up guitar again after many years of not playing. My brain and fingers remembered what to do but the skin on the tips of my fingers was as sensitive as those of a beginner. I had to work through several weeks of pain before getting the calluses back on my fingers.
To be honest, I just ignored the pain even though it was quite bad. I knew that I would get over it eventually.
All beginners experience sore fingers although I'm not sure how the scar tissue affects this. As long as the scars don't actually break open, I would simply endure the pain until it goes away. Maybe get some topical anaesthetic.
Keep an eye on the scars. You don't want them to actually bleed but, short of this, I say just tough it out. Consult a medic if there's any doubt about long-term effects.
As others have said, nylon strings (as used on a classical guitar) are softer and the space between strings on a classical guitar is wider than with an electric or steel string guitar.
Comment: I am not sure, if "you must welcome the pain" will help my husband ^^ But the visit by a medic may be an option, even mention it when the next visit is dated.


Regex Expression Conditional Validation In JavaScript

Question: Actually i am trying to add Validation to textbox field in ASP.NET.The validation is like first 2 characters must be Alphabets and last two characters Numeric in a max length of 4..Here is the code block
 function IsValidate(evt) {
    var charCode = (evt.which) ? evt.which : evt.keyCode;
    var Con = String.fromCharCode(charCode);
    var exp= new RegExp("[A-Za-z]{2}[0-9]{2}");
    if(exp.match(Con))
    {
    return true;
    }
    else
    {
    return false;
    }
    }

<asp:TextBox ID="txttest" runat="server" MaxLength="4" onkeypress="return IsValidate(event);">
</asp:TextBox>

Any help will be well appreciated...
Comment: AMember's answer seems good, but there is another problem. Your regex only looks for 2 letters followed by 2 digits somewhere inside the string (i.e. `!=asdasda5XX00asdasd=!` would match, because of the `XX00`). You should include anchors in the pattern: `^[A-Za-z]{2}[0-9]{2}$`
Comment: Why are you converting the keycode pressed to a char and then validating that. I don't think that contains the text in the textbox, does it?
Comment: I modified the pattern,not working out either m.buettner!
Comment: @Renji yes, because you are still validating only a single character. What I was saying was, that even if you ran this on the full string it would not work as you want it to.
Comment: @ m.buettner So what would be the apt code for this situation exactly..i am clueless :)
Answer: I am no expert in ASP.NET but a quick search revealed that you can use a RegularExpressionValidator to validate the contents of your textfield.
<asp:TextBox ID="txttest" runat="server" MaxLength="4">
</asp:TextBox>

<asp:RegularExpressionValidator
  id="RegularExpressionValidator1"
  runat="server"
  ControlToValidate="txttest"
  ErrorMessage="Your input must be 2 letters followed by 2 numbers"
  ValidationExpression="^[A-Za-z]{2}[0-9]{2}$">
</asp:RegularExpressionValidator>

For more info go to MSDN here
Answer: You are trying to validate a single char to a regexp that expects to match 4 chars...
Move your validation to the onblur event or your form submission.
Comment: It is not possible to make it onkeypress/onchange event?
Answer: Just a few recomendations

set the regular expression like this "/..../"
define in the expression the beginning and the ending of the string
define the modifier

so the regex would end in something like this:
var exp = /^[A-Z]{2}[0-9]{2}$/i

I hope it helps, best regards.
Comment: I believe you should clarify that initialization with this syntax doesn't use the constructor at all (maybe by providing the full assignment line instead of just the regex). And why `{2,2}` instead of `{2}`? And lastly, if you use `i`, then you can remove either `a-z` or `A-Z`
Comment: why {2,2} instead of {2}?, to make sure the user gives 2 letters and numbers, I believe you should clarify that initialization with this syntax doesn't use the constructor at all (maybe by providing the full assignment line instead of just the regex), as I know, javascript also use this way ("var exp = /regex/") to define regex, f you use i, then you can remove either a-z or A-Z? ko ko ko my bad, don't set the modifier or if you set it don't specify the capital letters, I tested here http://www.rubular.com/r/q9b1Iz5I2l
Comment: `{2,2}` is absolutely equivalent to `{2}`. And yes JavaScript supports `var exp = /regex/`, but if the OP doesn't know it he might infer from your answer that he should put `/regex/` inside the constructor.
Comment: i tried changing the expression and executed it..still it doesnt make any difference.. :(
Comment: @mechdeveloper also, for JavaScript-based regec questions you shouldn't use rubular, but either [RegexPal](http://regexpal.com/) or simply the JS console of your browser. In this case it doesn't matter, because the regex is sufficiently simple, but there are important differences between the regex flavors of JS and Ruby.
Comment: ko, I learned the lesson, I just wanted to help, just that, not to confuse, complicate or waste the time of someone else.


Apache forward https port 4434 to non https port on internal server

Question: Im trying to set up a subversion edge server that is accessible from outside my network, I have one public IP and so the main webserver proxies to other internal server, i got the non https port (3343) to proxy to the internal server but i cant get the https port (4434) to proxy to the internal server http port (3343), I set apache to listen for https on port 4434 and I can telnet to that port on the main webserver but when it tries to proxy to the internal server it times out
heres what my apache virtualhost is for that proxy
VirtualHost *:4434
ServerName sub.domain.com
<code>    SSLEngine On
    SSLOptions +StrictRequire
    SSLCertificateFile /etc/ssl/certs/server.crt
    SSLCertificateKeyFile /etc/ssl/private/server.key
    ProxyRequests Off
            <Proxy *>
                    Order deny,allow
                    Allow from all
            </Proxy>
    ProxyPass / http://ipofinternalserver:3343/
</code>
VirtualHost
Comment: Can you clarify "times out"?  Does your browser display a timeout message, or do you get an error response for a proxy timeout from Apache?
Comment: it says this web page is not available because ipofinternalserver took too long to respond
Comment: Sounds like you got redirected, then?  Did the URL in your address bar change to be the internal server's address?
Comment: Yes and even the correct port and URL but that error message comes up on the screen
Comment: Well, let me clarify; if the address bar has changed to the internal IP, then that's wrong.  The client browser should talk only to the proxy, and never to the server behind it; if a redirect has sent you away from the proxy then that's a bad thing.  Try adding a `ProxyPassReverse / http://ipofinternalserver:3343/` right with your existing `ProxyPass`?
Answer: you can try iptables redirect
 iptables -t nat -A PREROUTING -i eth0 -p tcp --dport 443 -j REDIRECT --to -port 4443


Question about an integral of Bessel function $J_0$

Question: Suppose one wants to evaluate the integral
$$I = \int_0^\infty J_0(x) \, dx \ ,$$
where $J_0$ is the Bessel function of the first kind (od order zero). One seemingly simple way is to take well-known Lipschitz's integral,
$$\int_0^\infty e^{-ax} J_0(bx) \, dx = \frac{1}{\sqrt{a^2 + b^2}}  \quad (*)$$
valid for $a > 0$ and any real $b$, insert $b = 1$ and look at the limit $a \to 0^+$, which leads us to the correct result $I = 1$.
Side note: one way to prove (*) is to take integral representation of the function $J_0$ and exchange order of integration (cf. Watson: "Treatise on the Theory of Bessel Functions", page 384).
Now, the problem is how to prove that
$$\lim_{a \to 0^+} \int_0^\infty e^{-ax} J_0(x) \, dx = \int_0^\infty \lim_{a \to 0^+} e^{-ax} J_0(x) \, dx \ ?$$
Monotone convergence theorem does not seem to be useful as $J_0$ is not a non-negative (nor non-positive) function, and dominated convergence theorem does not seem to be useful as $|J_0|$ is not integrable (cf. On the absolute integrability of Bessel functions).
Is this procedure, exchange of limit and integral above, even meaningful?
Answer: Note that by dominated convegence, we have that
$$\lim_{a\to 0}\int_0^c e^{-ax}J_0(x)dx=\int_0^c J_0(x)dx.$$
Thus it suffices to show that
$$\lim_{c\to \infty}\lim_{a\to 0}\int_c^{\infty}e^{-ax}J_0(x)dx=0.$$
As you have observed, there seems to be no cheap way to do this, but it isn't that bad employing the asymptotic for $J_0(x)$ are $x\to \infty$. We can write
$$J_0(x)=\sqrt{\frac{2\pi}{x}}\cos(x-\pi/4)+\frac{1}{x^{3/2}}g(x),$$
where $g(x)$ a bounded function on $[1,\infty)$, such that say $|g(x)|\le C$.
Using this we see that
$$\int_c^{\infty}e^{-ax}J_0(x)dx=\int_c^{\infty}e^{-ax}\sqrt{\frac{2\pi}{x}}\cos(x-\pi/4)dx+\int_c^{\infty}\frac{e^{-ax}}{x^{3/2}}g(x)dx.$$
For the second integral, note that
$$|\int_c^{\infty}\frac{e^{-ax}}{x^{3/2}}g(x)dx|\le C|\int_c^{\infty}\frac{1}{x^{3/2}}dx|\le \frac{C}{2c^{1/2}},$$
so that
$$\lim_{c\to \infty}\lim_{a\to 0}\int_c^{\infty}\frac{e^{-ax}}{x^{3/2}}g(x)dx=0.$$
To bound the first integral, we can use integration by parts:
$$\int_c^{\infty}e^{-ax}\sqrt{\frac{2\pi}{x}}\cos(x-\pi/4)dx=-\int_c^{\infty}\frac{\sqrt{2\pi}}{2x^{3/2}}\int_x^{\infty}e^{-ay}\cos(y-\pi/4)dy+\sqrt{\frac{2\pi}{c}}\int_c^{\infty}e^{-ay}\cos(y-\pi/4)dy.$$
Now we can compute that
$$\int_{c}^\infty e^{-ax}cos(x-\pi/4)dx=e^{-ac}\frac{(1+a)cos(c)-(1-a)sin(c)}{\sqrt{2}(1+a^2)}.$$
We see from the right that for such that for $a<1$, $$|\int_c^{\infty}e^{-ay}\cos(y-\pi/4)dy|\le 4.$$
Thus
$$|\sqrt{\frac{2\pi}{c}}\int_c^{\infty}e^{-ay}\cos(y-\pi/4)dy|\le \sqrt{4\frac{2\pi}{c}}.$$
$$|\int_c^{\infty}\frac{\sqrt{2\pi}}{2x^{3/2}}\int_x^{\infty}e^{-ay}\cos(y-\pi/4)dy|\le-\int_c^{\infty}\frac{4\sqrt{2\pi}}{2x^{3/2}}\le \frac{4\sqrt{2\pi}}{c^{1/2}}.$$
Both of these expressions vanish taking interactive limits, so we see that
$$\lim_{c\to \infty}\lim_{a\to 0}\int_c^{\infty}e^{-ax}\sqrt{\frac{2\pi}{x}}\cos(x-\pi/4)dx=0.$$
This completes the proof.
Comment: Great answer! By the way, there is a typo on the rhs of the equation after "Now we can compute that...", it should be cos(c) and sin(c) instead of cos(x) and sin(x), right? Also, "To bound the second integral..." should read "To bound the first integral...".
Comment: @IvicaSmolić Ah yes, good catches.


Poisson distribution exercises. Are my answers correct?

Question:
Suppose that a book contains an average of $\lambda$ misprints per
  page.
(a) What is the probability that 10 pages will contain at most 1
  misprint?
(b) What is the probability that $n$ pages will contain at most 3
  misprints?
(c) If the book has $n$ pages, what is the probability that there will
  be at least $m$ pages that each contain more than $k$ misprints?

My answers:
$X=$ number of misprints per page.
(a) $P(X\leq1), X\sim P(10\lambda)$
(b) $P(X\leq3), X\sim P(n\lambda)$
(c) I'm not sure how to answer this one. Any hint?
Are my answers correct? How can I answer (c)? Thank you.
Answer: Hint:
If $X \sim$ Poisson$(\lambda)$, then the number of pages with more than $k$ misprints is distributed binomial$(n, p = P(X > k))$.
Comment: So, the answer to (c) would be $P(Y\geq m), Y\sim$Binomial$(n,p=P(X>k))$, correct?
Comment: That looks good.


Creating a .bat file to copy the latest file from a network drive and change its name and extension

Question: I have the following in a .bat. I am trying to pull the most recent file (as the file name changes each time a new file is generated) from a network drive and copy it to a folder on my desktop changing the name so I can hit it from an outside DB. Unfortunately I am relatively new with .bat files and cannot figure out how to pull the latest file instead of the defined file below. I will turn this around and put it into a task scheduler to pull the file every thirty minutes.
copy \\fipr01\SNAP\P161201135302673.tmp C:\Users\ddtacopy\Desktop\AutoCopy\SNAP.txt

Answer: You could use dir to get a list of files sorted by age, take the newest file and then copy it:
pushd "\\fipr01\SNAP"
for /F "delims=" %%F in ('
    dir /B /O:D /T:C "*.tmp"
') do (
    set "NEWEST=%%F"
)
copy /Y "%NEWEST%" "C:\Users\ddtacopy\Desktop\AutoCopy\SNAP.txt"
popd

How does it work?

pushd creates a temporary drive letter that points to the given network path and changes to that; this is done because many batch commands do not support network paths;
dir /B /O:B /T:C returns a list of files *.tmp in the current directory, with the newest item last; /T:C tells dir to sort by the creation date; omit that if you want to use the modification date;
the for /F loop around dir reads its output and enumerates all the items; for each iteration it assigns the currently iterated item to variable NEWSET the set; the variable value is overwritten each time, so since the newest item is listed as last, NEWEST contains that one finally;
at that point the retrieved item is copied; the /Y tells the copy command to overwrite an already existing target file without asking; if you want a prompt to appear, change it to /-Y;
popd cleans up the temporary drive letter created by pushd and returns to the former directory;


Allow a range of IP's with IPTABLES from a file

Question: I would like to allow only certain ip ranges (CIDR) and block everything else, however, I have those IPs that I want to allow on a text file. How could I load them up from the allow.file to IPTABLES interface eth0?
Answer: Off the top of my head:
while read range; do
    iptables -A INPUT -i eth0 -s $range -j ACCEPT
done < allow.file

Addendum: A comment in chat asked whether using -I INPUT might be better than -A INPUT -- that is, inserting the rule at the beginning of the chain rather than at the end of the chain.  This is, really, a local issue -- I've seen firewall rulesets where inserting would break things, and rulesets where appending would break things.  You've got to make that choice for yourself and your situation.  If you don't know which, then you shouldn't be writing iptables rules by hand, and should be using a management program like shorewall or ufw.
Comment: @Tom Well caught.
Comment: Sorry, was thinking "IP blacklist".  It should be `ACCEPT`, and I've modified my answer to suit.
Comment: Actually, there's a UUOC in here.. You don't need to cat into while, just do:
... `done < allow.file `
.. instead


show that Cov(X+ Y, X-Y)= Var(X) - Var(Y)

Question: I have up until Cov(X+Y,X-Y) = E[((X-E(X))+(Y-E(Y)))((X-E(X))-(Y+E(Y)))] and now I am stuck and do not know how this turns into Var(X)-Var(Y)
Comment: Expectation is linear, so, for example, $\mathbb{E}[X+Y] = \mathbb{E}[X] + \mathbb{E}[Y]$.
Comment: Yeah I know but first I would have to multiply the 4 different expressions through and then separate them and that is where it gets messy @Clarinetist
Comment: I am also unsure where the E(X^2)-E(X)^2 comes in since this is Var(X). I just don't see it
Comment: Your last $Y+E(Y)$ should actually be a $Y\color{blue}{-}E(Y)$. If you expand that, you should be able to factor the terms, notice a few perfect squares and get something in the form

$$\text{E}\left[(X-\mu_X)^2 - (Y-\mu_Y)^2\right],$$
which is a difference of variances!
Answer: Use the bilinearity of covariance. We have
$$\begin{align}\text{Cov}(X+Y,X-Y)&=\text{Cov}(X,X-Y)+\text{Cov}(Y,X-Y)\\
&=\text{Cov}(X,X)-\text{Cov}(X,Y)+\text{Cov}(Y,X)-\text{Cov}(Y,Y).\end{align}$$
Remark: We used an approach somewhat different from the one you suggested, because of its greater  smoothness. However, if you calculate
$$E((X+Y)(X-Y))-E(X+Y)E(X-Y)$$
by expanding and using the linearity of expectation, things will turn out well.
Comment: so then would -Cov(X,Y)+Cov(Y,X) just cancel out? @AndreNicolas
Comment: Yes, $\text{Cov}(U,V)=\text{Cov}(V,U)$.
Comment: I redid it the way you mentioned it and it was way easier and cleaner. Thank you
Comment: You are welcome. The other way is more complicated, but not by much.


How do I know when Hooks are called and in what order?

Question: I want to alter a HTTP header and I am looking for the appropriate hook to use.  I can tell a general time of when some hooks are called but not exactly when.  How do I know exactly when hooks are called, and what hook I should be using to change my header?
edit:  I have managed to change my HTTP header. But something else is adding to my header and that is taking precedent over my header portion.  Is there a way to know where this is coming from?
Comment: The simplest way would probably be to fire up XDebug and put breakpoints in [`ModuleHandler::invoke`](https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Extension%21ModuleHandler.php/function/ModuleHandler%3A%3Ainvoke/8) and [`ModuleHandler::invokeAll`](https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Extension%21ModuleHandler.php/function/ModuleHandler%3A%3AinvokeAll/8)
Comment: https://api.drupal.org/api pages for hooks also show where hooks are invoked from which can be useful in some cases.
Comment: @rooby I am looking on the page and thats where I am finding my hooks, but I dont see a tree or hierarchy of hooks or anything.  They seem to be sorted alphabetically
Comment: You have to search for the hook you are interested in (for example hook_theme), then look for the collapsed fieldset that lists invocations of the hook, then you can follow the links in that fieldset.
Answer: You're looking for an event, not a hook to do this in 8.x
Specifically, you're looking for the RESPONSE event, see \Drupal\Core\EventSubscriber\AnonymousUserResponseSubscriber for an example. Create a class like that, register it in yourmodule.services.yml and then do whatever you want with the $response object.
Comment: How do I create a class like this?  Do you mean I would define the class in my .module file?  or is it in the service.yml file?  I am not sure what all is necessary in the module.services.yml file?
Comment: You need to create the class in the src/ folder of your module, according to the PSR-4 standards, like every other class as well. In services.yml, you need to register it. Look at core.services.yml, search for AnonymousUserResponseSubscriber, then use the definition there as an example.


Dovecot authenticate against Active directory cant send to users that was in aliases

Question: I use Dovecot and sendmail on centos 6, it authenticates against my Server 2012 R2 Domain. I can log in with all user accounts but I have problems with two users sales and info that was getting send to root.
I removed them from /etc/aliases and ran newaliases whic solved the mail going to root but now those two emails give user unknown errors when I mail them.
The Username for sales in the AD is Sales and email is email@example.com when I email it tells me user does not exist.
info username in AD is Operations and email is email@example.com the email to firstname.lastname@example.com gets send but then bounces back user unknown
[root@sogo domain.com]# cat /etc/dovecot-ldap.conf
hosts = CB2012r2DC:3268
dn = cn=Administrator,cn=Users,dc=cb,dc=local
dnpass = password
ldap_version = 3
base = dc=cb,dc=local
scope = subtree
auth_bind = yes
user_attrs = sAMAccountName=user
user_filter = (&(ObjectClass=person)(sAMAccountName=%u))
pass_filter = (&(ObjectClass=person)(sAMAccountName=%u))
pass_attrs = sAMAccountName=user

[root@sogo dovecot]# cat dovecot.conf
disable_plaintext_auth = no
info_log_path = /var/log/dovecot_lda.log
log_path = /var/log/dovecot_lda.log
log_timestamp = "%Y-%m-%d %H:%M:%S "
mail_gid = 500
mail_location = maildir:/home/vhostmail/domain.com/%u/Maildir
mail_privileged_group = mail
mail_uid = 500
mail_debug = yes
mail_plugins = acl
managesieve_notify_capability = mailto
managesieve_sieve_capability = fileinto reject envelope encoded-character vacation subaddress comparator-i;ascii-numeric relational regex imap4flags copy include variables body enotify environment mailbox date
#auth_verbose = yes
#auth_debug = yes
#auth_debug_passwords = yes

passdb {
  args = /etc/dovecot-ldap.conf
  driver = ldap
}
protocols = imap pop3 sieve
service auth {
  unix_listener auth-client {
    mode = 0600
  }
  unix_listener auth-master {
    group = vhostmail
    mode = 0600
    user = vhostmail
  }
  user = root
}
service imap-login {
  user = dovecot
}

protocol imap {
  mail_plugins = $mail_plugins imap_acl
}

service pop3-login {
  user = dovecot
#  mail_plugins = acl imap_acl
}
ssl = no
userdb {
  args = /etc/dovecot-ldap.conf
  driver = ldap
}
protocol lda {
  auth_socket_path = /var/run/dovecot/auth-master
  hostname = localhost
  mail_debug = yes
  info_log_path = /var/log/dovecot_lda.log
  log_path = /var/log/dovecot_lda.log
  mail_plugin_dir = /usr/lib/dovecot
  mail_plugins = sieve
  postmaster_address = email@example.com
  sendmail_path = /usr/lib/sendmail

}

service managesieve-login {
  user = dovecot
  inet_listener sieve {
  port = 4190
}

protocol sieve {
#managesieve_logout_format = bytes=%i/%o
#managesieve_implementation_string = Dovecot Pigeonhole
#managesieve_implementation_string = Cyrus timsieved v2.2.13

}

}
plugin {
  # Used by both the Sieve plugin and the ManageSieve protocol
  sieve = /home/vhostmail/domain.com/%u/.dovecot.sieve
  sieve_dir = /home/vhostmail/domain.com/%u/sieve

}

bounced mail only if you send to info, sales never gets one
The original message was received at Sat, 24 Sep 2016 16:20:22 +0200
from localhost.localdomain [127.0.0.1]

  ----- The following addresses had permanent fatal errors -----
<email@example.com>
    (reason: User unknown)

   ----- Transcript of session follows -----
550 5.1.1 <email@example.com>... User unknown

Reporting-MTA: dns; sogo.domain.com
Received-From-MTA: DNS; localhost.localdomain
Arrival-Date: Sat, 24 Sep 2016 16:20:22 +0200

Final-Recipient: RFC822; firstname.lastname@example.com
X-Actual-Recipient: RFC822; email@example.com
Action: failed
Status: 5.1.1
Diagnostic-Code: X-Unix; 67
Last-Attempt-Date: Sat, 24 Sep 2016 16:20:23 +0200

I send one email from firstname.lastname@example.com to firstname.lastname@example.com and one from email@example.com to firstname.lastname@example.com
here is the mail logs
Sep 24 19:08:19 sogo sendmail[1579]: u8OH8IGB001579: from=     <firstname.lastname@example.com>, size=772, class=0, nrcpts=1, msgid=<269-57e6b300-f-   26620080@66074461>, proto=ESMTP, daemon=MTA, relay=localhost.localdomain   [127.0.0.1]
Sep 24 19:08:20 sogo sendmail[1581]: u8OH8IGB001579: to=  <email@example.com>, delay=00:00:01, xdelay=00:00:00, mailer=dovecot,   pri=120772, relay=dovecot, dsn=5.1.1, stat=User unknown
Sep 24 19:08:20 sogo sendmail[1581]: u8OH8IGB001579: u8OH8KGB001581: DSN:  User unknown
Sep 24 19:08:20 sogo sendmail[1581]: u8OH8KGB001581: to= <firstname.lastname@example.com>, delay=00:00:00, xdelay=00:00:00, mailer=dovecot,  pri=32017, relay=dovecot, dsn=5.1.1, stat=User unknown
Sep 24 19:08:21 sogo sendmail[1581]: u8OH8KGB001581: u8OH8KGC001581: return  to sender: User unknown
Sep 24 19:08:23 sogo sendmail[1581]: u8OH8KGC001581: email@example.com,   delay=00:00:02, xdelay=00:00:02, mailer=relay, pri=33041,   relay=mail.mail.com. [x.x.x.x], dsn=2.0.0, stat=Sent   (u8OH8MqY017480 Message accepted for delivery)
Sep 24 19:10:23 sogo sendmail[1604]: u8OHAMNp001604:   <email@example.com>... User unknown
Sep 24 19:10:23 sogo sendmail[1604]: u8OHAMNp001604: from=  <firstname.lastname@example.com>, size=0, class=0, nrcpts=0, proto=ESMTP,   daemon=MTA, relay=localhost.localdomain [127.0.0.1]

Comment: Please add the bounce messages and log output for sendmail/dovecot, otherwise the issue can hardly be analyzed.
Answer: Ok so both my problems were in /etc/mail/virtusertable
I had a entry there for sales that should not have been there
email@example.com  sales

then for info I should have had a entry as the username in AD is not same as the email address
firstname.lastname@example.com    email@example.com

Problem solved happy days!


A problem related to Toeplitz operator

Question: I am learning the Toeplitz operator theory and I encounter a problem.
First, I need to introduce some definitions.
Definition: $T$ is the circle in $\mathbb C$, we have $C(T)$, and $\mathcal H=L^2(T)$ with its special orthonormal basis $\{e_n\}_{n=-\infty}^\infty$, whose elements are also viewed as elements of $C(T)$. For each $f\in C(T)$ $(\text{or even $f\in L^\infty(T)$}\,)$ we let $M_f$ denote the corresponding point wise multiplication operator on $\mathcal H$. Let $P$ denote the projection onto the subspace of $\mathcal H$ spanned by $\{e_n\}_{n=0}^\infty$. For each $f\in C(T)$ $(\text{or even $f\in L^\infty(T)$}\,)$ the corresponding Toeplitz operator, $T_f$, on $P\mathcal H$ is defined by $T_f=PM_FP$.
Questions:
$1.$ Show that for $f\in C(T)$, if $T_f$ is invertible, then $M_f$ on $\mathcal H$ is invertible.
I have a hint saying that, first let $c=\vert\vert T_f^{-1}\vert\vert^{-1}$, and then show that for each $n\in \mathbb Z$ and each $\zeta\in P\mathcal H$ we have $\vert\vert M_fM_{e_n}\zeta\vert\vert\ge c\vert\vert \zeta\vert\vert$, and finally let $\mathcal H_n=M_{e_n}P\mathcal H$, and show that $\cup_{n=-\infty}^0\mathcal H_n$ is dense in $\mathcal H$.
I am not quite familiar with the theory and can not recover the whole proof. Can someone help me recover the proof?
$2.$ Use the result of $1$ to prove that for each $f\in C(T)$ we have $\vert\vert T_f\vert\vert=\vert\vert M_f\vert\vert$.
As for $2$, I also have no any clue. Any hint and answer to problem $2$ will be helpful and I will be so grateful.
Thanks!
Answer: I can try to provide some hints.
I assume you mean that $e_n(z) = z^n$. Then $M_{e_n}$ is an isometry on $L^2(T)$, and it of course commutes with $M_f$, so that for any $\zeta \in \mathcal{H}$ you have $$\|M_f z^n \zeta \| = \|M_f M_{e_n} \zeta\| = \|M_{e_n}M_f \zeta \| = \|M_f \zeta \| \geq \|PM_f \zeta \| = \|T_f \zeta \| \geq c \| \zeta \|.$$ The point now is that the elements of the form $z^n\zeta, \zeta \in \mathcal{H}$ are clearly dense in $L^2(T)$. This is easy to see from Fourier expansions and Parseval's formula. Thus the inequality $\|M_f \zeta\| \geq c \|\zeta\|$ actually holds for all $\zeta \in L^2(T)$. This then easily implies that $f$ is bounded from below, i.e, $|f(z)| > c$ for all $z \in T$. Then $1/f \in C(T)$, and the inverse of $M_f$ is $M_{1/f}$.
As for the second part, I would use a contradiction argument. It is clear that $\|T_f\| \leq \|M_f\|,$ because $\|T_f \zeta\| = \|PM_f \zeta\| \leq \|M_f \zeta\|$. On the other hand, if it would be so that $\|T_f\| < \|M_f\|$, then consider $\lambda \in \mathbb{C}$ such that $\|T_f\| < |\lambda| < \|M_f\|$. It is easy to show that the spectrum of $M_f$ on $L^2(T)$ is just the range of the function $f$, and that the norm of $\|M_f\|$ equals the supremum norm of $f$, so we can arrange $\lambda$ to be in the range of $f$. Now, since $|\lambda| > \|T_f\|$, we know that the operator $T_f - \lambda = T_{f - \lambda}$ is invertible. By the first part, $M_{f - \lambda}$ is invertible. But this is a contradiction, since $0$ is in the range of $f - \lambda$, so $M_{f-\lambda}$ should not be invertible.
Comment: Thanks Malman, I will check it tomorrow :)

A problem related to Toeplitz operator


Area and Integral of step functions in Tom Apostol's Calculus vol. $1$

Question: At the beginning of the section $1.18$ of Tom Apostol's Calculus vol $1.$ (second edition), it is written that from the area properties introduced in section $1.6$, he proved that the area of the ordinate set of a nonnegative step function is equal to the integral of the function.
However, in the section $1.12$, where he is defining the integral for step functions, he just says that the definition is made such that the integral is equal to the area of the function's ordinate set, but I do not see any proof for that later.
Is there a proof maybe in an earlier version of the book, and it was removed from the second edition (which is the one I have)? In particular, I would be interested to see the proof that the step function integral satisfies the exhaustion property (i.e. Axiom $6$ of an area function).
Thank you!
Answer: I still didn't find the proof in the book, but it seems it could be derived from the Additive and the Choice of scale properties, which are the axioms of an area function. Namely:

Any rectangle is measurable and has area $a(R) = hk$ (by Property 5).
A set of rectangles is also measurable and has the area which is the sum of the areas of the individual rectangles (by Property 2).

The definition of the integral of a non-negative step function is the sum of the areas of individual rectangles, which fits in the Property 2. Therefore, by being the part of the assumed area function, the integral of the non-negative step functions also satisfies the other properties too, including the exhaustion property.
Please let me know if I went wrong somewhere.


Koa Server-sent Events yields only errors to EventSource in browser

Question: I've got a Koa Node server which I'm trying to send server-sent events from. However I'm only seeing the EventSource.onerror callback being invoked when the events arrive.
Here is my SSE implementation:
import * as Koa from 'koa';
import { PassThrough } from 'stream';
import { KoaServerSentEvent } from './koaServerSentEvent';

export class KoaServerSentStream {
  private readonly eventStream: PassThrough;
  private readonly retryInterval: number;
  private eventCount: number;
  readonly request: Koa.Request;
  readonly response: Koa.Response;

  constructor( req: Koa.Request, resp: Koa.Response ) {
    this.retryInterval = 10000;
    this.eventCount = 0;
    this.eventStream = new PassThrough();
    this.request = req;
    this.response = resp;
    this.configureLifecycle();
  }

  static buildStreamContext( ctx: Koa.Context ): KoaServerSentStream {
    const stream: KoaServerSentStream = new KoaServerSentStream( ctx.request, ctx.response );
    // order matters here: https://github.com/koajs/koa/issues/1120
    ctx.body = stream;
    ctx.type = 'text/event-stream';
    ///////////////////////////////////////////////////////////////
    return stream;
  }

  private configureLifecycle(): void {
    this.request.req.on( 'close', this.response.res.end );
    this.request.req.on( 'finish', this.response.res.end );
    this.request.req.on( 'error', this.response.res.end );
    this.eventStream.write( `retry: ${this.retryInterval}` );
  }

  queueEvent( event: KoaServerSentEvent ): void {
    const formattedData: string = ( typeof event.data === 'string' ) ? event.data : JSON.stringify( event.data );
    const payload: string = `id: ${this.eventCount}\nevent: ${event.name}\ndata: ${formattedData}`;
    this.eventStream.write( payload );
    this.eventCount++;
  }

  publish(): void {
    this.eventStream.write( '\n\n' );
  }
}

POC RouteHandler:
export async function handler( ctx: Koa.Context ): Promise<void> {
  const stream: KoaServerSentStream = KoaServerSentStream.buildStreamContext( ctx );
  setInterval( () => {
    stream.queueEvent( {
      name: 'greetings',
      data: {
        french: 'bonjour tout le monde',
        english: 'hello world',
        german: 'hallo welt',
        spanish: 'hola mundo'
      }
    } );
    stream.publish();
  }, 2000 );
}

When I try to consume these events in a browser using:
            const events = new EventSource( 'http://localhost:3000/v1/helloWorld' );
            events.onmessage = ( e ) => {
              console.log( 'We received an event!', e );
            };

            events.onerror = ( error ) => {
              console.error( 'An error occurred:', error );
              console.info( 'ReadyState', events.readyState.valueOf() );
              // events.close();
            };

            events.onopen = ( opened ) => {
              console.info( 'Opened:', opened );
              console.info( 'ReadyState', events.readyState.valueOf() );
            };

The output from this is

Opened: Event {isTrusted: true, type: "open", target: EventSource, currentTarget: EventSource, eventPhase: 2, …}
ReadyState 1
An error occurred: Event {isTrusted: true, type: "error", target: EventSource, currentTarget: EventSource, eventPhase: 2, …}
ReadyState 0
Opened: Event {isTrusted: true, type: "open", target: EventSource, currentTarget:
  EventSource, eventPhase: 2, …}
ReadyState 1
An error occurred: Event {isTrusted: true, type: "error", target: EventSource, currentTarget: EventSource, eventPhase: 2, …}
ReadyState 0
...
Answer: I was able to start successfully processing events by properly assigning the stream object to the Koa ctx.body object.
static buildStreamContext( ctx: Koa.Context ): KoaServerSentStream {
    // ...
    ctx.body = stream;
    ctx.type = 'text/event-stream';
    // ...
  }

should have been:
static buildStreamContext( ctx: Koa.Context ): KoaServerSentStream {
    // ...
    ctx.body = stream.eventStream;
    ctx.type = 'text/event-stream';
    // ...
  }

Hopefully this can help someone!


Mass-adding user fields using Bulk Creator

Question: I am new to open atrium and Drupal and I am building a new site to manage volunteers. I have about 200 fields to add to my users' profiles (So new fields below password, picture, display name, etc...)
Doing this from the Administration » Configuration » People » Account parameters panel will be a cumbersome process so I want to avoid it and instead use a script to create all my fields. This is the best approach because all those fields are very similar, they are there to store multiple integer values for all days within 5 weeks (Notably catering information : number of meals for morning/noon/evening)
After a few researches, I found this module which seems to do exactly what I want : Bulk Creator
The issue is that I don't really understand how I can specify that the fields I want to add are related to user profile. The only way I can think off is to specify it in the content_type parameter, however I can't find any content type related to users in the configuration.
Any other solution to batch create my hundreds of user fields is welcome. I've thrown an eye to the DB tables in order to do it using SQL instructions, but I quickly understood that it was not a good idea :)
Comment: Are you 100% sure you will have to attach 200 fields to one entity? Drupal for sure will not like it... Loading one user would perform an SQL join over all those fields (each field gets is own table). Since you mention fields are similar, perhaps look into [field collections](https://www.drupal.org/project/field_collection). Add a field collection field to the user allowing 5 (or unlimited) values, and then add all repeating fields into a collection? It is lighter for Drupal and now you'd have to create way less fields.
Comment: I am sure of nothing. As I specified, I am new to Drupal. Atm I am exploring the possibilities offered by Open Atrium in order to migrate my old PHP site to this new platform. It should be able to handle those 200 fields at user level in order to be a good candidate, and your answer tends to show that it is not the case. I will look into the field collection option then. Thanks
Comment: You can add the field collections module to open atrium, no problem there. If you can explain the fields you have to create more, I might be able to help you better. (are they indeed repeating, etc)
Comment: It's for a music festival. Our workers/volunteers (500 persons) are there for max 5 weeks (some only one week, other 4...). They will register on the new  site and for each day they have to specify if they take their meal at the catering, for possibily 3 lunches a day (breakfast, noon ,dinner), and since they might register for other people it should not be a boolean but rather an integer value. Other daily fields are there  to reserve a room or just signal their presence. All this is thus repeatable for each day within 5 weeks. You know everything :)
Comment: No need to say that admins should be able to extract easily accurate lists from this information entered by users.
Answer: Rather than creating 200 fields on one entity (this will definitely slow down Drupal), you could group the repeating fields using field collections.
Since you mention there are several fields per day, I'd combine all similar fields into a collection.
So start of with the user and add a field collection field which you name 'weeks' or something and configure it to take 5 values (one for each week).
Now edit the newly created field collection (admin > structure > field collections) and add a new field collection which you name 'days'. This field can contain 7 values.
Again, edit the created field collection and add all fields you need for one day. So one field for the room, one for the amount of breakfasts, etc.
You now have a structure like this:
User
  - 5 week field collection
    - 7 days field collection
      - room
      - # of breakfasts
      - ...

This is structure you can create by hand it would be about 10 fields.
Reading and printing the data can be easy done with views, but there are quite some tutorials out there already. If you can't figure it out, feel free to ask a new question.
Comment: I see. Sounds like an elegantly structured approach :) I will look into it tonite. I am just a bit worried about this : _Drupal 8 Versions Paragraphs is likely to replace field collection for Drupal 8. Field collection is on its way to being deprecated._ Open Atrium is running on Drupal 7 but wont for life. So it looks like a risk that my data wont be exploitable anymore after the next big upgrade and that i would have to rebuilt everything differently... nope?
Comment: Good point never noticed that. Considering the 170k sites there will likely be some sort of migration path. If you prefer to use paragraphs instead, it works pretty similar to this. The order of actions is only a bit different; you should create the paragraph type first and then add it as a field.
Comment: I started with field collection. It looks promising ! I only have a major issue atm: I see no way to adapt the label of each occurrence. So I end up with tons of fields but we have no idea for which day it is. Is there a way to setup different labels for each occurrence of weeks and days?  In my actual PHP application, those labels are generated dynamically to match the exact date in format `ddddd dd/mm`, based on the festival start date which is a parameter in our control panel. Ideally I should achieve the same thing here otherwise that won't be practical...
Comment: You would not have been able to achieve that with 200 fields either ;) (Writing a longer response)
Comment: yes I would with some PHP kung fu^^  Not sure how but I would lol. So you see no simple way to do this?
Comment: The disadvantage of field collection is that you cannot reference the same collection more than once (each field is one collection). If you would use paragraphs, you could use distinct paragraph fields (eg. 7 fields for the days in the week) that all refer to the same paragraphs bundle. You could label them with the days of the week. For the weeks you could label them something like `Week x - april x - april y`. Additionally you could use [field_group](https://www.drupal.org/project/field_group) to wrap every week field in a collapsible group, so users can open close every week individually.
Comment: Roger. In the meantime I read [this answer](http://drupal.stackexchange.com/questions/188532/field-collection-vs-paragraphs) and I would have better to mix both modules in order to take advantage of what each of them has to offer. Thank you for the support anyway that helped me a lot. I would be pleased to help you on the SQL tag over SO if you lurk there as well :)
Comment: Have not been there for a long time ;) Good luck implementing!


Decoding base64 after stripping padding

Question: I am stripping the padding from the end of of a base64 encoded string. I have found that I can successfully decode the string without adding the padding back on first (in php at least). Is this a result of the specification of base64 or implementation dependent?
And a related question, can a = sign exist in a base64 encoded string other than as padding, i.e. If it is not implementation dependent, is it safe just to strip the trailing equals signs or is it possible that the last "real" character could have been one?
Answer: While padding isn't necessary to decode a base64 string, there are some implementations that will throw an error if the padding has been stripped away.
The RFC states:
Implementations MUST include appropriate pad characters at the end of
   encoded data unless the specification referring to this document
   explicitly states otherwise.

The = character will only ever be used for padding.

Decoding base64 after stripping padding


Expanded row getting collapsed on state update on react-table

Question: How to stop the expanded React-Table row from collapsing on state change in-class component.
Please find the code link here https://codesandbox.io/s/agitated-dubinsky-t0hcn?file=/src/nestead-table/index.js
on selecting or unselecting the checkbox (state update) the expanded row is getting collapsed please help me in solving this.
I have tried the below code. it's kept opening that nested row but inside the subcomponent nested table didn't show up (Please find below first image).... didn't work for me as it's a nested table. followed some documents https://react-table.tanstack.com/docs/api/useExpanded no luck!
here is the code which I have tried.
return (
    <ReactTable
      data={data}
      columns={columns}
      className='-striped -highlight'
      minRows={0}
      defaultPageSize={PAGE_SIZE}
      showPagination={data && data.length > PAGE_SIZE ? true : false}
      expanded={this.state.expanded}
      SubComponent={(row) => {
        // get current active key which needs to be expanded (triggered by clicking on a td element)
        const currentExpandedKey = currentExpandedKeys[row.index];
        let columnData = [];
        console.log('currentExpandedKey------------------', currentExpandedKey, this.state.expanded);
        return (

              {keyMaps[currentExpandedKey] || currentExpandedKey}

            {this.renderByData(
              row.original[currentExpandedKey],
              keyMaps,
              onCellDisplay
            )}

        );
      }}
      // onExpandedChange={(newExpanded, index, event) => {console.log('onExpand', newExpanded, index, event)}}
      getTdProps={(state, rowInfo, column, instance) => {
        return {
          onClick: (e, handleOriginal) => {
            // used to identify which column is expanding
            if (column.expander) {
              const expanded = { ...this.state.expanded };
              expanded[rowInfo.viewIndex] = this.state.expanded[rowInfo.viewIndex] ? false : true;
              console.log('expanded-----', expanded)
              this.setState({ expanded: expanded });
              currentExpandedKeys[rowInfo.index] = column.id;
              console.log('currentExpandedKeys-----', currentExpandedKeys);
            }

            // IMPORTANT! React-Table uses onClick internally to trigger
            // events like expanding SubComponents and pivots.
            // By default a custom 'onClick' handler will override this functionality.
            // If you want to fire the original onClick handler, call the
            // 'handleOriginal' function.
            if (handleOriginal) {
              handleOriginal();
            }
          }
        };
      }}
    />
  );

With the above code, I am getting below output.

looking for the following output.

Thanks in Advance.
Comment: Please include what you have tried doing already. Else, it shows a lack of effort from your side in asking the question. Please read: https://stackoverflow.com/help/how-to-ask
Comment: @ZameerHaque I have added what I have tried. please help me in solving this thank you.
Comment: No, you haven't, you linked to an external site.  You need to put your code in the question as text.  See [mre].
Answer: in the useTable() table options, set autoResetExpanded: false. This fixed the problem for me.
You can also take a look at the documentation:
Info about the autoResetExpanded option: https://react-table.tanstack.com/docs/api/useExpanded
How do I stop my table state from automatically resetting when my data changes?: https://react-table.tanstack.com/docs/faq#how-do-i-stop-my-table-state-from-automatically-resetting-when-my-data-changes
Answer: I'm using session storage to cache the expanded row, therefore after update it stays open.
{
  JSON.parse(sessionStorage.getItem(row.id) || "false") || row.isExpanded ? (

              Name

Text

  ) : null;
}


bash command with shell scripting doesn't work

Question: when I start ubuntu server 14 I must start bearerbox and smsbox.
The commands are:
bearerbox -v 0 /etc/kannel/kannel.conf

and
smsbox -v 0 /etc/kannel/kannel.conf

The first command block the shell soo for start smartbox I need open new shell.
(The second command also block the second shell too)
I've tried to use:
bearerbox -v 0 /etc/kannel/kannel.conf &
smsbox -v 0 /etc/kannel/kannel.conf &

But bearerbox and smsbox doesn't work.
I've also tried to create a shell script like:
#!/bin/sh
bearerbox -v 0 /etc/kannel/kannel.conf
smsbox -v 0 /etc/kannel/kannel.conf

And start it with ./start.sh but doesn't work.
Someone can help me please?
Comment: I do not know kannel. Does starting it with nohup helps (`nohup bearerbox -v 0 /etc/kannel/kannel.conf > /tmp/bearartrace.log 2>&1 &`) ?
Comment: if i use

nohup bearerbox -v 0 /etc/kannel/kannel.conf &

nohup bearerbox -v 0 /etc/kannel/kannel.conf &

In the terminal It worsk, but if I create a script with only this 2 rows doesn't work
Comment: "doesn't work" isn't enough information to debug, well, _anything_.
Answer: Try a script running with bash and starting with :
#!/bin/bash
nohup bearerbox -v 0 /etc/kannel/kannel.conf > /tmp/bearer.out 2>&1 &
nohup smsbox -v 0 /etc/kannel/kannel.conf > /tmp/smsbox.out 2>&1 &

In /tmp you should find files that might explain possible problems.
When those files don't get created/show nothing, you might want to debug with echo:
#!/bin/bash
nohup echo bearerbox -v 0 /etc/kannel/kannel.conf > /tmp/bearer.out 2>&1 &
nohup echo smsbox -v 0 /etc/kannel/kannel.conf > /tmp/smsbox.out 2>&1 &

When all is clear, redirect to /dev/null:
#!/bin/bash
nohup bearerbox -v 0 /etc/kannel/kannel.conf > /dev/null 2>&1 &
nohup smsbox -v 0 /etc/kannel/kannel.conf > /dev/null 2>&1 &

(and remove the /tmp files)


Mockito-Android Testar retorno do método

Question: Estou tentando testar um retorno de um método da minha classe em um projeto Android. Estou fazendo desta maneira:
MyClass var = Mockito.mock(MyClass.class);

Com isto, eu já tenho minha instância. Agora eu preciso testar métodos desta minha classe, eu fiz desta maneira:
Mockito.doCallRealMethod().when(var).loadTexture("back.png")

O retorno está sempre vindo null. Porém a imagem existe e não era para estar retornando null...
Comment: tente Mockito.when(var.loadTexture("back.png")).thenCallRealMethod() e fala se acontece algo.
Comment: O teste passa com sucesso independente do valor que eu passo no `loadTexture("blablabla");`
Answer: O problema é que você está tentando testar uma classe "Mockada", ou seja, você não está testando a classe real e sim uma instancia "default" dela. Por isso que quando você dá loadTexture() é retornado null.
Os mocks devem ser utilizados para representar objetos externos e que são necessários para a execução de métodos de uma classe. Por exemplo:
public class MinhaClasseA{

    private MinhaClasseB mcB;

    public MinhaClasseA(MinhaClasseB mcB){

        this.mcB = mcB
    }

    public int fazAlgumaCoisa(){

        return mcB.fazOutraCoisa();
    }
}

public class MinhaClasseB{

    public int fazOutraCoisa(){

        return 10;
    }
}

Nesse caso, percebe-se que a classe A tem uma dependecia da classe B, portanto, se você quisesse testar a classe A, você teria que criar um Mock da classe B e explicitar quais valores ela retorna, ou seja, você diria o comportamento da classe B e depois você verificaria se o a classe A age corretamente conforme recebe os dados de B.
Exemplo:
MinhaClasseB mcBMock = Mockito.mock(MinhaClasseB.class);
MinhaClasseA mcA = new MinhaClasseA(mcBMock);

int intMock = 10;

when(mcBMock.fazOutraCoisa()).thenReturn(intMock);

assertEquals(mcA.fazAlgumaCoisa(),intMock);

Nesse caso, você está dizendo que quando o método fazOutraCoisa() de B for chamado, ele deve retornar 10 para quem o chamou ( a classe A). Portanto ao usar o assertEquals você quer saber se a classe A realmente está recebendo o valor de retorno do método fazOutraCoisa de B.


What does this figure in "Introduction to statistical learning" mean?

Question: I am currently reading the book "Introduction to statistical learning" and on Page 3 there is a problem statement regarding the SMarket data (stock exchange data) fig 2.2 whose left panel states the relation shown is the percentage vs up/down trend of stock market. But here Author is saying that one box for 648 days and one for 602 days.
I don't quite get that. There is no information given for the days. Is the print faulty or am I missing something here? If someone has gone through the book and has any idea, please help me to understand the following chart.
Comment: perhaps he means the number of data points represented in each box plot?
Answer:
The left-handed panel of Figure 1.2 displays two boxplots of the previous day's percentage changes in the stock index: one for the 648 days for with the market increased on subsequent days, and one for the 602 days for which the market decreased.

The blue boxplot of the left-most figure is based on data from 648 days. These days are not randomly chosen, they are selected because they have a special characteristic: the day after the market increased. The red boxblot in the left-most figure is based on 602 days for which the market decreased the day after.
In short, the red and blue boxplot visualize multiple datapoints.
Answer: The leftmost Boxplot says:
There has been 602 days(data points) for which the market value on the previous day decreased. For those observations, we measure the percentage change in market value on the subsequent day, and we plot it (Blue boxplot).
As you can see, although for all such observations the market change on the day before was negative, on the subsequent day, their average percentage return was positive (box plot mean is above zero).
The analogous logic is applied for the 643 days(data points) for which the market value on the previous day increased (Red Boxplot).

What does this figure in “Introduction to statistical learning” mean?


Python paho MQTT loop_forever(): how to redirect output to a file while the script is running?

Question: I'm running a script to subscribe to topics of an MQTT broker and fetch the data associated to them. I run the script like this:
$ python3 test_mqtt_client.py
import paho.mqtt.client as paho
import ssl
import random

from config import BROKER_ADDRESS, PORT, CLIENT_CERT, CLIENT_KEY, CA_KEY, SUBSCRIBED_TOPICS, DEST_FOLDER

#"on_message" callback
def on_message(client, userdata, message):

  print("received message =",str(message.payload.decode("utf-8")))

  filename = str(random.randint(0,4294967295))

  file = open(DEST_FOLDER + filename + '.json', 'w+')
  file.write(str(message.payload.decode("utf-8")))
  file.close()

client=paho.Client()
client.on_message=on_message

print("connecting to broker")

client.tls_set(
    CA_KEY,
    certfile=CLIENT_CERT,
    keyfile=CLIENT_KEY,
    cert_reqs=ssl.CERT_REQUIRED,
    tls_version=ssl.PROTOCOL_TLSv1_2,
    ciphers=None
)

client.tls_insecure_set(True)

client.connect(BROKER_ADDRESS, PORT, 60)

for x in SUBSCRIBED_TOPICS:
  client.subscribe(x)
  print('Subscribed to topic "' + x + '".')

client.loop_forever()

time.sleep(1)

The problem: if I try to output to a file like this:
$ python3 test_mqtt_client.py >> /tmp/test_mqtt_client.log
I don't get any content on the file untill I interrupt the script using Ctrl+C.
How can I get the output of the script inside /tmp/test_mqtt_client.log while the script is running? I mean, before interrupting it.
Answer: By default, output to stdout is buffered: that means it's not actually flushed to a file until the output buffer is full, which in turns means that when redirecting stdout to a file, you often won't see anything in the file until your code generates sufficient output to overflow the output buffer.
There are various ways of dealing with with this behavior:

Just output to stderr instead of stdout. stderr is not buffered by default and you should see output immediately. This is the  default behavior of e.g. the logging module, which is generally a better idea than print for logging output from long-running programs. You can, of course, just set file=sys.stderr in your print command instead:
print("this is a test", file=sys.stderr)

(If you do this, remember to redirect stderr instead of stdout on the command line.)

You can run Python in unbuffered mode by adding the -u flag to the command line:
python -u test_mqtt_client.py >> test_mqtt_client.log

You can explicitly flush the output buffer after each print statement:
print("some log message")
sys.stdout.flush()

Comment: Thanks! the "-u" option works.


How to login by single role if user have multiple roles?

Question: In my latest project client asked me to add extra interface after login where all roles assigned to that user will be shown and user can choose the single role and login by that role only. But i don't know how to do this in drupal. I tried with role switcher and other module but they didn't  work for me ? Any suggestions will be appreciated.
Suppose
User x have roles A B C D
x can choose single role(eg A) after login and do the work only with that role.
Answer:
Create a custom module
Create a custom form where Admin can whitelist users for certain roles .. Form should have  username and roles as a list or checkboxes.
Store these settings in database - uid - roles
When a user logs in redirect user to a form where he can select user roles from above list
On Form Submit, Update user programatically and assign role to the user he selected, remove other roles that user has if any
Comment: After submitting the form the user roles, which user didn't select will be removed from the roles table, so it will not preserve the other roles identity of the user.  I need a solution where role identity must preserve and user must be able to select with other assigned roles next time.
Comment: I am talking about custom form if you read my answer correctly... Where you store user - role data in custom table in Drupal database... So you always preserve that association...


Storing command output in array?

Question: When I am trying to storing ls -ltr *.sh output in an variable it is working fine, But when I am trying to store in array it is throwing me error. How to store the commands output in array, As same as it is storing in variable.

Example(1):

set -A arr $(ls -ltr *.sh)
echo "${arr[@]}"

Error:

-rw-r--r--: bad option(s)

why this error is coming, How this array treating the command ouput. I have tried as below.

Example(2):

set -A arr "$(ls -ltr *.sh)"
echo "${arr[@]}"

Error: here output is coming in single row, And saying badoptions. how to print output of array in line by line.

-rw-r--r--    1 root     system            0 Apr 23 07:06 tt2.sh^J-rw-r--r--    1 root     system            0 Apr 23 07:06 tt1.sh^J-rw-r--r--    1 root     system            0 Apr 23 07:06 test.sh^J-rw-r--r--    1 root     system           49 Apr 23 07:09 tt.sh: bad option(s)
Answer: I know been a while...but just in case.

Bad option can be avoided by using set -A arr -- $(ls -ltr *.sh)

But you'll end up with an array that will store the data not line per line but with a new index each space.

The error with echo (you should use print instead by the way) can be avoided with the same --
I don't know any oneliner that would do what you want. I would do this with a loop myself. Something like that :
#!/bin/ksh

j=0

while read line; do
        array[$j]="$line"
        ((j++))
done <<< "$(ls -ltr *.sh)"

print ${#array[*]}
print -- ${array[2]}

Hope it can still helps

Storing command output in array?


Specific file permissions in .deb

Question: I can create a .deb package successfully with all the file owner fields set correctly. Unfortunately the permission fields are ignores. For example I install one file with:
install -v -cm 400 -o ${user} *.pl ${DESTDIR}${dir}

but all the files in the package are 644 anyways. How can I force different permissions?
Answer: Find the dh_fixperms line in debian/rules (should be in the binary-arch or binary-indep target, as appropriate) and add -Xpath/to/file to that call.
SEE ALSO
dh_fixperms(1)

Specific file permissions in .deb


Exchange 2007: Add email address from another domain to one user

Question: I want to add the email address firstname.lastname@example.com to only one of our users. This is an additional domain and has nothing to do with the existing domain. I set up the MX records accordingly (pointing to our Exchange 2007 server). Now the server has to accept emails from this domain.
From this article I found out that I can add an accepted domain  under hub transport. The user which should receive the mails from firstname.lastname@example.com has already an existing email account. Normally, I add an mail alias to the user easily. This is what I have don yet but only users in the domain can send mails to email@example.com now. If I add the accepted domain all users in the domain will get mails from firstname.lastname@example.com I think.
What is the best solution for me? Can I add an email account from another domain to only one existing user account and how?
Answer: Your users will not receive the new email addresses unless you modify your Email Address Policy to include it.  Just add the new accepted domain and then modify the individual user that you wish to have the new address.


Adding a button in CKEditor for KCFinder

Question: I have CKEditor running with KCFinder integrated and working, but the application will be used by people with little-to-no computing experience and I would therefore like a button in the CKEditor toolbar which looks like the current Image button but jumps straight to KCFinder.
If you imagine looking at CKEditor, clicking "Image" then "Browser Server", I'd like to basically cut out the middle step of CKeditor's initial popup.
Ideally though, users would still be able to right-click on the image and click "Image Properties" to view CKEditor's popup.
Any help appreciated!
Answer: Requires a custom plugin and cannot be accomplished as easily as hoped.


Intercept of logistic regression too high, probability not close to zero

Question: Through an L0 and L2 regularization method I have developed a logistic model that has an intercept of around -3. Taking the exp() of that alone I get a probability of around 5%. So that is when other parameters in the model are zero (they cannot be negative).
My question: Is that wrong for a logistic model ? Should they go from 0 to 1 no matter what, and hence my model is completely wrong, or...?
Comment: Actually your $0.05$ should presumably be interpreted as the odds, with a corresponding probability slightly less; it is certainly possible to have an intercept greater than $0$ and so `exp()` of that greater than $1$ but this again will be the odds rather than probability - if the intercept had been $+3$ then the odds would be about $20.86$ and the probability about $0.9526$.  There is nothing wrong with $5\%$ in a particular case if that reflects reality
Comment: Please specify what "they" refers to in "Should _they_ go from 0 to 1 no matter what...?" Do you know for a fact that the probability of the positive outcome would be 0 when all the parameter values are 0? As a probability of 0 would mean an odds ratio of 0 and an infinitely negative log-odds, if you know that for a fact then you might need to consider a different approach than logistic regression.
Comment: @EdM No, just that it is quantities that are not negative. And not from 0 to 1 either. 0-100 is not uncommon for these parameters at least.
Answer: A few thoughts:

The intercept is the log-odds of a positive class membership when all categorical predictors are at their reference levels and continuous predictors are at values of 0. An intercept of -3 represents odds of 0.05 and a probability of 4.7% at those conditions.
Predictor variables can have any reasonable values. The important trick is making sure that their values are linearly related to the log-odds of class membership.
As a probability of 0 means infinitely negative log-odds, a simple logistic regression model will not be able to handle actual probabilities of 0 adequately. It's possible to have perfect separation in a logistic model, with some combination of predictor values exactly distinguishing cases with probabilities of 0 and 1. In that case penalization of the model coefficients is one way to proceed.
Whether you are penalizing to deal with perfect separation or for other reasons, note that penalization seeks deliberately to trade off increased bias for decreased variance. So if you are using a penalized model you should expect some bias.