How to check the OS X version from R?

Question: You can check whether you are running OS X using Sys.info()["sysname"] == "Darwin".
On Windows, finer control is possible by checking for specific versions of the OS using utils::win.version().
How do you check the version of OS X?  (I can't find a mac.version or osx.version function.  There are some low-level OS commands for finding the version, but I'm not aware of any R wrapper.)
Do Sys.info()["release"] or system("uname --kernel-release", intern = TRUE) return anything useful? (I don't have a machine to check.)
Comment: I am not on OS X, but doesn't `R.version$os` provide useful information? ([source](https://stat.ethz.ch/R-manual/R-devel/library/base/html/Version.html))
Comment: I only know about Linux and Windows. There, `R.version$system` gives information on the OS in general and `sessionInfo()$running` provides details concerning the version of the OS that is used.
Comment: doesnt `Sys.info()` already tells you the version name in `version` field. In windows the value in the field `version` and the output of `win.version` is same. it has also clubbed sysname and release name in the output that is it.
Comment: @Pascal The help page for `R.version` explicitly states "Do not use R.version$os to test the platform the code is running on".
Comment: @RichieCotton It also says "## a good way to detect OS X:
if(grepl("^darwin", R.version$os)) message("running on OS X")"
Comment: `.Platform` reports the Os type, but not the version number.
Comment: @DhawalKapil `Sys.info()["release"]` looks promising.  I don't have access to a mac, so if you can post some examples of what it returns under OS X, that's worth at least an upvote.
Answer: Depending on what you actually want, I would use:
system("uname -r")
14.5.0

or
system("uname -s")
Darwin

or
system("uname -v")
Darwin Kernel Version 14.5.0: Wed Jul 29 02:26:53 PDT 2015; root:xnu-2782.40.9~1/RELEASE_X86_64

Answer: Sys.info()["sysname"] returns "Darwin" on Mac OS X.
Sys.info()["release"] tells you what version of Mac OS X. For example, "13.4.0" is Mac OS X 10.9.5.
There probably is no need to do a system() call: Sys.info()["version"] seems to return exactly the same as system("uname -v"). And this version really combines different pieces of information and is not convenient for just checking whether or not you're running on Mac. For example
> Sys.info()["version"]
version
"Darwin Kernel Version 13.4.0: Wed Mar 16 09:03:04 PDT 2015; root:xnu-2422.115.14~1/RELEASE_X86_64"

Comment: FYI, under windows only `Sys.info()["release"]` gives a good answer.
Answer: Use Sys.info() to get most of the information about the current platform:
Example:
osname_version<-c(paste(" System: ",Sys.info()[['sysname']],
                      "\nVersion: ",Sys.info()[['version']],
                      "\nRelease: ",Sys.info()[['release']],
                      "\nMachine: ",Sys.info()[['machine']]))
cat(osname_version,"\n")

Result:
 System:  Linux
Version:  #1 SMP Fri Sep 2 15:45:09 CEST 2011
Release:  18.104.22.168
Machine:  i686

More Information: https://stat.ethz.ch/R-manual/R-devel/library/base/html/Sys.info.html
Answer: Since Sys.info() gives the kernel version rather than the product version, I've opted for using sw_vers instead.
as.numeric_version(system("sw_vers -productVersion", intern = TRUE))

Comment: Nicer wrappers to this now in the devel version of `assertive.reflection`. https://bitbucket.org/richierocks/assertive.reflection

How to check the OS X version from R?


Retrieve all the contact from contact in ng-cordova ionic

Question: I want to retrieve all the contact from iPhone using ng-cordova and ionic. And I want to display all contact where user can choose the contact
Comment: Would you be able to show us what you have so far?
Answer: There is a great blogpost about the case you are asking about:
http://calendee.com/2014/07/17/cordova-contacts-plugin-with-ionic-framework/


SQL SELECT FIELDS IN A DIFFERENT TABLE

Question: I have two tables, one called orders and the other one is invoices. I want to know if I have a closed order without an invoice.  they're joined by id_order, so I have this.
select  I.ID_Order,O.ID_order from Invoices I
inner join Orders O on o.ID_Order = I.ID_Order
where o.Status='x'

if o.iD_order is found in invoices that means the order is invoiced.
if o.id_order is not found in invoices that means its not invoiced.
I want to get in the select statement all of the orders that are not invoiced.
Answer: Method1:
select *
From Order
Where ID_Order not in (Select ID_Order from Invoices)

Method 2:
select  O.*
from Orders O
Left join
Invoices I
on o.ID_Order = I.ID_Order
where I.ID_Order IS NULL

Method 3:
select *
From Order as O
Where Not Exists (Select ID_Order from Invoices as I Where I.ID_Order = O.ID_Order)

Stick to the first one, usually that has a better performance.
Comment: I'm new to sql and I don't know how I didn't see this. it worked, thank you.
Comment: not a problem xD @taby, just updated you with two more methods if you are trying to use `join`

SQL SELECT FIELDS IN A DIFFERENT TABLE


Elementos sumindo quando entra em modo responsivo e só aparece quando clica nele

Question: Assim que minha página é carregada, todos os elementos que cabem na tela são renderizados, porém ao descer um pouco a tela, os elementos não são mostrados, somente são renderizados quando clico em cima deles, e quando este elemento é mostrado, outro elemento na parte de cima some (?)

Pagina logo quando é carregada mostra todos os elementos que cabem na tela:

Ao descer a página percebo que os elementos não estão sendo mostrados:

Ao clicar em cima, o elemento é renderizado:

Alguém já passou por isso? Eu tentei algumas coisas como:
Verifiquei se as divs estão fechando corretamente onde deveriam;
Verifiquei se existem ids iguais;
Verifiquei se todas as variáveis do ngmodel existe no ts.
To sem saber o que fazer.
Answer: Pra quem se interessar, eu utilizo o material design bootstrap e quando alterei o card deles pra position: sticky, os elementos foram renderizados conforme o esperado. Não entendi muito bem porque deu certo


Research: Looking for a sequence that produce variation's of Pascal's triangle

Question: Prologue
I am an undergraduate so if my terminology or approach seem inappropriate/confusing please explain in the comments.
I created a notation where
$$F(0 \rightarrow n,x) = [\hspace{1mm}F(0 ,x),\hspace{2mm}F(1, x),\hspace{2mm}F(2, x), \ldots,\hspace{2mm} F(n-2,x),\hspace{2mm}F(n-1,x),\hspace{2mm}F( n,x)\hspace{1mm}]$$
Last semester in Calculus 1 I created a function noted as $\mu(e,f)$ where $f$,$e$ are just positive integers including 0 and if c is any numerical value then $\mu(c,c)=0$ and $\frac{d \mu(c,c)}{dx}=0$.  The interesting part was $$\frac{d \mu(e,f)}{dx}=\mu(e+1,f)+\mu(e,f+1)$$  I then figured out by playing around with the function that if $f>e + c$ for any real c then: $$\frac{d^\lambda \mu(e,f)}{(dx)^\lambda}=\sum_{i=0}^{\lambda}\binom{\lambda}{i}\mu(e+i,f+\lambda-i)$$
I figured this out by putting the Function into Pascal's Triangle,  where each row represents the derivative of the row before it.  I will call this triangle Pascal's Triangle for Functions (PTF).  For clarity I made some stuff that makes the patterns easier to see. In the equation $\frac{d \mu(e,f)}{dx}=\mu(e+1,f)+\mu(e,f+1)$, The $\mu(e+1,f)$ will be presented as $\swarrow$ and $\mu(e,f+1)$ will be presented as $\searrow$.  Let $G(j,k) = \mu(e+j,f+k)$ therefore $\frac{d G(j,k)}{dx}=G(j+1,k)+G(j,k+1)$.
\begin{equation}
G(0,0)\\
\swarrow\searrow \\
G(1,0)+G(0,1)\\
\swarrow\searrow\hspace{12mm}\swarrow\searrow\\
G(2,0)+2G(1,1)+G(0,2)\\
\swarrow\searrow\hspace{12mm}\swarrow\searrow\hspace{12mm}\swarrow\searrow \\
G(3,0)+3G(2,1)+3G(1,2)+G(0,3)\\
\swarrow\searrow\hspace{12mm}\swarrow\searrow\hspace{12mm}\swarrow\searrow\hspace{12mm}\swarrow\searrow \\
G(4,0)+4G(3,1)+6G(2,2)+4G(1,3)+G(0,4)\\
\swarrow\searrow\hspace{12mm}\swarrow\searrow\hspace{12mm}\swarrow\searrow\hspace{12mm}\swarrow\searrow\hspace{12mm}\swarrow\searrow \\
G(5,0)+5G(4,1)+10G(3,2)+10G(2,3)+5G(1,4)+G(0,5)\\
\ldots
\end{equation}
Anyways knowing $\mu(c,c)=0$ and $e$,$f$ are finite then let $\alpha = e-f$ so $\mu(f+\alpha,f)$.  I as the writer am going to ignorantly for the sake of clarity assume if a function ever becomes 0 that it no longer exists and therefore loses it's significant.  Therefore 0 will be replaced with white space for these illustrations.
If $\alpha=1$ and $e =0$
\begin{equation}
\hspace{5mm}\mu(0,1)\\
\hspace{5mm}\swarrow\searrow\\
[\hspace{1mm}0=\mu(1,1)\hspace{1mm}]+\mu(0,2)\\
\hspace{26mm}\swarrow\searrow\\
\hspace{25mm}\mu(1,2)+\mu(0,3)\\
\hspace{28mm}\swarrow\searrow\hspace{12mm}\swarrow\searrow\\
\hspace{15mm}[\hspace{1mm}0=\mu(2,2)\hspace{1mm}]+2\mu(1,3)+\mu(0,4)\\
\hspace{50mm}\swarrow\searrow\hspace{12mm}\swarrow\searrow\\
\hspace{51mm}2\mu(2,3)+3\mu(1,4)+\mu(0,5)\\
\hspace{58mm}\swarrow\searrow\hspace{12mm}\swarrow\searrow\hspace{10mm}\swarrow\searrow\\
\hspace{45mm}2[\hspace{1mm}0=\mu(3,3)\hspace{1mm}]+2\mu(2,4)+3\mu(1,5)+\mu(0,6)\\
\hspace{78mm}\swarrow\searrow\hspace{12mm}\swarrow\searrow\hspace{10mm}\swarrow\searrow\\
\hspace{75mm}2\mu(3,4)+5\mu(2,5)+4\mu(1,6)+\mu(0,7)\\
\ldots
\end{equation}
if $\alpha=2,e=0$:
\begin{equation}
\hspace{5mm}\mu(0,2)\\
\hspace{5mm}\swarrow\hspace{5mm}\searrow\\
\hspace{5mm}\mu(1,2)+\mu(0,3)\\
\hspace{8mm}\swarrow\hspace{5mm}\searrow\hspace{2mm}\swarrow\hspace{5mm}\searrow\\
\hspace{0mm}[\hspace{1mm}0=\mu(2,2)\hspace{1mm}]+2\mu(1,3)+\mu(0,4)\\
\hspace{28mm}\swarrow\hspace{5mm}\searrow\hspace{2mm}\swarrow\hspace{5mm}\searrow\\
\hspace{30mm}2\mu(2,3)+3\mu(2,4)+\mu(0,5)\\
\hspace{30mm}\swarrow\hspace{5mm}\searrow\hspace{3mm}\swarrow\hspace{5mm}\searrow\hspace{3mm}\swarrow\hspace{5mm}\searrow\\
\hspace{15mm}2[\hspace{1mm}0=\mu(3,3)\hspace{1mm}]+5\mu(2,4)+4\mu(1,5)+\mu(0,6)\\
\hspace{50mm}\swarrow\hspace{5mm}\searrow\hspace{3mm}\swarrow\hspace{5mm}\searrow\hspace{3mm}\swarrow\hspace{5mm}\searrow\\
\hspace{50mm}5\mu(3,4)+9\mu(2,5)+5\mu(1,6)+\mu(0,7)\\
\hspace{55mm}\swarrow\hspace{5mm}\searrow\hspace{6mm}\swarrow\hspace{5mm}\searrow\hspace{6mm}\swarrow\hspace{5mm}\searrow\hspace{6mm}\swarrow\hspace{5mm}\searrow\\
\hspace{40mm}5[\hspace{1mm}0=\mu(4,4)\hspace{1mm}]+14\mu(3,5)+14\mu(2,6)+6\mu(1,7)+\mu(0,8)\\
\ldots
\end{equation}
I created a function noted as $\Upsilon_\alpha(\beta,R)$, where $\beta=0,1,2...$ represents the row number, $\alpha=1,2...$ represents variation, $R$ represents the column of a row.  using the illastrations above I created some examples but I noted $\Upsilon_\alpha(\beta,R)$as $\binom{\beta}{R}_\alpha$ and I did not include the arrows.
If $\alpha=1$ and $e =0$
\begin{equation}
\hspace{5mm}\binom{0}{0}_1\mu(0,1)\\
[\hspace{1mm}0=\mu(1,1)\hspace{1mm}]+\binom{0}{0}_1\mu(0,2)\\
\hspace{25mm}\binom{1}{0}_1\mu(1,2)+\binom{1}{1}_1\mu(0,3)\\
\hspace{15mm}[\hspace{1mm}0=\mu(2,2)\hspace{1mm}]+\binom{1}{0}_1\mu(1,3)+\binom{1}{1}_1\mu(0,4)\\
\hspace{51mm}\binom{2}{0}_1\mu(2,3)+\binom{2}{1}_1\mu(1,4)+\binom{2}{2}_1\mu(0,5)\\
\hspace{45mm}2[\hspace{1mm}0=\mu(3,3)\hspace{1mm}]+\binom{2}{0}_1\mu(2,4)+\binom{2}{1}_1\mu(1,5)+\binom{2}{2}_1\mu(0,6)\\
\hspace{65mm}\binom{3}{0}_1\mu(3,4)+\binom{3}{1}_1\mu(2,5)+\binom{3}{2}_1\mu(1,6)+\binom{3}{3}_1\mu(0,7)\\
\ldots
\end{equation}
if $\alpha=2,e=0$:
\begin{equation}
\hspace{5mm}\binom{0}{0}_2\mu(0,2)\\
\hspace{5mm}\binom{1}{0}_2\mu(1,2)+\binom{1}{1}_2\mu(0,3)\\
\hspace{0mm}[\hspace{1mm}0=\mu(2,2)\hspace{1mm}]+\binom{1}{0}_2\mu(1,3)+\binom{1}{1}_2\mu(0,4)\\
\hspace{30mm}\binom{2}{0}_2\mu(2,3)+\binom{2}{1}_2\mu(2,4)+\binom{2}{2}_2\mu(0,5)\\
\hspace{15mm}[\hspace{1mm}0=\mu(3,3)\hspace{1mm}]+\binom{2}{0}_2\mu(2,4)+\binom{2}{1}_2\mu(1,5)+\binom{2}{2}_2\mu(0,6)\\
\hspace{50mm}\binom{3}{0}_2\mu(3,4)+\binom{3}{1}_2\mu(2,5)+\binom{3}{2}_2\mu(1,6)+\binom{3}{3}_2\mu(0,7)\\
\hspace{30mm}[\hspace{1mm}0=\mu(4,4)\hspace{1mm}]+\binom{3}{0}_2\mu(3,5)+\binom{3}{1}_2\mu(2,6)+\binom{3}{2}_2\mu(1,7)+\binom{3}{3}_2\mu(0,8)\\
\ldots
\end{equation}
if $\alpha=c,e=0$:
\begin{equation}
\binom{0}{0}_c\mu(0,c)\\
\binom{1}{0}_c\mu(1,c)+\binom{1}{1}_c\mu(0,c+1)\\
\ldots\\
\binom{c-1}{0}_c\mu(c-1,c)+\binom{c-1}{1}_c\mu(c-2,c+1)+\ldots+\binom{c-1}{c-2}_c\mu(1,2c-2)+\binom{c-1}{c-1}_c\mu(0,2c-1)\\
[\mu(c,c)=0]+\binom{c-1}{0}_c\mu(c-1,c+1)+\ldots+\binom{c-1}{c-2}_c\mu(1,2c-1)+\binom{c-1}{c-1}_c\mu(0,2c)\\
\end{equation}
I then realized that if I allow.
\begin{equation}
  R_{max}=\left\{
  \begin{array}{@{}ll@{}}
    \frac{\beta+\alpha+mod_2(\beta+\alpha)}{2}, & \text{if }\beta\geq\alpha \\
    \beta, & \text{if }\beta<\alpha
  \end{array}\right.
\end{equation}
AND
\begin{equation}
  \Gamma=\left\{
  \begin{array}{@{}ll@{}}
    \frac{\beta-\alpha+mod_2(\beta-\alpha)}{2}, & \text{if }\beta\geq\alpha \\
    0, & \text{if }\beta<\alpha
  \end{array}\right.
\end{equation}
Then the sum can be summarized by:
$$\frac{d^\beta \mu(e,e+\alpha)}{(dx)^\beta}=\sum_{i=0}^{R_{max}}\Upsilon_\alpha(\beta,R_{max}-i)\mu(e+i+\Gamma,e+\alpha+\beta-i)$$
And since I've always called $\binom{i}{R}$ the Pascal's Triangle notation I will call $\Upsilon_\alpha(\beta,R)$ the Variant of Pascal's Triangle notation (VPT)
another notable behavior is When $\beta<\alpha$ then $R_{max}=\beta, \Gamma=0$, remembering $f = e+\alpha$ then $$\frac{d^\beta \mu(e,e+\alpha)}{(dx)^\beta}=\frac{d^\beta \mu(e,f)}{(dx)^\beta}$$ $$\sum_{i=0}^{\beta}\Upsilon_\alpha(i,\beta-i)\mu(e+i,f+\beta-i)=\sum_{i=0}^{\beta}\binom{\beta}{\beta-i}\mu(e+i,f+\beta-i)$$
therefore $\Upsilon_\alpha(\beta,R_{max}-i)=\binom{\beta}{\beta-i}$ for $\beta<\alpha$
BUT If $\beta\geq\alpha$ then all of the Pascal's rules apply for all $R$'s in $\beta$ EXCEPT when $\beta=\alpha+1$ a the horizontal column of blank space called the "You Shall Not Pass Line", YSNPL, prevents any new functions from becoming created at the beyond or on the line. This is because of the property $\mu(c,c)=0$ and $\frac{d \mu(c,c)}{dx}=0$ prevent any function from going beyond or on that line of 0's.
examples of $\Upsilon_\alpha(\beta,R)$
In order to understand what I just wrote I created 3 examples classified as functions called Pascal's Triangle Numerical Version (PTN$(\alpha)$), Variant of Pascal's Triangle Numerical Version (VPTN$(\alpha)$), and Variant of Pascal's Triangle $\Upsilon_\alpha$ form (VPTY$(\alpha)$).
Both PTN$(\alpha)$ and VPTN$(\alpha)$ will produce 6 rows of their given sequence.
PTN$(\alpha)$ will produce Pascal's Triangle with $\alpha$ number circles around the left most 1 on a given row, starting with the top row.  The circles represent that part of Pascal's Triangle will not change after it encounter the given VPT.
VPTN$(\alpha)$ will show the VPT in numerical form.
VPTY$(\alpha)$ will produce the VPT in $\Upsilon_\alpha$ form
$
\hspace{10mm}\text{PTN(0):}\hspace{54mm}\text{VPTN(0):}\hspace{30mm}\text{VPTY(0):}\\
\hspace{12mm}(1)\hspace{70mm}1\hspace{40mm}\Upsilon_0(0 \rightarrow 0,0)\\
\hspace{12mm}1,1\hspace{72mm}1\hspace{38mm}\Upsilon_0(0 \rightarrow 0,1)\\
\hspace{10mm}1,2,1\hspace{68mm}1,1\hspace{36mm}\Upsilon_0(0 \rightarrow 1,2)\\
\hspace{8mm}1,3,3,1\hspace{68mm}2,1\hspace{34mm}\Upsilon_0(0 \rightarrow 1,3)\\
\hspace{6mm}1,4,6,4,1\hspace{64mm}2,3,1\hspace{32mm}\Upsilon_0(0 \rightarrow 2,4)\\
\hspace{2mm}1,5,10,10,5,1\hspace{62mm}5,4,1\hspace{30mm}\Upsilon_0(0 \rightarrow 2,5)
$
$\hspace{10mm}\text{PTN(1):}\hspace{55mm}\text{VPTN(1):}\hspace{30mm}\text{VPTY(1):}\\
\hspace{12mm}(1)\hspace{70mm} 1\hspace{40mm}\Upsilon_1(0 \rightarrow 0,0)\\
\hspace{10mm}(1),1\hspace{66mm}1,1\hspace{38mm}\Upsilon_1(0 \rightarrow 1,1)\\
\hspace{10mm}1,2,1\hspace{68mm}2,1\hspace{35mm}\Upsilon_1(0 \rightarrow 1,2)\\
\hspace{8mm}1,3,3,1\hspace{64mm}2,3,1\hspace{33mm}\Upsilon_1(0 \rightarrow 2,3)\\
\hspace{6mm}1,4,6,4,1\hspace{64mm}5,4,1\hspace{31mm}\Upsilon_1(0 \rightarrow 2,4)\\
\hspace{2mm}1,5,10,10,5,1\hspace{58mm}5,9,5,1\hspace{28mm}\Upsilon_1(0 \rightarrow 3,5)\\
$
$
\hspace{10mm}\text{PTN(2):}\hspace{55mm}\text{VPTN(2):}\hspace{30mm}\text{VPTY(2):}\\
\hspace{12mm}(1)\hspace{70mm}1\hspace{40mm}\Upsilon_2(0 \rightarrow 0,0)\\
\hspace{10mm}(1),1\hspace{66mm}1,1\hspace{38mm}\Upsilon_2(0 \rightarrow 1,1)\\
\hspace{8mm}(1),2,1\hspace{62mm}1,2,1\hspace{36mm}\Upsilon_2(0 \rightarrow 2,2)\\
\hspace{8mm}1,3,3,1\hspace{64mm}3,3,1\hspace{33mm}\Upsilon_2(0 \rightarrow 2,3)\\
\hspace{6mm}1,4,6,4,1\hspace{60mm}3,6,4,1\hspace{31mm}\Upsilon_2(0 \rightarrow 3,4)\\
\hspace{2mm}1,5,10,10,5,1\hspace{58mm}9,10,5,1\hspace{26mm}\Upsilon_2(0 \rightarrow 3,5)\\
$
$
\hspace{10mm}\text{PTN(3):}\hspace{55mm}\text{VPTN(3):}\hspace{30mm}\text{VPTY(3):}\\
\hspace{12mm}(1)\hspace{70mm}1\hspace{40mm}\Upsilon_3(0 \rightarrow 0,0)\\
\hspace{10mm}(1),1\hspace{66mm}1,1\hspace{38mm}\Upsilon_3(0 \rightarrow 1,1)\\
\hspace{8mm}(1),2,1\hspace{62mm}1,2,1\hspace{36mm}\Upsilon_3(0 \rightarrow 2,2)\\
\hspace{6mm}(1),3,3,1\hspace{58mm}1,3,3,1\hspace{34mm}\Upsilon_3(0 \rightarrow 3,3)\\
\hspace{6mm}1,4,6,4,1\hspace{60mm}4,6,4,1\hspace{31mm}\Upsilon_3(0 \rightarrow 3,4)\\
\hspace{2mm}1,5,10,10,5,1\hspace{52mm}4,10,10,5,1\hspace{26mm}\Upsilon_3(0 \rightarrow 3,5)\\
$
Remember $\alpha$ represents a variation of Pascal's Triangle, $\beta$ represents a row in $\alpha$ and $R$ represents a column in $\beta$.  One should have noticed for each $\alpha$ there is a invisible line where no new number exists on or to the left of that line, YSNPL.  One should have noticed for every column in $\beta$ the top right column and the top left column sum together in the row underneath, $\beta+1$, to create a new column in between both of the original columns.
While researching this phenomena I produced some results for $\alpha=1,2,\infty$
\begin{equation}
  \Upsilon_2(\beta+1,R)=\Upsilon_1(\beta,R) \text{ can be found in }\left\{
  \begin{array}{@{}ll@{}}
    \frac{R+1}{\beta+1}\binom{\beta+1}{(\frac{\beta-R}{2})}, & \text{if  }R<\beta \text{ and } mod_2(\beta-R)=0\\
    , & \text{otherwise}
  \end{array}\right.
\end{equation}
let $\eta=2R-mod_2(\beta+\alpha-1)$
if maximuim $R$ = $R_{max}$
$$\Upsilon_1(R,\beta)=\Upsilon_2(R,\beta+1)=\frac{\eta+1}{\beta+1}\binom{\beta+1}{\frac{\beta-\eta}{2}}$$
I found this by creating my own variant from the formula given in A008313
$\Upsilon_3$ in A026009 EQ UNKNOWN
$\Upsilon_4$ in A026022 EQ UNKNOWN
Since YSNPL only exists if $\beta=\alpha+1$ and $\beta\neq\infty$ if $\beta$ is finite.  Therefore the following statement must be true.$$\Upsilon_\infty(R,\beta) = \binom{R}{\beta}$$
My Question: Is this a known pattern?  Are there other known $\alpha$'s?  This code can find any triangle with a given $\alpha,\beta$
def tri(alpha,beta) :
    if alpha > 0 :
        D = [0]*((beta)//2+alpha); D[0] = 1
        b = False; h = 1
        for i in range(beta) :
            print([D[z] for z in range(0,h,1)])
            if i < alpha-1 :
                for R in range(h-1, -1, -1) : D[R+1] += D[R]
                h += 1
            else :
                if b :
                    for R in range(h, -1, -1) : D[R] += D[R-1]
                    h += 1
                else : for R in range(0, h-1, 1) : D[R] += D[R+1]
                b = not b
tri(1,10)
Comment: Where you wrote $\alpha{\leq}\beta{\leq}i$ I changed it to $\alpha\leq\beta\leq i$ simply by changing the code from \alpha{\leq}\beta{\leq}i to \alpha\leq\beta\leq i.  Why do you make that extra effort to put in those {curly braces} whose only effect is to prevent proper spacing? $\qquad$
Comment: @MichaelHardy I thought I always had to use the brackets to separate known words from characters and numbers which I believed included known words.  But thank's you for the assistance.
Comment: To write $\int_0^{12}$ you write \int_0^{12}, and if you omit the braces you see $\int_0^12$.  To write $\frac 1 {12}$ you can write \frac 1 {12} and if you omit the braces you see $\frac 1 12$.  For $\int_0^\infty$ you can write \int_0^\infty but for $\int_0^{+\infty}$ you write \int_0^{+\infty} and if you omit the braces you see $\int_0^+\infty$.  Those are some examples of what braces do. $\qquad$
Comment: Binary relation symbols and binary operators have some space before and after them, as in $5+3=8$, coded as 5+3=8, and if you write 5{+}3{=}8 then there's nothing before or after the "+" or the "=" so that space does not appear and you see $5{+}3{=}8$ instead of $5+3=8$. $\qquad$
Comment: I don't see where you actually define $\Upsilon_\alpha(\beta,\gamma)$.
Comment: @joriki I'm Trying to find $\Upsilon_\alpha(\beta,\gamma)$.  I am only a undergraduate so my terminology is very limited but the function $\Upsilon_\alpha(\beta,\gamma)$ should produce these results.
Comment: Are you saying that all you know about $\Upsilon_\alpha(\beta,\gamma)$ is these examples and you're looking for a general form that will produce these values? If so, what do you mean when you say that you "figured out" $\Upsilon_\infty(\beta,\gamma)$? Does this denote the limit of $\Upsilon_\alpha(\beta,\gamma)$ for $\alpha\to\infty$? If so, how can you "figure out" this limit if you don't have a general form for $\Upsilon_\alpha(\beta,\gamma)$ yet?
Comment: @joriki Yes the general form of $\Upsilon_\alpha(\beta,\gamma)$ should produce these results and $lim_{n{\rightarrow}\infty}\Upsilon_n(\beta,\gamma)\neq\Upsilon_\infty(\beta,{\gamma})$.  The $\alpha$ represents the left side cut off point on Pascals Triangle.  So if $\alpha$ = T then I use the techniques for producing Pascal's Triangle but only add T number of "1"s on the left side, including the first "1", and then I stop adding anything past that point.  So $\Upsilon_\infty(\beta,\gamma)$ represents a inifite number of "1" 's which should produce Pascal's Triangle.  srry bout gamma
Comment: This is still quite opaque to me. I think you need to specify much more clearly (in the question, not just in comments) what you know and what you're trying to find out. For instance, what you wrote in the above comment was not at all clear to me from the present phrasing of the question.
Comment: @joriki Does this make more since?
Comment: Yes, I can now figure out from the description and the examples what you mean; though I still think it would be a lot clearer if you gave a definition instead of mostly relying on examples.
Comment: @joriki How would I give a definition?
Comment: Something roughly like "Form Pascal's Triangle as usual, with each number the sum of the two numbers to its top left and top right (using $0$ for missing numbers), but, starting at row $\alpha$, omit $\left\lfloor\frac{\beta-\alpha}2\right\rfloor+1$ numbers on the left." I'm not sure about the details; that's just to give you an idea how to do it. You could then still use examples to clarify and illustrate, but at least one would have an explicit description of what you're doing instead of having to reverse-engineer it all from the examples.
Comment: Please do not use the [tag:undergraduate-research] tag. It is being removed.
Answer: \begin{equation}
  \Upsilon_\alpha(\beta,R)=\left\{
  \begin{array}{@{}ll@{}}
    \binom{\beta}{R}, & \text{if }\beta\leq\alpha  \\
     \binom{\beta}{R}, & \text{if }\beta\leq R+\alpha  \\
    \binom{\beta}{R}-\binom{\beta-\alpha}{R}, & \text{otherwise}
  \end{array}\right.
\end{equation}


Joining another table with existing junction table

Question: I'm fairly new to database design and could use some guidance with a project I'm working on.
I have three existing tables accounts, users, and a junction table representing the many-to-many relationship called accounts_users.
As you may guess, the accounts_users table looks like this:
| accountId | userId |
| --------- | ------ |
| 1         | 1      |
| 1         | 2      |
| 2         | 1      |

I need to add roles for users, where a user can have a singular role for each account they belong to.
I have created a role table (containing an id and name), but am looking for guidance on what the next step would be, in order to create a relationship between the roles and the accounts_users tables.
Should an extra column be added within the accounts_users table, containing the roleId or should there be another junction table added?
Thank you!
Comment: I would add a role column(s) to the junction table with a foreign  key to a roles table which contains role enrichment data (eg description). You might also consider if roles time expire (eg temporary power of attorney)
Answer: It is completely fine to store additional data in your junction table. You could use different approaches however, depending on the real meaning of your "role" entity.

If each account-user pair have its unique role associated (1:1 relationship), you could create the name column directly in the accounts_users table.
If one single role is shared between multiple account-user pairs (1:N relationship), you should use separate roles table and connect the tables by adding roleId foreign key into accounts_users table (just as you have written yourself).

The second solution is also suitable when the role entity bears big amount of information with it (multiple columns, not only name), so it's undesirable to mess the junction table with unrelated and possibly unneeded data.
Comment: The second bullet point is what I had in mind, so I'll go that route. Thank you so much!


Transpose an array of arrays

Question: Hah, I had no idea how else to phrase that. I'm trying to reformat a set of three arrays generated by form field inputs, into something that better matches my models, so I can save the values to the db.
Not sure if the solution should be some array manipulation or that I should change the "name" attribute in my form fields.
currently I have an array of my input data:
array(
  'image_id' =>
    array
      0 => '454' (length=3),
      1 => '455' (length=3),
      2 => '456' (length=3)
  'title' =>
    array
      0 => 'title1' (length=6),
      1 => 'title2' (length=0),
      2 => '' (length=6)
  'caption' =>
    array
      0 => 'caption1' (length=8),
      1 => '' (length=8),
      2 => 'caption3' (length=8)
);

and would like to change it to something like, so I can iterate over and save each array of values to the corresponding resource in my db.
array(
    0 =>
        array
        'image_id'  => '454',
        'title'     => 'title1',
        'caption'   => 'caption1'
    1 =>
        array
        'image_id'  => '455',
        'title'     => 'title2',
        'caption'   => ''
    2 =>
        array
        'image_id'  => '456',
        'title'     => '',
        'caption'   => 'caption3'
);

Comment: foreach trough the image_id child array
Comment: bit of google search would save your day :)
Comment: and what would I have googled? I tried but was having a hard time tryin to think of how to describe.
Answer: This'll do it:
$array = call_user_func_array('array_map', array_merge(
    [function () use ($array) { return array_combine(array_keys($array), func_get_args()); }],
    $array
));

Assuming though that this data is originally coming from an HTML form, you can fix the data right there already:
<input name="data[0][image_id]">
<input name="data[0][title]">
<input name="data[0][caption]">

<input name="data[1][image_id]">
<input name="data[1][title]">
<input name="data[1][caption]">

Then it will get to your server in the correct format already.
Comment: hmm if I do this I just get one big ol array with key "data" and the values all in one level:

`0 => 454
1 => title1
2 => caption 1
3 => 455
4 => title2`

etc.
Answer: This would iterate through the array with 2 foreach loops. They would use each other's key to construct the new array, so it would work in any case:
$data = array(
    'image_id' => array(454, 455, 456),
    'title' => array('title1', 'title2', ''),
    'caption' => array('caption1', '', 'caption3')
);

$result = array();
foreach($data as $key => $value) {
    foreach ($value as $k => $v) {
        $result[$k][$key] = $v;
    }
}

Transpose an array of arrays


After Spartacus upgrade from v1.5.5 to v2.1.6 shows error "Cannot read property 'getActive' of undefined"

Question: I have updated my storefront from v1.5.5 to v2.1.6.
It shows below error,
ERROR TypeError: Cannot read property 'getActive' of undefined
at spartacus-core.js:12517
check here for console output
Help me to fix this issue
Answer: did you follow the upgrade instructions?
Comment: Thanks @Erik.
I followed instructions from below docs, but not working.

https://sap.github.io/spartacus-docs/updating-to-version-2/

https://update.angular.io/?l=3&v=8.2-9.1


Does guitar fret spacing solely depend on the length of the string?

Question: On a typical guitar, the fret board has certain spacing between each fret.
Does the spacing of frets on a guitar solely depend on the length of the string? Meaning if I have multiple guitars of different shapes and materials, but all of the guitars have the same length of string, will their fret spacing be identical?
Do any other factors play into this spacing?
Comment: Yes..............
Answer: The spacing of the frets depends solely on the scale length of the guitar - which is easiest to understand if you think of it as being the distance between the nut and the saddle.  The nut is the slotted piece that is located at the base of the headstock and establishes the string spacing at that end of the guitar neck.  The saddle is located next to the bridge on the body of the guitar, and is what the strings pass over after being secured at the bridge by the ball ends of the strings (in the case of steel string guitar - nylon strings are usually tied to the bridge before passing over the saddle). The distance between the nut and saddle equals the length of the portion of the guitar string that vibrates to make sound.  It does not matter how long the guitar string is in total, the only part that matters is the part between the nut and saddle.
In the picture you included in your question, the scale length of the guitar pictured is indicated by the red line labeled # 1.
Your picture illustrates the fact that the fret spacing gets shorter as you get closer to the bridge.  If you were to put a capo on a guitar and then retune the guitar to standard tuning with the capo in place, you would in effect be shortening the scale.  The fret the capo is behind becomes the new "nut" in effect.  The new "first fret" after the capo will have a shorter space between the new "nut" and the new "first fret" than exist between the nut and the first fret on the guitar without the capo.
Different guitars even by the same maker will often have different scale lengths from model to model and a corresponding adjustment must be made to the spacing between frets.
If the spacing is not precise between frets, the guitar will not play in tune on all frets.  Some guitars have adjustable saddles which permit fine adjustments to the intonation to compensate for varying tuning characteristics of the particular guitar strings used - which can vary based on the type metal alloy the strings are made of and the diameter of the string.
Most saddles on acoustic guitars are "compensated" meaning they create a slightly different distance between point of contact at the saddle and the nut to compensate for the tuning differences between the larger diameter strings and smaller diameter strings.  But the frets are always perpendicular to the fretboard and the spacing between frets is always based on the overall scale.
Technically a guitars scale is the distance between the nut and the center of the 12th fret doubled.  The 12th fret is (for practical purposes) the midpoint between the nut and saddle.  Therefore, the distance between the nut and 12th fret would mandate the location of the saddle and the fret spacing would be calculated based on the scale length using Pythagoras Ratios (a mathematical calculation). The Pythagoras ratios determine how the length of a guitar string (as altered by each fret) corresponds to the relative difference in pitch of the same string at each different length.  For example, we know that halving the length of a guitar string (12th fret) will cause it to vibrate at a frequency which we will hear as the same note exactly one octave higher.  The other divisions are more complicated than dividing by two - but each ratio will have a specific effect on the relative vibration frequency (and thus pitch) of the strings.
For a more detailed explanation of how fret spacing is calculated you may click this link Math for Guitar Fret Spacing
Comment: 3/4 scale guitars aren't actually 3/4! It's a misnomer! They're actually closer to 7/8! Nut around fret two-and-three-quarters!
Comment: @CarlWitthoft You are correct about the actual fretted note played with or without a capo assuming the tuning remains standard.  Some folks will use a capo to shorten the scale and then re-tune to standard tuning with capo in place which would render the scale shortening effect I was alluding to.  I edited my answer to make that clear.  Thanks for the observation.
Comment: Just a comment: yes, a capo will change the harmonic series for that string so far as the position of open-fingered notes goes, but otherwise, for closed-fingerings (fully press string to fret) you get the same notes as un-capoed.
Comment: @Tim I believe you are correct.  I have a so called "3/4 scale" guitar and it is actually more like a 7/8.  Not sure why they call it 3/4.  I edited my answer to remove the questionable assertion.  Thanks for pointing it out.  Input in comments can help improve the content of the site and I appreciate you and Carl and others when helpful observations are made.
Comment: @CarlWitthoft  Here is proof that some folks shorten the scale by installing capo and re-tuning the guitar.  (https://music.stackexchange.com/q/53144/16897)
Comment: Wouldn't the ratios (typically) be the 12th root of two between each fret? Which would approximate / be approximated by the Pythagorean divisions, but also be more accurate for thirds and other intervals.
Comment: @awelotta you may be on to something there.  The only math I like is geometry so I will take your word for it.  Sounds logical.
Answer: Primarily, but not solely.
The fret spacing, and the progression of frets along the fretboard as you move toward the bridge, are based on the equal-tempered scale, and are primarily based on the total length of the string from nut to bridge.
However, two other variables affect how close a fit that fret progression is to the "ideal". Those are tuning and action. Simply put, the higher the open string is tuned, or the further the strings are intended to be off of the neck, the higher the tension a fretted string will have, and that will "pull" fretted notes sharp. If the instrument is designed for a higher (or lower) action, or for a higher (or lower) tuning,  the fret spacing may need adjustment in order to ensure that the transverse pressure placed on the string as it's fretted, adding to its tension, combines with its shorter fretted length to keep the note in tune at each fret.
In reality, these concerns are relatively minor for a factory-built instrument, unless your tastes in your guitar's action are really off. However, when building an instrument yourself, you cannot just lay out a totally mathematically-derived progression of frets along the fretboard and expect the thing to stay perfectly in tune. Even with the bridge intonation properly adjusted to bring the octave in tune, other frets are going to  be sharper if you lay out the fretboard this way. Most commercially-available layout guides leave the string's speaking length slightly longer than the mathematically-ideal length at each fret to compensate for the increased tension of the fretted string.
Comment: Technically correct.  Practically - not so easy for the average guitarist to comprehend or care about.  I know that the saddle on my acoustic guitars are less tall on the higher pitched treble strings to keep them closer to the fretboard which may also explain why the saddle is slanted - thereby creating a different scale length for the treble strings which are generally set up closer to the fretboard.
Answer: If you are talking about equal temperament 12 tone western tuning then yes. The length from bridge to nut sets the fret locations and hence the spacing.
Answer: Does the spacing of frets on a guitar solely depend on the length of the string? Meaning if I have multiple guitars of different shapes and materials, but all of the guitars have the same length of string, will their fret spacing be identical?
Yes.* ‡ Two guitars with the same scale length will have the same fret position.

You may find that, on a perfectly-intonated, perfectly-tuned guitar, that the G on the third fret of the E string will be flat. The C on the A string will be flat but less so. My recollection is that the culprit here is the radius of the string, but I could remember incorrectly. There are alternate nut systems, namely Earvana and Buzz Feiten, that change where the nut sits to allow better tuning on the first five frets. This will change where the nut sits in relation to the first fret. They're systems; it's not just the nut, but that's a big part of it.

‡ String radius is also a contributing factor in bridge position. Look at the bridge of a steel-string guitar and you will see the saddle for the lower strings will be further back than the higher strings. Doesn't change the scale length or the fret spacing, but the lower strings will be longer, saddle-to-nut, than the higher strings.
Comment: And a low string for a .008-.038 set will come in shorter than for a .012-.058 set


pandas time series average monthly volume

Question: I have csv time series data of once per day date, and cumulative sale.  Silimar to this
01-01-2010 12:10:10      50.00
01-02-2010 12:10:10      80.00
01-03-2010 12:10:10      110.00
.
. for each dat of 2010
.
01-01-2011 12:10:10      2311.00
01-02-2011 12:10:10      2345.00
01-03-2011 12:10:10      2445.00
.
. for each dat of 2011
.

and so on.

I am looking to get the monthly sale (max - min) for each month in each year.   Therefore for past 5 years, I will have 5 Jan values (max - min), 5 Feb values (max - min) ... and so on
once I have those, I next get the (5 years avg) for Jan, 5 years avg for Feb .. and so on.
Right now, I do this by slicing the original df [year/month] and then do the averaging over the specific month of the year.
I am looking to use time series resample() approach, but I am currently stuck at telling PD to sample monthly (max - min) for each month in [past 10 years from today]. and then chain in a .mean()
Any advice on an efficient way to do this with resample() would be appreciated.
Comment: It would be best if you showed the code you've tried.
Answer: It would probably look like something like this (note: no cumulative sale values). The key here is to perform a df.groupby() passing dt.year and dt.month.
import pandas as pd
import numpy as np

df = pd.DataFrame({
    'date': pd.date_range(start='2016-01-01',end='2017-12-31'),
    'sale': np.random.randint(100,200, size = 365*2+1)
})

# Get month max, min and size (and as they are sorted - last and first)
dfg = df.groupby([df.date.dt.year,df.date.dt.month])['sale'].agg(['last','first','size'])

# Assign new cols (diff and avg) and drop max min size
dfg = dfg.assign(diff = dfg['last'] - dfg['first'])
dfg = dfg.assign(avg = dfg['diff'] / dfg['size']).drop(['last','first','size'], axis=1)

# Rename index cols
dfg.index = dfg.index.rename(['Year','Month'])

print(dfg.head(6))

Returns:
            diff       avg
Year Month
2016 1       -56 -1.806452
     2       -17 -0.586207
     3        30  0.967742
     4        34  1.133333
     5        46  1.483871
     6         2  0.066667

Answer: You can do it with a resample*2:

First resample to a month (M) and get the diff (max()-min())
Then resample to 5 years (5AS), and groupby month and take the mean()

E.g.:
In []:
date_range = pd.date_range(start='2008-01-01',end='2017-12-31')
df = pd.DataFrame({'sale': np.random.randint(100, 200, size=date_range.size)},
                  index=date_range)

In []:
df1 = df.resample('M').apply(lambda g: g.max()-g.min())
df1.resample('5AS').apply(lambda g: g.groupby(g.index.month).mean()).unstack()

Out[]:
            sale
              1     2     3     4     5     6     7     8     9     10    11    12
2008-01-01  95.4  90.2  95.2  95.4  93.2  93.8  91.8  95.6  93.4  93.4  94.2  93.8
2013-01-01  93.2  96.4  92.8  96.4  92.6  93.0  93.2  92.6  91.2  93.2  91.8  92.2


Feed Forward Neural Network - How to Visualize the Weight Matrix?

Question: I'm a bit confused about the visualization of the weights of a feed forward neural network as provided in this example from scikit-learn. The network has an architecture of [784 x 50 x 10] (MNIST dataset), so n_hidden = 50 (there are 50 hidden units). Each of the hidden units is a column of the weight matrix W_1 (with dimension 784x50), right? From this, I thought, we could create 50 images, each of size 28x28 (=784). However, there are only 16 images shown? What is my mistake here?

EDIT
Since someone downvoted the question without explanation, here is what I assume. In the particular example stated above, one could acutally draw 50 pictures. Visualizing only 16 filters (4x4) was choosen for convenience.
Comment: Interesting question. But I have a question for you too: have you run the code yourself too? The author of the article might have chosen to show only 16/50 neurons. So if you didn't run the script yourself: do so!
Comment: @Thomas W, I did and came to the same conclusion as you. Just really thought I misunderstood something and went over and over again. There is a similar example on the theano tutorial side where they just visualized 100/500 neurons without further explanation.
Answer: You're right, and there should be 50 images. You could easily verfiy this by:
[coef.shape for coef in mlp.coefs_[0]]

where mlp is the trained MLP classifer in the example.
So here are the two things caused confusion:

Clearly, the author of the example did not mention anything about why only 16 images
In Python when you zip two things in the for loop that don't have equal length (number of items) in this example zip(mlp.coefs_[0].T, axes.ravel()), Python will automatically ignore the extra items in the bigger lists (arrays, etc.). Here axes.ravel() has only 16 items, therefore, the loop iterates over first 16 vectors in mlp.coefs_[0]


Why is the set of all non-decreasing sequence not open in the real sequence space?

Question: Given the set $B=\{a\in \Bbb R^{\Bbb N}|\exists C \in \Bbb R \forall n \in \Bbb N:|a(n)<C\}$ with the distance $d(a(n),b(n)):= \sup|a(n)-b(n)|$.
Take the set $J:=\{a\in B| \forall n \in \Bbb N: a(n+1)\geq a(n)\} $
I know that $J$ is not open in the metric space $B$ but I want to make sure I know exactly why.
So take the null sequence $0\in J$. This is an element of J as each member is zero and so the condition $a(n+1)\geq a(n)$ is satisfied as zero is equal to zero.
Next consider an open ball centered at $0$, $B_r(0)$, so the taking the metric $d(0,b(n)):=\sup|0-b(n)|= \sup |b(n)|$ the open ball is $B_r(0)=\{b(n)|d(0,b(n)) <r\}$, In other words $\sup|b(n)|<r$. okay honestly after this I'm stuck. I don't know why no open ball exists in $J$ which is centered at zero . could anyone explain ?
Answer: The assertion is equivalent to the existence of arbitrarily small points in the complement of the set. Now consider the element
$$
c(n) := \begin{cases}
\epsilon & n=1 \\
0 & n \ge 2.
\end{cases}
$$
It violates the condition of $J$, but is close to zero with regard t your metric.
Comment: okay I think I understand...c(n) is arbitrarily close to my null sequence 0 so it exists in an open ball $B_\epsilon(0)$ but it does not exist in Jso then this open ball does not exist soley in J and so J cannot be open ?
Comment: could you tell me if that's correct ?
Comment: Unfortunately my browser does not render comments with math-dollars. Could you rephrase accordingly?
Comment: okay I think I understand...c(n) is arbitrarily close to my null sequence 0 so it exists in an open ball Bϵ(0) but it does not exist in Jso then this open ball does not exist soley in J and so J cannot be open ?I took out the math dollars around the open ball... i thjink this is what you meant
Comment: if not I can rewrite it again, just not sure if that's what you meant or not
Comment: Thanks. The point is that for any open ball about J, if we make epsilon sufficiently small, then c(n) is not in it. An open set (with regard to the topology induced by the metric) has by def. the property that each point contains an open ball about it. And the 0-element violates that condition for J.
Comment: surely though $c_n$ is not in J regardless of how small epsilon is though , no ? considering that it is constructed to have its first entry as some number greater than zero and all the rest zero, which already violates J's condition ? secondly I'm still not totally sure why the 0-element  has NO open ball around it , is it because there are sequences that do belong to J and others that don't that exist within any open ball centred around 0 ?
Comment: "surely though c(n) is not in J regardless of how small epsilon is though , no ?" that's precisely the point.
Comment: I mean even if we didn't make it sufficiently small, like say epsilon was 10000. but perhaps i'm focusing too much on an unimportant detail here
Comment: still though what about my second point about why there is no open ball around the null-element
Comment: Because c(n) is not in it, it's not in J but it's in the open ball. So the open ball is not in J.
Comment: excellent we're on the same page now.. thank you :)


Python Regex Named Groups

Question: I'm currently trying to solve a problem splitting following string
[@x arg-xa, arg. xb, arg xc @y arg-ya, arg. yb, arg yc @z arg-za, arg. zb, arg zc]

into some kind of structured dict object. A result like the following list would be appreciated:
[
    {
        'command': 'x',
        'args': ['arg-xa', 'arg. xb', 'arg xc']
    },
    {
        'command': 'y',
        'args': ['arg-ya', 'arg. yb', 'arg yc']
    }
    {
        'command': 'z',
        'args': ['arg-za', 'arg. zb', 'arg zc']
    }
]

The command is prefixed with an "@" sign, the following arguments for the command are separated by a "," sign.
Splitting the string with string.split('@') and some loops would work, but I'm wondering if it would be possible to solve this with one single regex.
Maybe some regex master would be so kind and show me the light!
As always, thank's a lot.
(I used the search, but haven't found a solution for this kind of problem)
Comment: This pretty weird regex: `\@(?P\w+)(?P,\s?[\w\s-]+)\@?`
Answer: I'd just use .split() and cut the string up:
import string

s = '@x arg-xa, arg. xb, arg xc @y arg-ya, arg. yb, arg yc @z arg-za, arg. zb, arg zc'

result = []

for part in s.split('@')[1:]:  # `[1:]` skips the first (empty) element
    command, _, arguments = part.partition(' ')

    result.append({
        'command': command,
        'args': map(string.strip, arguments.split(', '))
    })

Comment: Yeah, it does work - I don't use Python much. I think it can be improved a bit by trimming spaces, though.
Comment: @Blender Thank's for your solution! Really appreciate it. But I know that it works with string.split method and loops. I was specificaly interested in a regex. Sure, your's is working and if no regex comes up, I'm happy to accept your answer...
Comment: @Blender: There are some excessive space at the end of last argument of the 1st and 2nd item in result.
Comment: @hetsch: You won't be able to do it with just regex.
Comment: @Blender Think you are right. Trying now for some time, but no result. Really like your solution. Thank's again for your help, accepted!
Comment: @Blender: I think it is possible with just regex - just provide replacement function to `sub` with closure, and an appropriate regex. But I think the straightforward solution above is much cleaner.
Comment: @nhahtdh This was also my idea. My problem was to find a working repeating pattern for the arguments.

Python Regex Named Groups


Does a folder need to be unzipped in order for a macro to access its files?

Question: Does a folder need to be unzipped in order for a macro to access its files? I am trying to move files from a zipped file to their respective folder and would like to know if the folder needs to be unzipped for a File System Object to copy it. Thanks
Comment: The easiest way to find out is to try it, but the answer is no.
Comment: I hope this old link can help you:
[Can Windows' built-in ZIP compression be scripted?](https://stackoverflow.com/questions/30211/can-windows-built-in-zip-compression-be-scripted/124775#124775)
Comment: A good resource for this:  https://www.rondebruin.nl/win/section7.htm  Basically you can do what you want but I don't think you can use FSO to do it.
Comment: Thanks for the input!
Answer: <code>Sub MoveFiles()
    Dim FSO As Object
    Dim SourceFileName As String, DestinFileName As String

    Set FSO = CreateObject("Scripting.Filesystemobject")

    SourceFileName = Sheets("NIS File Allocation").Cells(2, 2).Value
    DestinFileName = Sheets("NIS File Allocation").Cells(2, 7).Value
    MsgBox FSO.FileExists(SourceFileName)

    Call FSO.CopyFile(SourceFileName, DestinFileName, False)

    MsgBox (SourceFileName + " Copied to " + DestinFileName)

End Sub
</code>
When running this code, SourceFileName must be in an unzipped folder in order to copy it to the destination file. Otherwise a "Path Not Found" Error will result. Tested with .FileExists


Rate-limiting & dropping natted packets, EXCEPT for 5 local networks

Question: Basically, I am trying to rate-limit requests to a mailserver at the firewall level, but whitelist several company-owned IP ranges.  I can whitelist one IP addresses range, but not several, because of the nature of "first matching rule takes the packet."
Here is what I have currently... (sorry for the mix of -I and -A)
# Send traffic to rate-limiter before allowing it to continue to the mail server.
iptables -t nat -I PREROUTING -d 188.8.131.52 -p tcp --destination-port 25 -j DNAT --to-destination 192.168.250.71:25
iptables -t nat -I PREROUTING -d 22.214.171.124 -p tcp --destination-port 143 -j DNAT --to-destination 192.168.250.71:143
iptables -t nat -I PREROUTING -d 184.108.40.206 -p tcp --destination-port 993 -j DNAT --to-destination 192.168.250.71:993
iptables -t mangle -I PREROUTING -d 184.108.40.206 -p tcp --destination-port 25 -j rate-limiter
iptables -t mangle -I PREROUTING -d 18.104.22.168 -p tcp --destination-port 143 -j rate-limiter
iptables -t mangle -I PREROUTING -d 188.8.131.52 -p tcp --destination-port 993 -j rate-limiter

# Create a new chain, which logs all traffic then drops it.
# We make sure that localnets are not part of this...
iptables -t mangle -N rate-limiter
iptables -t mangle -A rate-limiter -p tcp --syn -d 188.8.131.52 ! -s 192.168.254.0/24 -m state --state NEW -m recent --set --name MailRateLimiter --rsource
iptables -t mangle -A rate-limiter -p tcp --syn -d 126.96.36.199 ! -s 22.214.171.124/24 -m state --state NEW -m recent --set --name MailRateLimiter --rsource

iptables -t mangle -A rate-limiter -p tcp --syn -d 188.8.131.52 ! -s 192.168.250.0/24 -m state --state NEW -m recent --rcheck --seconds 60 --hitcount 20 --name MailRateLimiter --rsource -j LOG --log-prefix 'RATE EXCEEDED' --log-level 4
iptables -t mangle -A rate-limiter -p tcp --syn -d 22.214.171.124 ! -s 192.168.250.0/24 -m state --state NEW -m recent --rcheck --seconds 60 --hitcount 20 --name MailRateLimiter --rsource -j DROP

iptables -t mangle -A rate-limiter -p tcp --syn -d 126.96.36.199 ! -s 184.108.40.206/24 -m state --state NEW -m recent --rcheck --seconds 60 --hitcount 20 --name MailRateLimiter --rsource -j LOG --log-prefix 'RATE EXCEEDED' --log-level 4
iptables -t mangle -A rate-limiter -p tcp --syn -d 188.8.131.52 ! -s 220.127.116.11/24 -m state --state NEW -m recent --rcheck --seconds 60 --hitcount 20 --name MailRateLimiter --rsource -j DROP

So, the first rule matches the packet, then marks it in the recent table, so when I cat /proc/self/net/xt_recent/MailRateLimiter, I see IPs that should be whitelisted:
src=18.104.22.168 ttl: 57 last_seen: 56654988107 oldest_pkt: 8 56654320106, 56654370481, 56654426548, 56654480458, 56654564349, 56654565421, 56654952936, 56654988107
src=22.214.171.124 ttl: 63 last_seen: 56655077970 oldest_pkt: 9 56654962465, 56654962465, 56654978465, 56655024835, 56655031038, 56655037096, 56655048206, 56655059305, 56655077970, 56654768325, 56654777150, 56654802008, 56654807677, 56654816481, 56654842497, 56654846996, 56654855809, 56654886875, 5665489136

Forgive me if it is something stupid... It has been a long day, and I kind of got thrown into this...
Answer: You can whitelist anything you want writing the following at the top of the CHAIN:
iptables -t mangle -A rate-limiter <rule to match whitelisted> -j RETURN
Packets matching the whitelisted networks will return to POSTROUTING without modification.
Comment: THANK YOU!  I didn't know you could do that!  Worked perfectly.


Match user from list against filenames

Question: I have a long winded script that gets a user from an CSV file, matches user against a CSV filename from a specific directory.
The user is matched against this CSV file in this format <data><samaccountname><text>.csv
The aim here is to get an AD User from a list, then scan a folder with CSV Files in it and match against the user. From there restore the user AD attributes.
The issue here is that the output is always of the last user twice, I have REM out the export at the end so I can see what is on screen first.
Clear-Host
#Get username from users list and match against CSV file name.
$FDate = (get-date).ToString("yyyMMdd")
$Project = "<FolderPath>" #Project name used to setup folders and for reports etc
$ProjectRoot = "<path>\" # Backup folder
$RestorePath = $ProjectRoot + $Project #combined path for restoring
$UsersListFile = $ProjectRoot + '\Userlist.csv' #Userlist
$Results = @{} # Storage for all csv files
$PSObject = New-Object psobject
$Report = @() #For Export-CSV
$Results = gci $RestorePath -Filter '*.csv'

$i = 0
foreach ($File in $Results) {
  $i += 1
  Write-Host 'Number of passes - '$i
  Write-Host 'Current file processing - '$file.Name -for Green
  foreach ($User in (import-csv $UsersListFile)) {
    $SAM = $User.SamAccountName
    Write-Host 'Current User processing - '$SAM -ForegroundColor Magenta

    if ($file.Name -match $SAM) {
      Write-host "Filename and user $SAM match " -for Yellow
      $Row= New-Object psobject
      $ROW | Add-Member -type NoteProperty -name Name -value $SAM -force
      $Report += $Row

      foreach ($Attrib in (import-csv $restorepath\$file)) {
        #Write-host 'Attributes in file - ' $attrib.samaccountname $Attrib.mail -for Yellow
        #Use this to restore AD User data
      }
    } else {
      Write-Host "No match" -ForegroundColor Red
    }
  }
}
#$Report | Export-Csv $RestorePath'\Test.csv' -NoTypeInformation -Force
$Report | Sort-Object Name

Answer: Updated script to move New-Object psobject to above $Row, so this creates a new object each time, rather then overwriting previous entry.

Match user from list against filenames


Qual proveito tirar do life cycle do Jsf?

Question: Pessoal eu vejo pessoas falando que se deve entender o ciclo de vida do JSF. E eu queria entender quais utilidades teremos ao entender?
Answer: Como toda linguagem de programação, vc deve saber o básico de como ela funciona. JSF não é diferente mas não significa dizer que vc não consiga construir um sistema se não souber o seu ciclo de vida. Estudar-lo é apenas para saber como, quando e onde utilizar os recursos avançados dele. Se vc souber as respostas das questões abaixo significa que não precisa estudar o ciclo de vida. Vejamos:

Vc sabe quando a árvore do JSF não precisa ser renderizada ou quando os dados precisam ser mantidos na página caso aconteça algum problema?
Vc sabe quando os métodos SET são chamados, ou seja, quando os valores são atualizados?
Vc sabe quando são realizados os processos de validações? Sabe quando ele verifica se um campo é obrigatório ou quando seu validador personalizado é executado?
Vc sabe quando a ação originada de um botão ou link clicado é executada?
E, por último, vc sabe quando tudo que foi pedido pra ser feito, e processado com sucesso, é apresentado?

Se vc souber as respostas pra essas e outras questões, como saber que o immediate em um componente de ação faça com que alguns ciclos de vidas sejam ignorados, pode ajudar e muito em certos casos.
Obs.: O escopo utilizado influencia e muito no ciclo de vida assim, além de estudar o ciclo, estude os escopos.
Comment: @Macario1983 é por esses motivos que muita gente recomenda estudar-lo. Boa sorte!
Comment: @Macario1983, acho que é proibido recomendar coisas aqui mas, arriscando, eu recomendo o Core JavaServer Faces - David Geary. Esse é excelente!
Comment: Bacana sua resposta, eu realmente não sei atualmente responder todas. Mas minha curiosidade partiu porque vejo muito a se falar disso e também de um problema outro dia que surgiu de certos métodos serem chamados a todo momento quando se esta carregando a página.
Comment: Cara você recomenda algum material para ler.?


How to divide a data.frame into seversal data.frames according to the first row numer? or divide data.frame when the number is not ascending

Question: df <- tibble(NumberA = c(1,2,3,4,5,1,2,3,4,1,2),NumberB = c(2,3,4,3,3,1,2,3,2,2,1))

original data:

divided data:

Then, calculate: mean(abs(the column of Number B minus the column of Number A)))
Comment: Most likely this post is a duplicate, try: `split(df, cumsum(df$NumberA == 1))`
Answer: split(df, cumsum(c(FALSE, diff(df$NumberA) < 0)))
# $`0`
# # A tibble: 5 x 2
#   NumberA NumberB
#     <dbl>   <dbl>
# 1       1       2
# 2       2       3
# 3       3       4
# 4       4       3
# 5       5       3
# $`1`
# # A tibble: 4 x 2
#   NumberA NumberB
#     <dbl>   <dbl>
# 1       1       1
# 2       2       2
# 3       3       3
# 4       4       2
# $`2`
# # A tibble: 2 x 2
#   NumberA NumberB
#     <dbl>   <dbl>
# 1       1       2
# 2       2       1

Comment: Same story......
Comment: split(df, cumsum(c(FALSE, diff(df$NumberA) < = 0)))
Comment: @zx8754 same reply. I have no issue with marking it as duplicate, in fact I support it. The premise of duplicates is strong, but sometimes new users don't know how to adapt the other question's answer(s) to their particular question. It's not hard to justify this difficulty as "growing pains", I think saying it's a dupe and then how to apply that to their details are both relevant. While I agree that it would be better if I found the dupe first, sometimes it's much easier to just dump some code quickly and label as dupe second. Thanks for your diligence, don't judge me please.


Calculating Revenue per customer for a series of emails over time, which have a normal decay rate

Question: I am analyzing data for an email marketing company.
We have x amount of subscribers that come in at some point in time.
We promote zero or more emails to these individuals daily, for several months.
I want to determine what the "best performing" emails are, as a function of Revenue per subscriber (RPS).

revenue per subscriber = revenue for that email/number of subscribers that email was sent to

Where I am facing difficulty is factoring the natural decline in revenue that occurs as the email list becomes old. Average RPS declines naturally over time for several reasons (people unsubscribe, people stop opening emails, etc.)
The natural decline means that I cannot simply rank the RPS over time and look at what values are the highest, because this would not account for the natural decline. i.e. and RPS of 100 is much more valuable when the list is 6 months old, than when it is 1 week old.
Hopefully that makes sense, and I apologize if this question is simple. I am pretty new to statistics and data analysis, so bear with me.
I would appreciate if you could tell me how to arrive at an answer (what are the best performing emails) as opposed to just giving me a straight answer.
Answer: There's a ton of marketing science literature now on "customer lifetime value." For instance, there's a paper from 2004 by Gupta, Lehmann and Stuart Valuing Customers that is one of the first papers by academics. Wharton has it's Customer Analytics Initiative that is quite actively developing CLV models today.
What you're describing as a "natural decline" in response is simply a survival (or attrition) curve which could be fit with a Cox hazard model or any number of other parametric and nonparametric forms beginning with an exponential curve (constant decay rate) and extending from there.
So, at its simplest for a given time period (e.g., weekly, monthly, quarterly), Revenue (or net profit) can be a function of (Expected Revenue - Costs (acquisition, fulfillment, creative, etc.)) * Probability of Survival.
The models become more complicated as more factors are introduced. For instance, the Wharton guys try to improve and augment financial models of corporate valuation by introducing customer metrics such as these.
Comment: Will have to do a lot of reading before I can fully grasp your comment, but that is exactly what I wanted, a lead. Thank you


Maclaurin series of $\frac{2}{1+ \cosh(z)}$

Question: I'm trying to find the radius of convergence of the Maclaurin series of $f(z)= \frac{2}{1+ cosh(z)} $.
I've tried substituting for z in the known series $ \frac{1}{1-z} = \sum_{n=0}^\infty{z^n}$ with known radius of convergence $|z| < 1$, and get the  following:
$$ \frac{2}{1+\cosh (z)} = \sum_{n=0}^\infty{(-1)^n (e^z + e^{-z})^n}$$
$$|\cosh{z}| < 1 \Rightarrow  |\frac{e^z + e^{-z}}{2}|<1 \Rightarrow |z| < \pi i$$
The radius of convergence is therefore $\pi$.

Does this reasoning make sense?
I'm unable to get any further with the series above. How can I convert it into a power series?
The answer to this question states that the radius of convergence is the distance in the complex plane to the nearest singularity, which makes the problem much easier - one can just set the denominator equal to 0 and solve for $z$, which gives the same answer. However, this seems to assume that every function is analytic everywhere except at singularities, an assumption I have trouble justifying.
Comment: The problem is not all expansions have nice derivatives. Try expanding $( \sech ( \frac{z}{2} ))^2$
Answer: This makes little sense since:
$$\cosh z\ge 1$$
along the real axis so that you cannot apply the formula for geometric series which is valid only for $|z|<1$.
The reasoning (3.) is the correct one.
Comment: If a function $f(z)$ is analytic everywhere and has only isolated zeros  its reciprocal $1/f(z)$ is analytic everywhere except for zeros of $f(z)$.
Comment: Thanks for the explanation. How does one get around (or prove) the assumption that the function is analytic everywhere except at singularities?


Are these two definitions for paracompactness equivalent at least for manifolds?

Question: My lecturer defined paracompactness as follows:

A topological space $X$ is called paracompact if for any open cover $\{U_\alpha\}$ of $X$ there is a locally finite subcover, i.e. for any $x\in X$ there are some $\alpha_1, ..., \alpha_k$ such that $x\in U_{\alpha_1} \cap ...\cap U_{\alpha_k}$.

Then another instructor defined paracompactness like this:

A topological space $X$ is called paracompact if for any open cover $
   \{U_\alpha\}$ of $X$ there is a locally finite refinement, where locally finite and refinement are defined exactly like here.

These two definitions don't look equivalent to me simply because a subcover is a refinement, but this is not true the other way around. However, I encountered these definitions in a differential geometry course, so I am wondering whether for manifolds (which are Hausdorff and second countable) the first definition is in fact equivalent to the second one (which I am sure is the correct one since this is how I found paracompactness defined everywhere).
Comment: @SassatelliGiulio you are right. In words, my lecturer wanted to say that every point $x \in X$ is only in finitely many sets of the cover $\{U_\alpha\}$ (he basically took the usual definition of paracompactness and replaced "refinement" with "subcover"). Is it clear now? I am not quite sure how to express this mathematically, now I see that his wording on the blackboard was indeed incomplete.
Answer: I think in the first definition you've meant

i.e. for any $x\in X$ the set $\{U_\alpha\ |\ x\in U_\alpha\}$ is finite

or maybe

i.e. for any $x\in X$ there is an open neighbourhood $U$ of $x$ such that $\{U_\alpha\ |\ U_\alpha\cap U\neq\emptyset\}$ is finite

The second variant is closer to the (as you will see soon) correct definition of paracompactness. Otherwise the definition you've proposed is satisfied by every open cover of every topological space.

Either way, the answer is: no, these are not equivalent. For manifolds as well.

Lemma. Assume that $X$ is a topological space. Then every open cover of $X$ admits locally finite subcover if and only if $X$ is compact.

Proof. "$\Leftarrow$" Simple exercise.
"$\Rightarrow$" Let $\mathcal{U}$ be an open cover of $X$. We will show that under our assumptions it has a finite subcover.
Pick $U\in\mathcal{U}$ and $x\in U$. Define $\mathcal{V}=\{V\cup U\ |\ V\in\mathcal{U}\}$. Note that $\mathcal{V}$ is a new cover of $X$ such that $x$ belongs to every open set in the cover. By our assumption $\mathcal{V}$ admits a locally finite subcover $\mathcal{V}'$, but that is possible only when $\mathcal{V}'$ is finite (regardless of which definition we choose), because $x$ belongs to every element of $\mathcal{V}'$ as well. But then for each $V'\in\mathcal{V}'$ there is $V\in\mathcal{U}$ such that $V'=V\cup U$. These new $\{V\}$ together with $U$ form a finite subcover of $\mathcal{U}$. Thus $X$ is compact. $\Box$

As you can see your first definition is equivalent to compactness. And therefore is wrong.
Comment: @MathIsCool correct. Your lecturer made a mistake with the first one.
Comment: The first variant describes point-finiteness.
Comment: @freakish thank you very much! So, only the second definition that I wrote is correct and the first one is just something that has nothing to do with paracompactness even for manifolds, right?


How can one Rewrite results of a view using a Group By

Question: I have created a view and then added a group by a certain field. Normally one would just add a new field then rewrite the results with custom html using replacement patterns.
How would I go about this when I use group by
Answer: You can use both Rewrite and Grouping at the same time. You can Rewrite the field and use that as Group by.
If you need the same Field in the results as well as in the Group by headings, then simply add the Field twice. You can style/Rewrite them separately too.
If you want to style the grouping in a special way, or need more than one field in the Group, then you can use the Custom text field for advanced styling of the Group. You can see an example in this article: Control Group by styling with Custom text field


Question concerning how a map extends to a homomorphism.

Question: Let $G$ be a finite group with finite set of generators $g_1,g_2,...$ that is not known "explicitly" as a group, but rather indirectly as a faithful representation as a subgroup of $S_n$. If I define a map $f$ from $G$ to another group $H$, that is defined on the generators $g_i$ satisfies $g_i^t=1$ then $(f(g_i))^t=1$ and I do not have a full set of relations, but just know the group as a subgroup in $S_n$, is there something I can do to check whether $f$ can be extended to a well defined homomorphism, that does not require checking if $f(ab)=f(a)*f(b)$ holds for all elements $a,b$? So does there exist a smaller subset I can check this equation on to ensure it holds on the whole of $G$? Or can always no matter how big this proper subset is, something go wrong?
As an example, suppose I know the orders of the pairwise products $(g_ig_j)^k=1$ and I check $(f(g_i)*f(g_j))^k=1$ does this imply $f$ can be extended as a well defined homomorphism? (I assume not)
Answer: A collection of relations $R_1(g_1,g_2,\ldots),R_2(g_1,g_2,\ldots),\ldots$ in the generators is sufficient for your check (that is: it suffices to verify that $R_1(f(g_1), f(g_2),\ldots)=1$ etc.) if and only if the group presentation $\langle \,x_1,\ldots,x_n\mid R_1(x_1,x_2,\ldots), R_2(x_1,x_2,\ldots), \ldots\,\rangle$ is isomorphic to $G$ (via $x_i\mapsto g_i$).
Hence only verifying orders of the $g_i$ is not suffifiecnt (unless you have only one generator) because groups $\langle\,x_1,\ldots,x_k\mid x_1^{n_1}=x_2^{n_2}=\ldots=x_k^{n_k}=1\,\rangle$ are infinite (if $k\ge2$) and your $G$ is finite.
Only verifying orders of pairwise products will also not be sufficient except in trivial cases. It is hard to tell when a set of relations is sufficient, but one pleasent situation is when the relations allow you to rewrite an arbitrary word in the generators (and their inverses!) into a standard order (e.g. always into the form $g_1^{a_1}g_2^{a_2}\ldots g_n^{a_n}$), for example if you have relations $g_ig_j=g_j^ag_i^b$ for all $i>j$ - which is not possible for all $G$.


What are the best practices around changing the DNS for a major site

Question: We just completed a site redesign and the new version was deployed to a different server.  The domain name entry was updated and everything works fine.  But some users who still have the old DNS value cached are getting the old site.  This is expected to happen for a short period.  But I want to know what things we can do to minimize this in the future.  I'm thinking of tips involving TTLs and things.
Unrelated: It seems that once something is marked community wiki you can't undo it.  It was my mistake and I'm not sure if it's good or bad.
Answer: I'd recommend changing the TTL to something low a couple of days before you change DNS entries.  That way, hopefully, when you change the dns the site will go live much quicker for most people.
Comment: Yeah that's what I was thinking, but didn't know if that was a "best practice" or if it had any downsides. I'm just a lowly web dev who has been coerced into doing sys admin work ;)
Answer: Last time I needed to do this, I arranged for the old server to transparently redirect all traffic to the new for the TTL period following the DNS record change.
Comment: There are a couple of reasons I can't do this.  The domain is the same, it's only the ip that has changed.  So if their cached dns is still sending them to the old ip, where would I redirect to?  Also, there are other small apps running in virtual hosts on the new server.  So hitting the ip doesn't give you the main site (and probably shouldn't).
Comment: What the parent is suggesting is to keep the old IP live during the transition (Either put it on the new server or have the old server port-forward).  This (in combination with reducing the TTL a few days before the migration) is generally the best way to go as some ISPs DNS servers don't respect TTL values.
Answer: As there are many systems that ignore TTL I suggest that on the original server you kill the site and replace it with a redirect using the IP address of the new server. That will ensure everyone ends up at the correct place while waiting for the cached DNS entry to expire and be updated. After a week or so you should be able to remove the original server.


Interrupt command line execution in Fortran without killing main program

Question: I have a Fortran program that runs a series of identical calculations on a number of different input data. After doing these calculations the code then always writes a GNUplot script that does some diagnostic plotting (nothing too difficult) and runs it using execute_command_line in Linux.
This usually works well, but after some time I think there must be a memory leak of some kind that works cumulative, because the GNUplotting becomes slower and slower. At some point it virtually stalls.
My question is therefore: Is it possible to interrupt the call to execute_command_line using the keyboard without killing the main Fortran program? Needless to say, CTRL-C kills everything, which is not what I want: I want the main program to continue.
I have been playing with the optional flag wait=.true. but this does not help.
Also, I know that the memory leak has to be fixed (or whatever the cause is), but for now I would like to first see the diagnostic output.
Comment: I doubt the OP meant this. BTW, PAUSE is a deleted feature.
Comment: See http://stackoverflow.com/questions/26540044/how-do-you-kill-all-child-processes-without-killing-the-parent  You must trap the signals in the main program.
Comment: pause statement...? http://docs.oracle.com/cd/E19957-01/805-4939/6j4m0vnal/index.html
Comment: I would prefer a C extension instead, see https://airtower.wordpress.com/2010/06/16/catch-sigterm-exit-gracefully/
Comment: I created an example, but I cannot test it, because in my shell it does not terminate the main program at all? Which OS and shell do you use?
Comment: Sorry Vladimir, I hadn't seen your previous comment.

I am using ubuntu 14.04 LTS. I compile using gfortran (with C preprocessiong). The F program is run using mpirun.

Do you need more information?
Comment: It is better to put the solution in an answer, even if it is just a workaround.
Answer: The only solution I have been able to come up with is kind of a workaround:

Modify the shell script so that it

runs the Fortran program in the background: ./mpirun prog_name options &
gets the PID of this proces: proc_PID=$!
waits for the process: wait $proc_PID
traps an interrupt signal: trap handler SIGINT
lets the handler send a SIGURS1 signal: function handler() { kill -SIGUSR1 $proc_PID }

modify the Fortran code so that it catches the SIGUSR1 signal and does what you want with it. For example by having a look here.

By running the mpi process in the background you avoid killing mpirun with SIGINT, which cannot be trapped but you send instead a SIGURS1, which is properly propagated to the mpi processes where it can be handled with directly.
As a side note, however, I realized that this will not solve my problem as my problem was related to an external call to gnuplot using execute_command_line. Since I had a cumulative memory leak, at some point this call started taking for ever because memory resources became scarcer. So the only thing I could have done is manually killing the gnuplot process.
Better, of course, was fixing the memory leak, which I did.


How to Insert parameters and declare stored procedure

Question: I'm trying to write a stored procedure to get 2 parameters of usersID and Month.
Right now I have this, but I want to put those to variables like parameters. How can I do it?
ALTER PROCEDURE [dbo].[SP_TaskObjDashboard]
AS
BEGIN
    DECLARE @UserID INT = 20
    DECLARE @Dateinput DATETIME

    SELECT
        COALESCE(@UserID, users.UserID) AS TC,
        Objtask.Pace, Objtask.Month, salesobj.SalesObjectiveMonth
    FROM
        TBL_User AS users
    JOIN
        TBL_Objectives_Task AS Objtask ON users.UserID = Objtask.Consultant
    LEFT JOIN
        TBL_SalesObjective AS salesobj ON users.UserID = salesobj.UserID
    WHERE
        users.IsActive = 1
        AND MONTH('2019-08-25') = MONTH(Objtask.Month)
        AND users.UserID = COALESCE(@UserID, users.UserID)
END

Comment: Side note: you should **not** use the `sp_` prefix for your stored procedures. Microsoft has [reserved that prefix for its own use (see *Naming Stored Procedures*)](http://msdn.microsoft.com/en-us/library/ms190669%28v=sql.105%29.aspx), and you do run the risk of a name clash sometime in the future. [It's also bad for your stored procedure performance](http://www.sqlperformance.com/2012/10/t-sql-queries/sp_prefix). It's best to just simply avoid `sp_` and use something else as a prefix - or no prefix at all!
Comment: [CREATE PROCEDURE (Transact-SQL) - Examples
: Passing Parameters - Creating a procedure with input parameters](https://learn.microsoft.com/en-us/sql/t-sql/statements/create-procedure-transact-sql?view=sql-server-2017#d-creating-a-procedure-with-input-parameters) If you're ever not sure what the syntax for something is, the documentation should be one of your first port of calls. SQL Server's documentation is very complete, and the has a user community that helps maintain and update it. There are very often examples contained in the article as well, making things easier to understand.
Answer: Your Procedure Definition Should Be
ALTER PROCEDURE [dbo].[SP_TaskObjDashboard]
  @UserID INT, @Dateinput datetime
AS

Answer: This should do it:
ALTER PROCEDURE [dbo].[SP_TaskObjDashboard]
  @UserID INT, @Dateinput datetime
AS
...

Also, don't forget to remove the DECLARE-statements for the variables that you change into parameters.
https://learn.microsoft.com/en-us/sql/t-sql/statements/alter-procedure-transact-sql?view=sql-server-2017
Answer: I think...your error was....
1. "Cannot assign a default value to a local variable."
2. "Must declare the scalar variable "@UserID"."
Sol:-
ALTER PROCEDURE [dbo].[SP_TaskObjDashboard]
AS
BEGIN
    DECLARE @UserID INT
    SET @UserID=20

    DECLARE @Dateinput DATETIME

    SELECT
        COALESCE(@UserID, users.UserID) AS TC,
        Objtask.Pace, Objtask.Month, salesobj.SalesObjectiveMonth
    FROM
        TBL_User AS users
    JOIN
        TBL_Objectives_Task AS Objtask ON users.UserID = Objtask.Consultant
    LEFT JOIN
        TBL_SalesObjective AS salesobj ON users.UserID = salesobj.UserID
    WHERE
        users.IsActive = 1
        AND MONTH('2019-08-25') = MONTH(Objtask.Month)
        AND users.UserID = COALESCE(@UserID, users.UserID)
END

For More Info...this type of Error..you can follow this link...
http://www.sql-server-helper.com/error-messages/msg-139.aspx


When $ t\mapsto X_t(\omega)$ is continuous for almost all omega then does it imply$t \mapsto E[X_t]$ continuous?

Question: When $ t\mapsto X_t(\omega)$ is continuous for almost all omega then does it imply that $t \mapsto E[X_t]$ continuous?
If this is true how can go about proving it? If not what condition do I need?
Obviously if $X$ is a martingale then  $t \mapsto E[X_t]$ continuous. How could I show this in the general case. I am just not sure how can i start to approach this problem. Any hints would be appreciated
Comment: In this case the assertion is a direct consequnce of the dominated convergence theorem.
Comment: Which integrability assumptions do you have on $X_t$?
Comment: A sufficient condition is that $\{X_t\}$ is uniformly integrable.
Comment: @saz it's uniformly bounded in both variables
Answer: Take as your probability space $[0;1]$ with the Lebesgue measure and the Borel-sigma-algebra. Pick $f:\mathbb{R} \rightarrow \mathbb{R}$ continuous with $supp(f)\subseteq [0;1]$ and $E[f]\neq 0$ and define
$$ X_t(\omega) = \begin{cases} t^{-1} f(\omega\cdot \vert t\vert^{-1}),& t\neq 0,\\
0,& t=0 \end{cases} $$
Then $[-1;1] \rightarrow \mathbb{R}, t \mapsto X_t(\omega)$ is continuous for every $\omega\in [0;1]$, but
$$ E[X_t] = sgn(t) E[f] $$
which is not continuous. Indeed, for $0< \vert t \vert \leq 1$ we have
$$ E[X_t] = \int_0^1 X_t(\omega) d\omega = \int_0^1 t^{-1} f(\omega \cdot \vert t \vert^{-1}) d\omega \stackrel{s=\omega \cdot \vert t \vert^{-1}}{=} \frac{\vert t \vert}{t}\int_0^{\vert t \vert^{-1}} f(s) ds = sgn(t) E[f]  $$
where we used $\vert t \vert^{-1}\geq 1$ (as we assumed $\vert t \vert \leq 1$) and $supp(f) \subseteq [0,1]$.
Comment: @saz Thanks for pointing out my mistake. I fixed it. I meant $t^{-1} f(\omega \cdot \vert t\vert^{-1})$ exactly such that the change of variables will give what I wrote.


Drum tuning/timbre?

Question: How integral to the harmony of the music is the tuning/timbre of the drum-set?  It must be more aesthetically pleasing, even on a subconscious level, to have the drums tuned somewhere in the vicinity  of the general keys in which the other musicians are playing but, can this factor make or break a song?
Live performance versus recording?
Comment: not sure it's a dupe, but have a look at http://music.stackexchange.com/questions/38221/do-i-need-to-be-concerned-with-drum-tuning-when-using-drum-samples?rq=1
Comment: There are drummers who will tune to the key of the song, but for the most part it really doesn't matter. I've seen or heard of a drummer running to a song outside of more experimental music.
Answer: This article is very insightful on the subject. Highlights:

Intricate tuning of acoustic drums can have a significant impact on the quality and contextuality of the instrument when played live or in the recording studio. Indeed, many musicians and producers will spend a number of hours achieving a preferred drum sound prior to a performance.
In many recording sessions, the drum setup has a very important role. The setup involves choosing the correct drum kit, choosing and positioning microphones for recording the drum kit, and tuning the drum kit to give the desired sound.
Repeatability of sound can be an issue on high profile tours where, for example, the drum sound is required to be as close to that of the artist's recorded work as possible. In this case the drum sound is desired to be consistent on every night of the tour, and some method for achieving this is attempted by the sound technicians. Repeatability and benchmarking also become issues when considering that many percussionists desire to tune their drums to a particular musical scale or the key of a particular song...
Each drum has its own range of tone that it can be suitably tuned to. For example, a 12" tom can be tuned to have a fundamental within a specific frequency range. But as it is tuned lower and lower, eventually the drum head will go slack and the tone will become poor. At this stage if a lower tone is required, a larger drum should be used. Drums are also made with different depths and of many different materials by many different methods. Similarly, the types of drum heads used have a major impact on the available tuning ranges and attack and decay profiles. Furthermore, the choice of whether to use the same or different heads on the batter and resonant sides of the drum have a major influence. These factors are all under consideration in the current research.
A quantifiable method for drum tuning has been developed and is being evaluated in the author's current research. Of course, some musicians and producers will not embrace yet another technical method within their artistic field. But, it is felt that, at the technical level where waveform and spectrum analysis are the norm, this approach could be embraced to give the valuable capture, analysis and benchmarking of drum sounds and tuning setups.

This research aligns with my experiences and discoveries when performing and recording.
Part of the reason I asked the question was because I very recently recorded a track on which the original key was G. The drum part on the recording is temporarily an open-source-stock loop - for mood and timing. After the first take, I realized a slight dissonance and then discovered that the kick-drum was tuned to A - and, asked that we transpose the tune up a whole step. The result was a much more engaging and aesthetically pleasing product. Everyone involved in the recording was much more into the tune once the switch was made too...
I know the balance is ultimately achieved based on the necessities of the group itself... Sometimes it's easy - for the first Rage Against the Machine album, Brad Wilk would've only had to tune his drums to D, at least during live performance (the whole album is damn near in D.)
Perhaps the subject is too negligible that it truly can be ignored in music.... but, I don't like to. :)

Drum tuning/timbre?


A step of a proof regarding the Nadaraya-Watson estimator

Question: Let the data be $(y_i , X_i) $ where $y_i$ is real valued and $X_i$ is a q-vector.
The regression function for $y_i$ on $X_i$ is $g(x) = E(y_i | X_i = x)$, we can write this as:
$$y_i = g(X_i) + e_i$$ where $E(e_i | X_i ) = 0$.
Now since $E(e_i | X_i ) = 0$ then it follows that $E(k(\frac{X_i - x}{h})e_i) = 0$
where $k$ is a kernel function. What is the reason of this implication?
Answer: If $X_i$ is known, then this implies that the function $k\left(\frac{X_i - x}{h}\right)$ is known. In other words we have that for the conditional expectation:
$$
\operatorname{E}\left( k\left(\frac{X_i - x}{h} \right) e_i \mid X_i \right)
= k\left(\frac{X_i - x}{h}\right) \operatorname{E}(e_i \mid X_i)=0
$$
Therefore, we have by the law of iterated expectations that:
$$
\operatorname{E}\left( k\left(\frac{X_i - x}{h} \right) e_i \right)
= \operatorname{E}\left( \operatorname{E}\left(k\Big(\frac{X_i - x}{h}\Big) e_i \mid X_i \right) \right)
= \mathrm{E}(0)
= 0
$$
as required.
Answer: $E(k(\frac{X_{i} - x}{h})e_{i}) = E(E(k(\frac{X_{i} - x}{h})e_{i}|X_{i}))$ by tower property
$= E(k(\frac{X_{i} - x}{h})E(e_{i}|X_{i}))$ because $k(.)$ is deterministic given $Xi$
$=E(k(\frac{X_{i} - x}{h})0)=0$ since $E(e_{i}|X_{i})=0$


Fuzzy top A on saxophone

Question: Some time ago, I picked up tenor saxophone and I'm learning to play in my (very scarce) free time. Recently, I've noticed that the top A sounds fuzzy compared to other notes. It's quite pronounced. G# and Bb seems to be unaffected. A is the note on which octave pip is changed.
Is this a common problem? Is there something I can do with my technique to remedy this, or might this be a problem with the instrument?
Comment: @evamvid The octave key opens two different holes depending on the note you're playing, one is open for C to G#, the other one for A and higher.
Comment: MusicMedic.com involves using pantyhose.Have a look.
Comment: I'm confused...are you letting up the octave key, or pressing it down? Wouldn't you have the octave key pressed for the G# below _and_ the Bb above?
Comment: Which B♭ fingering have you tried? Left hand or side? How long since the latest maintenance?
Comment: @Édouard I understand now...I thought OP was talking about the octave key as in the part you press with your thumb =)
Answer: This is probably caused by interference with one of the tone hole covers, but it might just be caused by the construction of your particular model.  I'd recommend getting it serviced and point out the issue to the repair-person.
Answer: Try using a pipe-cleaner to clean out the air hole in your top octave key.
Also watch the mechanism when you hold the octave key and raise and lower the G-key.   Is the pad fully lifting above the top octave key?

Fuzzy top A on saxophone


Is this a repeated measures ANOVA problem?

Question: Here is the problem I have (the figure below tries to depict the problem):

There are two groups of patients -  the BURN_GRP and the TVC_GRP, and all the patients are different (i.e. no patients in the BURN_GRP appear in the TVC_GRP and vice versa).
The number of patients in each group is different, 125 vs. 219 (but I can randomly discard patients from the TVC_GRP in order to have the same number of patients in each group).
Each patient has four measures of their SA_VAL taken over time (6 hours apart).
I would like to test the hypothesis that the average SA_VAL of the patients in the BURN_GRP is statistically significantly different than the average SA_VAL of the patients in the TVC_GRP.

If there were no repeated measures I would perform a standard (non-paired) t-test.  However, now that there are four (non-independent) measures for each patient I am unsure about how to proceed.  I think it might be a repeated measure ANOVA.  Is it?  If so, how would I go about modeling it in R?
Answer: There are two solutions here:
1.) If systematic differences between the four time-points are not expected or not of interest (simple replications): Just calculate the average SA_VAL for each subject and  compare the resulting MEAN_SA_VALs between both groups using an unpaired t.test or wilcox.test (aka Mann-Whitney U). If you suspect/observe that variances differ between groups , use the var.equal = FALSE option of t.test. Simple as that.
2.) If there is the possibility that SA_VALs can change systematically over the course of the four measurements then you should definitely use a model that takes a potential main effects with time and more importantly interaction effects between time and group into account. This is a little complicated because R's aov function usually used for repeated-measures ANOVA is designed for balanced designs. But you should not discard data, since this only means a loss of valuable information and statistical power.
What you can do is to create a mixed model with functions lme (nlme package), or lmer (lme4 package) and then run an ANOVA. The model should look like this:
model1 <- lmer(SA_VAL ~ time+group+time:group+(1+time|subject),data=df)
anova(model1)

If the effects of time on SA_VAL are linear in both groups, you may use time as a continuous regressor (0,6,12,18). If you expect other effects of time, define time as a factor (factor(time)).
Bonus: The mixed model will even be able to handle  subjects with missing data-points (missing at random).
Malus: Working with mixed models can become quite involved, so you may require some reading. Btw: here you can find a lme/lmer example that matches your design very closely.
Comment: If there are systematic differences between the four time points, then what hypothesis is being tested?


How does the Rust compiler know whether a value has been moved or not?

Question: A simple example:
struct A;

fn main() {
    test(2);
    test(1);
}

fn test(i: i32) {
    println!("test");
    let a = A;
    if i == 2 {
        us(a);
    }
    println!("end");
}

impl Drop for A {
    fn drop(&mut self) {
        println!("drop");
    }
}

#[allow(unused_variables)]
fn us(a: A){
    println!("use");
}

When I run it, the output is:
test
use
drop
end
test
end
drop

I understand in the test(2) case, a is moved at us(a), so it's output is "test-use-drop-end".
However, in the test(1), the output is "test-end-drop", meaning that the compiler knows that a was not moved.
If us(a) is called, it will be unnecessary to drop a in test(i), it will be dropped in us(a); and if us(a) is not called, a must be dropped after println!("end").
Since it's impossible for the compiler to know whether us(a) is called or not, how does compiler know whether a.drop() shall be called or not after println!("end")?
Answer: This is explained in the Rustnomicon:

As of Rust 1.0, the drop flags are actually not-so-secretly stashed in a hidden field of any type that implements Drop.

The hidden field tells whether the current value has been dropped, or not, and if it has not then it is. Thus, this is known at run-time, and requires a bit of book keeping.

Looking to the future, there is a RFC to remove these hidden fields.
The idea of the RFC is to replace the hidden fields by:

Identifying unconditional drops (those don't need any run-time check)
Stash a hidden field on the stack, in the function frame, for those values conditionally being dropped

This new strategy has several advantages over the old one:

the main advantage being that #[repr(C)] will now always give a representation equivalent to the C's one even if the struct implements Drop
another important advantage is saving memory (by NOT inflating the struct size)
another slight advantage is a possible slight speed gain due to unconditional drops and better caching (from reducing memory size)


styled-components — how to use :not() selector on a prop?

Question: Let's say I have an element with a property "selected":
<Button selected>
    Text
</Button>

const Button = styled.div`
    &:not(???) {
        color: red;
    }
`;

How do I select all instances of Button which don't have the "selected" property?
Maybe there is another way to do what I'm trying to achieve?

Сlarification edit:
I actually need to use :not together with :hover, like this:
const Button = styled.div`
    &:not(???):hover {
        color: red;
    }
`;

Answer: styled-components uses some template magic to allow you to access passed props like so:
const Button = styled.div`
    color: ${props => props.selected ? "color when selected" : "red"};
`;

With styled-components, this tends to be the more idiomatic way of setting things based on props rather than using CSS selectors.
Comment: The thing is, I actually need this :not to be used together with :hover. I probably should have reflected this in my question.
Answer: That's how you can do it:
const Button = styled.div`
    ${props => !props.selected && css`
        :hover {
            color: red;
        }`
    }
`;

Don't forget to import css from styled-components;


Simplifying $\frac {56+29i}{9-4i}$

Question: How would I simplify this expression?
$$\frac {56+29i}{9-4i}$$
I thought about doing this:
$$  \frac {56+29i}{9-4i} \times \frac {56-29i}{56-29i} \times \frac {9+4i}{9+4i}  $$
is it right?
Comment: You're almost right, you just wouldnt need to multiply by $\frac {56-29i}{56-29i}$ Conjugation multiplication cancels out the imaginary parts as you seem to know and you only need to remove this from the demominator. Nothing here needs 'solving' but just simplifying by the way unless there' s more to it as you've only supplied an expression.
Comment: @JackPedley Thanks
Answer: Why would you want $\frac {56-29i}{56-29i}$? You just want an integer in the denominator, and that can be achieved by multiplying by $\frac{9+4i}{9+4i}$.
$$4+5i$$ would be the answer.

Simplifying $\frac {56+29i}{9-4i}$