Measuring interval in pseudo-Euclidean space

Question: Suppose we have a 2D pseudo-Euclidean space positioned on a rectangle sheet of paper with one axis parallel to one side and another axis parallel to another side. And we have a line segment drawn on this sheet. Is it possible to measure interval of this line in this pseudo-Euclidean space in a similarly simple way as in case of Euclidean space (using a ruler)? Does one have to measure projections on axes and then use definition of interval in such space? Or is there an easier way?
Comment: The triangle inequality can be false in pseudo-Euclidean spaces, so  terms like length and distance are avoided.
Comment: @DavidH OK, fixed to interval.
Answer: Lenght seems a bit slippery for pseudo-Euclidean spaces, but for a straight line if you start with the standard definition of length of a curve (limit with finer and finer partitions of the parametrising interval) you will get exactly the same as if you were computing distance of the endpoints (any sum approximating the limit will have this value).
However you clearly can't just use ruler if the metric is not Euclidean (unless your line is vertical), you must use the definition (as usually in maths;) ) - just in the way (with projections) you described.


Regular expression for a single letter word

Question: I use Java for an app with a stream of strings input. I want a regex that could detect whether there is a single-letter word "C/c", but not just a letter "C/c" in a longer.
For instance:

"I like C." -> true
"I like Canada." -> false
"C." -> true
"I like C and C++." -> true

I think this pattern should be like "*c*", the former * should not be letter, the latter * should be one of , .; )! or space.
I just get confused with the regex. I tried some pattern pattern like [^A-Za-z]{0,}c[\,\.\;\s]{0,}, but it doesn't work yet.
Answer: Use word boundary markers
String pattern = ".*\\b[Cc]\\b.*";

The \b matches a word boundary, i.e., anything of letter next to non-letter.
You need the 2 backslashes to escape the backslash for Java.
The .* in the beginning and end make sure that Java does not try to anchor the pattern at beginning and end of the input.
Comment: Thank you for your answer.This is really helpful. But for furthure requirement,which I didn't stated, like syntax checking. for  instance, c-- would be no valid. So I revised the latter "b.*". And I notice the very first ".*" could be removed.
The final example is here:  https://regex101.com/r/C7XICk/1
Answer: Use \W. \Wis non-word character.
\W[cC]\W

https://regex101.com/r/khvMQk/1
Comment: So thanks for the regex website. It is really helpful to test. And just to revise it better, here is the final outcome:https://regex101.com/r/C7XICk/1
Answer: Try his
var pattern=   /(\bC\b)/i;
https://regex101.com/r/gN5Z8Q/1
Comment: Thanks for your answer. The pattern your gave is quite ok except for single statement ,like "c". Check this:https://regex101.com/r/5uUXkE/1

And this is what I revised,https://regex101.com/r/C7XICk/1. Anyway, thanks for your answer.


Bayesian Prediction Simple Explanation

Question: I have read through other questions on the site and I feel that none provide a great answer to this question. Simply put - could anyone explain, common approaches for generating predictions on new unseen data with a Bayesian model.
For example, suppose you have a simple linear regression:
$$ y = \alpha + \beta * x $$
Which under a probabilistic framework is given by:
$$ y \sim N(\mu = \alpha + \beta *x, \sigma = \epsilon) $$
We set prior distributions for the parameters $ \alpha, \beta$ and $\epsilon$ and with our training data $X_{train}$ we return samples from   posterior to obtain posterior distributions across these parameters.
My question is, given new data $X_{new}$, how are predictions then made on that data?
For example, would you:

For each new data point in $X_{new}$, take the posterior samples from the 'training' process, and calculate $Y_{new}$ using combinations of coefficients from the posterior samples (for a given data point in $X_{new}$) - to generate a vector of predictions for each data point in $X_{new}$?
Answer: Correct.
You have draws from posterior, so for a new $x_i$ the corresponding prediction for $\mu$ is $\dfrac{1}{N} \sum _i \alpha_i + \beta_i x%$.  If you're familliar with rstanarm, this is what posterior_linpred does. Since the predictor is linear, this should be equal to $E(\alpha) + E(\beta)x$, where $E$ is the expectation. Here is an example using Stan.
Let's first set up the model and fit it.
library(tidyverse)
library(tidybayes)
library(cmdstanr)

model_code = '
data{
  int N;
  vector[N] x;
  vector[N] y;
}
parameters{
  real alpha;
  real beta;
  real<lower=0> sigma;
}
model{
  alpha ~ normal(0,1);
  beta ~ normal(0,1);
  sigma ~ cauchy(0,1);
  y ~ normal(alpha + beta*x, sigma);
}
generated quantities{
  real yppc[N] = normal_rng(alpha + beta*x, sigma);
}
'
fl = write_stan_file(model_code)
model = cmdstan_model(fl)

N = 10
x = rnorm(N)
y = 2*x + 1 + rnorm(N, 0, 0.45)
model_data = list(N=N, x=x, y=y)
fit = model$sample(model_data, parallel_chains=4)

Now, extract the draws
beta = as.numeric(fit$draws('beta'))
alpha = as.numeric(fit$draws('alpha'))
sigma = as.numeric(fit$draws('sigma'))

Let's say I want to make a prediction for $x=3$. I should compute $\alpha_i + \beta_i \cdot 3$ for all my posterior $\alpha_i, \beta_i$. In R...
prediction = alpha + beta*3
hist(prediction)

Note that we get a distribution of possible values.  Our prediction in this case is the mean of this distribution
mean(prediction)
>>>7.281336

Which is close to the true value of 7.

Bayesian Prediction Simple Explanation


svnadmin create -- Error?

Question: ok I installed the subversion binary from collabnet onto my win7 computer.
when I ran the installed it put the main files in:

C:\Program Files\CollabNet\Subversion Server

it also create an empty directory for my repositories here:

C:\svn_repository

I opened up a cmd.exe and rain this line:

C:\Program Files\CollabNet\Subversion
  Server>svnadmin create /var/svn/repos

it gave me this error:

Repository creation failed
  Could not create top-level directory
  The system could not find the path specified

After research I found that the file path /var/svn/repos has to already exist. but WHERE?
I tried add this file path to C:\svn_repository making it C:\svn_repository\var\svn\repos I also tried adding the path to C:\Program Files\CollabNet\Subversion Server
still get the same error everytime I run:

C:\Program Files\CollabNet\Subversion
  Server>svnadmin create /var/svn/repos

I also tried making the slashes backwards like:

C:\Program Files\CollabNet\Subversion
  Server>svnadmin create \var\svn\repos

Can someone tell me what I am doing wrong?
Thanks!!!
Answer: The problem is that /var/svn/repos is itself a (Unix-style) path, and doesn't exist. Considering that you're on Windows, you probably want something like this instead:
svnadmin create C:\svn_repository\newrepository
(If that fails, try creating the directory manually first: mkdir C:\svn_repository\newrepository and then the command above.)
Comment: An aside: You may prefer to use TortoiseSVN instead of the command line. With TortoiseSVN, it's simply a matter of right-clicking on a directory and choosing "Create Repository Here".  Of course, learning the command line is a good idea in any case, but for the infrequent requirements (creating repositories, etc), a GUI is often helpful.

svnadmin create -- Error?


Properties of certain type of measures

Question: Let $p\in (0,1)$. For each $k\in\mathbb{N}$ and tuple $(\varepsilon_1,\ldots,\varepsilon_k)\in\{0,1\}^k$ denote
$$
S_{\varepsilon_1,\ldots,\varepsilon_k}=\left\{\sum\limits_{j=1}^\infty x_j 2^{-j}: x\in\{0,1\}^\mathbb{N}\;\wedge\;x_1=\varepsilon_1,\ldots,x_k=\varepsilon_k\right\}
$$
$$
\mathcal{S}=\{S_{\varepsilon_1,\ldots,\varepsilon_k}:(\varepsilon_1,\ldots,\varepsilon_k)\in\{0,1\}^k,\;k\in\mathbb{N}\}\cup\{\varnothing\}
$$
One can show that $\mathcal{S}$ is a semiring of diadic segments. By $\mathfrak{B}(\mathcal{S})$ we denote minimall $\sigma$-algebra that contains $\mathcal{S}$. Define measure
$m_p:\mathcal{S}\to\mathbb{R}_+$ by equalities
$$
m_p(S_{\varepsilon_1,\ldots,\varepsilon_k})=\prod\limits_{i=1}^k p^{\varepsilon_i}(1-p)^{1-\varepsilon_i}\\
m_p(\varnothing)=0
$$
Consider Lebesgue extension of $\lambda_p$ of measure $m_p$. It is defined on some $\sigma$-algebra $\mathfrak{M}_p(\mathcal{S})$. Since I want to consider this extensions for different $p$ I will restrict $\lambda_p$ to $\mathfrak{B}(\mathcal{S})$ and denote the resulting measure $\mu_p$.
I will be happy to get answers to some of the following questions.
1) How to prove that $m_p$ is $\sigma$-additive?
2) Is it true that $\mu_p$ is regular?
3) Is it true that $\mathfrak{M}_{p_1}(\mathcal{S})\neq \mathfrak{M}_{p_2}(\mathcal{S})$ for $p_1\neq p_2$?
4) Does there exist explicit construction of the set $B\in\mathfrak{B}(\mathcal{S})$ such that $\mu_{p_1}(B)=1$ and $\mu_{p_2}(B)=0$ for $p_1\neq p_2$.
Less concrete questions are:
1) Does this type of measures have a name?
2) Where can I find articles about their properties?
Thank you for taking time.
Comment: You are making the digits in the binary expansion i.i.d. bernoulli(p) ?
Comment: @maike yes, you are right
Answer: You want "credible and/or official sources"???  You mean on-line sources are not wanted?  There is this....
(22.35) through (22.44) in Real and Abstract Analysis by Hewitt & Stromberg (Springer, 1965)
Comment: on-line sources are also good

Properties of certain type of measures


Pesquisa aleatório laravel

Question: Estou efetuando uma consulta aleatório na tabela users da minha aplicação em laravel, exemplo abaixo:
User::inRandomOrder()->paginate(10)
Ele realmente me retorna o resultado de forma aleatório, mas preciso que todo o registro da tabela users com a coluna users_destaque = 1 seja listado primeiro de forma aleatório, e todo registro com a coluna users_destaque = 0 seja listado depois e também de forma aleatório, fico no aguardo.
Answer: Deves colocar também a tua ordenação princípal, neste caso ...('users_destaque', 'DESC').
Tenta o seguinte, versões Laravel < 5.2:
User::orderBy('users_destaque', 'DESC')->orderByRaw("RAND()")->paginate(10);

Para uma versão de Laravel >= 5.2 é como estavas a fazer, com acrescento da ordenação principal:
User::orderBy('users_destaque', 'DESC')->inRandomOrder()->paginate(10);

Comment: estou ultilizando o laravel 5.4, tento esse código mesmo ?
Comment: Olá @BrunoSantos, nesse caso é o segundo exemplo que deves usar

Pesquisa aleatório laravel


When finding a diagonal matrix of a linear map does it matter which way we order the eigenvalues down the diagonal?

Question: Suppose we wish to find a diagonal matrix $D$ and an invertible matrix $P$ such that $D=P^{-1}AP$ where
$$A=\begin{pmatrix}
-10 &18 \\
 -6&11
\end{pmatrix}$$
When we find the eigenvalues of the matrix we get $2,-1$ my question is this does it matter whether we take $$D=\begin{pmatrix}
-2 &0 \\
 0&1
\end{pmatrix}$$ or $$D=\begin{pmatrix}
1 &0 \\
 0&-2
\end{pmatrix}$$
then when you want to find $P$ you find a basis for each eigenspace and then just let $P$ be the matrix with the elements of each basis for the two eigenspaces as the columns for $P$, does the order in which you place these column vectors matter as well?
Will it give the same matrices whichever order? Is some orders wrong? Or does it just give different matrices with the property we desire?
Answer: The order of the columns of $P$ will correspond to the order of the diagonals in $D$. The first column of $P$ is the eigenvector corresponding to the eigenvalue $D_{11}$, the second column corresponds to $D_{22}$, and so on. If you reorder the elements on the diagonal of $D$, you have to reorder the columns of $P$ in the same way so that $P^{-1}AP=D$ is still true.


Camera position and 3D perspective projection

Question: I have 3D points $P_1, P_2, P_3,..., P_N$ and the result of a 3D perspective projection: $p_1, p_2, p_3,..., p_N$. Is there a way to obtain camera position having only that data? Is it possible having camera fov?
Answer: Suppose your 3D points and the projections are given in homogeneous coordinates $X_1, X_2, X_3,..., X_N \in \mathbb{R}^4$ and $x_1, x_2, x_3,..., x_N \in \mathbb{R}^3$. Then they have the simple relationship $$x_i=PX_i$$ with the camera matrix $$P= \begin{pmatrix}
    p_{11} & p_{12} & p_{13} & p_{14}\\
    p_{21} & p_{22} & p_{23} & p_{24}\\
    p_{31} & p_{32} & p_{33} & p_{34}\\
  \end{pmatrix} \in \mathbb{R}^{3\times4}\textrm{.}$$
This relationship is linear in the unknowns $p_{11}, p_{12}, \cdots p_{34}$. To put it in the usual form $b=Ax$, where $x$ are the unknowns, use the vector $$p:=\begin{pmatrix}
    p_{11}\\
    p_{12}\\
    p_{13}\\
    \vdots\\
    p_{34}
  \end{pmatrix}.$$ Then
$$x_i=\begin{pmatrix}
    X_{i1} & X_{i2} & X_{i3} & X_{i4} & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0\\
    0 & 0 & 0 & 0 & X_{i1} & X_{i2} & X_{i3} & X_{i4} & 0 & 0 & 0 & 0\\
    0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & X_{i1} & X_{i2} & X_{i3} & X_{i4}\\
  \end{pmatrix}p$$ where $$X_i:=\begin{pmatrix}
    X_{i1}\\
    X_{i2}\\
    X_{i3}\\
    X_{i4}
  \end{pmatrix}.$$
Each of these correspondences gives us $3$ linear equations that involve the components of $p$ so at least $N\geq 4$ correspondences are required. If $A$ is the matrix of stacked rows involving $X_i$ as shown and $$b:=\begin{pmatrix}
    x_{1}\\
    x_{2}\\
    x_{3}\\
    \vdots\\
    x_{N}
  \end{pmatrix}$$ then $p=A^{-1}b$ if $N=4$ (which makes $A\in \mathbb{R}^{12\times12}$) and otherwise $p=(A^tA)^{-1}A^tb$ gives you the linear least squares estimate.
We have $P=K[R,t]$ where $K$ is the calibration matrix, $R$ the rotation and $t$ the translation. Your camera fov is determined by the components of $K$ - for example the focal length $f$.


How can I use git repos as dependencies for my PyPi package?

Question: I have a package which I'm pushing to PyPi and some of the depedencies are not packages, but installable git repositories. My requirements.txt looks like this
sphinx_bootstrap_theme>=0.6.5
matplotlib>=2.2.0
numpy>=1.15.0
sphinx>=1.7.5
sphinx-argparse>=0.2.2
tensorboardX
tqdm>=4.24.0
Cython>=0.28.5

# git repos
git+git://github.com/themightyoarfish/svcca-gpu.git

Accordingly, my setup.py has this content:
#!/usr/bin/env python

from distutils.core import setup
import setuptools
import os

with open('requirements.txt', mode='r') as f:
    requirements = f.read()
    required_pkgs, required_repos = requirements.split('# git repos')
    required_pkgs = required_pkgs.split()
    required_repos = required_repos.split()

with open('README.md') as f:
    readme = f.read()

setup(name=...
      ...
      packages=setuptools.find_packages('.', include=[...]),
      install_requires=required_pkgs,
      dependency_links=required_repos,
      zip_safe=False,   # don't install egg, but source
)

But running pip install <package> does not actually install the git dependency. I assume that pip doesn't actually use the setup script. It works when I run python setup.py install manually.
Edit:
I also tried removing dependency_links and just using install_requires with the repository, but when installing my repository from GitHub (the project including the above files), I'm met with
    Complete output from command python setup.py egg_info:
error in ikkuna setup command: 'install_requires' must be a string or
list of strings containing valid project/version requirement specifiers; Invalid requirement, parse error at "'+git://g'"

It has been suggested in other answers that one can put something like
git+https://github.com/themightyoarfish/svcca-gpu.git#egg=svcca

into requirements.txt, but that fails with
   error in <pkg> setup command: 'install_requires' must be a string or list of strings containing valid project/version requirement specifiers; Invalid requirement, parse error at "'+https:/'

Question: (How) Can I list git repositories as dependencies for a pip package?
Comment: The linked question and top answers do not seem to solve the problem because it deals with requirements files, but not with `pip`. The idea is having to state the requirement in a way that `setup()` understands it.
Comment: I should have made it clearer in the question that `requirements.txt` is merely a proxy for `setuptools` dependencies in this case.
Comment: Possible duplicate of [How to state in requirements.txt a direct github source](https://stackoverflow.com/questions/16584552/how-to-state-in-requirements-txt-a-direct-github-source)
Answer: Out of the 50 or so different ways to specify git dependencies for Pip, the only one that did what I intended was this one (outline in PEP 508):
svcca @ git+ssh://firstname.lastname@example.com/themightyoarfish/svcca-gpu

This can be used in install_requires, which solves the issue of dependency_links being ignored by pip.
An amusing side-effect is that the package cannot be uploaded to PyPi with such a dependency:
HTTPError: 400 Client Error: Invalid value for requires_dist. Error: Can't have direct dependency: 'svcca @ git+ssh://firstname.lastname@example.com/themightyoarfish/svcca-gpu' for url: https://upload.pypi.org/legacy/

Comment: "Don't use PyPi" is the only solution until they change this.
Comment: I *had to* release a package to PyPi. So I ended up releasing two packages: first, the direct dependency, and then releasing my actual package after converting direct dependency to regular dependency!
Comment: I am stuck on " Error: Can't have direct dependency:" issue and not sure how to solve it :-(
Comment: Ran into the same problem with pypdfium2 ([issue 177](https://github.com/pypdfium2-team/pypdfium2/issues/177)). Not so amusing after all.
Answer: We tried it with pyproject.toml and it didn't work for us either.
requires = [
    "geci_plots @ git+https://firstname.lastname@example.com",
    "lmfit",
    "pandasql",
    "scikit-learn==1.1.3",
]

It seems that direct references don't allow it.
ERROR    HTTPError: 400 Bad Request from https://upload.pypi.org/legacy/
         Invalid value for requires_dist. Error: Can't have direct dependency:
         'geci_plots @ git+https://firstname.lastname@example.com'

I assume the direct references are the GitHub repos.
Answer: According to the next post related to How to state in requirements.txt a direct github source.
You could add a package from git remote repository with the next syntax:
-e git://github.com/themightyoarfish/svcca-gpu.git

Reference:
 Install a project in editable mode (i.e. setuptools "develop mode") from a local project path or a VCS url with-e
Comment: I don't want to use editable mode, but it doesn't seem to work without `-e`.
Comment: See edited question; this does not work because `install_requires' must be a string or list of strings containing valid project/version requirement specifiers;`, which apparently that is not.
Comment: Hi oarfish! I really recommend you follow the next structure created by kennethreitz.
On this repository you will see how to create an awesome [Setup.py](https://github.com/kennethreitz/setup.py)
Comment: Maybe, you should split a break space, something like that: `required_pkgs = required_pkgs.splitlines()` [Reference](https://www.reddit.com/r/Python/comments/3uzl2a/setuppy_requirementstxt_or_a_combination/)
Comment: I really don't see how your linked `setup.py` file deals with non-pypi packages at all.
Comment: No, it was just in order to improve and standarize your setup.py file.


Can a key signature express Phrygian mode (not just major or minor)?

Question: Relative modes share the same note.
I was told the key signature could mean either major or minor.
But can it not also mean the other five modes like Phrygian, Locrian, etc.?
Comment: Yup! But the composer faces a choice: for, say, G mixolydian, you could use a key signature of no sharps or flats, _or_ you could use one sharp to signal "G" to the reader and then puts naturals on all the Fs.
Comment: Closely related: [Key signature for writing in modes other than major and minor](https://music.stackexchange.com/questions/930/key-signature-for-writing-in-modes-other-than-major-and-minor)
Answer: Yes, the major/minor key signatures can represent any of the diatonic modes. However, it's not uncommon to use the key signature for the "nearest" major or minor key and then use accidentals to adjust for the mode.
Comment: To spell it out, by "nearest" key this means Lydian = major + raised 4, Mixolydian = major + lowered 7, Dorian = minor + raised 6, Phyrgian = minor + lowered 2.   (I say "raised" and "lowered" and not "sharp" and "flat" because in some cases the necessary adjustment is a natural - for example in F Lydian you'd change B flat to B natural.)
Answer: There are two ways of writing key signatures of modes. One is to use the key signature of the parent key, the other is to use the traditional key signature based on the root note of the mode, as if it was a key in its own right.
Using the first method, it will give the reader the expectation of the parent key, just like any key sig. would. In fact, (let's take one sharp) that would tell G major or E minor. We only know (or suspect) which it actually is by looking for the last note/chord, or searching for the D♯ which would tend towards E minor.
Or, as Phoog points out, since Phrygian (B in this case) is minor, a key sig. of Bm could be used - 2 sharps would tidy up things, and only leave all the C♯ notes to be naturalised.
The Phrygian mode of G is B Phrygian. Using the key sig. of B would be pretty cumbersome - 5 sharps, 4 of which may well need cancelling each time they appeared, making the music dense, and not so easy to read, I think.
So, it would depend on the writer, who decides whether the second method is in fact harder or easier to read (and write!). But rather like the original major key sig., which only accurately reflects notes from the scale, the first method is more favourable.
Comment: A more likely choice of key signature for Phrygian is that of the parallel minor, not the parallel major.  That is, you might use the key of B minor and just cancel the C sharps with accidentals.
Comment: @phoog - very good point, it's been incorporated into the answer. Many thanks!
Answer: Yes.
What you are really asking is when presented with a key signature how do I know the tonic and mode of the music?
For example, let's say the key signature is one sharp. You've probably been told that is the key signature for one sharp is either G major or E minor. But how do you know which? Without going into too much detail, determining whether the music is major or minor mode is a type of quick harmonic analysis.
Usually that harmonic analysis is done with a quick reading of the starting and ending of the music. You look for the tonic which will be something like the final tone of the melody or the root of the final chord. If that tonic were G, the music is in G major, and if the tonic were E the music is in E minor.
You would follow the same basic analysis steps to determine whether the music was in a mode other than major or minor. For example, in general terms, if the music ended with a tonic of A (again, assuming a key signature of one sharp) the mode would be A dorian.
Whether the music is in phrygian can be a bit complicated depending on which modal style the music uses. "Modal" can be used to describe music in jazz, rock, folk, and early "classical" styles of Medieval and Renaissance music. Each of those styles can treat phrygian mode differently.
Again, let's assume a key signature of one sharp. The phrygian tonic for that key signature will be B. Using just the basic diatonic tones of the key signature the step above the tonic will be a C natural and the tonic chord will be a B minor triad. A potential source of confusion for you could be phrygian music in Medieval or Renaissance styles where the second scale tone may sometimes take a sharp and the final triad is very often a major triad. So, in our example key signature of one sharp, that would mean seeing some C sharps and the final chord being B major. Without getting into details, you can think of those things as characteristic chromatic inflections of phrygian mode in Medieval and Renaissance style music.


Alias criado em shell-script não funciona

Question: Estou tentando criar um aliás utilizando um shell-script, porém ao finalizar a execução o alias desaparece.
#!/bin/sh

echo "Configurando ambiente...";
mkdir -p ~/.dna

alias teste="node $HOME/.dna/start.js"
echo "Exibindo alias criado";
alias teste

O código acima cria o alias, pois logo abaixo do último echo ele é exibido, mas ao tentar executar o comando teste no terminal ele não encontra o comando.
Caso eu execute o trecho alias teste="node $HOME/.dna/start.js" diretamente no terminal o alias funciona.
Alguém sabe o motivo disso ocorrer e possui alguma solução de contorno?
Obrigado.
Comment: Pessoal porque fora de escopo? É uma dúvida de programação.
Comment: Provavelmente o alias não está sendo salvo,ele existe apenas na sessão que está atualmente,  dá dando um `export`?
Comment: Não tá dando export não @Tuxpilgrim .
Comment: Dá uma olhada nisso: https://stackoverflow.com/questions/2197461/how-to-set-an-alias-inside-a-bash-shell-script-so-that-is-it-visible-from-the-ou
Comment: Obrigado @Tuxpilgrim era exatamente isso que eu precisava. Se quiser traduzir para a comunidade brasileira eu vou marcar como correta a resposta. Obrigado. ;)
Comment: Opa, que ótimo que deu certo! Resolveu usando o `source` ou o `shopt -s expand_aliases`?
Comment: @Tuxpilgrim utilizando o `source` mesmo.
Comment: Pronto, quando puder aceitar a resposta @Hiago!
Answer: O alias que está criando está apenas dentro do shell que está executando o script, para persistir os aliases que está criando é precisar usar o source ./script.sh.Quando executa o comando source o conteúdo do arquivo vai ser executado no shell atual, e os aliases vão ser persistidos no ambiente.
Obs¹: Resposta baseada nessa postagem do SOen.
Obs²: Mais sobre o comando source ver esse link.


Em/C: Sound Notation, or Dirty Shorthand?

Question: A recent post about slash chords got me started thinking about whether it is technically "correct" to use a slash chord to mark a root position chord. For example, in C/E, the root is C. In Gm9/F, the root is G. In general, slash chords follow the pattern A/B where A would be the root of the chord and B the bass note. In other words, slash chords usually denote inversions. If I had to guess, that meaning probably comes from the old figured bass notation.
However, slash chords are also sometimes used to indicate not only inversions, but also marking specific voicings with upper structures. For example, C/D. The root of this chord is often not C, but instead D, in a D9sus context. In this case, the slash chord notation isn't so much of an inversion as it is an indicator of a voicing or a selected interpretation of the chord. The same logic can also be applied to other slash chords where chord A does not normally contain the note B: Em/C is a way to express Cmaj7, even though Em does not contain a C.

My current understanding on slash chords would be best stated as:

Slash chord notation is meant to signal to the reader that the bass is acting independently of the rest of the chord above.

I have seen a few sources online define slash chords more strictly such that the root note cannot be in the bass:

"A slash chord [...] is a chord whose bass note or inversion is indicated by the addition of a slash and the letter of the bass note after the root note letter." - Wikipedia

"In simple terms, a Slash Chord is a chord where the bass note – the lowest note heard in a chord – is different from the root note." - Hello Music Theory

"A slash chord is a chord which indicates emphasis of a bass note other than the root of the chord." - StudyBass

Emphasis above is mine. I recognize that these are not among humanity's most reputable or rigourous sources, and that not all sources agree with that definition. However, there's something to be said for a number of top search results all turning up this non-root-bass definition, and I also did interact with at least one person on this site echoing similar sentiments. In fact, the Wikipedia article makes the claim that slash chords can be the bass note in easy arrangements "to avoid writing chords more complex than triads" for beginners, implying that this is not the intended usage of the notation.
I already know that both usages of slash chords are common. My question: is using a slash chord in this voicing/independent bass context an accepted standard concept for chord symbols? Or is it more of a fast and loose shorthand notation that is (getting) adopted for convenience? Should Em/C always be taken to mean E is the root with C in the bass, or should it be equally valid to use the symbol to write C as the root and Em as upper structure?
Bonus points: for those in the "accepted and valid notation" camp, is there any difference between the chord symbols Em/C and Cmaj7 (or C/D vs. D9sus)? I would assume the stricter "inversions only" theorists would argue that there is no difference whatsoever. Would the "inversions-only" camp accept any bass notes that are not in the upper chord (e.g. G/F vs. G7/F)? My thinking is that the looser group is fine with either notation.

I did read this very similar question. However, from what I can tell, that question asked whether it could be used. My question hopefully is more about whether it is technically correct notation vs just a common shortcut.
Comment: I've been giving this careful thought and have figured it out. E=mc^2, thus Em/c = cm^2. However, Em/c = C-E-G-B and cm^2 = Bb-C-Eb-G. Therefore, we have a contradiction. Music theory disproves the theory of relativity!
Comment: I absolutely love this question. Hoping it gets more votes. I want to put together a full answer, but I think a subtlety (which those pure definitions seem to miss) is that slash chords tend to be more restrictive in the range of voicings that emerge. In addition to the applications you mention, they also cover scenarios like C/Db and Gb/A, which at first glance seem to fit neither (a) the idea of bass ≠ root, nor (b) the idea that slash chords = alternate spelling for another well-known chord. I think these facts impact how to ultimately conceive of (and define) them.
Comment: @Aaron - 'square' was a '60s term for someone non-hip/musical. But how did square centimetres get into the act?
Comment: Of course it's a *sound* notation. It represents an audible waveform.
Comment: @Tim Game, set, and match.
Answer: Who is it meant for, are you writing the notation for jazz players, pop/rock or is it a hymnal or what? Cmaj7 is not that strange, but it's just written communication from people to people, so you are allowed to take your target audience into account. If you mean that the keyboard player should keep the same right-hand chord and the bass should step down, you can write Em - Em/D - Em/C - Em/B. Chord symbols were developed to get accompaniment done, not for harmonic analysis.
I don't want to demand all players to care about analysis stuff and know about extended chord symbols. A lot of people just need to play the tunes and see the chords in terms of something familiar, and every added letter and number creates a bigger obstacle. I've noticed that a good way to explain slash chords is: the guitarist plays the chord on the left side of the slash, and the bassist plays the note on the right side. For piano and keyboard players, play the chord on the left side of the slash with the right hand, and the bass note with the left hand or leave it out if you're just playing a string pad.
"C/D" gets the job done right, without talking about elevenths etc. Yes, it  works as a V chord and it's a D dominant, and there's the sus4 aspect, which might not be obvious from the symbol "C/D", but it's a very tiny minority of players who would benefit from something like "D7 sus4 add9 omit5" and didn't already know what C/D is. I don't think such players exist at all. But there are lots of players who would balk at "D11" or "D7 sus4 add9", which I guess is what's usually meant when someone writes "C/D", i.e. C6/D but the extra 6 doesn't add anything that a competent player wouldn't add at will anyway.
I also like to do combinations like C/D - D/C - G/B. It looks clean and understandable and easy to play. Those who know what they're doing can add all kinds of extra notes, and those who don't can still play the song. :)
Answer: I agree with most of what has been written. The one exception where I would rather write Em/C than CMaj7 is if the C is a pedal tone/point that has been started before that chord and probably continues after.  (example of C as a pedal point is Jump by Van Halen, though it uses G7/C rather than Em/C).
It's a subtle distinction.  Many listeners and musicians will hear the chord as containing an Em sonority over a drone tone C bass.  Others will hear it as a CMaj7.
Comment: That's a really great point about pedals. If we're looking at a progression like | CΔ7 | D- / C | F#ø7 / C | B7alt / C | E- / C | FΔ7 / C | G7 / C | CΔ7 |, then a soloist would definitely not treat Emin/C as equivalent to CMaj7.
Answer: Slash bass is widely used for both inversions and what we might call 'rudimentary polychords' such as C/D.
The whole point of C/D is that it DOESN'T include A.  And the chord has a quite different flavour with and without an A.
OK, the jazz improviser won't take any notice of that.  But most musical performances are not jazz improvisations, the aim as accurate a copy of the composer's intention as possible.   And, if we can't have full notation, C/D is a very useful and precise indication of something quite commonly written - a C triad over a D bass note.
Answer: Slash chords serve several distinct functions. You already identified the first two:

they describe inversions (e.g., C/E)
they offer alternate spellings of known chords (e.g., C/D instead of D7sus)
they describe chords that might not be otherwise easily described (e.g., B/C or Gb/A)

So, can we define slash chords in ways that only capture the first usage? (E.g., "slash chords are chords where the bass is different from the root.") To answer, we need to look closer at usages #2 and #3 and determine if they're valid.
The second usage: a chord like C/D may initially seem like an equivalent spelling of D7sus. (And sometimes, it is.) But when we write C/D on a lead sheet, we're telling the chordal instrument how to voice the chord. On the other hand, D7sus doesn't come with this same constraint and leaves room for interpretation. D7sus could be voiced in many ways (G-B-C-E, A-C-E-G, A-D-E-A, D-G-A-C, etc.) that don't contain a strong sound of C triad. This is totally fair. Sometimes, songs have iconic sounds/voicings that we want to convey in the chords. There might be scenarios where C/D captures how the pianist played the chord on the original recording.
The third usage: there may be some instances where the harmony isn't extremely well-defined. In this case, a slash chord might show the only notes that will sound good in that context. In a scenario like that, an alternate spelling may not be available, because the alternate spelling would imply other notes or a harmony that isn't accurate.
So ultimately, I don't think we can use a definition like "slash chords are chords where the bass is different from the root." This doesn't quite encompass everything slash chords can achieve, and there isn't always a suitable alternative like D7sus.
(As an aside, I don't think Em/C should be used to convey CMaj7. Em/C would look more confusing, and Em/C doesn't convey anything that CMaj7 fails to capture. But if the underlying harmony truly is Em, and the bass truly should be playing the b6, then Em/C is a perfect use of slash chords for inversion.)
Comment: I disagree about C/D and D7sus being equivalent. IMO you should soften the statement. C/D doesn't include A, and D7sus doesn't include E ("sus" in my experience at least always means sus4). C6/D and D9sus, however, are pitch-equivalent.
Comment: BTW, in the first of the D7sus voicing examples, did you mean G-*D*-C-E?
Comment: @Aaron, no the voicing I had in mind was G-B-C-E, which is "Type B" rootless voicing for Amin. D7sus is often played as Amin/D. We hear that sort of voicing for sus chords on Wayne Shorter tunes.
Comment: @Aaron, I think the whole point of "D7sus" is that it leaves the door open to more possible voicings (provided they fit within the boundaries of the genre being played). In jazz, D7sus doesn't have to have the 5th. D7sus can contain the 9th, the 11th, the 13th, and combinations of those. Give all that, in jazz, C/D is one of the possible ways to voice D7sus, but it's not the only way.
Comment: @Aaron, also, did you mean to say that you disagree with my characterization of them
 as being "alternates"? (I don't call D7sus and C/D equivalent in my answer.)
Comment: Yes, I took "alternate spelling" to mean "representing the same chord".
Comment: @Aaron, so I would suggest that "alternate" here is closer to substitute or alternative. I do specifically say later that they aren't quite equivalent, despite the fact that it might initially appear that way. The distinction I draw is the one I've described here, and in the paragraph about how C/D is more a more restrictive choice than D7sus (at least, in jazz).
Answer: The idea of slash chord is that the first part indicates the overall harmony of the chord, and the different bass alters the "color" of that harmony, but without changing its role.
This is very important, as the chord indicates not only the triad, but the possible scale intended for that chord.
Let's take your example of E-/C and Cmaj7.
Given an E minor chord, the player assumes that the notes that can be played (the harmonic context) is that of E minor: the root - as in the most important note of that chord - is E, no matter the bass, and the scale includes F#, which does not exist in C major.
So, while those chords are conceptually very similar, they are not, as their function and harmonic context is different.
Comment: *"and the scale includes F#, which does not exist in C major"* right, but Cmaj7 could also exist in G major, where F# *is* included in the scale. I see what you're trying to say, but that part seems off to me.
Comment: @user45266 Yes, you're right, it also depends on the context. I'll update the answer later.
Comment: @ musicamante NO, NO, absolutely NOT!  Gsus4 has G, C and D in the upper structure.  F/C has F, A, and C.   Two quite different flavours, deserving two quite different chord symbols.
Comment: @jdjazz "G9sus isn't the same as G11 because G11 would contain a B, but G9sus would not. " I agree, and that's why I don't use G11 to mean G9sus! Some people insist on it, though... bugs me a bit, but what can you do?
Comment: But this ISN'T the idea of (say) F/G, in a C major context.   F is a subdominant.   The G root changes its role to a dominant.
Comment: @LaurencePayne In fact, F/G should be more properly noted as Gsus4, especially if it has that function: while it's often written as slash chord, I think that in that context is just a wrong writing, which is not the case of E-/C and Cmaj7 which can indicate two different chords/functions.
Comment: @LaurencePayne I obviously meant G7sus4.
Comment: @musicamante I believe that F/G should be more properly notated G11 (or Gm11 depending on the context, since it has no 3rd), since it's structure is G-(H)-(D)-F-A-C
Comment: I think Laurence Payne is saying that even if one refers to G7sus4, that's still not quite it. Should be G9sus4, if it's to be written that way. Gsus4 is not exactly the same as F/G (aka G9sus, *occasionally* referred to as G11).
Comment: @user45266, G9sus isn't the same as G11 because G11 would contain a B, but G9sus would not. (G11 can be voiced as F-B-C-E, C-F-A-B, etc.) I agree with musicamante that F/G (almost always) implies G7sus as the harmony, and G7sus is often better in the sense that it's more descriptive & a truer representation of the underlying harmony. However, even if the underlying harmony is G7sus, I think it's still okay to write F/G in some scenarios. Specifically, F/G is tends to convey a specific voicing--in a way that G7sus does not--and this can be useful information in certain contexts.
Answer:
Slash chord notation is meant to signal to the reader that the bass is acting independently of the rest of the chord above.

I disagree with this. Bass is an independent voice, and it might be well expected that a good bass player won't stick to the roots of the chords, appropriately for a given style, and in accordance with other musicians, in particular the soloist.
Slash notation is used when:

A specific bass line is strongly suggested in specific arrangement (rather than a bass line chosen by the performer),
A specific chord sound is strongly suggested (like in Laurence's example).

Chord symbol notation is not very precise in specifying the voicing and it's not meant to be. The main usefulness of the chord symbols is that they mark the harmonic motion while leaving freedom of selecting the actual notes to play to the performer/arranger.


fundamental group of the union of two subsets

Question: Let $X$ be a topological space and $U,V \subset X$ two open subsets such that $U \cap V$ and $U \cup V$ are both simply connected. How can i show that $U$ and $V$ are simply connected? Thanks in advance.
hilary
Comment: yes i know. but i tried with van kampen's. but i have no idea how to apply it.
Answer: Ok. Let me expand my answer. By Seifert–van Kampen theorem, we know that the fundamental group $\pi_1(U\cup V)$ of $U\cup V$ is the free product of the fundamental groups of $U$ and $V$ with amalgamation of $\pi_1(U\cap V)$. Since $U\cap V$ is simply connected by assumption, i.e. $\pi_1(U\cap V)=0$, $\pi_1(U\cup V)$ is the free product of $\pi_1(U)$ and $\pi_1(V)$. Since $U\cup V$ is simply connected by assumption, i.e. $\pi_1(U\cup V)=0$, we must have $\pi_1(U)=0$ and $\pi_1(V)=0$; otherwise, if $\pi_1(U)\neq 0$ or $\pi_1(V)\neq 0$, the free product of $\pi_1(U)$ and $\pi_1(V)$ must be non-trivial. For the above facts about free product, you can refer to here.
Note added: As Chris said, I should prove that $U$ and $V$ are path-connected before I can apply Seifert-van Kampen theorem. Here is the proof: note that $U\cup V$ and $U\cap V$ are simply-connected by assumption, which implies that $U\cup V$ and $U\cap V$ are connected. Now by the Mayer-Vietoris sequence, we have
$$H_0(U\cap V)\rightarrow H_0(U)\oplus H_0(V)\rightarrow H_0(U\cup V)\rightarrow 0.$$
Since the rank of the zero homology  $H_0$ is equal to the number of connected components, by the above exact sequence $H_0(U)$ and $H_0(V)$ has rank 1, which implies that $U$ and $V$ are connected. Since $U$ and $V$ are open by assumption, $U$ and $V$ must be path-connected.
Comment: But we *need* $U$ and $V$ to be path-connected *before* we can use van Kampen to conclude they are simply-connected. It's not hard to show that if $U$ and $V$ are open and both $U \cup V$ and $U \cap V$ are path-connected, then $U$ and $V$ are path-connected, but it has to be done.
Comment: Surely we need to show that $U$ and $V$ are path-connected before we can apply the theorem?
Comment: Right, but I think this is standard: if $U$ and $V$ are simply connected, then of course they are connected. Moreover, they are open by assumption. And it can be proved that open connected set must be path connected.
Comment: @Chris: Oh yes, you are right. I should be more careful. See my edited answer.
Comment: Please do not overlook the fact that there is a Seifert-van Kampen theorem for the fundamental groupoid on a set of base points, which allows for the computation of the fundamental group of the circle, as well as many other examples. For the use of groupoids, see http://pages.bangor.ac.uk/r.brown/gpdsweb.html
Comment: It is possible to extract from the usual proof of the Seifert-van Kampen Theorem a proof that the union of two open simply-connected sets with path connected intersection is simply connected, without using the notion of group or groupoid.  But you get more information by having these concepts around. The same applies in higher dimensions,  using  higher order versions of the fundamental groupoid.
Comment: I think the end of the argument is not correct. On a general topological space, connected + open does not imply path connected.


Running ssh-add from git bash using Windows 10's OpenSSH

Question: I've setup OpenSSH following the 2019 Update of this question including setting GIT_SSH=C:\Windows\System32\OpenSSH\ssh.exe.  Which works great, except when using when using git from git bash I get following error:
$ git pull
CreateProcessW failed error:193
ssh_askpass: posix_spawn: Unknown error
firstname.lastname@example.com: Permission denied (publickey).
fatal: Could not read from remote repository.

If I use ssh-add from git bash I get a different error:
$ ssh-add
Could not open a connection to your authentication agent.

Which, seems to be because ssh-add is using /usr/bin/ssh-add rather than the ssh-add in C:\Windows\System32\OpenSSH\, to correct this I tried using the full path:
$ /c/Windows/System32/OpenSSH/ssh-add.exe
CreateProcessW failed error:193
ssh_askpass: posix_spawn: Unknown error

Which gives me the same error as before.
How can I use Window's OpenSSH commands from git bash?
Answer: I ran into the same problem and found out that git bash prepends /usr/bin to PATH.
My really hacky solution was to just prepend the Path to OpenSSHs ssh-add to the path in my .bashrc:
PATH="/c/Windows/System32/OpenSSH:${PATH}"

Answer: I know that this topic is somewhat old, but I stumbled across this problem just recently and found a solution.
Regarding to the OpenSSH documentation, askpass ist used to display the password gui. And OpenSSH is only trying to use this "askpass command" if the environment variable SSH_ASKPASS is set! So the easiest solution to get rid of this problem, is to simply unset this env var.
unset SSH_ASKPASS

Just put this in your .bash_profile and/or your .bashrc and reopen the shell to see the effect. You can even execute it in the open shell to test it first, but its obviously not permanent then.
Answer: Adding the following snippet from the github docs to .bashrc in the gitbash shell did the trick for me:
env=~/.ssh/agent.env

agent_load_env () { test -f "$env" && . "$env" >| /dev/null ; }

agent_start () {
    (umask 077; ssh-agent >| "$env")
    . "$env" >| /dev/null ; }

agent_load_env

# agent_run_state: 0=agent running w/ key; 1=agent w/o key; 2=agent not running
agent_run_state=$(ssh-add -l >| /dev/null 2>&1; echo $?)

if [ ! "$SSH_AUTH_SOCK" ] || [ $agent_run_state = 2 ]; then
    agent_start
    ssh-add
elif [ "$SSH_AUTH_SOCK" ] && [ $agent_run_state = 1 ]; then
    ssh-add
fi

unset env

Read the full instructions on the github docs
Answer: For me with those below steps on win11, when I add ssh private key with password, and reboot my pc, then launch the gitbash again, I do NOT need to input password again, so it is works fine for me! Hope it works for you too!
The significant step here is to set the ssh private key with appropriate permission, my OS is Win11 21H2, git version is git version 2.40.0.windows.1, the following steps works well for me. You can refer to it.
First of all, set the correct ssh private key with appropriate permission,

select the file(ssh private key), right click, select file properties
click securty tab, click the advanced button, in the pop up windows, then
you may see many users has ssh private key access ability, then
click disable inheritance button, in pop up window select first one, it will clean up the inheritanced from properties from the drive(like E:\\
add or add user, then select add body or add object in pop up, in put you pc UserName, click the right button checking name, the result will change to something like PcName\UserName, then click OK button to confirm
delete all other users, just left the user name just add, which is PcName\UserName, then click OK button

Set up correct Windows OpenSSH for GitBash command, the windows openssh for windows 11 is located at C:\Windows\System32\OpenSSH\(if not, search it)

edit ~/..profile with the following line
export PATH="/C/Windows/System32/OpenSSH/":$PATH

Launch GitBash, then to make sure in GitBash you can get the windows system ssh commands: run the following command to check which ssh, the output of command should shows up with(or something like that)
/c/Windows/System32/OpenSSH/ssh.exe

Then the next is quite simple, just do the normal thing:

ssh-add -l To see if ssh-agent is start or not, if not do it
ssh-add path/to/you/ssh/private/key the key oper upper steps
ssh-add -l do check again
ssh -T email@example.com

The following is the shell script i use, it works both for windows and linux. You can reference to it. Copy and set the SSH private key file path to yours, then save it to a file, like ~/.ssh/EnableGitHubSSH.sh, then add a line of code source ~/.ssh/EnableGitHubSSH.sh to ~/.profile, then done! Try luanch GitBash or terminal to do github SSH login checking!
is_windows=$(uname -s | grep '[MINGW|MSYS_NT|CYGWIN_NT]')
if [ -n "${is_windows}" ]; then
  # 将系统 OpenSSH 查找路径提前
  # 删除 $HOME/bin (Git为啥会有这个设置?)
  # Windows 系统 PATH 修正,使用系统默认 OpenSSH, 不用每次重启后都输入密码
  # NOTE: 使用系统默 OpenSSH 时, 密码加密保存在系统中,SSH 的配置目录在 C 盘用户目录下
  XPATH=$(echo $PATH | sed "s#/c/Windows/System32/OpenSSH:##g" | sed "s#$HOME/bin:##g");
  export PATH="/c/Windows/System32/OpenSSH":$XPATH;
  unset XPATH;
fi

# 自动生成的文件,缓存Agent运行状态
tmpfile=~/.ssh/_SSHAgentEnvInfo.sh

# SSH私钥(GitHub免密登录认证)
sec_key=~/.ssh/YOUR-SSH-PRIVATE-KEY-ONE

test -f "$tmpfile" && source "$tmpfile" >| /dev/null

# agent_run_state:
# 0 = agent running with key
# 1 = agent running without key
# 2 = agent not running
agent_run_state=$(ssh-add -l >| /dev/null 2>&1; echo $?)

# 添加 Git 免密登录 GitHub 使用的 SSH 私钥
if [ ! "$SSH_AUTH_SOCK" ] || [ $agent_run_state = 2 ]; then
  if [ -z "${is_windows}" ]; then
    # Linux 需要运行的命令
    (umask 077; ssh-agent -s >| "$tmpfile")
    source "$tmpfile" >| /dev/null
  else
    # Win 11 手动配置 OpenSSH 开机启动
    # SSH_AUTH_SOCK 随便设置一个值,防止每次启动 GitBash 都加载私钥(需要输入密码)
    echo "SSH_AUTH_SOCK=OK;" > "$tmpfile"
  fi
  ssh-add "$sec_key" 2>/dev/null
elif [ "$SSH_AUTH_SOCK" ] && [ $agent_run_state = 1 ]; then
  ssh-add "$sec_key" 2>/dev/null
fi

unset tmpfile sec_key is_windows


When playing the oboe, should I touch the top or the bottom side of the reed?

Question: I have been playing the oboe for one year now but I was touching the reed on its top side and I was told that's now the best way.
My teacher says I should touch just the bottom side
So my question is:
Should I touch the reed on its top or bottom side?
Comment: You need to take lessons.  There is no other way to learn correct embouchure.
Comment: @CarlWitthoft I am have a lessons for more than a year now. Question updated
Comment: In that case, why do you distrust your teacher's instructions?
Comment: @michaelSalam - touching the reed with your tongue to stop its vibration is called "tonguing". On the oboe, it's normally done by touching the tongue to both upper and lower parts of the reed at the same time.
Answer: No, you don't need to touch the top of the reed in general to play the oboe. If you play off the tip a lot your top lip will probably touch it, but most likely not near the tip since you want it free to vibrate. You don't want the roof of your mouth to touch it and your tongue should always be controlling the bottom of the reed.
Answer: My teacher always told me to let the instrument rest on your lower lip, never press it against the top. It gives you a better overall control and it is more relaxing. Especially when breathing you should let it rest on the bottom and lift the top of your mouth over it.
So while you need some pressure from both sides when playing consider the bottom the leading part of the reed.


Counting integers $k$ such that $(k,n)=(k+1,n)=1$.

Question: Let $f(n)$ denote the number of integers for which $(k,n)=1$ and $(k+1,n)=1$. Then how do I show that $$f(n)=n\cdot \prod_{p|n}\left(1-\frac{2}{p}\right)$$
I have no idea how to start
Comment: I think there need to be a condition about $k$, such as $1\leq k\leq n$.
Comment: how do you prove the close form of Eulero's phi? Same way
Answer: First note that we have exactly $n$ pairs of consecutive integers, as the pair is determined by the first number. Now you can use the Inclusion-Exclusion principle.
$$f(n) = N - \sum N(c_i) + \sum N(c_i,c_j) - ... \pm \sum N(c_i,c_j,...,c_k)$$
Where $c_i$ is the condition that one of the numbers in the pair $(k,k+1)$ is divisible $p_i$, a prime divisor of $n$. You can notice that $N(c_i,c_j,...c_k) = \frac{2^{k}n}{p_ip_j...p_k}$, as every integer is in $2$ pairs (we don't count $n+1$ and also we never remove pair $(1,2)$ due to $1$, so we can skip the boundary cases). So now substitute this and after a little bit of factorizing you have.
$$f(n) = n - \sum \frac{2n}{p_i} + \sum \frac{2^2n}{p_ip_j} - ... \pm \sum \frac{2^kn}{p_ip_j...p_k} = n \prod_{p \mid n}\left(1-\frac{2}{p}\right)$$
Answer: You have to prove two things :
1) $f(n)$ is multiplicative, i.e. $f(mn)=f(m)f(n)$ for $(m,n)=1$.
2) The formula holds for $n=p^{k}$.
For 1), let $M=\{0\leq a\leq m-1|(a,m)=(a+1,m)=1\},N=\{0\leq b\leq n-1|(b,n)=(b+1,n)=1\},K=\{0\leq c\leq mn-1|(c,mn)=(c+1,mn)=1\} $, then there exists bijection between $M\times N$ and $K$ by Chinese remainder theorem.
2) is easy, just count.


Ethernet to Fiber Converters, reliable? or maybe better solutions

Question: Not sure if this is relevant to ask here ... but I cannot find any information on the net about it.
But here goes:
Today I have a fiber that comes into building B from A(I have no control here. Lets just say it's our ISP). This goes to a switch Cisco 2960G with a CWDM SFP Fiber module. Then from a Ethernet port to a Firewall.
This all works ... no problem.
In the near future another building will be connected with a Single Mode Fiber cable to building B. Lets call this C. ( We have no equipment in building C )
Since SFP CWDM Fiber modules is expensive(Compared to NON-CWDM ... in denmark, it's a factor 12) ... what would the best option be? ( I can see there is non-original CWVM, but these prices here is only compared to original )
Is "Ethernet to Fiber media converters" reliable? I don't see many of them and most of them are from rather unknown vendors?
I'm looking for an affordable solution ... so any vendor/products is most welcome.
Or is an additional switch to convert the RJ45/Ethernet from the switch in building B something that is beign used?
Comment: Define 'expensive'.
Comment: Updated the question. I guess i'm also looking for good advise here.
Answer: I had very good experience with Allied Telesis. Have been using them since the late 90s and never had a problem with them. Currently I am using them in a rack mounted case with dual power supply, so you're even protected against power supply failure.
Comment: +1 - I've used quite a number of Allied Telesis 10/100/1000 media converters (including both the long-haul and short-haul gigabit varieties) over the last 15 years and had good success with them. I've used them standalone with their wall warts, but their rack mount chassis is nice, too.
Answer: You're looking for a media converter. Black Box, StarTech, and Allied Telesis all make models in the $100-$200 USD range that would suit your needs.
Answer: In my experience a small switch with an SFP port (or several) is often cheaper or no more expensive than a media converter, and more likely to be made by a known/reliable vendor (and thus tends to be be more reliable than a "media convertor.")


How to set multiple domains for one language

Question: I have a multilingual site with Drupal 7 using subdomains like en.example.com to detect the language. Everything works like expected, but I have a mobile version of the website witch I want to be accessible by domains like en.m.example.com etc. How do I do this? I can set in admin/config/regional/language only one domain per language, but would have to set two in order to get that working, like:
for English:
en.example.com & en.m.example.com

for German:
de.example.com & de.m.example.com
etc.

(I would like to have the same structure as Wikipedia has.)
The problem is, that using subdomains for language selection, Drupal creates all internal links as absolute pathes. For example, a menu link will be created as:

test

and not as

test

So, I could create a domain alias with Apache, to send requests from en.m.example.com to en.example.com, but all internal links would bring the user back from  the mobile version to the normal. How can I solve this problem?
Comment: This doesn't really answer your question exactly but it would be better not to have separate mobile sites. It would be better to have a responsive layout that changes for mobile. It gives a better experience, it is easier to maintain, and you skip the negatives of browser detection and switching sites. - It will require a bit of investment in design/themeing though.
Comment: Thank you, I know that this is generally the best. But the use case of my website is different for mobile and normal users. So the functions and the content, that will be delivered differs as well. That why I do not have that option.
Comment: I don't understand this! This is a basic thing. It must be possible to use Drupal with languages domain in combination with subdomins for a mobile theme. Isn't there anybody out there doing this with Drupal?
Answer: Once you've set up Drupal to serve different languages in different domains, you need to instruct your web server to send requests from multiple domains to the same Drupal site.
In Apache, you'll need to edit the .conf (httpd.conf) file and add aliases to all the different domains. For example:
ServerName en.example.com
ServerAlias en.m.example.com

In addition to this, you'll also need to point the domain name server (DNS) to your server for all the domain names in different languages.
Comment: That does not work for me. The problem is that using different domains for language selection as described above, results in all internal links being created as absolute paths. So I can reach the page with en.example.com & en.m.example.com, but all internal link under en.m.example.com does not have the second sub domin, for example a link to a sub page looks like en.example.com/node/1234 , but should look like en.m.example.com/node/1234.
Answer: The answer is: using multiple domains for one language is not possible with Drupal 7 and there is – as far as I know – no module that adds that functionality.
But to achieve this aim anyway, there is workaround: As mentioned above, the problem with language domains is, that all internal pathes that have an language specific path alias and are created with the Drupal core function url() are created as absolute pathes. Responsible for that behaviour is the function:
locale_language_url_rewrite_url(&$path, &$options)

Don't set a language domain for that default language. If you don't do that, Drupal will not create absolute pathes for the default language if – for example – use the domain xyz.example.com, where xyz.example.com is not set as domain for any language, Drupal will create al urls relative and so clicking of any internal link will keep the subdomain.
But you can't use that method, if you want to have language sensitive subdomains as described above:
for English:
en.example.com & en.m.example.com
for German:
de.example.com & de.m.example.com
etc.
So the second method would be, to alter the current language of all types with the function:
hook_language_init. I use the following code, to get the above example working:

:
# hook_language_init()
function my_module_language_init() {
  // Current path
  $url = $_SERVER['SERVER_NAME'];

  // Global language object and get languages
  global $language;
  $languages = language_list();

  // Get all subdomains
  $reg = '/^((?:([^\.]+)\.)?(?:([^\.]+)\.))?([^\.]+\.[^\.]+)$/i';
  preg_match($reg, $url, $up);

  # We won't allow all subdomains, only 'm.' and 'm2.'
  # Change this for an other use case.
  if ($up[3] == "m2" || $up[3] == "m") {

    if (!isset($languages[$up[2]])) {
      $langcode = $language->language;
    } else {
      $langcode = $up[2];
    }
    $new_language         = $languages[$langcode];
    $new_language->domain = $new_language->language . "." . $up[3] .".". $up[4];

    // Set url options
    $options['language'] = $new_language;
    $types = language_types();

    // Set all language types and language domains
    foreach ($types as $type) {
      $GLOBALS[$type] = $new_language;
      $GLOBALS[$type]->domain = $new_language->domain;
    }
  }
}

Comment: I believe this module does something similar: https://drupal.org/project/language_multidomain  BUT... I wonder why it's not possible to use this hook: https://api.drupal.org/api/drupal/modules!system!language.api.php/function/hook_language_negotiation_info/7 (which is what the locale module uses) to define language negotiation provider that handles multiple domains??
Comment: @leon.nk I did not find that module, thank you for that hint. Maybe you are right and the  hook_language_negotiation_info is the right hook to use. I'll try it.
Comment: Apparently the language_multidomain module does not exist any more.
Comment: Shouldn't the above hook be [hook_language_init()](http://api.drupal.org/api/drupal/modules%21system%21language.api.php/function/hook_language_init/7)?  There is no *hook_api_language_init()*.  You should also update the language switcher links with [hook_language_switch_links_alter()](http://api.drupal.org/api/drupal/modules!system!language.api.php/function/hook_language_switch_links_alter/7).
Comment: @colan The custom module is called `custom_api` and the hook `hook_language_init()`. Together it is `custom_api_language_init()`. May be this is confusing, so I edited the example to make that point clear. You are right, to use ´hook_language_switch_links_alter()´ may be the better way. But as it seems that almost nobody is interested in this problem, I think it may not be worth to rewrite this example.
Comment: @user5950: In your "2.", there's a link to the function in the API, which doesn't exist. That's what threw me off. ;)
Comment: @colan Sorry, totally my fault. You were absolutely right. I would have accepted you edit request, but didn't see it in time...
Comment: With this solutions metatags are not working ? Please suggest !  Site Title, description (og:title, og:description") are shown as for other language version or default language of site...
Comment: This is because sitename, sitedescription etc also need to get fixed I think.


RGB image masking using opencv and numpy arrays (shape mismatch)

Question: I have a problem using a mask to keep only few parts of an image.
What I do :
1 -> Select the color I want to keep (OK)
2 -> I convert everything to Lab space to compute deltaE (OK)
3 -> Create the mask using deltaE value (OK)
4 -> Morphological opening of the mask (OK)
5 -> Apply this mask to the original image (not OK)
When I try to apply my mask to the image, I get this error :
"shape mismatch: value array of shape (720,1280,3) could not be broadcast to indexing result of shape (21045,3)"

The shape (720,1280,3) is the shape of my original image but, for the second shape, I get a different result each time I start my code.
All the data (original image and final image) are 720x1280x3 and the mask is 720x1280. Also, all the data is uint8.
Here is my code :
couleur_mire = im_Lab[mouseY,mouseX,:]
image_unie = np.ones_like(im) * couleur_mire
video.set(cv2.CAP_PROP_POS_FRAMES,frame_k)
_, im = video.read()
im_Lab = cv2.cvtColor(im, cv2.COLOR_BGR2Lab)
mask = np.zeros((h,w))
im_finale = np.zeros_like(im)
L1 = np.array(im_Lab[:,:,0],dtype=int)
a1 = np.array(im_Lab[:,:,1],dtype=int)
b1 = np.array(im_Lab[:,:,2],dtype=int)
L2 = np.array(image_unie[:,:,0],dtype=int)
a2 = np.array(image_unie[:,:,1],dtype=int)
b2 = np.array(image_unie[:,:,2],dtype=int)
deltaE =np.sqrt(np.multiply(L1-L2,L1-L2) + np.multiply(a1-a2,a1-a2) + np.multiply(b1-b2,b1-b2))
th = 25
mask[deltaE<th] = 1
mask = cv2.morphologyEx(mask,cv2.MORPH_OPEN,np.ones((20,20)))
mask = np.array(mask,dtype=np.uint8)
im_finale = np.zeros_like(im)
im_finale[mask==1] = im <--THIS IS THE LINE THAT DOES NOT WORK

Any help is welcome. Thanks to anyone who will take some time to answer :)
Edit : The second shape changes whenever the mask changes (if I select the same color two times in a row, the second shapes remains the same)
Edit 2 : The first value in the second shape corresponds to the number of 1 in the mask (in this case, 21045 pixels are kept with this mask)
Edit 3 : When I do it like that it works perfectly but it is too slow :
for i in range(h):
   for j in range(w):
      if mask[i,j]:
         im_finale[i,j,:] = im[i,j,:]

Answer: Based on my understanding you need to mask the image based on the mask you created, You can use multiplication to achieve this affect.
def mask_image( img, mask ):
   newImg = img.copy()
   newImg[:,:] = img[:,:] * mask[:,:]
   return newImg

With this you don't have to convert the mask to uint8.
Comment: Thank you for your answer. I didn't think of the possibility to use multiplication.


Create a Context/Condition and get a view display used on the page

Question: I want to create a context/condition plugin that checks the total results returned from a view display on the page (its a block), and if its less/greater than a certain figure, hide certain peripheral display elements.
I cannot seem to find a ContextDefinition for the view being executed, does this exist? Do I need to grab the context from the Block itself? How?
Answer: I wound up writing a specific module for this.
https://www.drupal.org/project/views_minimum


MS RemoteApp broken after changing IIS bindings

Question: OS is Server 2008 R2. In an effort to make the internal and external hostnames match (the SSL cert only matches the public hostname), I edited the bindings for our 'RDWeb' site. This somehow broke WelbyApp and I can't seem to undo it. The error I get is:
Your computer can't connect to the remote computer because the Remote Desktop Gateway server is temporarily unavailable.
I have downloaded the .RDP file from RemoteApp and opened it with Notepad++: the RD Gateway is correct. Worth noting that the RD Gateway does still work to RDP into the TS server via RDC 'connect from anywhere.' Any ideas here? Thank you.
Answer: Even though I still have a mismatch between public and private hostnames, I got RemoteApp working again via instructions here: http://www.concurrency.com/blog/w/remote-desktop-can%E2%80%99t-find-the-computer-through-rdw


Normal Distribution, percent less than mean minus one std. dev

Question: GRE Question, part b. My answer is 16%, but the book says 15%. Why?
mean = 65 cm
stdev = 5 cm
Probability that penguin chosen at random will be less than 60 cm is 16%, it shows in Normal Distribution graph. Why would the book say it is 15%

Update
During GRE, we can use standard calculator, i.e no scientific calculator. And I don't believe they will provide standard distribution table.
Kindly explain how to DERIVE the 15%, I wish to understand the mathematics.
Comment: @AhmedS.Attaalla I need to know how they got the answer for the actual GRE exam
Answer: The percentages shown in your diagram are only approximates. To more significant figures your answer should be 15.866..% so both your answer and the book answer are just rounded differently.
If you look at the question it states: "Give your answer to the nearest 0.05."
Comment: Where would I get 15.866,,,% from?
Comment: A standard distribution table, a statistical calculator, the internet, ... $$$$http://www.wolframalpha.com/input/?i=one+standard+deviation+from+the+mean
Comment: @ian-miller During the GRE exam, we will be given simple 4-function calculator, and I don't think they will give standard distribution table. How to derive these numbers?
Comment: You don't. You read it off the graph then you follow the instruction - **"Give your answer to the nearest 0.05."**


ZipArchive creates file, but ZipArchive::close() unable to rename it

Question: I've looked around, and while the error message I'm getting shows up, this particular problem seems novel.  I have a PHP script constructing a zip file using the ZipArchive library.  The file is actually being created successfully, but when I call close() I get the commonly reported ErrorException:
ZipArchive::close(): Renaming temporary file failed: No such file or directory

The zip file is created successfully, but when I look for it after the exception is thrown it has an extension like .zip.a04896.  If I chop off .a04896 then I can open the file without a problem and it contains the expected content; I assume it's some sort of indicator that the file is still under construction. Since I'm not specifically accessing the zip archive by file name I would assume that would not interfere with the renaming attempt.
I'm running Windows 10, and the code is part of a Laravel 5.3 app.  Here is the code in question:
            $zip = new \ZipArchive();
            $zipFile = config( 'app.upload_root' ).'\\downloads\\Interventions_'.$fileTime.".zip";
            if ($zip->open($zipFile, \ZipArchive::CREATE)!==TRUE) {
                throw new \Exception("cannot open <$zipFile>\n");
            }
            foreach ($interventions as $row) {
                $pdf_name = config( 'app.upload_root' ).'\\uploads\\'.$row->UIC.'_'.sprintf("%010d",$row->id).'.pdf';
                if( file_exists($pdf_name) ){
                    $result = $zip->addFile( $pdf_name, $row->UIC.'_'.sprintf("%010d",$row->id).'.pdf' );
                    if ($result == FALSE ){
                        throw new \Exception( $pdf_name.' did not add to ZIP succesfully');
                    }
                }
                else{
                    throw new \Exception( $pdf_name.' does not exist' );
                }
            }
            file_put_contents ( $textFile, $output );
            $result = $zip->addFile($textFile, $textFileName);
            if ($result == FALSE ){
                throw new \Exception( $testFileName.' did not add to ZIP succesfully');
            }
            sleep(1);
            $zip->close();

Any suggestions as to what's going wrong here?  Is it possible that under Windows 10 I need different permissions to rename a file than to create it?  Or is that weird extension after .zip the problem?
Comment: I suspect that `file_put_contents()` is interfering with `\ZipArchive`. If you need to generate ZIP contents dynamically, you may want to try `ZipArchive::addFromString()`.
Comment: The file_put_contents() call is saving a text file to the `downloads` directory.
 After it has been saved, it is separately added to the zip file.  The saved text file is getting added just fine, so I'm not sure how the means of its creation could be at fault.
Comment: Despite my incredulity I tried switching to `addFromString()` and it didn't change anything. I'm still getting a valid zip file with all contents and a weird additional suffix on the extension, along with the same error message.
Comment: I'm sorry it didn't work, but I can't see why it was such a crazy idea. Unexpected file system failures sometimes happen because a given item is held open by another operation (I've had endless problems in the past to rename an Access file on which I've established and closed an ODBC connection).
Comment: I appreciated the suggestion, and you're right, stranger things have happened.  I'm considering looking at other zip libraries for PHP, but I'd prefer to figure this out...
Answer: Ok, this is annoying:  the problem has subsequently disappeared, and the zip archives are closing without a hitch.  My development machine has been rebooted since my original posting, so my assumption is that >something< had a lock persisting as Álvaro had suggested.


Como posso fazer o efeito blur no IE?

Question: Estou a usar esse código css para fazer o efeito blur numa div:
.blur
{
    -webkit-filter: blur(25px);
    -moz-filter:    blur(25px);
    -o-filter:      blur(25px);
    -ms-filter:     blur(25px);
    filter:         blur(25px);
}

O problema é que os browsers IExplorer não suportam filter effects.
Como posso fazer esse efeito no IE? Há alguma alternativa?
Comment: Relacionada: [Como fazer o efeito de fundo dinâmico do iCloud?](http://pt.stackoverflow.com/a/136352/7210)
Answer: Como vc deu poucos detalhes vou responder com uma opção simples. Pode ser que essa opção não funcione para todos os casos, mas não deixa de ser uma alternativa já que não temos demais detalhes.
Opção 1: Usando box-shadow. repare que essa é uma propriedade já muito bem aceita pelos browsers, mesmo os mais antigos! Elá funciona do I9+ https://caniuse.com/#feat=css-boxshadow
Opção 2: Usando SVG. Veja que o SVG é bem aceito mesmo pelo IE a partir de versão 9 como vc pode conferir aqui https://caniuse.com/#feat=svg
imagem feita no IE11

Segue o código referente a imagem acima.
A opção com box-shadow foi feita nada mais é que um elemento com vários box-shadows sobrepostos. Em IEs mais antigos caso ele não aceite mais de um box-shadow vc pode sobrepor o elemento inteiro um sobre o outro com position:absolute
O SVG basta utilizar o Filter <feGaussianBlur in="SourceGraphic" stdDeviation="5" />. Vc pode fazer como no primeiro exemplo com o filter só no rect ou então no rect e no text dando a impressão que tudo está com blur

body {
    margin: 10px 0 0 40px;
    display: flex;
}
.box {
    width: 115px;
    height: 115px;
    background-color: red;
    top: 10px;
    position: relative;
}
.box.bs {
    box-shadow:
    0px 0px 8px 0px red,
    0px 0px 8px 0px red,
    0px 0px 8px 0px red,
    0px 0px 8px 0px red
}

div {
    margin-right: 30px;
}

DIV com box-shadow

123

DIV com filtro

123

SVG com defs filter

    <svg height="140" width="140">
        <defs>
            <filter id="f1" >
                <feGaussianBlur in="SourceGraphic" stdDeviation="2" />
            </filter>
        </defs>
        <rect x="10" y="10" width="120" height="120"  fill="red" filter="url(#f1)" />
        <text x="10" y="25" fill="black">123</text>
    </svg>

SVG com defs filter em tudo

    <svg height="140" width="140">
        <defs>
            <filter id="f1" >
                <feGaussianBlur in="SourceGraphic" stdDeviation="2" />
            </filter>
        </defs>
        <rect x="10" y="10" width="120" height="120"  fill="red" filter="url(#f1)" />
        <text filter="url(#f1)" x="10" y="25" fill="black">123</text>
    </svg>

Comment: @JorgeB. legal, testa ai e veja se funciona! No teste que fiz no IE 11 ficou bom! Qual quer dúvida é só me dar um toque que te ajudo.
Comment: Que detalhes necessitas de saber?
Comment: @JorgeB. no caso seria se vc queria aplicar o Blur apenas no background por exemplo, ou em um conjunto de elemento, tipo uma div e tudo que está dentro dela. De qq forma tentei dar exemplos que atendessem as duas situações. Mesmo com mais de 2 anos de atraso na resposta espero que ainda possa ajudar alguém :)
Comment: Pode-me ajudar a mim, que eu ainda tenho sem esse efeito quando é para iE. Quando tiver um tempinho eu vou testar isso.
Answer: Olá,
já tentou utilizar filter:progid?
filter:progid:DXImageTransform.Microsoft.Blur(PixelRadius=25);

Caso queira saber mais: https://msdn.microsoft.com/pt-br/library/ms532979(v=vs.85).aspx
Comment: Não funciona, porque não é o efeito para uma imagem, é para uma `div` HTML.

Como posso fazer o efeito blur no IE?


Is there a software/website to play notes on snare drums?

Question: I am a student for (or is it 'to'? I'll have to look that up on ell.stackexchange) snare drums, and I'm given sight-reading homework, with lots of triplets with rests, sixteenth note triplets and all kinds of subdivisions.
Is there a software or a website that you can edit and play notes on (including most subdivisions, sixteenth note triplets are helpful, but not nessecary)?
For example, you could put in a triplet with a rest on the first triplet, then an eighth note and then a rest, and then the software/website reads it and plays it to a tempo you set it.
Comment: something like this? switch from "voice" to "drums" http://www.philtulga.com/counter.html
Comment: It's ok, but you have to buy it to use triplets
Comment: I can really recommend Guitar Pro 6 if you're still interested. It is an awesome program with a great sound engine which sounds very realistic. It's also easy to use.
Answer: I'm sure you will find many programs that give you want you are looking for (any notation program for example).  However, you need to learn to play the rhythms yourself.  Using the programs will result in you learning by rote, which is essentially just copying what you're hearing without really understanding the concepts.  This is akin to being a parrot.
Being a musical parrot is not sustainable nor is it as fun as being a musical person.
Either ask your teacher to give you materials that are less complicated, or take the time to learn the concepts necessary in order to play the appropriate rhythms.
Comment: I know how to play it, I'm just making sure that I'm correct. Thanks for the advice anyways.
Answer: Yes, plenty.
Guitar Pro is commercial, but there are free alternatives:
http://sourceforge.net/projects/tuxguitar/
I'm sure Tux has the MIDI voice for percussion available.


How to make this function dynamic? R function

Question: i have a function in R that generates a table graph picking data from a dataframe and every time i want to pass a different variable (column name from dataframe) i have to repeat the code. So sometimes it can be the variable and sometimes the variableb, other times the variablec... etc.
generates_table_variablea <- function(data) { ## how to pass the column = variablea here like this
                                              ####### function(data, column = variablea) .. ???

  big_data <- data %>%
    group_by(a, b, c, d) %>%
    mutate(total_categoria_abs = sum(abs(f))) %>%
    mutate(volume_negativo = if_else(variablea < 0, f, 0)) %>%
    mutate(volume_positivo = if_else(variablea > 0, f, 0)) %>%
    mutate(total = sum(volume_positivo) - sum(volume_negativo)) %>%
    mutate(e = if_else(variablea < 0, sum(variablea), 0)) %>%
    ungroup() %>%
    filter (variablea < 0) %>%
    group_by(a, b, c, d) %>%
    summarise(e = mean(e), vendas = sum(f*-1), frac_vendas = vendas*-1/mean(total_categoria_abs)) %>%
    arrange(e) %>%
    ungroup()

  big_data$frac_vendas <- round(big_data$frac_vendas, digits = 2)

  big_data$e <- round(big_data$e, digits = 0)

}

If I want to change this variable, I have to do the follow:
generates_table_variableb <- function(data) { ## HERE IT WILL BE function(data, column = variableb)...

  big_data <- data %>%
    group_by(a, b, c, d) %>%
    mutate(total_categoria_abs = sum(abs(f))) %>%
    mutate(volume_negativo = if_else(variableb < 0, f, 0)) %>% #### HERE I NEED TO CHANGE ALWAYS TO VARIABLEA, VARIABLEB, VARIABLEC...
    mutate(volume_positivo = if_else(variableb > 0, f, 0)) %>%
    mutate(total = sum(volume_positivo) - sum(volume_negativo)) %>%
    mutate(e = if_else(variablea < 0, sum(variableb), 0)) %>%
    ungroup() %>%
    filter (variableb < 0) %>%
    group_by(a, b, c, d) %>%
    summarise(e = mean(e), vendas = sum(f*-1), frac_vendas = vendas*-1/mean(total_categoria_abs)) %>%
    arrange(e) %>%
    ungroup()

  big_data$frac_vendas <- round(big_data$frac_vendas, digits = 2)

  big_data$e <- round(big_data$e, digits = 0)

}

Having multiple functions doing the same thing is slowing down my code...
How could this be better? All that I want is to pass this column dynamically.
Answer: This is one of the way
library(dplyr)
x <- data.frame(v1=1:3, v2=4:6)
f <- function(data, var1){
  x %>% select(!!var1)
}
f(x, quo(v1))

You can see more explanation in https://adv-r.hadley.nz/quasiquotation.html
Comment: Kevin, thank you for your aswser, could you please apply this to my function? Sorry I am new in R.
Answer: I found a other away that works too:
generates_table_variablea <- function(dataframe, variable) { ## Here pass variable

  big_data <- dataframe %>%
    group_by(a, b, c, d) %>%
    mutate(total_categoria_abs = sum(abs(f))) %>%
    mutate(volume_negativo = if_else(.data[[variable]] < 0, f, 0)) %>%
    mutate(volume_positivo = if_else(.data[[variable]] > 0, f, 0)) %>%
    mutate(total = sum(volume_positivo) - sum(volume_negativo)) %>%
    mutate(e = if_else(.data[[variable]] < 0, sum(variablea), 0)) %>%
    ungroup() %>%
    filter (.data[[variable]] < 0) %>%
    group_by(a, b, c, d) %>%
    summarise(e = mean(e), vendas = sum(f*-1), frac_vendas = vendas*-1/mean(total_categoria_abs)) %>%
    arrange(e) %>%
    ungroup()

  big_data$frac_vendas <- round(big_data$frac_vendas, digits = 2)

  big_data$e <- round(big_data$e, digits = 0)

}

Only replace the variable by .data[[variable]] and you can pass any column inside the function.


Proving that if $ a_{2n}, a_{2n + 1}, a_{5n} $ are convergent, then so is $ a_n $

Question: I want to prove that if $ a_{2n}, a_{2n + 1}, a_{5n} $ are convergent, then so is $ a_n $, I'm not sure if this is true or false. Can you verify my proof, or give me a hint if it's false?
Let  $ a_{2n} \to L, a_{2n + 1} \to K, a_{5n} \to E $.
Assume $ L \neq M $. Therefore, $ \exists \epsilon_1 \gt 0 : \forall N, \exists n \gt N : \left|a_{2n} - M\right| \ge \epsilon_1 $. $ \exists N : \forall n \gt N : \left| a_{2n} - M \right| \lt \epsilon_1 $. $ \exists n \gt N : \left| a_{2n} - M \right| \gt \epsilon_1 $. Therefore, $ \left| a_{10n} - M \right| \ge \epsilon \rightarrow a_{5n} \not \to M $ - contradiction.
Do the same process with $ a_{2n + 1} $. Because $ a_{2n}, a_{2n + 1} $ cover $ a_n $, $ a_n \to M $.
Comment: Check this for a very similar question: https://math.stackexchange.com/q/746306/42969
Comment: $a_{10n}$ is part of both $a_{2n}$ and $a_{5n}$ then it should converge to both $L$ and $E$ then $L=E$. $a_{10n+5}$ is part of both $a_{2n+1}$ and $a_{5n}$ then it should converge to both $K$ and $E$ then $K=E$. Then $L=K=E$. As $a_{2n+1}$ and $a_{2n}$ cover all values $a_{n}$ then $a_{n}$ converges to the same limit $L=K=E$.
Answer: The problem with your proof is that it's unclear. First I assume $M=E$. First statement is clear. Second and third not. The statement after 'therefore' is for sure incorrect (what is $\epsilon \rightarrow a_{5n} \not \to M$?).
In my opinion it's better to use subsequences. Since $(a_{10n})_{n\in\Bbb N}$ is a subsequence of both $(a_{2n})_{n\in\Bbb N}$ and $(a_{5n})_{n\in\Bbb N}$, it's convergent to both $L$ and $E$. Therefore $L=E$. Similarly $(a_{10n+5})_{n\in\Bbb N}$ is a subsequence of both $(a_{2n+1})_{n\in\Bbb N}$ and $(a_{5n})_{n\in\Bbb N}$, it's convergent to both $K$ and $E$. Therefore $K=E$.
Answer: The subsequence $(a_{10n})$ is a subsequence of both $(a_{2n})$ and $(a_{5n})$, so
$$
\lim_{n \to \infty}a_{2n} = \lim_{n \to \infty}a_{5n}.
$$
Similarly, the subsequence $(a_{10n+5})$ is a subsequence of both $(a_{2n+1})$ and $(a_{5n})$, so
$$
\lim_{n \to \infty}a_{2n+1} = \lim_{n \to \infty}a_{5n}.
$$
Therefore, both sequences $(a_{2n})$ and $(a_{2n+1})$ converge to the same limit, so $(a_n)$ is convergent


Função Impulso-Resposta no R

Question: Estou com uma dúvida em relação ao output da função irf do pacote vars.
Qual a diferença em relação ao output quanto aos argumentos _cumulative = TRUE/FALSE_ e _ortho = TRUE/ FALSE_?
Outra coisa, o impulso sobre a variável é de 1%, 10% ou 1 desvio padrão? E onde posso escolher o valor do impulso?
Answer: Ao que parece ortho = TRUE/FALSE serve para controlar uma possível autocorrelação entre as variáveis (ou seus erros), fazendo com que o efeito marginal seja "mais limpo". Isso é realizado internamente ajustando os impulsos por uma matriz que resulta da decomposição de cholesky da matriz de covariâncias dos erros.
Já cumulative = TRUE/FALSE permite que os efeitos marginais sejam ou não acumulados (um clássico cumsum()).
Quanto ao impulso, aparentemente é predefinido, e nessa função não teria como ser alterado. Pode ver, na função Phi, que é definido como diag(K), onde K é o número de variáveis.
Maiores informações em (inglês): https://stats.stackexchange.com/a/143296/77852
Pode ver os códigos das funções usando:
methods(irf)
getS3method("irf","varest")
vars:::.irf
vars:::Psi
methods(Psi)
getS3method("Psi","varest")
getS3method("Phi","varest")

Função Impulso-Resposta no R


Notifications from Workbench included content type

Question: I added a new content type for my drupal 7 site and I have a form in this content type. It has the workbench enabled in this form so that the moderator can approve the submissions and close the forms if they are complete.
The functionality that I am looking to implement now is mailing the user upon the status change of the form. i.e, if the form changes from draft to closed, the user should be notified. I looked for modules or related content for implementing this, but could not find any. What is the best way to do this? Please let me know.
Thanks in advance.
Answer: You can do this with the Rules module: http://drupal.org/project/rules
It should be pretty straightforward, once you figure out how to use Rules. (You can find some video tutorials here: http://drupalize.me/videos/basics-rules-link)
Basically, you are going to create a rule that is triggered when a node's workbench moderation state changes. When the rule runs, it will send an email. In that email, you should be able to include tokens (http://drupal.org/project/token) that will be specific to the node that was just changed.
Hope that helps.
Comment: Thanks for the information. However, meanwhile I wrote a custom module using the hook_node_presave and drupal_mail function. It works perfect.


RFM & customer lifetime value modeling in R

Question: Can anybody tell me how to do recency, frequency & monetary value (RFM) modeling & customer value modeling in R?
Also, can somebody refer me some literature on it?
Comment: you can also look at [BTYD](http://cran.r-project.org/web/packages/BTYD/index.html) package in R. Or buy till you die package. I think Bruce Hardie is one of the authors. Not too sure though.
Answer: As for references, Data Mining Using RFM Analysis should help as far as terminology and further references go.
One of the simplest (and popular) ways to model the probability of customer response is to use logistic regression with RFM as explanatory variables (among other available variables).
For modeling monetary value, one could just regress revenue on RFM directly (by using a simple linear model for starters) which usually does surprisingly well. More advanced/non-linear models (such as Random Forest or Gradient Boosting Machine) do better than linear models in my experience.
Another popular approach is to build a slightly more complex model for predicting monetary value based on two sub-models: one for probability of response (e.g. using logistic regression as a function of RFM), and the other for revenue conditional on response (again, it could be as simple as a linear model of RFM). Expected monetary value is the product of the two predictions.
If randomized test/control data are available then uplift/netlift based techniques are quite popular for modeling the incremental benefit of a treatment.
As for customer life cycle value, see Modeling Customer Lifetime Value for a review and further references.
With regards to modeling in R, I am not aware of any "off-the-shelf" packages for that type of modeling. R does provide all necessary building blocks for that though (unless you have enormous amount of data - in that case you may have to rely on more scalable tools)
Comment: Very nice answer, but I think the first link might be broken.
Comment: 1) It is okay as long as you are not confusing the explanatory/input variables (from past data) and the target variable (from "future" data)  2) Just choose the subset of data where customers bought something and regress the revenue on the explanatory variables
Comment: @Yevgeny, I have two questions regarding the suggestions you have given. First, as for modelling monetary value, is it ok to regress revenue using Monetary among the predictor variables? I'm afraid they will be quite the same variable. In the second place, do you have any online resources that could help me understand how to carry out linear regression conditional on the response (using the second approach you described)? Thank you very much!
Answer: Not sure if you are still working on the RFM modeling. Here (pdf) is an article / the vignette for the BTYD package in R that might be helpful to you. The whole article is based on R and it has 3 different models to look at. On Page 1, 2.1 Data Preparation, you can see the context about RFMs.
Comment: Thanks Gung! Even though at present I'm not working on it. But this is most helpful. Also, might helpful to other people who are working on it now.
Comment: package was deprecated.
Answer: There is a new R package that implements some of the latest modeling techniques for CLV in non-contractual settings (e.g. retailing):
https://cran.r-project.org/package=CLVTools
Here is a step-by-step walk-through based on data from an apparel retailer:
https://www.clvtools.com/articles/CLVTools.html


Use a variable in jquery .css()?

Question: I'm trying to use an api call to change the background of a div based on the current weather. The url is not working in the last line. If I add a path from a file in my folders it works, but not when I try to add a variable as the url path. Is there a workaround to use a variable in the url path? Here's what I have:
<code>function loadImage(conditions){
    var imageSRC = "img/weather/hero-";
    var validConditions = ["clear", "cloudy", "rain", "snow"];
    var timeOfDay = getTimeOfDay();
    conditions = conditions.toLowerCase();
    if (validConditions.indexOf(conditions) === -1) {
        conditions = "cloudy";
    } else {
        conditions = conditions;
    }
    console.log(conditions);

    var apiImg = imageSRC + conditions + ".jpeg";
    console.log(apiImg);

    $('#intro').css("background-image", 'url(apiImg)');
}
</code>
Comment: $('#intro').css("background-image", 'url('+apiImg+')');
Answer: Use strings concatenation:
<code>$('#intro').css("background-image", 'url(' + apiImg + ')');
</code>
or ES6 template literals:
<code>$('#intro').css("background-image", `url(${apiImg})`);
</code>
Comment: Thanks for your answers! I used (' + apiImg + ') and it worked.

Use a variable in jquery .css()?


Conversão de array com json_encode PHP

Question: Opa, alguém sabe porque quando eu faço isso:
json_encode(array("0" => 0));

Retorna isso: [0]
Em vez disso: {"0":0}
Answer: O PHP deteta automáticamente se estás a usar chaves numéricas e converte numa array.
Se quiseres mesmo um objeto podes usar JSON_FORCE_OBJECT no segundo argumento (PHP 5.3+), opcional do json_encode. (exemplo: https://ideone.com/kFftSu)
Repara que se juntares outro elemento a essa array, sem chave numérica, o json_encode já lê como objeto.
Exemplo (https://ideone.com/yyrya4):
echo json_encode(array("0" => 0, "foo" => "bar"));
// dá:
{"0":0,"foo":"bar"}

Conversão de array com json_encode PHP


vbs execute from network with credentials

Question: I need to run a setup.exe from the local network with credentials.
I was able to do this with a bat file, but the problem is, but i don't want the cmd window showing up when this is executing.
So from what i've read, a good option is to use a vbs script like this, except i can't find a way to use it with credentials.
Set shell = WScript.CreateObject("Wscript.Shell")
shell.Run("\\192.168.0.100\Setup\setup.exe"), 0 , True

Basically what i need is the equivalent of this batch script in vbs:
net use Z: \\192.168.0.100\sh /user:user password /persistent:yes
start /d "Z:\Setup" setup.exe

Comment: Scratch that, instead use psexec. See answer.
Answer: you may do this:
Set WshNetwork = WScript.CreateObject("WScript.Network")
WshNetwork.MapNetworkDrive "Z:", "\\192.168.0.100\sh", True, user, password

Set shell = WScript.CreateObject("Wscript.Shell")
shell.CurrentDirectory = "Z:\Setup"
shell.Run("setup.exe"), 0 , True

Note: MapNetworkDrive will fail if Z: is already mapped. You will need to handle that.
Comment: what is the error? have you tried `WshNetwork.RemoveNetworkDrive "Z:", True, True` ?
Comment: This is what i was looking for. Yes the mapping is a problem, but i would need a way to unmap the drive after the setup is run.
Comment: And there is also a nasty vbs error if u click cancel instead of run for the setup.exe, but that is also another story.
Comment: To unmap, just use the RemoveNetworkDrive method, you should lookup for the WSH reference online for more details.
Comment: I tried this `WshNetwork.RemoveNetworkDrive "Z:"` after `shell.Run`, but it doesn't seem to work.
Comment: Yep that works aswell. This really helped me. Thank you!!
Answer: PSExec is what you want:
https://technet.microsoft.com/en-us/sysinternals/pstools.aspx
Like this:
Set shell = WScript.CreateObject("Wscript.Shell")
shell.Run("psexec.exe -u User -p Password -accepteula \\192.168.0.100\Setup\setup.exe"), 0 , True

Documentation:
https://technet.microsoft.com/en-us/sysinternals/pxexec

Using PsExec
Usage: psexec [\computer[,computer2[,...] | @file]][-u user [-p
  psswd][-n s][-r servicename][-h][-l][-s|-e][-x][-i [session]][-c
  [-f|-v]][-w directory][-d][-][-a n,n,...] cmd [arguments]
-u    Specifies optional user name for login to remote computer.
-p    Specifies optional password for user name. If you omit this
        you will be prompted to enter a hidden password.
-accepteula   This flag suppresses the display of the license dialog.
Comment: Does this mean i have to have PsTools copied/installed on every machine where i need to run the setup.exe file?
Comment: You just need the psexec.exe executable. You can put it on a share somewhere or you could base64 encode the exe then put the base64 encoded info in your script. Either way would work fine.


Resgatar valores de um XML contido em uma String

Question: Tenho uma String, que contem um XML com uma estrutura parecida a esta:
<TAG0>
   <TAG1>
      <TAG2>valor1</TAG2>
   </TAG1>
   <TAG1>
      <TAG2>valor2</TAG2>
   </TAG1>
</TAG0>

No caso eu tenho Tags com o mesmo nome, que se repetem no corpo do XML, como uma venda, que contem vários itens. A String com o XML esta com o texto corrido sem espaços. Ex.:
String VARIAVEL = "<TAG0><TAG1><TAG2>valor1</TAG2></TAG1><TAG1><TAG2>valor2</TAG2></TAG1></TAG0>"

O que tenho que fazer, como segue nesse exemplo, é resgatar os valores das tags "TAG2", sabendo que posso ter N tags como "TAG1". O caso real é resgatar todas os CFOPs dos itens de uma NFe.
Comment: Veja se este link lhe ajuda em algo: http://www.guj.com.br/java/169353-ler-conteudo-xml-contido-em-uma-string
Answer: Você pode resolver o problema utilizando expressões regulares. Se você tem o texto bem definido no formato que mostrou o código abaixo vai resolver.
public static void main(String[] args) {
    String texto = "<TAG0><TAG1><TAG2>valor1 x</TAG2>" +
                      "</TAG1><TAG1><TAG2>valor2</TAG2></TAG1></TAG0>";
    Pattern p = Pattern.compile("<tag2>(.+?)</tag2>", Pattern.CASE_INSENSITIVE);
    Matcher m = p.matcher(texto);
    while( m.find() ){
        System.out.println(m.group(1));
    }
}

Eu quebrei a string apenas para ficar melhor apresentável aqui.
O que o código está fazendo é identificando o padrão que você solicitou através de uma expressão regular <tag2>(.+?)</tag2> que significa:
Encontre o texto <tag2> seguido de qualquer coisa de forma não gulosa, seguido do texto </tag2> utilizando o parâmetro Pattern.CASE_INSENSITIVE para ignorar maiúsculas e minúsculas.
while( m.find() ) percorre o texto enquanto existir o mesmo padrão e m.group(1) para imprimir o agrupamento 1 definido no padrão pelos parênteses,  no caso (.+?)
Para visualizar a regex funcionando, veja aqui:

O link da ferramenta que usei com o padrão criado: https://www.debuggex.com/r/3aqFTNWTTpkHkPCe
Answer: É possível pegar os valores com regex, mas há a desvantagem de precisar alterá-lo sempre que precisar procurar por outro elemento. Eu sugiro que você crie um Document, assim fica mais simples pegar os elementos pelo nome.
Alterei o nome das tags para o código ficar mais sucinto, mas a estrutura continua a mesma e a ideia é pegar o texto nos elementos <c>:
<?xml version="1.0" encoding="UTF-8"?>

     <c>Valor 1</c>

     <c>Valor 2</c>

Segue uma solução utilizando essas classes do próprio Java:
import java.io.StringReader;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.NodeList;

import org.xml.sax.InputSource;

E o código para parsear a string em XML e obter o conteúdo dos elementos:
String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><c>valor 1</c><c>valor 2</c>";

DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();

Document xmlDocument = builder.parse(new InputSource(new StringReader(xml)));

// Pega os elementos em que o nome da tag seja "c":
NodeList nodes = xmlDocument.getElementsByTagName("c");
for(int i = 0; i < nodes.getLength(); i++)
    System.out.println(nodes.item(i).getTextContent());

output:

Valor 1
  Valor 2