Normal distribution transformation with $\phi(x)=x^2$

Question:
Let $X\sim N(\mu,\sigma^2)$ a normal distributed random variable. Let furthermore $\mu=0, \sigma^2=1$ and $\phi(x)=x^2, \phi:\mathbb{R}\to \mathbb{R}_{+}$. Compute the density function of the random variable $\phi \circ X$!

So I know that one can compute with the transformation theorem for density functions. For a random variable $Y$ one has:
$$f_Y(y)=
     \left\{\begin{array}{ll} \frac{f_X(\phi^{-1}(y))}{\phi'(\phi^{-1}(y))}, & y\in Image(\phi) \\
         0, & y\not\in Image(\phi)\end{array}\right. (1) .
  $$
For the density function of the normal distribution one has:
$$f_X(x)=\frac{1}{\sqrt{2\pi}\sigma}\cdot \mathrm{e}^{\left(-\frac{x-\mu}{2\sigma}\right)^2} (2)$$
To use (1) I have to compute $\phi^{-1}(y)$:
$$\phi^{-1}(y)=
\left\{\begin{array}{ll} \sqrt{y}, & y \ge \\
         -\sqrt{y}, & y < 0\end{array}\right. (3).$$
For (2) I get with the given parameter:
$$f_X(x)=\frac{1}{\sqrt{2\pi}}\cdot \mathrm{e}^{-\frac{1}{2}x^2}$$
I put it all together and I get the density function:
$$f_Y(y)=
    \left\{\begin{array}{ll} \frac{1}{\sqrt{8\pi y}}\cdot \mathrm{e}^{-\frac{1}{2}y}, & y\ge 0 \\
    -\frac{1}{\sqrt{8\pi y}}\cdot \mathrm{e}^{-\frac{1}{2}y}, & y<0\end{array}\right. (4).$$
It seemed quite easy, so are there any mistakes?
Comment: The transformation theorem that you wrote only applies under an assumption of monotonicity. Without that assumption you are better off finding the CDF and then differentiating it to find the PDF.
Answer: Consider that $\phi: \Bbb R \to \Bbb R_+$, so $\phi^{-1}: \Bbb R_+ \to \Bbb R$ BUT ofc it's not the true inverse due to the fact that $\phi$ is not injective…
Try by direct calculating, so let $Y = \phi \circ X = X^2$ then $f_Y(x) = F'_Y(x)$ with
$$\begin{align*} F_Y(x) &= P(X^2 \le x) \\ &= P(-\sqrt{x} \le X \le \sqrt{x}) \\ &= F_X(\sqrt{x}) - F_X(-\sqrt{x})\end{align*}$$
So:
$$\begin{align*} f_Y(x) &= F'_Y(x) \\ &= \frac{1}{2\sqrt{x}}\left(f_X(\sqrt{x}) + f_X(-\sqrt{x})\right)\end{align*}$$
Plug in by yourself…
Answer: Ok so the first point the change of variables is given by
$$
\begin{align}
f_{Y}(y) = f_{X}(\phi^{-1}(y) ) \left|\frac{d}{dy}\phi^{-1} \right|,
\end{align}
$$
Now as you noticed we have positive and negative roots where as the change of variable formula as stated just now is for a single monotonic transformation, however the symmetry around $x=0$ means that we can consider the positive and negative sections seperately, so taking the positive square root first we have
$$
\left| \frac{d}{dy}\phi^{-1} (y) \right| = \frac{1}{2}y^{-1/2},
$$
the term for the negative square root is just the same and so we have
$$
\begin{align}
f_Y(y) &= 2 \cdot f_X(\sqrt{y}) \left| \frac{d}{dy} \sqrt{y} \right|\\
&=2\frac{1}{2\sqrt{2\pi}}y^{-\frac{1}{2}} e^{-\frac{y}{2}} \\
&= \frac{1}{2^{1/2}\sqrt{\pi} }y^{-1/2}e^{-y/2} \\
&= \frac{1}{2^{1/2}\Gamma(1/2)}y^{1/2-1}e^{-y/2}
\end{align}
$$
where I have included that last line just to show that this equals the probability density function of a Chi-squared random variable with one degree of freedom which is what we would expect.
Comment: You can't have more than one distribution function, a random variable has a (Cumulative) distribution function and this is unique. If you mean why does it become additive if we have multiple roots of the transformation function then basically you have $P(Y \in A) = \int_{A} f_Y(y) dy = \int_{\phi^{-1}(A)} f_X(x)$, but in this case you can also split the preimage into $\int_{C_1} f_X(s)dx + \int  _{C_2} f_X(x) dx$ where we have disjoint sets $C_1 = {x : x < 0 , \phi(x) \in A }$ and $C_2$ is the equivalent positive part, integrate by substitution to both parts to get the additive form
Comment: Thanks for your answer! Can you explain how you get $\vert \frac{d}{dy} \phi^{-1}(y)\vert$?

And what's the argument for $2\cdot f_X(\sqrt{y})$? Why you multiply with 2?
Comment: Well if a function $g$ is invertible and increasing then speaking about the  Cumulative distribution functions  then we have
Comment: Sorry new here... anyway I'm not sure if you are asking why this is so in this particular case? Or where the argument comes from in general? I think maybe you need to go back and check where you got your formula from, including the division by $\phi^{\prime}(\phi^{-1} (y) )$ term
Comment: Oh, I'm sorry, my question was imprecise, I'm a blockhead! Forget the first question.

Ah, I see. So if one has more than one distribution function for a random variable the density functions behave additive with the argument that $F_X'(x)=f_X(x)$?
Comment: In general if the function $\phi$ has countable many routes you have $f_Y(x) = \sum_i f_X(\phi^{-1}_{i} y ) \left| \frac{d \phi_i^{-1} }{dy} \right|$ but maybe look this up?
Comment: Yes, I look it up, thanks!
Answer: Call $y = x^2$, then the PDF for $y$ can be constructed by realizing that
$$
f_X(x)dx = f_Y(y)dy
$$
or equivalently
$$
f_Y(y) = f_X(x)\left|\frac{dx}{dy}\right|
$$
the absolute value is there to ensure that $f_Y(y) \ge 0$. Since $dx/dy = y^{-1/2}/2$ you have
$$
f_Y(y) = \frac{1}{\sqrt{2\pi y}}e^{-y/2} \tag{1}
$$
Below there's a small simulation of the random variable $Y$. First a generate $10^5$ points following a standard normal distribution and squared them. The blue histogram is the result. The red line is Eq. (1)

Note Since $y=x^2 \ge 0$, there's no need to include the case $y<0$ in your derivation
Comment: @ArghyaChakraborty Indeed, I meant probability distribution function. Thanks
Comment: I am sorry, but i can't see atm why dx/dy=1/sqrt(y).
Since x^2=y => dx/dy=d sqrt(y)/dy= 1/2*1/sqrt(y). What did i get wrong?
Comment: @FeLix You're right, it was just a typo. Thanks for letting me know


How to create a custom file type in c# with a custom icon?

Question: I need the path of x.gdb(.gdb file type) . Which is a folder and contains different type of file. I want to give a custom icon of .gdb folders.
Project Open Window
When a user click the browse button prompts the OpenFileDialog. User select a .gdb folder, the .gdb folder name will show in filename textbox of OpenFileDialog. User click on open button the filepath will show in Project Open Window textbox. If user double click on .gdb file filepath will show in Project Open Window textbox. How can i do this?
Comment: See this: https://msdn.microsoft.com/en-us/library/61097ykx(v=vs.110).aspx
Answer: If you want to see your custom file icon in windows explorer and OpenFileDialog you should set an icon for your file extension in windows registry, Here is a simple .REG file that registers an icon for the file extension .gdb
Windows Registry Editor Version 5.00

[HKEY_CLASSES_ROOT\.gdb]

[HKEY_CLASSES_ROOT\.gdb\DefaultIcon]
@="D:\\icons\\gdb.ico"

For more information about how to register icon for a file type:
https://msdn.microsoft.com/en-us/library/windows/desktop/hh127427(v=vs.85).aspx
https://www.codeproject.com/Articles/29137/Get-Registered-File-Types-and-Their-Associated-Ico


Number of ways to form alternating subsequences of a binary string

Question: There is a binary string S of the form "ababaab"
We have to find the number of ways to form subsequences of the form "ab" * n (where n is natural number)
For example if there is a string "abab" it will have 4 subsequences of the given type :
(1,2) , (3,4) , (1,4) , (1,2,3,4) will form "ab" and "abab"
I thought of calclating the number of "a" before every "b" in the string and then computing the answer from this but it does not work for all possibilities
Is there any way in combinatorics to account for this problem ?
Answer: Here is a procedural approach.  Make an array of the length of your string.  Each entry that corresponds to an $a$ in the original string will get the number of substrings $(ab)*n\ a$ ending with that $a$, where $n=0$ is allowed.  Each entry that corresponds to a $b$ in the original string will get the number of substrings $(ab)*n$ ending with that $b$, where $n=0$ is not allowed.  Start at the first entry.  If it is an $a$, put in $1$.  If it is $b$, put in $0$.  At each subsequent entry, if it is an $a$ put in $1$ more that the sum of the previous $b$ entries.  You can accumulate this as you go so you don't have to add it each time.  If it is $b$ put in the sum of all the previous $a$ entries.  Your final answer is the sum of all the $b$ entries.  This gives an answer in time linear in the length of the string.
Comment: Great solution Ross.


R stacked percentage bar plot with percentage of binary factor and labels

Question: I want to produce a graphic that looks something like this (with percentage and legend) by R:

My original data is:
         AIRBUS BOEING EMBRAER
  2002     18     21      30
  2003     20     23      31
  2004     23     26      29
  2005     22     25      26
  2006     22     25      25
  2007     22     27      17
  2008     21     21      16
  2009     17     19      22
  2010     14     22      24
  2011     17     27      22
  2012     16     22      19
  2013     11     24      19

There are similar questions on SO already, but I seem to lack the sufficient amount of intelligence (or understanding of R) to extrapolate from them to a solution to my particular problem.
Comment: Percentage of what? Do the numbers represent percentage or do you need to calculate the percentage of total each year?
Comment: The numbers are already represent percentage. I need them to be seen on top of the bar, similar to the plot above. Also, I don't know how to add a title for the plot. I have tried:   ggtitle("Departure delays by company and Year") but it's not working. also, I would like to see all the years on axle x and not only 2005 and 2010.
Thank you very much!!! :)
Answer: First, gather or melt your data into long format. Then it's easy.
library(tidyverse)

df <- read.table(
  text = "
  YEAR AIRBUS BOEING EMBRAER
  2002     18     21      30
  2003     20     23      31
  2004     23     26      29
  2005     22     25      26
  2006     22     25      25
  2007     22     27      17
  2008     21     21      16
  2009     17     19      22
  2010     14     22      24
  2011     17     27      22
  2012     16     22      19
  2013     11     24      19",
  header = TRUE
)

df_long <- df %>%
  gather(company, percentage, AIRBUS:EMBRAER)

ggplot(df_long, aes(x = YEAR, y = percentage, fill = company)) +
  geom_col() +
  ggtitle("Departure delays by company and Year") +
  scale_x_continuous(breaks = 2002:2013)

Comment: First, Thank you very much! The numbers are already represent percentage. I need them to be seen on top of the bar, similar to the plot above. Also, I don't know how to add a title for the plot. I have tried: ggtitle("Departure delays by company and Year") but it's not working. also, I would like to see all the years on axle x and not only 2005 and 2010. Thank you :)
Comment: Did you add (`+`) the `ggtitle(...)`? The basics of ggplot are that you add features together. For x axis ticks of course you just use the standard `+ scale_x_continuous(breaks = 2002:2013)`


How can I add the values of some variables given in one data set by the nature of the variables given in another data sets?

Question: Please consider two data sets dat1 and dat2 in the following format.
Dat1:

 x1  x2  x3  x4  x5
 1    3   8   2  10
 2   12   2   9   6

and Dat2:
var     type
x1    discrete
x2     contns
x3    discrete
x4     discrete
x5     contns

I want to add the values of the variables in dat1 by the nature from dat2. In other words, I want to have variables adding values from from dat1  XX=x1+x3+x4 and YY=x2+x5. Can you please suggest me how can I do it in R. Actually, I have few more categories or types of variable.
Answer: Try something like this:
uniquetypes<-unique(Dat2$type)
result<-sapply(uniquetypes, function(curtype){
  rowSums(Dat1[, Dat2$type==curtype])
})

If you have other columns in Dat1, you may need a bit of editing (current code is index based, not based on the name of the column).
Comment: Sorry, had a few glitches. New code should work.
Comment: I needed to modify the code but the idea was same. Thanks.


Fechamento de arquivo

Question: Eu preciso deixar o arquivo livre, sem ficar em uso, pois está barrando. Segue o código:
StringWriter sw = new StringWriter();
XmlTextWriter tw = new XmlTextWriter(sw);

XmlSerializerNamespaces xsn = new XmlSerializerNamespaces();
xsn.Add("", "http://www.portalfiscal.inf.br/nfe");

XmlSerializer ser = new XmlSerializer(typeof(TNFe));
FileStream arquivo = new FileStream("C:\\" + chave_nfe + "-NFe.xml", FileMode.CreateNew);

ser.Serialize(arquivo, nfe, xsn);

Se eu faço:
sw.Close();

O arquivo ainda continua em uso, e não funciona como esperado. E se eu faço:
arquivo.Dispose();

Funciona, só que ele não monitora a pasta, não entendo o porque disso ocorrer, o código de monitoramento é logo em seguida:
 form = new FormProgressBar();
 form.Show();

 int X = 6000;
 form.MaximumBar(X);

 // Faço o laço para atualizar a barra
 for (int i = 0; i < X; i++)
 {
       // Método que atualiza a barra e o texto da barra
       form.AtualizaBarra("Aguarde...");
       // Insiro algum código que desejo e vou mostrando o status da atualização
 }

 // clsdb.ExecutaSQL("insert into nfe (n_nota, chave) values ('" + txtnumero.Text + "','" + digito(chave) + "')");
 messagebox = 0;
 messageboxxml = 0;

 #region MONITORAR PASTA

 //Dizemos agora se é para monitorar os subdiretórios ou não
 fsw.IncludeSubdirectories = false;

 //Através de um Enum dizemos quais eventos devem ser monitorados, modificação da data do arquivo, tamanho, etc...
 fsw.NotifyFilter = NotifyFilters.FileName | NotifyFilters.LastWrite;

 //Dizemos quais tipos de arquivos devem ser monitorados, *.*, *.xml, *.txt, etc...
 //fsw.Filter = "*.xml";
 //fsw.Filter = "*.ERR";

 //Definimos agora os eventos a serem gerados
 fsw.Created += new FileSystemEventHandler(fsw_Created);
 fsw.Changed += new FileSystemEventHandler(fsw_Changed);
 fsw.Error += new ErrorEventHandler(fsw_Error);

 // A propriedade abaixo define que a monitoração deve iniciar, se false, a pasta não será monitorada
 fsw.EnableRaisingEvents = true;

Esse é o código que fica tanto no evento Created ou Changed, ele não executa.
 FileInfo fileinfo = new FileInfo(e.FullPath);

 while (arquivoTravado(fileinfo))
 {
      Thread.Sleep(1000);
 }

 System.Xml.XmlDocument xmldoc = new System.Xml.XmlDocument();

 xmldoc.Load(e.FullPath);

 if (e.FullPath.Length == 97)
 {
     System.Xml.XmlNode DadosLote = xmldoc.SelectSingleNode("DadosLoteNfe");
     System.Xml.XmlNode NumeroLote = DadosLote.SelectSingleNode("NumeroLoteGerado");

     string nlote = NumeroLote.InnerText;
     clsdb.ExecutaSQL("update nfe set num_lote = '" + nlote + "' where n_nota = '" + txtnumero.Text + "'");
  }

Como posso fazer, para que o arquivo fique livre para ser tratado, e que o monitoramento continue funcionando?
Comment: está usando o `FileSystemWatcher` correto ? acredito que esteja usando de forma errada.

Se o arquivo ainda não foi fechado, ele deve estar disparando o evento `fsw_Changed` e aparenta estar funcionando pra você.
Se você fecha o arquivo, ele não irá disparar o evento `fsw_Created` porque o arquivo foi criado antes do evento ser associado ao `fsw`.  Seria bom se colocasse o código completo e sem essas quebras para que possa entender o que realmente está fazendo
Comment: você já tentou usando um bloco `using` ?
Comment: Não, vou tentar. Obrigado.
Comment: Preste atenção na forma que o código deve ser colocado na pergunta para as próximas vezes. Não crie snippets de código para c#, por exemplo.
Comment: Desculpe-me pelo engano.
Answer: Você deve abrir os recursos deforma que ele se fechem sozinho, algo assim:
using (var sw = new StringWriter())
using (var tw = new XmlTextWriter(sw))
using (var arquivo = new FileStream("C:\\" + chave_nfe + "-NFe.xml", FileMode.CreateNew) {
    // ... faz o que deve aqui
}

Em C# 8 já pode fazer:
using var sw = new StringWriter());
using var tw = new XmlTextWriter(sw));
using var arquivo = new FileStream("C:\\" + chave_nfe + "-NFe.xml", FileMode.CreateNew);
// ... faz o que deve aqui

Coloquei no GitHub para referência futura.
Tem erros no uso do formulário no acesso ao banco de dados (se tirar o comentário), mas são outros problemas, ficaria amplo demais responder isso, faça novas perguntas.
O problema do não monitoramento pode estar relacionado ao fato de não ter o arquivo fechado, se não for é um outro problema também, e precisaríamos de mais informações em nova pergunta para ajudar adequadamente, teria que ver como est´pa criando o monitoramento, o que está ocorrendo, como testou, etc.
Comment: Funciona por coincidência, porque não é o jeito correto. Primeiro precisa fazer o uso correto do arquivo e depois ver porque não funciona o monitoramento quando o resto está certo. Mas quando for perguntar sobre isso, certifique-se de colocar todas informações que possam ajudar as pessoas te ajudarem.
Comment: O problema, que quando não uso o close ou dispose, o monitoramento funciona, ele só não funciona quando utilizo. Vou fazer o teste com o using, pra ver se funciona conforme o esperado.
Comment: Tentei da forma que me auxiliou, o using, funciona, gera o arquivo e o libera, porém a pasta não está sendo monitorada, vou atualizar a pergunta com o código de monitoramento.
Comment: Desculpe pelo engano, funcionou sim, só mudei o monitoramento de lugar no código, porque fiz o debug e não estava entrando nele, então foi só mudar, e ficou do jeito que eu precisava, muito obrigado pela ajuda.

Fechamento de arquivo


Integration of $\sin(x)e^{-x^2}$

Question: I recently came across how to $\int e^{-x^2}dx$ by "change of variable". i.e.,
let $I = \int e^{-x^2}dx$
then, $I^2 = \int e^{-x^2}dx\int e^{-x^2}dx$
and changing $x$ to $y$ in one of the integrals above to make it $I^2 = \int e^{-x^2}dx\int e^{-y^2}dy$ and then convert it to polar coordinates, find the integral and take the squate root of the integral.
I think i understand this very well, what I wanted to know is that if I can use the same technique to evaluate $\int \sin(x)e^{-x^2}dx$. I would appreciate if anyone could shed some light on this. Thanks.
Comment: That technique only works to find the _definite_ integral over the entire real line (or half of it). It does not actually yield an indefinite integral for $e^{-x^2}$ in terms of elementary functions.
Comment: The same technique can be used if the question is
$$
\int_0^\infty\cos x\ e^{\Large -x^2}\ dx.
$$
Answer: This is not going to work, since you do not have $\sin x \sin y = \sin xy$, hence the integrand does not factor when expressed in polar coordinates.
Instead, you can calculate this integral is either by complex analysis or by differentiation under the integral sign. (Assuming you mean the integral from $0$ to $\infty$).

Integration of $\sin(x)e^{-x^2}$


Getting all entities from a slick query

Question: How to read all entities from a Query[TableType] or from a Query[TableType, EntityType, Seq] in slick 3.0.0? In the tutorial there was "result" method, but it isn't defined after all the configurations.
Edit:
I've tried to use qbooks.result and (for(book <- qbooks) yield(book)).result from this model:
import java.sql.Date
import slick.driver.H2Driver.api._
import slick.backend.DatabasePublisher
import slick.driver.JdbcProfile
import entities._

object tables {
  private val db = Database.forConfig("h2db")

  //one of the table queries
  val qbooks = TableQuery[Books]

  db.run(
    DBIO.seq(
      qbooks.schema.create,
      ...
    )
  )

  //one of the tables
  class Books(tag: Tag) extends Table[Book](tag, "books") {
    def isbn = column[Int]("isbn", O.PrimaryKey, O.AutoInc)
    def author = column[String]("author")
    def title = column[String]("title")
    def year = column[Int]("edition_year")
    def amount = column[Int]("amount")
    def * = (isbn, author, title, year, amount) <>
        (Book.tupled, Book.unapply)
  }

Comment: You should still use the result method. It might be your IDE not being able infer that the result method is there. IntelliJ has (or recently had) this problem. https://youtrack.jetbrains.com/issue/SCL-8436. Have you tried compiling outside of your IDE?
Comment: Still there: "value result is not a member of slick.lifted.TableQuery[TTable]" and "value result is not a member of slick.lifted.Query[TTable, Entity,Seq]."
Comment: Is it possible for you to post some more code?
Answer: val qbooks = TableQuery[Books] appears to be a macro (do macros have to be enabled in the compiler?). I haven't used that syntax but the following compiles for me
//one of the table queries
  object qbooks extends TableQuery[Books](tag ⇒ new Books(tag)) {
    def all = qbooks.result
  }

db.run(qbooks.all)

Comment: @Roman13 Now it works - in an ugly kind of way, therefore I dropped slick.
Comment: @Magnus Eklund Reading the values from the database - which is a pretty simple task. It isn't really flexible and requires too much configuration. Every year, I want to use slick in one of my projects but there are always huge changes which makes me to do unnecessary work.
Comment: Thanks for the answer. But I still can't read out the entities.
Comment: Yes it compiles but not the way I want. I still can't make it a list of entities.
Comment: @StevenDobay can you be a little more specific why you can't make it a list of entities? If it compiles, you should be able to access your books like this: `db.run(qbooks.all).map(books => /* do something with your books here */)` where `books` is of type `Seq[Book]`.
Comment: @StevenDobay What became ugly? I'm genuinely interested
Comment: When I use db.run(tableQuery.result) it gives me error: type mismatch;
AuthTokenDAOImpl.this.dbConfig.driver.StreamingProfileAction[Seq[models.auth.tables.AuthTokenTable#TableElementType],models.auth.tables.AuthTokenTable#TableElementType,slick.dbio.Effect.Read]
[error]     (which expands to)  slick.sql.FixedSqlStreamingAction[Seq[models.auth.tables.DbAuthToken],models.auth.tables.DbAuthToken,slick.dbio.Effect.Read]
[error]  required: slick.dbio.DBIOAction[Seq[models.auth.AuthToken],slick.dbio.NoStream,Nothing]
[error]       tokens.result
Answer: take a look at this:
https://github.com/cicco94/scala-akka-slick-demo/blob/master/src/main/scala/com/academy/service/UserService.scala
ie: db.run(TableQuery[UserTable].result)

Getting all entities from a slick query


How to change web service url dynamically

Question: I have one web service reference in my project but it has two url one is live and second one is test,how to switch between these url dynamically in vb.net
http://api.test/test/SOAP.wsdl
http://api.live/live/SOAP.wsdl
        'LOGPOINT:
        Call mobjLogWrite.prWriteLogEntry(clsLogWriter.enuLogEntryType.INFORMATION, ASSEMBLY_ID, "Start fnHOTELSPROSearchExecute()", "fnHOTELSPROSearchExecute")

        Dim objsoap As New b2bHotelSOAPService()
        Dim getres As New getAvailableHotelResponse()
        QLSearchXML = xmlData
        objsoap.Timeout = 20000
        objsoap.Url = "http://api.live/live/SOAP.wsdl"
        'objsoap.Timeout = TIMEOUT
        getres = objsoap.getAvailableHotel(HOTELSPRO_APIKEY.Trim(), strDestinationId, dtmCheckIn, dtmCheckOut, strCurrencyCode, "UK", True, fngetpax(xmlData), getfilter())
        Call mobjLogWrite.prWriteLogEntry(clsLogWriter.enuLogEntryType.INFORMATION, ASSEMBLY_ID, "Start DeSerializing the XML Output", "fnHOTELSPROSearchExecute")
        lHOTELSPROReturn = fnCustomSerializeObject(GetType(getAvailableHotelResponse), getres)
        Call mobjLogWrite.prWriteLogEntry(clsLogWriter.enuLogEntryType.INFORMATION, ASSEMBLY_ID, "End DeSerializing the XML Output", "fnHOTELSPROSearchExecute")
        lTempDOM.LoadXml(lHOTELSPROReturn)
        Return lTempDOM

    Catch ex As Exception
        Call mobjLogWrite.prWriteLogEntry(clsLogWriter.enuLogEntryType.ERROR, ASSEMBLY_ID, "Catch Block Error:" + ex.ToString(), "fnCreateHOTELSPROSearchRequest")

    Finally
        'LOGPOINT:
        Call mobjLogWrite.prWriteLogEntry(clsLogWriter.enuLogEntryType.INFORMATION, ASSEMBLY_ID, "Response From HotelsPro--->" & lHOTELSPROReturn, "fnHOTELSPROSearchExecute")
        Call mobjLogWrite.prWriteLogEntry(clsLogWriter.enuLogEntryType.INFORMATION, ASSEMBLY_ID, "END Finally Block fnHOTELSPROSearchExecute()", "fnHOTELSPROSearchExecute")
    End Try

the error response is returned
"I have one web service reference in my project but it has two url one is live and second one is test,how to switch between these url dynamically in vb.net"
Comment: objsoap.Url=someurl is correct, are you sure the two webservices are identical? What are the error exactly? Can you post it here?
Comment: @Duke can i know the what you are sending in fngetpax(xmlData), getfilter() those functions . as i have also to work with hotelsPro.com and not finding any example in c#
Answer: Dynamically based on what, exactly?
Assuming you mean based on where the app is running, i.e. Test or Live, how about:
EDIT : Just saw it was meant to be in VB.Net
Dim MyService as String
If HttpContext.Current.Server.MachineName.ToString() = "LIVESERVER" Then
    MyService = "http://api.live/live/SOAP.wsdl"
Else
     MyService = "http://api.live/test/SOAP.wsdl"
End If

And change
objsoap.Url = "http://api.live/live/SOAP.wsdl"

to
objsoap.Url = MyService

Comment: do you have any idea about HotelsPro.com api as i want to know what is passing for PAX and Filter
Comment: i check there documentaion but its confusing for me as i dont know PHP and there sameples are in PHP like $rooms = array();

      // First Room
      $rooms[] = array(array("paxType" => "Adult"));

      // Second Room
      $rooms[] = array(array("paxType" => "Adult"), array("paxType" => "Adult"), array("paxType" => "Child", "age" => 8));
Answer: If your Webservice is set to Dynamic, the URL is store in the app.config settings.  To make this easier to change at run time (the app.config is readonly unless run with admin privileges), go to the project Settings and change the webservice setting from application scope to user scope.
Now you can change the webservice URL at any time in code using the my.settings.yourwebserviceurl... = "newwebserviceurl"
Next time you call the webservice, it will be from the new location.  However, you will need to ensure both webservice call contain an indentical, or at least compatible webservice.


How to estimate cut off percentiles to classify cost per metric?

Question: I work at an ad agency and one of our key performance metrics is what we call "cost per outcome". Right now I have advertisements grouped by type of advertisement, lets say type "A", "B", and "C" and have 500,100, and 70 advertisements respectively in each group and their associated cost per outcomes.
I need to classify these cost per outcomes into categories "low cost" "medium cost", "high cost" for each group so that I can make a comparison between the groups.
The approach I have currently taken to do this for each group is to simply classify any cost per outcome < 25th percentile as "low cost", >= 25th and < 75th percentile as "medium cost" and >= 75th as "high cost".
My question: is there a better approach that I can take for doing this type of estimation and classification or is this a sound method? What I am thinking is this approach is looking at a snapshot in time of these metrics and down the road the percentiles and classifications will probably change, but I don't know if my estimates should take that into account and don't really know how I would do that.
Please advise! Thank so much.
Comment: When you find 'percentiles' is that relative to ads in the same type A/B/C, or relative to all 670 ads?  // Why three types A/B/C? Treat each type separately? Or is one goal to compare types? // You say one goal is to predict future performance.. I don't see how any classification as H/M/L now would help with prediction unless you know from historical studies that such  H/M/L classifications are stable over time. It has been said, "Prediction is difficult--especially, about the future." (Attributed an old Danish saying, Danish physicist Niels Bohr, or American baseball player Yogi Berra.)
Comment: Hey Bruce, thanks for the reply. Yes, I mean finding percentiles withih the same ad type. I want to compare the ranges of the low, medium, and high categories across the groups (A, B, C) as well as try to use those percentile ranges (or whatever is the most sound way to split the cost pers) as an estimation of what the "true" ranges are.
Comment: Well, determining H/M/L via quantiles for each type could make it different to compare groups using categories H/M/L. Will give example in Answer format. Not room in Comment format.
Answer: Actual costs by ad type. Here are cost per outcome scores (in dollars, pesos, bitcoin, or whatever) for three hypothetical types of ads. I will explore them to see whether various kinds of possible summaries may be useful.
set.seed(2020)
a = round(rnorm(500, 20, 3), 2)
 summary(a)
     Min. 1st Qu.  Median    Mean 3rd Qu.    Max.
    10.66   17.86   19.79   19.84   21.89   29.60
b = round(rnorm(100, 10, 2), 2)
 summary(b)
     Min. 1st Qu.  Median    Mean 3rd Qu.    Max.
    4.680   8.777   9.890   9.973  11.165  14.900
c = round(rnorm( 70, 30, 4), 2)
 summary(c)
     Min. 1st Qu.  Median    Mean 3rd Qu.    Max.
    20.94   27.10   30.19   29.89   31.95   39.99

For Type a ads, Medium cost is between 17.86 and 21.89, Low below 17.86 and High above 31.95; for Type b ads Medium is between 8.78 and 11.17; and for Type c ads Medium is between 27.10 and 31.95.
In the boxplots below (of varying widths as a reminder that sample sizes differ), the values inside the boxes correspond to Medium-cost ads.
boxplot(a,b,c, names=c("a","b","c"), varwidth=T,
        col="skyblue2", pch=20, main="Cost per Outcome")

Now, how would you make comparisons between Types? "Medium-cost"
adds have very different cost ranges, depending on ad Type.
"Standard" costs. You might try standardizing the scores for each type separately.
To do that, for each cost in a you would subtract the average cost for a, then divide by the standard deviation of costs for a. Similarly for b and c. You could call the standard
costs $A, B$ and $C.$ They not longer represent actual costs,
but relative costs within their ad Type. That might help make
comparisons of ads among various Types, but if you start to talke
about budgets, you'll have to go back to the actual costs $a, b,$ and $c.$
A = (a-mean(a))/sd(a)
 summary(A)
      Min.  1st Qu.   Median     Mean  3rd Qu.     Max.
  -2.87313 -0.61880 -0.01607  0.00000  0.64222  3.05702
B = (b-mean(b))/sd(b)
 summary(B)
      Min.  1st Qu.   Median     Mean  3rd Qu.     Max.
  -2.62840 -0.59362 -0.04117  0.00000  0.59198  2.44674
C = (c-mean(c))/sd(c)
  summary(C)
      Min.  1st Qu.   Median     Mean  3rd Qu.     Max.
  -2.18049 -0.67830  0.07431  0.00000  0.50211  2.46318

boxplot(A,B,C, names=c("A","B","C"), varwidth=T,
        col="skyblue2", pch=20, main="Standard Cost per Outcome")

Now the lowest relative costs for Medium ads would be $-0.62, -0.59,$ and $=0.67$ for Types A, B, and C, respectively. They
are nearly the same on the relative scale, but of very different
actual costs. Again with relative costs within Types, the medium cost ads lie within the boxes of the respective boxplots.

Because I don't fully understand the differences among ad Types,
the goal of your analysis of costs, and so on, I am not necessarily recommending you use any of the summaries or graphics above. But I'm hoping that thinking about these methods may
help you clarify what you should do.
Comment: Thanks, Bruce, you're the man! I think the most important part of my question was whether or not using percentiles to create ranges of cost metrics which could be used to create the H/M/L groups was a sound method. In terms of making comparisons, I think perhaps finding a way of combining the standard deviation and the mean of the cost per metrics could perhaps be useful i.e. picture a grid which is split into quadrants by the mean of the stdevs and mean of the means of the cost pers so the lower left quadrant represents groups with low cost, low variance and upper right high cost, high var
Comment: the example I gave only included 3 ad groups, but there are really more like 50 groups
Comment: If your ad costs have right-skewed distributions then you will have higher variability for High-cost ads. // My formula for standard scores is commonly used and you might be able to find some information on how others have used them. But there are other ways of putting distributions on roughly the same scale. For example (subtract the type _median,_ then divide by the type _IQR_). IQR ('interquartile range') is the distance btw the upper and lower quartiles. // Whatever you try, wishing you success.


What effect do the user and role labels have on a file in SELinux?

Question: When running ls -dZ /, I get the following output:
system_u:object_r:root_t:s0

Can the user and role fields have any effect access permissions involving a file? Do they mean anything?
Answer: TL;DR: Yes, they can have an effect, but on your system, they probably don't.

First some background:
Most Linux distributions shipping SELinux are using a policy based on the so-called reference policy, which contains a functional policy that can be used as a base for site-specific customization, or used as-is.
The attributes you're looking at are: the SELinux user, the role, and the type (or domain) for the file or process. In SELinux, login users are mapped to SELinux users, and then the SELinux users are assigned to roles which they are allowed to perform. Each role has a set of domains that it can transition to. In this way, one can switch a user's role (users can switch their own role with the newrole command, if they are allowed to change roles) to provide or deny access to a completely different set of domains.
In the case of files, access to the file is mediated based on the user and role of the process matching the user and role with which the file is labeled. However, in the case of unconfined users, (and whenever you want, in your own custom policies) these may be ignored and only the type used, or the type ignored as well.
If you're using the default targeted policy, user and role are almost entirely unused, as this policy really does very little with user- or role-based access control, focusing on confining outward-facing services instead. This policy does have some support for confining users, but it is off by default, and all interactive user logins are unconfined.
Under the strict or mls policies, though, user- and role-based access control are much more heavily used. Users are always confined under these policies, and even what the root user can do is limited by placing the root user in the sysadm_r role. Note that the mls policy causes X to break, so you won't generally see it on workstations.
Most SELinux systems you're likely to run across will only be using the targeted policy; it's unusual to find strict or mls in use, though you will see it in places that require the user- and role-based security (e.g. defense contractors). In those cases you'll also likely see that they've customized the users and roles in use.
It's possible to write a complete SELinux policy from scratch, but since this is a lot of work, and carries its own set of nightmares (e.g. documentation or the lack thereof) you won't see it very often. Though if you want to see a demo of role-based access control, this example from IBM of a policy written from scratch serves well.
(A complete answer would be even more theory, so I'll just leave you with this. Day-to-day, the SELinux User Guide is your friend, and for the really tough SELinux questions, the mailing list is also your friend.)
Comment: That gives a really good general breakdown of SELinux attributes. However, where it discusses user and role, it's only reference to a Linux user account. I still see no reference to the user and role attributes as labeled on a file having any bearing over affecting the handling of the file.
Comment: That's because, by default, they don't. Only if you've customized your installation with user- or role-based access controls would they have any meaning. And if you do that, then you're deep into "too localized" territory and should probably ask the mailing list.


The mode of multivariate Gamma distribution

Question: Let X, Y, Z be i.i.d. distributed Gamma random variables. What could the mode of the vector $(X, X+Y, X+Y+Z)$ be?
Does the mode of a random vector equal the combination of the marginal modes?
Comment: The last question is interesting.  You can construct counterexamples using bivariate Bernoulli variables (that is, $2\times 2$ contingency tables): try it!
Comment: The general answer to the second question is no\*. It's worth trying various simulations and some algebra. $\quad$ *I suspect (but haven't checked) that its not the case for your specific problem.
Comment: For multivariate mode see https://stats.stackexchange.com/questions/210107/whats-the-definition-of-multivariate-mode   and    https://stats.stackexchange.com/questions/33625/computationally-efficient-estimation-of-multivariate-mode
Comment: https://stats.stackexchange.com/questions/91937 is also relevant (it concerns comparing marginal modes to the joint mode).
Answer: Let's address the questions in reverse order.
First, there isn't any general relationship between the marginal modes and the joint mode for arbitrary multivariate random variables.  Counterexamples and explanations are given in the answers at How are the numbers of modes of marginal and joint distributions related?.
Despite that, in the special circumstances of the first question (iid continuous variables), there is a nice, simple result. To obtain it, let $f$ be the common density function.  The independence assumption means the joint density is their product,
$$f_{X,Y,Z}(x,y,z) = f(x)\,f(y)\,f(z).$$
In the change of variables $(X,U,V) = (X,X+Y,X+Y+Z),$ the probability element transforms as
$$\mathrm{d}x\,\mathrm{d}u\,\mathrm{d}v = \mathrm{d}x\,\mathrm{d}(x+y)\,\mathrm{d}(x+y+z) = \mathrm{d}x\,\mathrm{d}y\,\mathrm{d}z;$$
that is, it is unchanged.  (The statistical argot is "the Jacobian equals $1$ everywhere."  The actual calculation is performed with the wedge product as explained at https://stats.stackexchange.com/a/154298/919.)  This is the key insight, because it means the maximum value of the joint distribution is obtained by maximizing
$$f_{X,U,V}(x,u,v) = f(x)\,f(u-x)\,f(v-u).$$
All such maxima obviously occur at points $(x,u,v)$ where $x,$ $u-x,$ and $v-u$ are modes of $f.$  Thus

The modes of the joint distribution of $(X,X+Y,X+Y+Z)$ are the points $(x^{*},x^{*}+y^{*},x^{*}+y^{*}+z^{*})$ where $x^{*},$ $y^{*},$ and $z^{*}$ are univariate modes of the common marginal distribution of $X,$ $Y,$ and $Z.$

When $f$ has a unique mode $x^{*},$ this implies $f_{X,U,V}$ has a unique mode at $(x^{*}, 2x^{*}, 3x^{*}).$  This is the situation of the question, because a $\Gamma(k,\theta)$ distribution ($\theta$ is a scale parameter) has a unique mode at $x^{*}=(k-1)\theta$ when $k\ge 1$ (and otherwise its mode is $x^{*}=0$).

It is apparent that results of this type are available for any number of iid continuous variables and any invertible linear transformation (because again the Jacobian is constant and so does not affect the joint mode).


É possível aproveitar a mesma view WPF para Desktop e Web?

Question: Caros, nunca programei com WPF mas em breve terei a oportunidade e já pensando no futuro, que é agora, em que aplicações desktop estarão/estão sendo migradas para a web e, também pensando nos que ainda relutam contra isso, que nos caso são os clientes, eu quero fazer o sistema servir tanto pela web como que por desktop.
Tentando evitar redundância de código eu lhes pergunto: É possível usar a mesma view para desktop e para a web? Se não, até onde eu posso ir sem ter redundâncias de códigos desnecessárias, ou realmente a view para desktop é diferente para a view web?
Gostaria de aproveitar a oportunidade para perguntar se o WPF roda, pelo menos, nos browsers mais populares, como IE, Firefox e Chrome? Também se é multiplataforma, para Linux e Mac OS?
Comment: Resumindo, para a primeira pergunta, a resposta é não.
Comment: Obrigado pela ajuda! Mas saberia me responder sobre as outras questões também?
Comment: @user3628, acredito que seja mais interresante ter uma arquitetura multicamada, então você poderá ter quantas camadas de apresentação quiser (desktop, web, mobile, wearable, tvs, geladeiras, etc) e manter as suas regras de negocio centralizadas.
Answer: Como não era resposta, preferi mandar pelos comentários, mas aqui vai:
Ainda não ouvi reclamações do WPF em nenhum navegador. Se você utilizar Silverlight então, vai, com certeza ter a tranquilidade da compatibilidade cross-browser de forma nativa.
Quanto à migrar, isso acaba se tornando pessoal demais, eu, pelo menos, acho mais interessante iniciar novos projetos no WPF do que migrar, ou, se for migrar, como você disse que não tem experiência em wpf, sugiro projetos pequenos para não se deparar com um monstro de primeira. Mas tem gente que prefere grandes desafios logo de cara, então, como eu falei, é bem relativo.
Finalmente, já que você ainda está aprendendo, acho válido dar uma olhada neste exemplo que mostra o mesmo sistema em windows forms e wpf.
Comment: Exatamente isso. Bastante pesquisa, mas adianto que vale a pena.
Comment: Pra terminar de te convencer sobre o WPF. http://social.msdn.microsoft.com/Forums/pt-BR/602a3c75-d996-4a39-8c77-0439bde0034e/wpf-x-winforms
Comment: Perdoe minha ignorância, mas `Se você utilizar Silverlight então, vai, com certeza ter a tranquilidade da compatibilidade cross-browser de forma nativa.` para Linux e Mac OS, é isso mesmo?
Comment: E também.. WPF com Silverlight? Tenho muita coisa para pesquisar ainda.. (rs)
Answer: Não existe WPF para web e nunca existirá. Web é web, se não estiver usando HTML, CSS, JavaScript, não é web. Nem mesmo Silverlight é web, assim como Flash. O fato de rodar em cima de um navegador não significa que é web.
Se quer rodar WPF em um navegador se prepare para usar só o Internet Explorer, obviamente só no Windows. Até onde eu sei, nem mesmo o Microsoft Edge que substituiu o IE pode rodar WPF (que no fim virou Chromium). E não é qualquer Windows que vai rodar, precisa ter um .NET instalado e atualizado. Ou seja, esqueça isto.
Quer fazer algo para desktop, faça com WPF, Windows Forms ou WinRT. Não caia no marketing. Se vai fazer algo para web use as tecnologias padrões citadas acima. Não adianta tentar aproveitar que não dá.
E aplicações desktop não estão sendo migradas para web, a não ser que a pessoa goste de modismos. Existem novas aplicações ou pelo menos novos clientes web para aplicações quando elas são pertinentes e necessárias.
Com o fim do .NET Framework algumas coisas aí podem ter mudado.
Coloquei no GitHub para referência futura.


"message": "X-CSRF-Token request header is missing"

Question: When using postman to fire post request I get this message. Does anyone has idea how to disable it? In this case it is post to register user so no authentification is required.
Comment: Disabling the protection represents a security hole so I doubt there's a built-in way to disable it. CSRF is not related to authentication, it's a separate protection measure, so relying on the user being authenticated isn't enough. See https://www.drupal.org/docs/7/security/writing-secure-code/create-forms-in-a-safe-way-to-avoid-cross-site-request-forgeries for more info
Comment: I put header field X-CSRF-Token with value I got after running get request on my site with sufix /rest/session/token
Answer: One reason you may get an X-CSRF-Token request header is missing when testing with Postman is that you are using bearer authentication but you also have a session cookie.
Postman will automatically save session cookies and send them with requests, so if you are trying to debug decoupled registration, you may notice this error.
There is more info in the drupal.org issue here.
To fix it, you can be vigilant about deleting the cookies after each request when testing with Postman, or apply the patch in the linked issue.
Answer: This is not recommend to remove the X-CSRF-Token. Instead you should get the token from  /rest/session/token and add this token in your header with this value.
But if you want to disable it you can write this below line to your settings.php file  $conf['services_csrf_token_check_disabled'] = TRUE;
Answer: If you are using Drupal 8 to create a POST rest api with oauth2, and postman to test it, you can, in postman, create a new tab using GET, and point to the url:
https://drupal_localhost/rest/session/token

Then send the request and copy the response token to the POST tab in postman, under the Headers:
X-CSRF-Token          <previous_token>

Answer: Yeah for Drupal 9 ect
you can do the GET "session/token" ect then use the header
but if you think its silly to have to do 2 requests then you could do something like this....
make a Route Subscriber ...
class RouteSubscriber extends RouteSubscriberBase {

/**
 * {@inheritdoc}
 */
protected function alterRoutes(RouteCollection $collection) {
//Get the Route name here ..
if ($route = $collection->get('rest.something.POST')) {
   $req = $route->getRequirements();
   unset($req['_csrf_request_header_token']); //<-- this bit
   $route->setRequirements($req);
 }

Drupal Docs https://www.drupal.org/docs/drupal-apis/routing-system/altering-existing-routes-and-adding-new-routes-based-on-dynamic-ones
and Credit to @Patrick Kenny because yep postman does that so it will work the Frist time but then wont due to the auto cookie nice catch
confusing if using things like the key_auth module.


Calling a method in another class from the controller class

Question: I am new to asp.net mvc projects. I want to call a method in another class from ActionResult Index() method in Home Controller.
eg:
public class RestCall{
  public async Task<ActionResult> RestCall(string a, string b){
    //......
  }
}

I want to access RestCall() method from index method in following class and I want to get the output of RestCall class to the index() method in home controller.
public class HomeController : Controller
    {
        // GET: Home
        public ActionResult Index()
        {
            return View();
        }
    }

(I am using razor syntax.)Can anyone suggest a way?
Comment: Technically, your question doesn't have an answer. You can't call a method in another class unless that method is static. You can only call the method on an *instance* of that class. Normally, you would do that by calling `var x = new RestClass()` followed by x.RestClass("foo", "bar")`, but since it won't compile if you have a class that has a method with the same name that is not a constructor, that won't work. Please change your example to code that *will compile*.
Answer: Change your definition of Index() to be async and await RestCall:
public async Task<ActionResult> Index()
{
   RestCall rc = new RestCall();
   //rename method as @NightOwl88 says
   var result = await rc.DoRestCall("somestring", "somestring").ConfigureAwait(false);
   // do something with result
   return View();
}


Why perceptron is linear classifier?

Question: It is said that perceptron is linear classifier, but it has a non-linear activation function f = 1 if wx - b >= 0 and f = 0 otherwise
If i will use some non-linear function on linear combination of my data, i think i will get a non-linear classifier. Why it is false?
Answer: It is called a linear classifier because its decision boundary is given by a (linear) hyperplane. Such a hyperplane is given by the set $\{ x | w^tx =b \}$ which thus splits $\mathbf R^n$ into two classes, $\{x | w^tx \leq b\}$ and $\{ x | w^tx > b\}$. You can think of $w$ as the normal vector to this hyperplane and $b$ as an offset by which you shift the hyperplane.
Comment: @gunes: I see your point, to me the wikipedia article is ambiguous, i.e. it does not rigorously define what a linear classifier is. Having looked up a more reliable source (Wasserman's All of Statistics) I'll agree with you that the correct definition of a linear classifier is "a classifier such that the decision boundary is a hyperplane" and not "a classifier that only depends on a linear combination of the inputs". I'll edit my post accordingly :)
Comment: Is a last layer of neural network a linear classifier?
Comment: That depends on your neural network, in general that does not have to be the case.
Comment: The hyperplane comment is the correct reason, but the first one isn't sufficient and may not lead to linear classification for certain activation functions
Comment: @gunes: I think that depends on your definition of "linear classifier". Wikipedia (https://en.wikipedia.org/wiki/Linear_classifier) defines a linear classifier as a classifier that makes "decision[s] based on the value of a linear combination" of your data.
Comment: Can i consider a last layer of neurons a linear classifier relatively of inputs to the last neurons?
Comment: But if the decision boundary is not flat, the classifier is not a linear classifier. The statement of wiki is correct since it states that linear classifiers operate on linear combination of the data features. For example, if the decision function is $$f(x)=\begin{cases}
      0 & x\leq 0 \\
      1 & 0<x<1 \\
      0 & 1\leq x
\end{cases}$$ , the decision boundary will not be a hyperplane.
Answer: The activation function of a perceptron is linear in it's parameters, i.e. the decision boundary is defined by a linear function of the form $w^tx = b$ = $\sum_{i} w_{i} * x_{i}$.
Similar to linear least squares, the perceptron does not care whether the input $x_{i}$'s are non-linear combinations of your original data. You can indeed model a non-linear decision boundary using a polynomial basis function, e.g. if your data consist of a single independent variable $x$ you could include the square of $x$ as an additional variable.
Again, the perceptron can only model a linear decision boundary, but linear decision boundaries in quadratic space become a non-linear curve when mapped back to the original space.
Comment: I dont think this answers this question correctly. While the sumproduct is calculated with linear function, the activation is a nonlinear function (like Sigmoid, ReLU , tan() and others) , so, since sigmoid is the output and it is nonlinear, then the perceptron , even if it is a single one becomes a nonlinear function. If you are saying that perceptron is linear, then show a proof.
Comment: @Nulik You have a point, but I'm convinced that as long as the activation function is monotonic, choosing a threshold on the activation will lead to the input being separated by a single hyperplane, as there is a bijective mapping between the outputs of the linear model and the non-linear activation. However, if the activation is non-monotonic (I tried this using the activation f(x) = abs(x)), there is a surjective-only mapping of the linear outputs onto the activations, so there are two (or more?) separating hyperplanes in input space, which I'd say would be a non-linear classifier.
Comment: @Nulik In any case, all separating lines are **linear** hyperplanes.

Why perceptron is linear classifier?


How do you go about using contexts and a menu page callback?

Question: Currently we have a page that is generated by a hook menu page callback. The path is structured like menu/%location_name/menu/%parent_category/%child_category. The function requires at least one of the category wildcards to properly work.
In the page callback we then set up our context's condition which is to determine which of the categories we're in. See code below:
  if(empty($term_parent) == FALSE || empty($term_parent) == FALSE) {
    if ($plugin = context_get_plugin('condition', 'ss_menu_core_condition_default')) {
      if(empty($term_parent) == FALSE && empty($term_child) == TRUE) {
        $context_term = $term_parent->tid;
      } elseif(empty($term_parent) == FALSE && empty($term_child) == FALSE) {
        $context_term = $term_child->tid;
      }
      $plugin->execute($context_term);
    }
  }

Everything up until this point makes a bit of sense to me. And currently it validates fine and I can actually see the context when using context_active_contexts(). Although the gotcha that I must be missing is how do i go about allowing the metatags context module's reaction to use this term for token replacement?
At first the tokens avaliable were pretty generic default site wide things such as current page, current user, date, etc... It wasn't until i found a patch that taxonomy terms ended up showing up as token replacements. But none of them seemed to work as it seemed the context didn't know of what term to use.
This leaves me at a point where I felt like the only solution was to do something hackish and just set my values in the active context as follows:
  $context = context_active_contexts();
  $context['ss_menu_core_menu_sections']->reactions['metatag_context_reaction']['metatags']['und']['description']['value'] = $context_term->description;

This still doesn't feel right at this point since we can't actually use the metatags reaction form to populate the values. If anyone has any ideas that would be amazing.
Thanks.
Answer: Take a cue from metatag_context_entity_prepare_view() in that patch.  You need to stuff your desired term entities into the metatag_context_entities static variable in your page callback like so:
drupal_static('metatag_context_entities', array('taxonomy_term', $terms));

Comment: Oh wow! How did i manage to miss this? Is there another drupal_static() just for context or is this more of what i want to use?
Comment: I'm not sure I really understand your question, but drupal_static is in no way specific to the context module.  And what metatag_context is doing here is not specific to the context module, either.  When it processes tokens it has to decide what entities to use to populate the tokens and it's doing that by implementing hook_prepare_view and stuffing those entities into a static variable.  Is that the best way for it to do that?  It's debatable.  But that's how it's doing it, so you need to get your entities into that static var.
Comment: yeah sorry that was poorly phrased. Anyway that seems like the solution so i'll test it out. Thanks for your help and time. :)


DOS Protection EX Series

Question: So I've read a number of white papers from Juniper containing some DOS prevention strategies. I'm not looking to prevent any one in particular, but rather just ensure the network is as best protected as possible.
But I'm not inclined to copy+paste configs I've found online without fully knowing the implications.
I've got a EX4200 sat on the internet with a number of public subnets, all in their own VLANs with RVIs each.
This is one example I've found ...
term tcp-dos-protect-1 {
    from {
        protocol tcp;
        tcp-flags "syn&!ack";
    }
    then policer tcp-dos-policer;
}
term tcp-dos-protect-2 {
    from {
        protocol tcp;
        tcp-flags "fin|rst";
    }
    then policer tcp-dos-policer;
}

...

policer tcp-dos-policer {
    filter-specific;
    if-exceeding {
        bandwidth-limit 500k;
        burst-size-limit 15k;
    }
    then discard;
}

Now, would this particular rule affect genuine traffic? Under heavy network conditions - would it just start dropping genuine traffic, or does it really only block "bad" traffic ?
Answer: Without knowing how much data your environment serves, this filter shouldn't present any issues.  It's setting a hard limit on tcp-initializations and finished/reset flags at 500Kb/s.  To reach this limit, you would need to be serving several million new TCP requests per second.  Even if some good packets did reach that hard limit, they would just drop and then attempt again in a few seconds.
This is also (unfortunately) true for people attempting to DoS your servers.  If a single host was able to initiate several thousand connections to one of your servers every second, you'd still be in trouble.

The thing to note about these filters is that it's a very crude way of limiting traffic; in other words, it's limited but efficient.  It's good for making sure no unnecessary traffic traverses your network, but web-server technologies (e.g. mod_security, mod_evasive, etc.) will always do a more intelligent job of managing your server load and figuring out what it should and shouldn't be handling out.
In the example above, a person attempting repeat connections at those levels would be blocked for a predetermined amount of time.  The most you'd lose is a marginal amount of bandwidth and enough processing to close the connection.

DOS Protection EX Series


Does the person breaking get the choice of solids or stripes if he makes any ball in?

Question: When playing 8-ball, if the breaking player hits any ball on the break, does the shooting player have a verbal choice of stripes or solids? Or does he still have to call a shot in before he can?
If the rule is that he has to call his shot to get either stripes or solids, then what happens if on the break he hits a solid in, but calls a shot for stripes and misses it?
Answer:
does the shooting player have a verbal choice of stripes or solids?

No one ever has verbal choice.  Whenever the table is open (as is always true after a break), then the group is chosen by successfully pocketing a called shot.  The group containing the made shot is then that player's.  WPA Rules, rule 3.4.

what happens if on the break he hits a solid in, but calls a shot for stripes and misses it?

The table is open after the break (even if balls are pocketed) (Rule 3.3(c)).  By missing the called shot, the table remains open for the opponent.


Why ANOVA/Regression results change when controlling for another variable

Question: This question might be very basic, but somehow I don't understand this point.
Suppose initially I used a univariate regression equation  such as
GDP=a+b*Income

I'll get some coefficient values (say 0.5). Now, I'm using the same structure of the regression model, but added another independent variable. So, the new equation is
GDP=a+b*Income+c*Investment

Then the new coefficients value will be b=0.3 & c=0.4.
My question is why coefficient's value changes when we add another independent variable?
Hope I can put my question clearly.
Comment: Because your two independent variables correlate with each other
Comment: Thanks ttnphns! But can you please elaborate. Why correlation lead to change in coefficients?
Answer: Linear regression can be illustrated geometrically in terms of an orthogonal projection of the predicted variable vector $\boldsymbol{y}$ onto the space defined by the predictor vectors $\boldsymbol{x}_{i}$. This approach is nicely explained in Wicken's book "The Geometry of Multivariate Statistics" (1994). Without loss of generality, assume centered variables. In the following diagrams, the length of a vector equals its standard deviation, and the cosine of the angle between two vectors equals their correlation (see here). The simple linear regression from $\boldsymbol{y}$ onto $\boldsymbol{x}$ then looks like this:

$\hat{\boldsymbol{y}} = b \cdot \boldsymbol{x}$ is the prediction that results from the orthogonal projection of $\boldsymbol{y}$ onto the subspace defined by $\boldsymbol{x}$. $b$ is the projection of $\boldsymbol{y}$ in subspace coordinates (basis vector $\boldsymbol{x}$). This prediction minimizes the error $\boldsymbol{e} = \boldsymbol{y} - \hat{\boldsymbol{y}}$, i.e., it finds the closest point to $\boldsymbol{y}$ in the subspace defined by $\boldsymbol{x}$ (recall that minimizing the error sum of squares means minimizing the variance of the error, i.e., its squared length). With two correlated predictors $\boldsymbol{x}_{1}$ and $\boldsymbol{x}_{2}$, the situation looks like this:

$\boldsymbol{y}$ is projected orthogonally onto $U$, the subspace (plane) spanned by $\boldsymbol{x}_{1}$ and $\boldsymbol{x}_{2}$. The prediction $\hat{\boldsymbol{y}} = b_{1} \cdot \boldsymbol{x}_{1} + b_{2} \cdot \boldsymbol{x}_{2}$ is this projection. $b_{1}$ and $b_{2}$ are thus the ends of the dotted lines, i.e. the coordinates of $\hat{\boldsymbol{y}}$ in subspace coordinates (basis vectors $\boldsymbol{x}_{1}$ and $\boldsymbol{x}_{2}$).
The next thing to realize is that the orthogonal projections of $\hat{\boldsymbol{y}}$ onto $\boldsymbol{x}_{1}$ and $\boldsymbol{x}_{2}$ are the same as the orthogonal projections of $\boldsymbol{y}$ itself onto $\boldsymbol{x}_{1}$ and $\boldsymbol{x}_{2}$.

This allows us to directly compare the regression weights from each simple regression with the regression weights from the multiple regression:

$\hat{\boldsymbol{y}}_{1}$ and $\hat{\boldsymbol{y}}_{2}$ are the predictions from the simple regressions $\boldsymbol{y}$ onto $\boldsymbol{x}_{1}$, and $\boldsymbol{y}$ onto $\boldsymbol{x}_{2}$. Their endpoints give the individual regression weights $b^{1} = \rho_{x_{1} y} \cdot \sigma_{y}$ and $b^{2} = \rho_{x_{2} y} \cdot \sigma_{y}$, where $\rho_{x_{1} y}$ is the correlation between $\boldsymbol{x}_{1}$ and $\boldsymbol{y}$, and $\sigma_{y}$ is the standard deviation of $\boldsymbol{y}$. In contrast, the endpoints of the dotted lines give the regression weights from the multiple regression of $\boldsymbol{y}$ onto $\boldsymbol{x}_{1}$ and $\boldsymbol{x}_{2}$: $b_{1} = \beta_{1} \sigma_{y}$, where $\beta_{1}$ is the standardized regression coefficient.
Now it is easy to see that $b^{1}$ and $b^{2}$ will coincide exactly with $b_{1}$ and $b_{2}$ only if $\boldsymbol{x}_{1}$ and $\boldsymbol{x}_{2}$ are orthogonal (or if $\boldsymbol{y}$ is orthogonal to the plane spanned by $\boldsymbol{x}_{1}$ and $\boldsymbol{x}_{2}$). It is also easy to geometrically construct cases that sometimes seem puzzling, e.g., when the regression weight has the opposite sign as the bivariate correlation between a predictor and the predicted variable:

Here, $\boldsymbol{x}_{1}$ and $\boldsymbol{x}_{2}$ are highly correlated. Now the sign of the correlation between $\boldsymbol{y}$ and $\boldsymbol{x}_{1}$ is positive (red line: orthogonal projection of $\boldsymbol{y}$ onto $\boldsymbol{x}_{1}$), but the regression weight from the multiple regression is negative (end of green line onto subspace defined by $\boldsymbol{x}_{1}$.
Comment: @gung Sorry, these are scans from an old text I had lying around (based on Wicken's book).
Answer: Because multi-variable regression is, using economic jargon "ceteris paribus" i.e. controlling other elements unchanged.
The difference between
$GDP=\beta_{0}+\beta_{1}Income$ (1)
and $GDP=\gamma_{0}+\gamma_{1}Income+\gamma_{2}Investment$ (2)
is that $\beta_{1}$ in (1) captures the correlation (or effects) between GDP and Income and other elements (of course including Investment). That's $\beta_{1}$ absorb all effects of variable other than Income. But in (2) when Investment is added, $\gamma_{1}$ excluding the effects from Investment.
You can do a three-step regression. In the first step, regress GDP on Investment. Then you get the unexplained variance of GDP by Investment.
In the second step, regress Income on Investment. You get the unexplained variance of Income by Investment.
In the third step, regress the unexplained part of GDP by unexplained Income. Then you get $\hat{\gamma_{1}}$.
I mean $\gamma_{1}$ is direct effects of Income on GDP, excluding the indirect effects from Investment through Income on GDP.
Hope I say it clearly.
Comment: Thanks Yang! If I understand your answer properly, you want to say that in (1) Income is including all the direct & indirect effect. but in (2), due to the presence of Inv & c.p. condition Income is taking only the direct effect on GDP & not the indirect effect. So, that's why there's difference in coefficients.
Answer: The important thing to understand about regression is that you are finding estimated parameter values that minimize the sum of squared residuals.  Adding (or subtracting!) covariates to your model will always change the parameter estimates unless the new covariate is perfectly orthogonal to those already in the model, or perfectly orthogonal to the response variable, or both.  Furthermore, the issue isn't whether these variables are related in the population, but rather in your sample; it is quite reasonable to imagine that some variables aren't actually related to each other, but when you gather a sample, they will pretty much never be perfectly orthogonal in your sample.
Comment: Thanks Gung for your reply. My problem in understanding this issue is how come "correlation" between 2 independent variable lead to change in coefficients. I guess Yang to great extend help me understand this issue. But I'm not confident yet .
Answer: This is also called the Regression Anatomy. Regressing GDP on Income and Investment gives you the same coefficient on Income as this two-step procedure:
first regress Income on Investment and predict the residuals; then regress GDP on these residuals. The residuals have the property that they only contain that part of Income that is uncorrelated with Investment. Unless the two explanatory variables are uncorrelated the multivariate coefficient is different from the bivariate coefficient. As stated above, the multivariate regression makes sure that only the direct effect of Income is captured.
Hope this helps
Michael


Adding Total as a new row in Select Query

Question: Please help me write a SQL query (plsql) to transform data in Screenshot_1 to Screenshot_2.
Screenshot_1
(https://i.stack.imgur.com/66QJr.jpg)
Screenshot_2
(https://i.stack.imgur.com/ujTzR.jpg)
I tried following query but didn't work.
with t1 as
(select complex, sum(manpower) as tot_manpower from test1_tab group by complex)
select complex, manpower from test1_tab
union all
select complex, tot_manpower from t1

Comment: Please don't link to images, add all relevant information to your question as editable text
Comment: Hello, welcome to SO! I would recommend reading through [SO tour page](https://stackoverflow.com/tour) and through SO help center on [how to ask good question](https://stackoverflow.com/help/how-to-ask). Also, please read on [why using images of code/data/errors is bad](https://meta.stackoverflow.com/questions/285551/why-should-i-not-upload-images-of-code-data-errors-when-asking-a-question). Finally, if somebody answers your question and you are satisfied with it, upvote it and accept it as correct answer. Good luck with finding answers to your questions!
Answer: Here's one option; it uses group by rollup.
Sample data:
SQL> with test1_tab (id, complex, division, manpower, value1, value2) as
  2    (select 1, 'Ban', 'A', 10, 0.12, 0.15 from dual union all
  3     select 2, 'Ban', 'B', 20, 0.11, null from dual union all
  4     select 3, 'Ban', 'C', 30, null, 0.55 from dual union all
  5     --
  6     select 4, 'Hel', 'D', 15, null, 0.44 from dual union all
  7     select 5, 'Hel', 'F', 25, null, null from dual union all
  8     select 6, 'Hel', 'G', 35, 0.33, 0.06 from dual union all
  9     --
 10     select 7, 'MIG', 'E', 40, 0.33, 0.45 from dual union all
 11     select 8, 'MIG', 'A', 50, null, 0.77 from dual
 12    )

Query:
 13  select
 14    case grouping_id(division) when 0 then division else complex || ' Total' end as division,
 15    sum(manpower) manpower,
 16    case grouping_id(division) when 0 then min(value1) else null end as value1,
 17    sum(value2) value2
 18  from test1_tab
 19  group by rollup (complex, division);

DIVISION    MANPOWER     VALUE1     VALUE2
--------- ---------- ---------- ----------
A                 10        ,12        ,15
B                 20        ,11
C                 30                   ,55
Ban Total         60                    ,7
D                 15                   ,44
F                 25
G                 35        ,33        ,06
Hel Total         75                    ,5
A                 50                   ,77
E                 40        ,33        ,45
MIG Total         90                  1,22
 Total           225                  2,42

12 rows selected.

SQL>

Answer: Hello Your problem can also be solved using grouping sets and row_number to order properly in this way:
WITH data AS (
SELECT COMPLEX, DIVISION,  SUM(MANPOWER)AS MANPOWER, VALUE1, SUM(VALUE2)AS VALUE2,
row_number() OVER (PARTITION BY complex ORDER BY division) rn
FROM your_table
GROUP BY GROUPING SETS ((COMPLEX, DIVISION, VALUE1), (COMPLEX), ())
)
SELECT CASE WHEN DIVISION IS NULL and complex is not null THEN COMPLEX || ' '|| 'Total'
when DIVISION IS NULL and complex is  null THEN 'Total' else division end as division,
manpower, value1, value2,rn
from data;

I hope it helps.


Learning Bossa Nova Guitar

Question: It's been awhile since I have played guitar but I'm trying to get back into it. I really like bossa nova music and want to learn how to play it. I have some beginner sheet music that I am learning from (see image below) but I have a couple questions about it:

In the image below, I've added numbers (1&2&a, etc.) that represent my interpretation of the count. Is my counting correct?

I placed a circle around what I think is a shortcut way of writing a chord. Am I correct?

Thanks a lot for your help :)
Answer: Your almost there in counting some of your '&'s are off.
When counting 16th notes we count the following way:
1 - e - & - a - 2 - e - & - a
You start off good, but after the first 16th note there should be an 'e' instead of an '&'. So it should be counted like:
1 - & - 2 - e - a | 1 - & - 2 - e - a | 1 - & - 2 - e - a | 1 - & - 2 - e | 1 ||
The reason you count an 'e' instead of a '&' is because of where the 8th note lies in the measure. It is right after the 16th note which is on beat '2' so the next note no mater what the duration is it will land on the 'e' not the '&'. (Also I'm pretty sure the dotted quarter note in measure 4 should be a dotted 8th note.)
For you second question yes it is shorthand for a chord so you don't have to write out all the individual notes of a chord.
Hope this helps.

Learning Bossa Nova Guitar


$\mathbb{C}$ as the Lie algebra of $\mathbb{C}$

Question: It is known that $\mathbb{C}$ is a linear algebraic group as the set of matrices $\begin{pmatrix} 0 & a \\ 0 & 0 \end{pmatrix}$ with $a \in \mathbb{C}$. I read in some notes that $Lie(\mathbb{C})$, the Lie algebra associated to $\mathbb{C}$, is isomorphic to $\mathbb{C}$, but I cannot see why. I only know that if $G$ is a linear algebraic group, $Lie(G)$ is the set of all $\phi : O(G) \to O(G)$ (where $O(G)$ is the set of regular functions on $G$) that satisfy Leibniz rule and such that $g \cdot \phi(f) = \phi(g \cdot f), \forall g \in G, \forall f \in O(G)$. It looks hard to use this definition, so I was thinking of using the fact that $Lie(\mathbb{C})$ is isomorphic to the tangent space, but I am not really sure how. Any hints?
Answer: [In your setting both the group $G$ and the underlying field $k$ "are" the complex numbers (once, its additive group viewed as algebraic group, once as field), which can be confusing. So in the following I will use the notations $k$ and $G$. If you insert "$\mathbb C$" for both, see what a mess this would become!]
If you want to use the language in your question, you can also proceed by showing:

$O(G)$ is isomorphic to the polynomial ring $k[T]$ where further
the element $a \in G$ acts on a polynomial $p(T)$ via $p(T) \mapsto p(T+a)$

Then an element of the Lie algebra as defined in your post is a $k$-linear map $\phi: k[T] \rightarrow k[T]$ such that $\phi(f\cdot g) = \phi(f) \cdot g + f \cdot \phi(g)$. Show that this condition entails that $\phi$ is completely determined by $\phi(T)$, and that $\phi(c)=0$ for all constants $c$. Then, the compatibility with the $G$-action says that, if $\phi(T) = \sum c_iT^i$, we have
$$ \phi(T+a)= \sum c_i (T+a)^i$$
for all $a \in G$, but by $\phi$ being linear and our already established $\phi(a)=0$, the left hand side is just $\phi(T) = \sum c_i T^i$. Show that this is impossible unless $c_i = 0$ for all $i \ge 1$. Consequently $\phi(T) = c_0$ is a constant, and you can now show that $\phi$ must have been the differential operator $c_0 \cdot \dfrac{d}{dT}$ all along.
So $Lie(G)$, as a $k$-vector space, is the set $\{c_0 \cdot \dfrac{d}{dT} : c_0 \in k\}$ which obviously is of $k$-dimension $1$. You can now either use the fact that in any $1$-dimensional Lie algebra every Lie bracket is $=0$, or use whatever definition of the Lie bracket is given in your source to see that it is identically $0$ here. Probably all you need for that is that $G$ is abelian.
Worthwhile: Look at the two alternative definitions of the Lie algebra of an algebraic group in chapter 12b of Milne's online book draft, and see how they identify with our result above. (Most directly you should be able to identify, in 12.5, our $\phi$ with  Milne's $D$ once you see that in our setting, $I/I^2 = T \cdot k[T]/ T^2 \cdot k[T]$.) Note also that then your example is a special case of both 12.6. and 12.7.
Answer: Actually, if you want to see $\Bbb C$ as a linear group, you should see it isomophic to$$\left\{\begin{bmatrix}1&a\\0&1\end{bmatrix}\,\middle|\,a\in\Bbb C\right\};$$that set that you mentioned is not a group.
Clearly, this group is $1$-dimensional. Therefore, its Lie algebra $\mathfrak g$ is a $1$-dimensional complex Lie algebra. And the only way of defining a Lie braket $[\cdot,\cdot]$ on a $1$-dimensional vector space $V$ is to define $[x,y]=0$ for every $x$ and every $y$ in $V$. So, yes, it is naural to see $\mathfrak g$ as $\Bbb C$ endowed with the trivial braket.
Comment: Because, as a vector space, it is (isomorphic to) the tangent space of that group at the identity element. And the tangent space of a $n$-dimensional thing at any of its points is a $n$-dimensional vector space.
Comment: @cip I know that Jose knows this, but the tangent space at an $n$-dimensional *smooth* group is $n$. In characteristic $0$ this is contentless since all groups (with finite type hypotheses) are smooth, but in characteristic $0$ this is false in general.
Comment: @cip Characteristic 0. In characteristic $p>0$ it's false (e.g. $\mu_p$ over $\mathbb{F}_p$).
Comment: Why must the Lie algebra associated to a $1$-dimensional group be $1$-dimensional?
Comment: @AlexYoucis I think there is a typo in your answer, you wrote characteristic $0$ twice: what is the characteristic for which all groups are smooth?


Show that $A=\{x\in X\mid a\leq f(x)\leq b\:;\;a,b\in\mathbb{R}\}$ is closed if $f:X\to \mathbb R$ is continuous.

Question: Let $X$ be a set. Suppose that $f:X\to\mathbb{R}$ is a continuous function and let $A=\{x\in X\mid a\leq f(x)\leq b\:;\;a,b\in\mathbb{R}\}$. Is $A$ closed, open, clopen or none?
So I started by saying that $f(A)=\{p=f(x)\mid a\leq p\leq b\;\text{for some}\;x\in X\}$ but I can't figure out if the set is closed.
Comment: $A$ is the preimage of a closed set, so ...
Comment: How do I show that $f(A)$ is closed?
Comment: If $X=\mathbb R$ and $f(x)=x$ then $A=[a,b]$. Is it open?
Comment: There is a very similar answered question: http://math.stackexchange.com/questions/1020426/f-bbb-rn-to-bbb-r-continuous-l-in-bbb-r-show-s-x-in-bbb-rnfx-l/1020428#1020428
Comment: The question concerns set $A$ and not set $f(A)$.
Comment: It is not necessarily true that $f(A)$ is closed
Comment: But isn't $f^{-1}(A)=A$ in this case? If so, if I can show that $f^{-1}(A)$ is closed then $A$ is closed by the continuity of $f$
Comment: @AdelSaleh In general, $f^{-1}(A)$ clsed does not imply $A$ closed, even for continouos $f$. On the contrary, $A$ closed implie $f^{-1}(A)$ closed for continouos $f$.
Comment: I'm sorry, I meant $f^{-1}(f(A))$. Since in this case $A=f^{-1}(f(A))$ then we can try to show that $f(A)$ is closed and hence $A$ is closed
Comment: $f(A)$ is not necessarily closed. To see this, let $X=\mathbb R$, $a=-\pi/2$ $b=\pi/2$, and $f=\arctan$. Then, $A=\mathbb R$ and $f(A)=(-\pi/2,\pi/2)$, which is _not_ closed in $\mathbb R$.

However, $A$ _is_ closed in $X$ for any topological space $X$. This is because $A=f^{-1}([a,b])$ by definition, and $[a,b]$ is a closed set in $\mathbb R$. Now use the fact that the preimage of a closed set under a continuous function is always closed.
Comment: Again to clear things out, in this specific case it happened to be that $A=f^{-1}(f(A))$. So if I can show that $f(A)$ is closed, then $A=f^{-1}(f(A))$ closed. Correct me if I'm wrong please
Comment: @AdelSaleh _If_ you can show that $f(A)$ is closed, _then_ $f^{-1}(f(A))$ is closed as well. However, the problem is that $f(A)$ cannot be guaranteed to be closed in general. It _may_ be, but not necessarily so.
Answer: By (some variant of) definition, a map $f\colon X\to Y$ between topological spaces is continuous iff $f^{-1}(S)$ is a closed subset of $X$ whenever $S$ is a closed subset of $Y$. The interval $[a,b]$ is a closed subset of $\mathbb R$.
Answer: It is closed.
The simplest way to see it is the following: Let $\{x_n\}_{n\in\mathbb N}\subset\{x:a\le f(x)\le b\}$, with $x_n\to x_0$. Then,
$$
a\le f(x_n)\le b, \quad\text{for all $n$},
$$
and as $f$ is continuous, $f(x_n)\to f(x_0)$, which implies that
$$
a\le f(x_0)\le b.
$$
Thus $x_0\in\{x:a\le f(x)\le b\}$, and hence $\{x:a\le f(x)\le b\}$ is closed.
Comment: Could you please just explain: $f$ is continuous, $f(x_n)\to f(x_0)$, which implies that $a≤f(x_0)≤b$.
Answer: If $f$ is continuous then $f^{-1}(A)$ is closed if $A \subset \mathbb{R}$ is closed. You have that $A$ is closed in $\mathbb{R}$. Then it follows.
To show that $A$ is closed in $\mathbb{R}$, take any $x \in \overline{A}$ then there exists $\lbrace a_n\rbrace$ a sequence with elements in $A$ such that $\lim a_n = x$. As $f$ is continuous you have that $\lim f(a_n) = f(x)$ and
$$a\leq f(a_n) \leq b \Rightarrow a \leq \lim f(a_n) \leq b \Rightarrow a \leq f(x) \leq b $$
Then $x \in A$ so $\overline{A} = A$.
Answer: Do you know that $f: X \to Y$ is continuous iff for any open set $B\subset Y$, $f^{-1}(B)$ is also open. This is also the definition of continuity.
So notice that $[a,b]$ is closed, so $A=X\setminus f^{-1}(Y\setminus [a,b])$ is closed.


Finding expected order statistics from a normal with known parameters

Question: I'm interested in finding the expected value for the kth ordered observation of a normally distributed variable with known standard deviation, mean and n.
Could someone let me know the formula for that?
Thanks for your help
Comment: Note that "assuming the order holds" is the same as saying "assuming the rank correlation is 1". But with that assumption, the first set of ranks becomes irrelevant to the question; you can drop that and instead deal with the simpler question about expected order statistics from a normal with known parameters. Please edit (since it will make your question clearer); when you do please also remove your name -- you already have a signature next to your gravatar on the right (posts are 'signed' for you already).
Comment: thanks for the tip on making the description a bit clearer Glen
Comment: Now the first link under "Related" in the sidebar to the right -> is directly relevant.
Comment: @Glen_b: I know this is OT, but are Order Statistics used in determining goodness of fit for distributions? I mean, if we suspect our sample of size K comes from, say, a Standard Normal, we compare our ordered sample against the tables of Ordered Statistics from an N(0,1) of sample size K?
Comment: It would be best to post this as a question. If you need this question (or the linked question) for context, link it in the question. The brief answer is "yes, there are tests that make a "comparison" (in a sense) with expected order statistics or approximations to them, like the [Shapiro-Francia](https://en.wikipedia.org/wiki/Shapiro%E2%80%93Francia_test) and the closely related Ryan-Joiner test". Arguably the Shapiro Wilk could also count. Several answers on site discuss one or more of these tests.
Answer: For a sample of size $n$ from an absolutely continuous distribution, the general formula for the expected value of the $k$-th order statistic is
$$E[X_{k\,:\,n}] = \frac {n!}{(k-1)!(n-k)!}\int_{-\infty}^{\infty}x[F(x)]^{k-1}\cdot [1-F(x)]^{n-k}f(x){\rm d}x$$
where $F$ is the cumulative distribution function and $f$ is the probability density function. This is equivalent to
$$E[X_{k\,:\,n}] = E[F^{-1}(U_{k\,:\,n})]$$
where $U$ is a Uniform $U(0,1)$ random variable, and the "minus one" denotes the inverse, not the reciprocal.
This second expression uses the probability integral transform so one can compute the expected value of interest through simulation:
1) Generate a sample of size $n$ from a Uniform $U(0,1)$.
2) Pick the $k$-th order statistic of the sample.
3) Compute $F^{-1}(U_{k\,:\,n})$ and store, where $F$ is the CDF of interest.
4) Repeat steps 1-3 many times.
5) Take the average of the stored values.
Comment: @thanhtang Standard notation for "the $k$-th order statistic from a sample of size $n$ of random variable $U$.
Comment: @thanhtang David & Nagaraja, "Order Statistics" 3rd ed. p. 34
Comment: What's U_{k:n}?
Comment: Could you point to the reference paper for the equivalent form (the second equation) above? Thanks!


CQRS/ES - do I understand It correctly?

Question: I would like to sum my knowledge about CQRS/ES. I started to read about this subject some time ago and because of I'm young developer I don't understand every aspect of that concept. I will try to describe my understanding of CQRS on some example flow. So defining general steps of that architecture we have following flow:

User makes request to our controller. In that controller method we create specified Command (for example CreateOrder) and pass it to Handler.
The global message bus (or handler) is responsible to routing the command to specified command handler. So here we pass command to CreateOrderHandler
In handler we create Aggregate root (in this case OrderAggregate) and we apply all events from EventStore. In EventStore we keep only events data related to specified aggregate (defined by global id). So after this step we have aggregate in current state.
When we have created aggregate we pass to It our command and in method we werify if command can be executed. If we can run this command we create Event (in this case OrderCreated).
If there is't any exception we save out Event in EventStore (I think simple to use NoSql DB and simple save events)
Now handler pass saved event to our Denormalizer class which is gateway to create View Models. So if denormalizer get some event it updates/creates all ViewModels in our app. We save ViewModel in separate DB.
User can query for updated view model.

So I this It is simplified version of my understanding of CQRS/ES. Please correct me on every layer. My questions here are:
In 4-th step we created aggregate should we save this aggregate in DB? To keep current state. Am I missing something here? We created aggregate only for checking possibility to create event?
Should I have Entities? If I am correct in 5-th step I can update aggregate entities and use them in my view models. I have the biggest confusion here.
Thanks for all answers ;)
Comment: I read only about this topic, but afaik. you can save the actual aggregate with "snapshot"s, so you don't have to build it always from zero.
Answer:
In 4-th step we created aggregate should we save this aggregate in DB?
  To keep current state. Am I missing something here? We created
  aggregate only for checking possibility to create event?

If you use an EventStore,the ES itself keeps the state of your aggregates. You talk about "create" aggregate in command-handler, but generally it's better to say that in command-handlers the aggregates are re-hydrated from ES.
An Aggregate uses the commands (or their data) and raises (domain) events that are applied in the ES to trace the aggregate's state changes and, the same events are handled by event handlers (like denormalizer).
In the flow described usually I've a command validation step before step 3.
Anyway, some time ago I tried to depict the components of a typical CQRS/ES flow; there are several on web, but maybe it could be useful
Answer: An aggregates state is derived from the past events applied to it. So you don't need to store it's state as it is derived from the event stream. Having said that you may want to create snapshots to avoid a very long event history. Before designing a snap shotting system, it's worth testing how quick re-applying a list  of previous events is.
When you issue a command to an aggregate it handles it in 2 stages. The first stage essentially checks it can run. If so it builds up the event or events to represent the change before applying them to it's self. Key here is that the production of events can and often does require the application of domain logic. In other words it's not just an event producer.
If you find it helpful I have a more detail overview of a typical CQRS application on my blog. You can find it here: CQRS – A Step-by-Step Guide to the Flow of a typical Application

CQRS/ES - do I understand It correctly?


Penciling in piano fingering

Question: This question is related  to a previously asked question of mine about adding accidentals.
I often pencil in fingering in difficult places, but sometimes I even mark fingering on an entire piece (in order to help me play it). But unlike marking the accidentals, this habit does not seem to be as problematic because it might improve one's ability to process information while playing (one needs to pay attention at the same time to the notes and the fingering).
So, should I limit penciling in fingering to trouble spots, or should I just freely mark fingering as I wish?
Answer: You should do whatever it takes to improve your practice and thus performance of the piece. In almost all cases, this means gratuitous writing and penciling of all accidentals and missed notes and fingerings. If it will ever help you, write it down. Your goal is not having something be easy to read or being clean: your goal is to play it perfectly. If that happens to mean readable, fine. But usually during early practice, lots of markings in the music will help you rather than hinder. If you ever want to mark something, mark it. This is why you always use a pencil: if it becomes hindersome, erase it.
As an anecdote: in general, the better a musician is, the more they will mark up their music. In college, I have been reprimanded for few markings on my music. Few markings tend to indicate little or shallow practice. I have heard stories about professional orchestra players' music that has more markings than notes. When mistakes are made, mark it. If there is not a natural fingering, make one and mark it.
Comment: Haha +1; You gotta love the point where you've got more markings telling you what not to do than notes telling you what to do!
Comment: Gerald Moore tells in his autobiography how Elisabeth Schwarzkopf's scores would be totally crammed with notes, remarks etc., often more then one to a note, and usually about nuances he couldn't possibly have distinguished.
Answer: I assume you are referring to a manuscript for piano music.
Generally speaking, a proficient practice of scales will enable you to become more instinctive with your fingering so you should not have to write these in except for complicated unusual fingering. You should strive for a clean easy to read manuscript, here, less is more. The easier to read the better. Remember the manuscript is a set of instructions and a description to tell you what to play and how to play it. Keeping this simple will make it easier to interpret.
For instance you don't need to write "play it loud" next to the dynamic marking forte. People not familiar with the published markings on a manuscript tend to write redundantly all over it making it one big mess. If you don't understand a marking, learn it, don't write it out on top of it. It's like coming to a stop sign in the road and someone wrote "halt" next to the letters spelling out "stop". We can all agree that whatever marks you need to put on a manuscript that will help you play it better is a good thing, but let's face it at some point you should know what is what and how it should be played without spelling every detail out. My point about keeping it simple is also about how you need to keep your head clear of all the clutter and get down to how the music is intended to be played.
Answer: Hahaha I should probably go out and get a life instead of answering this question as well, but....
Ideally, you would work out an ideal fingering for the entire piece so that you can play it as accurately as possible.  In practice, most sections of music are easy enough that musicians don't bother to finger the entire piece and wing it.
In the end, this is the deal: as a musician, your job is to play the music as notated. That means that you need to hit all the right notes (obviously), but you also need to pay attention to the articulation (particularly legato if we're talking fingering), dynamics, and all the other little things on the page. Working out the fingering beforehand makes it much easier to do this.  More importantly, it also trains your fingers; if you practice playing with good fingering, you'll instinctively use that good fingering when you see similar motifs (riffs) later (this is, btw, why we teach scales; there are scales frigging EVERYWHERE in music).
So yes, finger everything.

Penciling in piano fingering


React-native erro apos instalar lib react-native-router-flux

Question: Apos instalar a lib react-native-router-flux no meu app apareceu este erro no:

Fiz o procedimento de remover a pasta
Answer: Esse não é um problema da lib router-flux, é um erro da versão mais nova na lib babel-preset-react-native.
Para solucionar o erro, basta seguir os procedimentos que informei no link abaixo:
Erro ao tentar rodar app no emulador do android studio


What is the simplest way to flush cache at a predetermined date and time?

Question: For site a) I would like to set up a schedule "page and else"cache clear every day at midnight.
For site b) I would like to set up a schedule full cache clear every Wednesday day at midnight.
I am using the modules Varnish and Expire (Cache Expiration) to clear node caches when events occur (added deleted node etc).
As far as I can tell Rules does not provide Time/Date as an event which can be used as a trigger.
I am looking to do this internally in Drupal rather than on the servers cron.
Is there a simple way to achieve this?
Comment: I'm sure drush has some command to do it; once found put it in a cron job.
Answer: May be How can I schedule a rule to always be run at a specific hour of the day? can be useful , but using cron, build a module and in it's hook_cron function check for the current time, if it is your specific time use the cache_clear_all function and it's parameters to clear the page and else cache. just make sure that the cron is ran on Wednesday day at midnight. it's periodic run time should come to 24:59.
you can also check the clear drupal cache - php script for more options of clearing the cache statement.


Call more than one function in match arm in Rust

Question: I currently have a match statement in the form of
match ball.side {
    Side::Left => x(),
    Side::Right => y(),
}

But what I would need is something along the lines of
match ball.side {
    Side::Left => x(),a(),
    Side::Right => y(), b(),
}

And of course this does not compile, but how could I make this kind of sequence work?
I know I could also just work with an if-statement but I am curious how this can exactly be solved with match.
Comment: https://doc.rust-lang.org/book/ch18-03-pattern-syntax.html - note the latter forms that take a block.
Answer: A sequence of statements in a block:
match ball.side {
    Side::Left => {
        x();
        a();
    }
    Side::Right => {
        y();
        b();
    }
}

Note that the right side of a match arm must be an expression, and that blocks are expressions (which can produce a value) in Rust.


8.4.4 CKEditor Link & Unlink Buttons suddenly missing

Question: In Drupal 8.4.4 the CKEditor is suddenly missing the Link and Unlink buttons for all content types, for the Basic Editor and the Full HTML Editor as well.  My users and I can no longer add links to anything, and if I edit articles any link html disappears in the editor altogether (I noticed the issue after editing and saving an article and then noticing the links that were there moments before were suddenly gone).
I went to admin/config/content/formats to configure the editors to add the buttons back, but when I click the Configure button for Basic HTML I get the dreaded "The website encountered an unexpected error. Please try again later." message.  Drupal error log shows the following:

TypeError: Argument 1 passed to Drupal\Core\Render\Element::children()
  must be of the type array, null given, called in
  /core/modules/ckeditor/src/Plugin/Editor/CKEditor.php on line 177 in
  Drupal\Core\Render\Element::children() (line 71 of
  core/lib/Drupal/Core/Render/Element.php).
Drupal\Core\Render\Element::children(NULL) (Line: 177)
  Drupal\ckeditor\Plugin\Editor\CKEditor->settingsForm(Array, Object,
  Object) (Line: 64)
  Drupal\editor\Plugin\EditorBase->buildConfigurationForm(Array, Object)
  (Line: 175) editor_form_filter_format_form_alter(Array, Object,
  'filter_format_edit_form') (Line: 501)
  Drupal\Core\Extension\ModuleHandler->alter('form', Array, Object,
  'filter_format_edit_form') (Line: 830)
  Drupal\Core\Form\FormBuilder->prepareForm('filter_format_edit_form',
  Array, Object) (Line: 272)
  Drupal\Core\Form\FormBuilder->buildForm('filter_format_edit_form',
  Object) (Line: 74)
  Drupal\Core\Controller\FormController->getContentResult(Object,
  Object) call_user_func_array(Array, Array) (Line: 123)
  Drupal\Core\EventSubscriber\EarlyRenderingControllerWrapperSubscriber->Drupal\Core\EventSubscriber{closure}()
  (Line: 582)
  Drupal\Core\Render\Renderer->executeInRenderContext(Object, Object)
  (Line: 124)
  Drupal\Core\EventSubscriber\EarlyRenderingControllerWrapperSubscriber->wrapControllerExecutionInRenderContext(Array,
  Array) (Line: 97)
  Drupal\Core\EventSubscriber\EarlyRenderingControllerWrapperSubscriber->Drupal\Core\EventSubscriber{closure}()
  call_user_func_array(Object, Array) (Line: 153)
  Symfony\Component\HttpKernel\HttpKernel->handleRaw(Object, 1) (Line:
  68) Symfony\Component\HttpKernel\HttpKernel->handle(Object, 1, 1)
  (Line: 57) Drupal\Core\StackMiddleware\Session->handle(Object, 1, 1)
  (Line: 47) Drupal\Core\StackMiddleware\KernelPreHandle->handle(Object,
  1, 1) (Line: 99)
  Drupal\page_cache\StackMiddleware\PageCache->pass(Object, 1, 1) (Line:
  78) Drupal\page_cache\StackMiddleware\PageCache->handle(Object, 1, 1)
  (Line: 50) Drupal\ban\BanMiddleware->handle(Object, 1, 1) (Line: 47)
  Drupal\Core\StackMiddleware\ReverseProxyMiddleware->handle(Object, 1,
  1) (Line: 50)
  Drupal\Core\StackMiddleware\NegotiationMiddleware->handle(Object, 1,
  1) (Line: 23) Stack\StackedHttpKernel->handle(Object, 1, 1) (Line:
  657) Drupal\Core\DrupalKernel->handle(Object) (Line: 19)

I don't know if this is related to recently updating Drupal to 8.4.4, but I was not encountering this issue before as I've made many articles in the past month with links that still work.  I have no idea how to debug or fix this issue, or if it's a known bug, please any help is appreciated.
Answer: I figured out the issue.  Apparently something changed in the Drupal 8.4.4 update that caused the scripts related to the link/unlink buttons to work longer than usual, which was causing a PHP timeout exception (when checking the browser console it gave an HTTP Result Code: 200 error, which apparently happens regularly with Drupal).  So in my settings.php file I increased the timeout by adding the line:
ini_set('MAX_EXECUTION_TIME', 7200);
You can also configure this in your host settings.


Sql Server 2005 Service Pack 3 does not install

Question: I'm trying to install SP3 on an install of Sql Server 2005 running on Server 2003 32 bit. When I run the installer it doesn't seem to recognize that I have SQL Server 2005 installed. The dialog box that asks what features should be updated doesn't show any by default. More troubling, it doesn't allow me to check any of those boxes to update features like Database Services or Reporting Services.
When I select one of these services, the "Status" box says "Not Valid". The message says something about more recent updates, but Select @@Version gives me this:
Microsoft SQL Server 2005 - 9.00.4053.00 (Intel X86)
    May 26 2009 14:24:20
    Copyright (c) 1988-2005 Microsoft Corporation
    Standard Edition on Windows NT 5.2 (Build 3790: Service Pack 2)
Answer: Just tossing this out there, but my knee-jerk response is to try the installation from safe mode.
Edit: Have you fully updated Windows? Have you tried stopping the SQL related services prior to upgrading? The installer should handle this kind of stuff, just trying to think of anything that may help ya..
Comment: The Windows Installer service won't run in Safe Mode without some additional coaxing.
Comment: I haven't tried safe mode. My best shot at this point is to come in on a Sunday and uninstall and then reinstall Sql Server from scratch.
Comment: Obviously you wanna make sure you have a really reliable backup of your database contents - provided there is any. Obviously obvious, indeed.