Could there be an irrational number $x$ such that the product of $x$ and $\pi$ are rational?

Question: I know that irrational numbers cannot be the quotients of any two rational numbers, and an irrational number times a rational number is thus also irrational.  But, could there be an irrational number, that, when multiplied by $\pi$, the product is rational?
Comment: How about $\frac 1{\pi}$?
Comment: "derived from $\pi$" doesn't mean anything.  If $\alpha\times \pi=\frac ab$ then $\alpha = \frac a{b\pi}$.
Comment: @qazwsx As lulu observed, any irrational number that satisfies the condition is of the form $\frac{a}{b\pi}$ with $a,b\in\Bbb Z\setminus\{0\}$. That means ALL the numbers you are looking for will be numbers as $\frac{3}{2\pi}$, $\frac{17}{23\pi}$, $\frac{217}{1000\pi}$, etc. ALL will be "derived from $\pi$"
Comment: @qazwsx "*a number not derived from pi*" $\;-\;$ You can "obfuscate" it like $\frac{1}{\arctan(1)}$ for example, but it must still be a rational multiple of $\frac{1}{\pi}$.
Comment: You're probably asking, "are there two known irrational numbers whose product was expected to be irrational, but was later to shown to be rational." Unfortunately, I don't know of any such examples, and I suspect there are hardly any nontrivial answers. However, you might be interested [in this related mathoverflow page](https://mathoverflow.net/questions/32967).
Comment: I mean a number not derived from pi.  For example, it is not known if e*pi is irrational or rational.  Is there an irrational number where it is known that it times pi is rational?
Answer: If $r=x\pi$ where $r$ is rational, then we have $x=\frac r\pi$.
This means that if you have an $x$ such that $x\pi$ is rational, then $x$ is of the form $\frac k\pi$ for some rational $k$. This explains why the answer to your question should always be "derived from $\pi$".


How come module-level validators are evaluated only after property-level validators?

Question: I'm using the module-level validator: 'PropertiesMustMatch' on my view-model, like so:
[PropertiesMustMatch("Password", "PasswordConfirm")]
public class HomeIndex
{
    [Required]
    public string Name { get; set; }

    public string Password { get; set; }

    public string PasswordConfirm { get; set; }
}

I'm noticing that if I submit the form without Name filled in, the ValidationSummary() helper returns only the following error:

The Name field is required.

However, if I fill in Name, then ValidationSummary() will return a PropertiesMustMatch error:

'Password' and 'PasswordConfirm' do not match.

So it looks like the property-level validators are being evaluated first, then the model-level validators.
I would much prefer if they were all validated at once, and ValidationSummary would return:

The Name field is required.
'Password' and 'PasswordConfirm' do not match.

Any ideas what I can do to fix this?
I'm studying the MVC 2 source-code to try to determine why this happens.
Answer: I found what's causing this, but my "solution" is probably going to break the normal processing of validators. Use with caution.
I found a conditional return statement in the OnModelUpdated function of the DefaultModelBinder:
protected override void OnModelUpdated(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
    IDataErrorInfo errorProvider = bindingContext.Model as IDataErrorInfo;
    if (errorProvider != null)
    {
        string errorText = errorProvider.Error;
        if (!String.IsNullOrEmpty(errorText))
        {
            bindingContext.ModelState.AddModelError(bindingContext.ModelName, errorText);
        }
    }

    // BEGIN CONDITION
    if (!IsModelValid(bindingContext))
    {
        return;
    }
    // END CONDITION

    foreach (ModelValidator validator in bindingContext.ModelMetadata.GetValidators(controllerContext))
    {
        foreach (ModelValidationResult validationResult in validator.Validate(null))
        {
            bindingContext.ModelState.AddModelError(CreateSubPropertyName(bindingContext.ModelName, validationResult.MemberName), validationResult.Message);
        }
    }
}

If I understand this code (which I might not) it seems that the MVC team intended model validators be skipped at this point.
I've made my own custom ModelBinder in which I re-run the code that would have been avoided by the condition:
public class CustomModelBinder : DefaultModelBinder
{
    protected override void OnModelUpdated(ControllerContext controllerContext, ModelBindingContext bindingContext)
    {
        base.OnModelUpdated(controllerContext, bindingContext);

        foreach (ModelValidator validator in bindingContext.ModelMetadata.GetValidators(controllerContext))
        {
            foreach (ModelValidationResult validationResult in validator.Validate(null))
            {
                bindingContext.ModelState.AddModelError(CreateSubPropertyName(bindingContext.ModelName, validationResult.MemberName), validationResult.Message);
            }
        }
    }
}

This seems to fix the issue.
Comment: Yup, as I suspected, inheriting this class creates issues: basically it skips every validator except [Required]. :(
Comment: Fixed the above issue. For some weird reason I have to call 'base.OnModelUpdated', then it all works as usual.


How do I safely remove a path string from a compiled library without corrupting the library?

Question: My RPM build process is complaining about the buildroot path string appearing inside several .so files. I've tried using both sed and perl to do a regex replacement of that string with '', but while that silences check-buildroot, it corrupts the .so file and causes anything that uses it to segfault.
This string is apparently not part of an rpath, as chrpath --delete doesn't silence the error message from check-buildroot. I have no idea why the buildroot path is appearing within these .so files.
So what's the "right" way to prevent that buildroot path from appearing in the .so files?
EDIT: Here's my specfile:
%{!?tgrelease: %define tgrelease() %2}
%if 0%{?amzn}

# Prevent /usr/lib/rpm/check-buildroot from running, because the only remedy we've found to silence its error messages
# also corrupts the .so files it complains about.
%define __arch_install_post /usr/lib/rpm/check-rpaths

%define __python python
%define __python_ver python2.6
%define __python_prefix python
%else
%define __python python2.6
%define __python_ver python2.6
%define __python_prefix python26
%endif
%define python_sitelib %(%{__python} -c "from distutils.sysconfig import get_python_lib; print get_python_lib()")

%define __package directory
%define __package_safe %(echo %{__package} | sed 's/[-. ]/_/g')
%define __pip_package %(echo %{__package} | sed 's/_/-/g' | tr '[A-Z]' '[a-z]')

%define __configdir etc/prod
%define __django_root REDACTED
%define __requirements REDACTED

Name:           %{__package}
Version:        %{__version}
Release:        %tgrelease 0 1
Summary:        REDACTED
Group:          Development/Languages
License:        Restricted
Source0:        %{rname}/%{name}-%{version}.tar.gz
BuildRoot:      %{_tmppath}/%{name}-%(%{__id_u} -n)

BuildRequires:  %{__python_prefix}
BuildRequires:  %{__python_prefix}-setuptools
BuildRequires:  %{__python_prefix}-virtualenv
# Uncomment this when we get git as an RPM on RH6
BuildRequires:  git
BuildRequires:  openldap-devel
BuildRequires:  libxml2-devel
BuildRequires:  libxslt-devel
BuildRequires:  chrpath

Requires:  %{__python_prefix}
Requires:  %{__python_prefix}-virtualenv
Requires:  openldap
Requires:  mysql

%description
REDACTED

%prep
%setup -q -n %{name}-%{version}

%install
rm -rf $RPM_BUILD_ROOT

%{__install} -d %{buildroot}%{__django_root}/conf.d
%{__install} -d %{buildroot}%{__django_root}/cron/daily
%{__install} -d %{buildroot}%{__django_root}/cron/hourly
%{__install} -d %{buildroot}%{__django_root}/%{name}/ve
%{__install} -d %{buildroot}%{__django_root}/%{name}/current_settings
%{__install} -d %{buildroot}%{__django_root}/html/static

#virtualenv
virtualenv-2.6 --no-site-packages %{buildroot}%{__django_root}/%{name}/ve
source  %{buildroot}%{__django_root}/%{name}/ve/bin/activate
pip install -r %{__requirements}
virtualenv-2.6 --relocatable %{buildroot}%{__django_root}/%{name}/ve
deactivate

# Put the settings file into current_settings and add the symlink we will want when installed.
%{__install} -m 664 %{buildroot}%{__django_root}/%{name}/ve/src/%{__pip_package}/%{__configdir}/settings/settings.py %{buildroot}%{__django_root}/%{name}/current_settings/settings.py
rm -f %{__django_root}/%{name}/current_settings/settings.py
ln -sf %{__django_root}/%{name}/current_settings/settings.py %{buildroot}%{__django_root}/%{name}/ve/src/%{__pip_package}/directory/settings/settings.py

#fix the wrong paths in easy_install.pth
perl -p -i -e "s#$RPM_BUILD_ROOT##g" %{buildroot}%{__django_root}/%{name}/ve/lib/%{__python_ver}/site-packages/easy-install.pth
#fix the wrong paths in activate
perl -p -i -e "s#$RPM_BUILD_ROOT##g" %{buildroot}%{__django_root}/%{name}/ve/bin/activate*

# The Linux build hosts we use have recently become persnickety about references to the build root in deployed files.
# egg-links and *.so files in our site-packages folder have this problem:
# THIS IS COMMENTED OUT BECAUSE IT CORRUPTS THE *.so FILES.
#find %{buildroot} -name "*.egg-link" -o -name "*.so" -o -name "*.txt" | xargs perl -p -i -e "s{\Q$RPM_BUILD_ROOT\E}{}g"

# The Linux build slaves we use are persnickety about rpaths in libraries pointing to directories that don't exist.
# So we use chrpath to purge them.
chrpath --delete %{buildroot}REDACTED/ve/lib/python2.6/site-packages/_ldap.so

# Un prelink everything
# http://www.alexhudson.com/2013/05/24/packaging-a-virtualenv-really-not-relocatable/
find %{buildroot}%{__django_root}/%{name}/ve -type f -perm /u+x,g+x -exec /usr/sbin/prelink -u {} \;
# re-point the lib64 symlink - not needed on newer virtualenv
if test -d %{buildroot}%{__django_root}/%{name}/ve/lib64; then
  rm %{buildroot}%{__django_root}/%{name}/ve/lib64
  ln -sf %{__django_root}/%{name}/ve/lib %{buildroot}%{__django_root}/%{name}/ve/lib64
fi

%clean
rm -rf $RPM_BUILD_ROOT

%preun
if [ $1 -eq 0 ]; then
    rm -rf %{__django_root}/%{name}/html
    rm -rf %{__django_root}/whoosh
fi

%files
%defattr(-,root,root,-)
# Prevent RPM from deleting our manually edited settings files during upgrade.
%config(noreplace) %attr(660,apache,apache) %{__django_root}/conf.d/%{name}_apache.conf
%config(noreplace) %attr(660,apache,apache) %{__django_root}/%{name}/current_settings/settings.py
%attr(775,apache,apache) %{__django_root}/%{name}/html/static
%{__django_root}/%{name}/ve
%{__django_root}/%{name}/current_settings

Comment: Fix the build process. Unfortunately you didn't say anything about it...
Comment: I'm still fairly new to this whole RPM thing. What kind of information should I add to help diagnose this problem?
Comment: I'd start with the spec file.
Comment: @MichaelHampton Alright, I added my specfile.
Answer:
While I can't give an authoritative answer on how exactly to fix your problem, as I too am new to this packaging thing, I do want to drop off a lead that helped me with such a problem of mine, for future readers.

During the build configuration phase, I thougt it best to use the tool's PREFIX to set the install directory to /path/to/buildroot/
This caused the exact issue with check-buildroot finding the path inside the built files.
What helped me was doing setup with PREFIX=/ instead, so that files passed the check, and then a DESTDIR=/path/to/buildroot make install, which had make drop the files in the appropriate location.
That's probably what you might want to look into. Build the project/library as if you were going to install it normally, and only perform the relocation to your rpm buildroot at a later phase, using whatever means your respective building/installing system provides.


Prove that metric space is complete

Question: I have metric space:
$$ X = <[0,+\infty), \rho>,  \rho(x,y) = |ln(1+x) - ln(1+y)|$$
I know it is complete, but I don't know how to prove it. How can I prove that fact?
Answer: If $\{x_k\}$ is Cauchy in the metric $\rho$, then $\{\ln(1 + x_k)\}$ is Cauchy in the standard metric. Thus there exists a real number $y$ with the property that $\ln(1 + x_k) \to y$. Show there exists $x \in [0,\infty)$ with $\ln (1+x) = y$ and $\rho(x_k,x) \to 0$.

Prove that metric space is complete


Error in my First JSF Program with Tomcat and Eclipse

Question: Im a Totally new in Java and JSF. I'm using eclipse Indigo and Tomcat 6.0.3 and JSF 2.0. Iam using the Maven and deploying the wars to server.
I configured the server in the Eclipse and i normally get the apache page in Localhost:8080.
But When i try to access my page like localhost:8080/ContactFormJSF/, I get the Message as
HTTP Status 404 - /ContactFormJSF/
type Status report
message /ContactFormJSF/
description The requested resource (/ContactFormJSF/) is not avilable.

This is code like, what there in Adduser.xhtml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <h:head>
        <title>JSF 2.0 Hello World</title>
    </h:head>
    <h:body>

JSF 2.0 Hello World Example - hello.xhtml

    </h:body>

I  Have even configured the "servlet-mapping","welcome-file-list" in the Web.xml
My web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee">
    <servlet>
        <servlet-name>Faces Servlet</servlet-name>
        <servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>Faces Servlet</servlet-name>
        <url-pattern>*.xhtml</url-pattern>
    </servlet-mapping>
    <welcome-file-list>
        <welcome-file>AddUser.xhtml</welcome-file>
    </welcome-file-list>
    <context-param>
        <param-name>javax.faces.PROJECT_STAGE</param-name>
        <param-value>Development</param-value>
    </context-param>

<session-config>
      <session-timeout>15</session-timeout>
    </session-config>
</web-app>

Comment: Iam not deplying the jars manually, Iam just deploying the Final War output in the Server. My pom.xml has lots of contents with Plugins, Repositories, Dependencies.
Comment: I have added my web.xml above and the Jars are there in lib folder and the url iam using is localhost:8080/ContactFormJSF/
Comment: Have a look : http://balusc.blogspot.ro/2011/01/jsf-20-tutorial-with-eclipse-and.html. This should help you.
Comment: @Khirthan..Your `web.xml` configuration seeem's to be correct. you are missing some part of `jar`. Ensure the reqired jar under `WEB-INF/lib`
Comment: @kark I have all the jars of jsf namely jsf-impl.jar, jsf-api.jar, jstl.jar, commons-beanutils-1.7.0.jar, commons-chain-1.1.jar,commons-collections.jar,commons-logging-1.0.4.jar,commons-digester-1.8.jar. should i add any other than this??
Comment: You said you are using Maven, why are you deploying jars manually? can you please post pom.xml code?
Answer: Check the following Conditions

Check the required jars inserted under WEB-INF/lib directory(Strongly recommended)
Check the servlet has been mapped in Web.xml
Check your invoking correct URL pattern in browser


I want to take a decision on two gaussian distributions, what approach can I take?

Question: I observe a one dimensional random source, which could be any of two Gaussian distributions with a different set of parameters that do not change over time. They have a the same variance and a slightly different median (plus or minus 5%).
I can ask for as many points of data as I want, however I want to be able to recognize the distribution as fast as possible (that is, with as little observations as possible). A simple threshold on one observation is not good enough, since both distributions overlap significantly.

This problem is probably very common, what is the name for it?
What is a standard approach to solve this?
Comment: I answered, but it occurs to me that I may have misinterpreted your question.  Clarification: is the situation that your point source is one *or the other* Gaussian, but not both, you know the means and variances already, and you want to know with respect to what Gaussian your point source is coming from?  This isn't what my brain heard the first time I read, possibly I read what I was expecting to hear.
Comment: Thanks for your quick reply ! Yes, the source is one or the other. I can't be both. The source doesn't change.
Comment: Ok then, I'll remove my answer for now, sorry about that. Quick follow up: It seems evident (though I haven't attempted to sketch a proof) that the best estimator would be to calculate the mean of your sample , determine which of the two known means is closest, and then choose the Gaussian associated with that closest mean (in the equal variance case).  What's probably interesting though, is to have some handle on how much data you need for this estimate to be "good".  Is this right?
Comment: Exactly :-) I want to have a way to calculate after how many points I can be certain of the nature of the source. Calculating the mean would be enough ?
What to do with it then, see when it crosses a threshold ?
Comment: I think this is most fruitfully cast as a Bayesian decision problem
Comment: Are you sure ? Because the source will always produce 100% of A, or 100% of B. Not sometimes A, sometimes B.
Comment: I think @Glen_b is correct.  If you had a prior belief that the points were coming from $A$ or $B$, you could use the probability calculation below along with bayes rule to update to a posterior belief.
Comment: Taiko I don't see why that's an issue; the Bayesian decision being made would yield one of the two (i.e. would pick the option that minimizes the loss for whatever loss function you use). Even if you skipped the decision-theory and just compute the posterior, it would be the posterior probability of "100% A", not "the proportion of A". You would then look at the relative sizes of the posterior probabilities (and if you wish, weigh those against the relative costs of the two wrong choices, taking you back toward a decision-theoretic framework).
Answer: Let's call the two Gaussians $G_0$ and $G_1$, their known means $\mu_0$ and $\mu_1$, and their common variance $\sigma^2$.  We may as well assume that $\mu_0 < \mu_1$ and that the data is coming from $G_0$, because the situation is totally symmetric.
Here's the decision precoedure:

Calculate the mean of the sample $\hat{\mu}$.
Calculate the distance from $\hat{\mu}$ to $\mu_0$ and $\mu_1$.
If the sample mean is closer to $\mu_0$, choose $G_0$, otherwise choose $G_1$.

To estimate how often we choose incorrectly, let's say we have $N$ data points.  Then the sampling distribution of $\mu_0$ is:
$$ \hat{\mu_0} \sim N \left( \mu_0, \frac{\sigma}{N} \right) $$
We make the wrong choice when:
$$ \hat{\mu_0} > \frac{1}{2} \left( \mu_0 + \mu_1 \right) $$
We can calculate the probability (taken with respect to the sampling distribution) of this event as:
$$ Pr \left( \hat{\mu_0} > \frac{1}{2} (\mu_0 + \mu_1) \right)
   = Pr \left( x \sim N \left( 0, \frac{\sigma}{N} \right) > \frac{1}{2} (\mu_1 - \mu_0) \right) $$
Everything in this final equation is known, so given a pre-specified error rate, you can back into how much data you need.
Comment: Say, in another setting, their variance is different as well. Is there a standard approach to differentiate them ?
Comment: That complicates things, but the basic framework should get you through.  1) the decision boundary is no longer $\frac{1}{2}(\mu_0 + \mu_1)$, but some other convex combination of the two means.  2) You can't rely on symmetry anymore, so you have to analyze both cases (truly coming from $G_0$ and truly coming from $G_1$) separately, and you'll need some apriori estimate of how likely it is that the true distribution is $G_0$ rather than $G_1$.  Give it a shot, if you're stuck tomorrow I'll try to help out.


Existe diferença entre Number e parseFloat?

Question: Quando preciso transformar uma string em número no Javascript, posso usar tanto o objeto Number como a função  parseFloat.
Exemplo:

var numero = "1.5";

console.log(Number(numero));
console.log(parseFloat(numero));

Porém eu gostaria de saber se existe algum caso onde uma outra têm comportamentos diferentes.

Quais das duas devo preferir para converter uma string em um Number do tipo float?
Existe alguma diferença entre ambas?
Comment: Relacionada: [Qual a diferença de parseInt() e Number()?](https://pt.stackoverflow.com/questions/180248/qual-a-diferen%c3%a7a-de-parseint-e-number)
Answer: Tem diferença em alguns casos.
Para string vazia ou contendo somente espaços, ou para null, Number retorna zero e parseFloat retorna NaN:

var numero = ""; // string vazia
console.log(Number(numero)); // 0
console.log(parseFloat(numero)); // NaN

numero = "    ";
console.log(Number(numero)); // 0
console.log(parseFloat(numero)); // NaN

numero = null;
console.log(Number(numero)); // 0
console.log(parseFloat(numero)); // NaN

Outra diferença é no algoritmo: parseFloat vai lendo os caracteres da string até encontrar algo que não seja reconhecido como parte de um número, como o sinal de menos e o ponto - que é o separador decimal - além do "e" seguido de números, que é parte da notação científica, e faz o parsing somente da parte que conseguiu ler. Number não faz isso, e retorna NaN se a string tiver caracteres que não estão entre esses já citados:

var numero = "123abc";
console.log(Number(numero)); // NaN
console.log(parseFloat(numero)); // 123

numero = "-123.45abc";
console.log(Number(numero)); // NaN
console.log(parseFloat(numero)); // -123.45

numero = "1.23e3abc"; // 1.23e3 é 1230 em notação científica
console.log(Number(numero)); // NaN
console.log(parseFloat(numero)); // 1230

Lembrando que ambos ignoram os espaços no início e fim da string (ou seja, espaços no início ou fim não caem na regra acima, de "caracteres inválidos"):

var numero = "   123   ";
console.log(Number(numero)); // 123
console.log(parseFloat(numero)); // 123
Answer: A diferença é sutil que pode ser notada na documentação parseFloat:

The parseFloat function parses an argument (converting it to a string first if needed) and returns a floating point number.

Em tradução direta:
A função parseFloat faz o parse do argumento (convertendo-o para string primeiro, se necessário) e retorna um número de ponto flutuante.
Já o construtor Number simplesmente tenta fazer a coerção do valor passado para o tipo numérico. Isso não significa necessariamente fazer o parse, já que a coerção de tipos tem comportamento diferente de um parse.
O parse, eventualmente, poderá remover alguns caracteres que seriam inválidos ao se fazer uma simples coerção. Ao analisar a diferença dos algoritmos descritos na especificação essa diferença torna-se ainda mais evidente:

Especificação para o construtor Number.
Especificação para parseFloat.

Note que, como Number faz a conversão de tipos, ele pode ser substituído pelo operador unário +, que tem a exata mesma função.
Vejamos alguns casos especiais (baseados nesta resposta do SOen) em exemplo:

Para qualquer entrada numérica válida, a saída será a mesma, já que esta pode ser parseada (por parseFloat) ou convertida (por Number) corretamente:
parseFloat('3'); // 3
Number('3'); // 3

parseFloat('1.501'); // 1.501
Number('1.501'); // 1.501

parseFloat('1e10'); // 10000000000
Number('1e10'); // 10000000000

Eventualmente, o valor passado para Number pode não ser corretamente convertido para o tipo numérico, mas ainda pode ser parseado corretamente. Um exemplo disso é quando a string contém caracteres adicionais:
parseFloat('1x'); // 1
Number('1x'); // NaN

Em relação aos literais numéricos da linguagem, parseFloat não consegue lidar strings que os representem, enquanto Number, sim. Isso significa que Number consegue converter da sintaxe literal de binário, octal e hexadecimal (assim como a decimal — já tratada anteriormente):
parseFloat('0b10'); // 0
Number('0b10'); // 2

parseFloat('0o10'); // 0
Number('0o10'); // 8

parseFloat('0xf'); // 0
Number('0xf');

NO exemplo acima, parseFloat retorna 0 pois lê a string da esquerda para a direita até deixar de encontrar caracteres numéricos válidos. Como b, o e x são inválidos, o restante da string é ignorada após tais demarcações.

Em relação aos valores literais da linguagem, Number faz a conversão normalmente, enquanto parseFloat sempre retornará NaN. Por exemplo, ao passarmos booleanos:
parseFloat(true); // NaN
Number(true); // 1

parseFloat(false); // NaN
Number(false); // 0

É por isso que se você passar uma string vazia para Number 0 será retornado.
Comment: Boa, tinha esquecido dos números em outras bases...
Comment: A ideia de fazer essa pergunta era ter uma resposta, justamente para ajudar naquela outra que respondemos [aqui](https://pt.stackoverflow.com/questions/479568/localizar-o-%c3%adndice-do-maior-e-do-menor-valor-de-um-array/479572?noredirect=1#comment898519_479572), kkkkkk. +1


In which game was a limited overs innings declared to prevent an opponent from qualifying?

Question: I recall reading about a limited overs tournament, in which if teams had equal points after the the league stage, the qualification for next round would be based on batting run rate only (or maybe, it was the aggregate runs scored, don't remember exactly).
In the last game of the league, team A needed to win and score about 260 runs. Team B won the toss, and captain had a clever idea. He chose to bat first and declared the innings on 1/0 (one run without loss). Of course, team A won easily, but they couldn't score the required 260-odd runs, and so team B's goal was met.
The writer also mentioned that this loophole abuse led to two changes in playing conditions:

Limited overs innings could not be declared any more.
Tournament-based competitions adopted the net run rate qualification (that is, the bowling run rate also came into the calculations).

I have tried hard to search for the details of this game, but I cannot seem to find it. I can only remember that it was an English domestic tournament. Could someone please help me identify this game?
Answer: I suspect the incident you're thinking of is one from the Benson & Hedges Cup in 1979, when Brian Rose, the captain of Somerset, declared his side's innings closed with one run on the board and no wickets down after one over in his team's final group match against Worcestershire. The situation was that the only way that Somerset could possibly not qualify for the quarter-finals would be if they lost and at the same time their bowling strike-rate (which was the tie-break used at the time) worsened, as well as Glamorgan winning their match. As Worcestershire scored the required two runs in ten balls, Somerset's bowling strike rate was not significantly worsened, so they qualified for the quarter finals.
Or... they would have qualified, except that the Test and Country Cricket Board, the controlling body for cricket in England at the time, expelled Somerset from the competition, with Glamorgan taking their place. Ironically, Glamorgan's final match the in group stage had been washed out, so Somerset would have qualified no matter what happened if they had just played the match.
Once you know the match, it's fairly easy to find additional commentary on the incident, for example the second half of the I do declare article at Cricinfo, which includes the amusing fact that even Somerset voted to expel themselves from the competition.


Task em await Task.WhenAll New transaction is not allowed because there are other threads running in the session

Question: Estou fazendo um programa Console, onde basicamente ele executa esses 4 procedimentos

Recupera um IEnumerable<_Url>
Faz um parsing nessas urls
Insere no Database
Marca essa _Url, como lida (processada) assim não processa mais

Porém estou recebendo um erro:

> New transaction is not allowed because there are other threads running in the session.

Meu program console está assim:
  private static void Main(string[] args)
    {
        IEnumerable<Urls> registros = db.UrlsTable.Where(w => w.Lido == false).Take(10);

        ExecutaTarefasAsync(registros).Wait();
    }

public static async Task ExecutaTarefasAsync(IEnumerable<Urls> registros)
        {
            var urlTasks = registros.Select((registro, index) =>
            {
                //parsing html
                var modelProduto = ExtraiDados.ParserHtml(registro.Url);
                db.Produto.Add(modelProduto);

                //save Database
                var downloadTask = db.SaveChangesAsync();

                //marca url como lida
                registro.Lido = true;
                db.Entry(registro).State = EntityState.Modified;
                db.SaveChangesAsync();

                return downloadTask;
            });

            await Task.WhenAll(urlTasks);
        }

Inicialmente estou fazendo com o EntityFramework porque seria a forma mais fácil e depois refatoraria para Dapper ou Ado.Net para máximo desempenho.
Não sei se posso fazer uma 2ª pergunta, mas caso eu faça com Ado.Net eu teria que criar uma função Parallel.ForEach para fazer os insert ?
Hoje o problema é que eu faço o download das fotos e essa etapa demora mais do que o parsing, por isso quero utilizar o async corretamente para maximizar o processo, até pq são milhares de registros todos os dias.
Comment: Começo a achar que o problema é um limite do Entity em tentar executar ele dentro do loop, vou tentar enquanto isso fazer uma solução em Ado.Net com Parallel.ForEach
Comment: Você está compartilhando a mesma sessão em mais de uma tarefa... para resolver o problema basta fazer com que o `ExecutaTarefasAsync` possua seu próprio `db`, o criando de tal forma que garanta que o método possua sua própria sessão conectada ao banco.
Answer: Você não pode fazer dois acessos async em um mesmo contexto ao mesmo tempo:
public static async Task ExecutaTarefasAsync(IEnumerable<Urls> registros)
        {
            var urlTasks = registros.Select((registro, index) =>
            {
                //parsing html
                var modelProduto = ExtraiDados.ParserHtml(registro.Url);
                db.Produto.Add(modelProduto);

                //save Database
                var downloadTask = db.SaveChangesAsync();

                //marca url como lida
                registro.Lido = true;
                db.Entry(registro).State = EntityState.Modified;
                db.SaveChangesAsync(); << ESSE VAI DAR ERRO

                return downloadTask;
            });

            await Task.WhenAll(urlTasks);
        }

Crie dois contextos diferentes ou espere um terminar para iniciar outro.
Comment: entendi, e como saberia qual task finalizou para poder executar o update? vou tentar colocar esse 2ª update normal pra ver
Comment: A segunda task do método nem começa, vai dar o mesmo erro com um savechanges normal. Tem que o primeiro `SaveChangesAsync()` terminar para fazer um segundo, mesmo não async
Comment: fiz um teste criando um classe com Dapper apenas para teste e dai funcionou....valeu...era esse problema 2 SaveChanges() não rola.


What is $\tilde{T}$ in Axler's Linear Algebra?

Question: On page 97 in section 3.E Axler gives definition 3.90: "Suppose $T \in L(V,W)$. Define $\tilde{T}: V/($null $T) \to W$ by $\tilde{T}(v+$null $T)=Tv$." Immediately preceding this was just some theorems about the dimensions of quotient spaces.
I don't quite understand what the purpose $\tilde{T}$ is, as it doesn't seem to be present in any of the exercises (at least not for 3.E), and it's not expanded upon afterward aside from presenting some statements about it's properties (e.g. $V/($null $T)$ is isomorphic to range $T$). I don't even understand what the map "represents". Isn't $v+$null $T$ a set? But $\tilde{T}$ doesn't equal another set, but rather a particular vector, $Tv$.
Does anyone have insight to this? Or a more common name for $\tilde{T}$? I haven't been able to find much on it anywhere.
Comment: How is $ \tilde{T} $ pronounced?
Comment: This is the map induced by $T$ on the quotient. Note that this map is one-to-one and has the same image as $T$. The construction may not show up much in the book, but it is a very common construction in abstract algebra in general. No, $v+\mathrm{null}(T)$ is not a vector space, it is an element of the quotient vector spaced $V/\mathrm{null}(T)$ (whose elements are equivalence classes of vectors in $V$. No, $\tilde{T}$ is not a particular vector: it is a linear transformation whose value at the element $v+\mathrm{null}(T)$ of $V/\mathrm{null}(T)$ is $T(v)$.
Comment: $v+{\rm null}T$ is not a vector space (unless $v$ is in null$T$) as, for one thing, it doesn't contain the zero vector.
Comment: My mistake, I meant set, not space; my question has been edited to reflect that. I was getting confused as $v+$null $T$ is a vector here, while it is a set of vectors too.
Comment: Yes, $v+\operatorname{null}T$ is a set, but so are elements of the quotient space. They are cosets of $\operatorname{null}T$, in fact.
Answer: $\tilde{T}$ is a very common construction... in abstract algebra. Not so much in linear algebra per se, but it fits into the general framework. No doubt this is why Axler introduces it, but does not do much with it.
Specifically: as you probably know already, given a vector space $V$ and a subspace $X$ of $V$, you can define the equivalence relation "congruent modulo $X$", by
$$\mathbf{v}_1\sim \mathbf{v}_2 \iff \mathbf{v}_1-\mathbf{v}_2 \in X.$$
This equivalence relation partitions $V$ into equivalence classes, and it is a good exercise to verify that the equivalence class of $\mathbf{v}\in V$ modulo $X$ is given by
$$[\mathbf{v}] = \{ \mathbf{v}+\mathbf{x}\mid \mathbf{x}\in X\}$$
and this set is denoted $\mathbf{v}+X$.
The set of equivalence classes is denote $V/X$, and it turns out that this set can be given a natural structure of a vector space (with vector addition $+_X$ and scalar multiplication $\cdot_X$), induced by the vector space structure of $V$, by defining
$$\begin{align*}
 (\mathbf{v}_1+X) +_X (\mathbf{v}_2 + X) &= (\mathbf{v}_1+\mathbf{v}_2) + X\\
\alpha\cdot_X(\mathbf{v}+X) &= (\alpha\mathbf{v}) + X.
\end{align*}$$
Now, given a linear transformation $T\colon V\to W$, we can associate to this linear transformation two natural subspaces: one of $V$ and one of $W$. The subspace of $V$ is $\mathrm{null}(T)$; the subspace of $W$ is $\mathrm{Im}(T)$. These are connected via the following important theorem, which is the vector space special case of what is often called the First Isomorphism Theorem of algebras (in the sense of universal algebra):

Theorem. Let $V$ and $W$ be vector spaces, and let $T\colon V\to W$ be a linear transformation. Then $V/\mathrm{null}(T)$ is isomorphic to $\mathrm{Im}(T)$. In fact, the linear transformation $\tilde{T}\colon V/\mathrm{null}(T)\to W$ defined by
$$\tilde{T}(\mathbf{v}+\mathrm{null}(T)) = T(v)$$
is one-to-one, with image $\mathrm{Im}(T)$, and so $\tilde{T}$ induces the isomorphism.

That is $\tilde{T}$ is a function; it's defined on the quotient $V/\mathrm{null}(T)$. Turns out, it's a one-to-one linear transformation induced (closely connected to) $T$.
There are lots of pieces to verify in this theorem:

You must verify that $\tilde{T}$ is well-defined. Note that it is defined in terms of the "name"/representative of the elements of $V/\mathrm{null}(T)$; but each element there has many "names". So you would have to verify that if $\mathbf{v}_1+\mathrm{null}(T) = \mathbf{v}_2+\mathrm{null}(T)$  (if they are the same element of $V/\mathrm{null}(T)$), then $\tilde(T)(\mathbf{v}_1+\mathrm{null}(T)) = T(\mathbf{v}_1)$ is in fact equal to $\tilde(T)(\mathbf{v}_2 + \mathrm{null}(T)) = T(\mathbf{v}_2)$.

You must verify that $\tilde{T}$ is a linear transformation.

You must verify that $\tilde{T}$ is one-to-one.

You must verify that $\mathrm{Im}(T) = \mathrm{Im}(\tilde{T})$.

As I mention above, $\tilde{T}$ is a special case of a general construction. In a way, it represents the "essence" of $T$: because the value of $T$ on any given vector $\mathbf{v}\in V$ depends only on its equivalence class modulo $\mathrm{null}(T)$.
For example: if you have a linear transformation $T\colon\mathbb{R}^2\to\mathbb{R}^2$ given by $T(a,b) = (a,a)$, then $\mathrm{null}(T)=\{(0,b)\mid b\in\mathbb{R}\}$.  We then have that $(a,b)\sim (c,d)\iff a=c$. And so we see that the equivalence class of $(a,b)\in \mathbb{R}^2$ depends only on the first coordinate... which is also the only thing that the value of $T$ depends on. In this example, the function $\tilde{T}\colon \mathbb{R}^2/\mathrm{null}(T)\to\mathbb{R}^2$ is defined by
$$ \tilde{T}\Bigl( (a,b)+\mathrm{null}(T)\Bigr) = T(a,b) = (a,a).$$
In linear algebra this theorem is not very powerful, because we have a very easy way to check isomorphism: look at the dimension. Since we know that $\dim(X) + \dim(V/X) = \dim(V)$, and we know that $\dim(V) = \mathrm{nullity}(T)+\mathrm{rank}(T)$, this automatically tells us that $\mathrm{rank}(T)=\dim(V/X)$, and so $\mathrm{rank}(\tilde(T)) = \mathrm{rank}(T)$ if and only if $\mathrm{nullity}(\tilde(T)) = 0$.
In group theory, ring theory, and other areas of abstract algebra, this is a very useful theorem (hence its name as the First Isomorphism Theorem).
In summary: not much use right now for you, but a special case of something that will be very useful later on. Axler is introducing you to it now so that you have an example to think about when you encounter it later in your studies of abstract algebra.
Comment: @ryanwebjackson: it's a relation symbol: it indicates $v_1$ is related to $v_2$. As the text says, it means "$v_1$ is congruent to $v_2$ modulo $X$".
Comment: I see! This makes a lot of sense tying it in with Hammack's Book of Proof, which has a section about equivalence classes and the modulo relation. He mentioned there it is useful in abstract algebra, and combined with this it gives me a better idea of what he meant.
Comment: What does the tilde in 1∼2 indicate?
Comment: Is "modulo X" an example of a required specifier for this relation? Why can we not say that the two vectors are equal?
Comment: @ryanwebjackson Are you reading the post at all? Yes, $X$ is absolutely necessary ,since the very definition of the equivalence relation involves $X$. No, it's not that the two vectors are equal, it's that they are **equivalent** under the defined relation. Of course, you can say the vectors are equal... you'll just be wrong most of the time when you say that.
Comment: Yes, and I didn't understand. That's why I'm asking for clarification. The notation was new to me.


Estimating same model over multiple time series

Question: I have a novice background in time series (some ARIMA estimation/forecasting) and am facing a problem I don't fully understand.  Any help would be greatly appreciated.
I am analyzing multiple time series, all over the same time interval and all of the same frequency, all describing a similar type of data. Each series is just one variable, there are no other corresponding predictors that I'm looking at.
I have been asked to estimate a single model that describes ALL the series - for example, imagine I could find one ARIMA (p,d,q) with the same orders, coefficients, etc. that could fit all the series.  My supervisor does not want me to separately estimate each series, nor does he want me to do some sort of VAR model with dependencies between the series.
My question is:  what would I even call such a model, and how might I go about estimating / forecasting it?  If it's easier for you to use code examples, I speak both SAS and R.
Comment: The standard approach is [vector autoregression](https://en.wikipedia.org/wiki/Vector_autoregression) and there is an R package called [var](http://cran.r-project.org/web/packages/vars/).
Comment: I'm trying to do the same thing. Apparently, there is something called a 'Multivariate AutoRegressive' model out there. I've found reference to it, but not how to use it. Based on the linked paper, I presume it has been implemented in R. http://journal.r-project.org/archive/2012-1/RJournal_2012-1_Holmes~et~al.pdf
Comment: Is a vector autoregession different than autoregression on panel data? Or is it a matter of different fields, different names? The plm package was suggested for panel data. http://cran.r-project.org/web/packages/plm/vignettes/plm.pdf

http://clidyn.ethz.ch/papers/arfit.pdf
Answer: One way to do that is to construct a long time series with all of your data, and with sequences of missing values between the series to separate them. For example, in R, if you have three series (x, y and z) each of length 100 and frequency 12, you can join them as follows
combined <- ts(c(x,rep(NA,56),y,rep(NA,56),z,rep(NA,56)),frequency=12)

Notice that the number of missing values is chosen to ensure the seasonal period is retained. I've padded out the final year with 8 missing values and then added four missing years (48 values) before the next series. That should be enough to ensure any serial correlations wash out between series.
Then you can use auto.arima() to find the best model:
library(forecast)
fit <- auto.arima(combined)

Finally, you can apply the combined model to each series separately in order to obtain forecasts:
fit.x <- Arima(x,model=fit)
fit.y <- Arima(y,model=fit)
fit.z <- Arima(z,model=fit)

Comment: +1, neat trick. Judging by the OP's comment to another answer, I was going to suggest some sort of panel data model, but this is way better.
Comment: To add to this trick - you could add external regressors (xreg) indicating category membership. This would account for separate means for the different series, while still keeping other coefficients in common.
Comment: If there is seasonality in the data (as there often is with monthly observations), you want the long series to still have the Januaries a multiple of 12 apart, the Februaries a multiple of 12 apart, and so on. Then, when the model is being chosen, the seasonality can be modelled appropriately.
Comment: This is a huge help, much appreciated.  Can you explain more re:  **the number of missing values is chosen to ensure the seasonal period is retained**?  Sorry I didn't fully follow - thanks.
Answer: You could do a grid search: start with ARIMA(1,0,0) and try all the possibilities up to ARIMA(5,2,5) or something.  Fit the model to each series, and estimate a scale-independent error measurement like MAPE or MASE (MASE would probably be better).  Choose the ARIMA model with the lowest average MASE across all your models.
You could improve this procedure by cross-validating your error measurement for each series, and also by comparing your results to a naive forecast.
It might be a good idea to ask why you're looking for a single model to describe all of the series.  Unless they're generated by the same process, this doesn't seem like a good idea.
Comment: Thank you - I will try this.  I agree that this doesn't seem like the best idea.  The argument I got was that each series does not have enough observations (~28) for a good estimation and that it would be more robust to estimate over all the series.  I'm not sure I agree with that argument.
Answer: Estimating single model for multiple time series is the realm of panel data econometrics.  However in your case with no explanatory variable @Rob Hyndman answer is probably the best fit. However if it turns out that the means of time series are different (test it, since in this case @Rob Hyndman's method should fail!), but ARMA structure is the same, then you will have to use Arellano-Bond type estimator. The model in that case would be:
$$y_{it}=\alpha_i+\rho_1 y_{i,t-1}+...+\rho_p y_{i,t-p}+\varepsilon_{it}$$
where $i$ indicates different time series and $\varepsilon_{it}$ can have the same covariance structure across all $i$.
Comment: @sparc_spread, suppose it's just two series.  One is centered at about 0 with variance 1 and the other is centered at 1000 with variance 1.  Then If both series are fit using the same coefficients, that means we're constraining alpha_1 = alpha_2, so the predictions for both series would be around 500, horribly off.  Basically, treating all series as belonging to the same model may require some recentering/normalization prior to fitting the joint model.
Comment: Really appreciate your solution and the others as well.  You mention that:  **However if it turns out that the means of time series are different (test it, since in this case @Rob Hyndman's method should fail!)**  Can you explain more about why this is?  Thanks.
Answer: An alternative to Rob Hyndman's approach, to make a single data series, is to merge the data. This might be appropriate if your multiple time series represent noisy readings from a set of machines recording the same event. (If each time series is on a different scale you need to normalize the data first.)
NOTE: you still only end up with 28 readings, just less noise, so this may not be appropriate for your situation.
t1=xts(jitter(sin(1:28/10),amount=0.2),as.Date("2012-01-01")+1:28)
t2=xts(jitter(sin(1:28/10),amount=0.2),as.Date("2012-01-01")+1:28)
t3=(t1+t2)/2

Comment: Yes, averaging your data is only appropriate when each date series is supposed to represent the same data, and (you are happy to assume that) they only differ in that each has different noise.
Comment: This will only work if all the signals are similar in nature (e.g. periodic) are all in phase - in your example if two of the sine waves were 180 degrees out of phase they would completely cancel!
Answer: I would look at hidden Markov models and dynamic Bayesian networks. They model time series data. Also they are trained using multiple time series instances e.g. multiple blood pressure time series from various individuals .
You should find packages in Python and R to build those. You might have to define structure for these models.


Mocking a class passed as argument

Question: I have something like this:
class ThisClass:
    def my_method(self, param):
        # Do normal stuff
        pass

class OtherClass:
    def my_method(self, param):
        # Do crazy stuff
        pass

def useful_function(some_class, some_param):
    internal = some_class()
    result = internal.my_method(some_param)
    uses_result(result)

# The useful_function can be called with any of the classes
useful_function(ThisClass, 10)

What I want to do is to test if my_method was called inside useful_function. I tried to mock the class and its method, but it did not work:
# Inside the test class
def test_case(self):
    MockSomeClass = mock.Mock()
    MockSomeClass.my_method.return_value = 'Some useful answer'
    useful_function(MockSomeClass, 100)
    MockSomeClass.my_method.assert_called_once()

The error relies on the fact I use the result of my_method in uses_result, but the mocked method do not return 'Some useful answer' as expected. What am I doing wrong?
Answer: The mock has to account for the instantiation some_class() as well:
MockSomeClass.return_value.my_method.return_value = 'Some useful answer'

internal = some_class()
internal.my_method() # 'Some useful answer

Comment: It worked like a charm. Just to complete the answer, the assertion must be done like `MockSomeClass.return_value.my_method.assert_called_once()`. Thank you!

Mocking a class passed as argument


why the difference between these two output using %r is single quote and double quote in python

Question: binary = "binary"
do_not = "don't"
x = "There are %s types of people." % binary
y = "Those who know %s and those who %s." % (binary, do_not)

print "I also said: %r." % y
print "I also said: %r." % x

This is an exercise of Learn Python. I am trying understand '%r' here so I tried the above  two prints. The output are
I also asid: "Those who know binary and those who don't.".
I also said: 'There are binary types of people.'.

Now I am wondering why the difference between these two prints is double and single quotes?
Thanks for your help.
Answer: The %r format causes Python to print using the repr function.  So the following are equivalent:
"%r" % my_string  ≡  "%s" % repr(my_string)

So then the question becomes, why does repr sometimes use single quotes and sometimes uses double quotes?  Well, first of all, the goal of repr is to produce a representation of a Python object that is also valid Python source code (this is not mandatory requirement but for many Python types it's indeed valid).  For a string that contains an apostrophe in it, there are multiple ways to represent it:
"Don't"  ≡  'Don\'t'

repr decides to be "smart" and picks the one that is easier to read, namely using double quotes, as long as it doesn't already contain double quotes.  In all other cases, Python falls back to the default single quotes.  This is why you see different behavior for different strings.
More relevantly, don't rely on repr (or %r) to quote strings for human consumption, write your own function for that.  It's not meant to for that, it's mostly used as a convenient way of dumping a Python object when debugging.
AFAIK there's no documentation that clearly stipulates as to what you will get when you repr a string, except that eval(repr(my_string)) == my_string is expected to hold true.
Answer: Its because if don't that use a single quotes , if a string contain single quotes python automaticaly put it in double quotes ". else it put the string in a single quote .
>>> x
'There are binary types of people.'
>>> y
"Those who know binary and those who don't."

Note : you cant put string that contain single quote in single quote it raise a syntax error :
>>> 'Those who know binary and those who don't.'
  File "<stdin>", line 1
    'Those who know binary and those who don't.'
                                             ^
SyntaxError: invalid syntax

and %r converts any Python object using repr()(Return a string containing a printable representation of an object.)).

This is the same value yielded by conversions (reverse quotes). It is sometimes useful to be able to access this operation as an ordinary function. For many types, this function makes an attempt to return a string that would yield an object with the same value when passed to eval(), otherwise the representation is a string enclosed in angle brackets that contains the name of the type of the object together with additional information often including the name and address of the object. A class can control what this function returns for its instances by defining a __repr__() method.

>>> repr("example")
"'example'"
>>> repr("exampl'e")
'"exampl\'e"'

read more about String Formatting
Answer: So let me give you an example
print "Let's try this example"

The following example will print fine but if you use a single quote, it will exit after the ' of let's.
Here's another example
print 'He said "Hello!"'

If you use a double quotes here, then it will escape before the Hello!. Those are simple use cases. They come in handy if you're using things like output html tags that need single or double quotes.


Data not being saved on user_save

Question: I having a problem saving user data to the database. Everything is being saved apart from 'street_address', 'town_city', 'region' 'postal_code' and 'country'.
full module_create_user:
function openid_connect_create_user($sub, $userinfo, $client_name) {

  $address = $userinfo['address'];
  $decodeAddress = json_decode($address);

  $firstName = $userinfo['given_name'];
  $lastName = $userinfo['family_name'];

  $streetAddress2 = $decodeAddress->{"street_address"};
  $townCity2 = $decodeAddress->{"locality"};
  $region2 = $decodeAddress->{"region"};
  $postalCode2 = $decodeAddress->{"postal_code"};
  $country2 = $decodeAddress->{"country"};

  $streetAddress = (string)$streetAddress2;
  $townCity = (string)$townCity2;
  $region = (string)$region2;
  $postalCode = (string)$postalCode2;
  $country = (string)$country2;

  $edit = array(
    'name' => $firstName.$lastName.$sub, //works
    'pass' => user_password(), //works
    'mail' => $userinfo['email'], //works
    'init' => $userinfo['email'], //works
    'family_name' => $userinfo['family_name'], //works
    'given_name' => $userinfo['given_name'], //works
    'nickname' => $userinfo['nickname'], //works
    'gender' => $userinfo['gender'], //works
    'birthdate' => $userinfo['birthdate'], //works
    'phone_number' => $userinfo['phone_number'], //works
    'street_address' => $streetAddress, //doesn't work
    'town_city' => $townCity, //doesn't work
    'region' => $region, //doesn't work
    'postal_code' => $postalCode, //doesn't work
    'country' => $country, //doesn't work
    'status' => 1, //works
    'openid_connect_client' => $client_name, //works
    'openid_connect_sub' => $sub, //works
  );

  return user_save(NULL, $edit);
}

different $edit i've tried:
$edit = array(
    'name' => $firstName.$lastName.$sub, //works
    'pass' => user_password(), //works
    'mail' => $userinfo['email'], //works
    'init' => $userinfo['email'], //works
    'family_name' => $userinfo['family_name'], //works
    'given_name' => $userinfo['given_name'], //works
    'nickname' => $userinfo['nickname'], //works
    'gender' => $userinfo['gender'], //works
    'birthdate' => $userinfo['birthdate'], //works
    'phone_number' => $userinfo['phone_number'], //works
    'field_street_address_pixelpin' => $streetAddress, //doesn't work
    'field_town_city_pixelpin' => $townCity, //doesn't work
    'field_region_pixelpin' => $region, //doesn't work
    'field_postal_code_pixelpin' => $postalCode, //doesn't work
    'field_country_pixelpin' => $country, //doesn't work
    'status' => 1, //works
    'openid_connect_client' => $client_name, //works
    'openid_connect_sub' => $sub, //works
  );

examples of the fields which are being programmability created:
Family name (works):
if (!field_info_field('field_family_name_pixelpin')) {
    $field = array(
        'field_name' => 'field_family_name_pixelpin',
        'type' => 'text',
    );
    field_create_field($field);

    $instance = array(
        'field_name' => 'field_family_name_pixelpin',
        'entity_type' => 'user',
        'label' => 'Family Name',
        'bundle' => 'user',
        // If you don't set the "required" property then the field wont be required by default.
        'required' => FALSE,
        'settings' => array(
           // Here you inform either or not you want this field showing up on the registration form.
            'user_register_form' => 1,
        ),
        'widget' => array(
            'type' => 'textfield',
        ),
        'display' => array(
          'default' => array('label' => 'above'),
      ),
    );
    field_create_instance($instance);
  }

postal code (doesn't work):
if(!field_info_field('field_postal_code_pixelpin')) {
    $field = array(
        'field_name' => 'field_postal_code_pixelpin',
        'type' => 'text',
    );
    field_create_field($field);
    $instance = array(
        'field_name' => 'field_postal_code_pixelpin',
        'entity_type' => 'user',
        'label' => 'Postal Code',
        'bundle' => 'user',
        // If you don't set the "required" property then the field wont be required by default.
        'required' => FALSE,
        'settings' => array(
           // Here you inform either or not you want this field showing up on the registration form.
            'user_register_form' => 1,
        ),
        'widget' => array(
            'type' => 'textfield',
        ),
        'display' => array(
          'default' => array('label' => 'above'),
      ),
    );
    field_create_instance($instance);
  }

Answer: In general, for custom user fields, user_save requires the field values to be provided as an array. An example would be the following:
 $edit['field_yourfield'] = array(
   LANGUAGE_NONE => array(
     0 => array('value' => $yourValue),
   ),
 );

Comment: I'll give it a try
Comment: It works, well done.

Data not being saved on user_save


Union of one-dimensional family of straight lines has zero measure

Question: Let $\gamma:[0,1]\to \mathbb S^2$ be a smooth curve. Consider the following set
$$
\bigcup_{t\in [0,1]}\mathrm{span}(\gamma(t))\subset \mathbb R^3
$$
My question is: does this set have Hausdorff dimension at most $2$, and as a result it has zero 3-dimensional Lebesgue measure?. Note that if the smoothness condition is removed then the answer is trivially false.
Comment: There is  a big mis-match between the title and the question.
Comment: I added a sentence.
Answer: It seems that the answer is pretty easy......
The set
$$
\bigcup_{t\in [0,1]}\mathrm{span}(\gamma(t))
$$
is just the graph of the smooth mapping $\Gamma(x,t):=x\gamma(t)$ over $\mathbb R\times [0,1]$. Therefore its Hausdorff dimension is exactly 2.


How to better plot and compare overlapping histograms?

Question: I want to compare the distribution of 3 different time spans:

So I plot the histograms together, along with the model curve.
But I'm afraid that overlapping histograms makes each hard to see. The histogram are also set to half-transparent so the overlapping could be seen. But it also makes the color overlap, making it hard to discern one from another.
An additional problem is that, I also want to compare the bootstrapped result of the histogram, so I re-sample and plot for a lot of times:

I believe this is also very hard to see.
I'm wondering, what would be a good way for plotting this comparison? What can I do to make the plot more discernible?
Comment: I think you want [this](http://docs.flowjo.com/vx/graphical-reports/graph-options-and-annotation/le-overlays/), but you get [this](http://stackoverflow.com/questions/3541713/how-to-plot-two-histograms-together-in-r).
Comment: @AntoniParellada, 3d plot may be a way, and I've seen this kind plot before. But in my case, I don't care about the addtional axis and the comparision along that axis, so I didn't use it.
Comment: OK Nice question in any case.
Answer: The usua alternatives to display "overlapping" histograms are to:

place the bar side by side (but I don't think that it is working well visually in most of the situations):

connect the heights of the bars with a line (and drop the bar itself - there exists alternatives where the outline of the histogram is plotted, like a skyline):

I am adding R code used to make the figures:
dataf <- bind_rows(lapply(1:10,
                          function(x) {
                              data.frame(grp=x,
                                         value=rnorm(100,
                                                     mean=runif(1)))
                          }))

ggplot(dataf) +
  geom_histogram(aes(x=value, fill=factor(grp)),
                 position="dodge", binwidth=.5)

ggplot(dataf) +
  geom_freqpoly(aes(x=value, color=factor(grp)), binwidth=.5)

Comment: One could take the second plot a step farther and do a density plot instead of using the heights of the histogram bars, which depend heavily on the choices of cutoffs. I often find a density plot, which is essentially a smoothed histogram, to be more informative about the underlying data distributions. For histograms you're making an arbitrary choice about the cutoff values for the bars,for density plots an arbitrary choice about the kernel for smoothing. Don't really see a good reason to prefer histograms.
Comment: @EdM : I think that the question author already has density estimates. Beside that histograms may have their merit when low number of values or when the binning has physical meaning.
Answer: Plotting histograms together can be fine, but it breaks down when you have more than two histograms, or the more they overlap, both of which apply in your case.  I would suggest you start by making a plot matrix (so long as you don't have so many groups the plots become unusable).
Likewise, plots with too many, and too different, objects can become difficult to interpret.  You want to compare histograms, and you want to compare kernel density plots.  Note that a plot matrix has a main diagonal for each group, and then the upper and lower triangles are symmetrical.  For a given plot in the upper triangle that compares two groups, there is a corresponding plot in the lower triangle that compares the same two groups.  Thus, I would suggest you compare histograms in the upper triangle plots, and kernel density plots in the lower triangle plots.
Because it might still be difficult to compare two overlapping histograms in the subplots, I would suggest you make back to back histograms instead of overlapping histograms.
Putting these suggestions together, you could get something like this:

This was coded using R.  The double histogram code was adapted from here.  I suspect the code won't be interpretable to people who aren't already very familiar with R, but for those who do want to see it, it is displayed below:
data(mtcars)
d  = mtcars[,c("qsec","cyl")]
ud = unstack(d)
ud = data.frame(four  = c(ud[[1]], rep(NA,3)),
                six   = c(ud[[2]], rep(NA,7)),
                eight =   ud[[3]]             )

upper = function(x, y){
  usr = par("usr"); on.exit(par(usr)); par(usr = c(0, 1, 0, 1), new=TRUE)
  hx        = hist(x, plot=FALSE)
  hy        = hist(y, plot=FALSE)
  lim       = ifelse(max(hy$counts)>max(hx$counts), max(hy$counts), max(hx$counts))
  hy$counts = - hy$counts
  plot(hy, ylim=c(-lim, lim), col="red", xlim=c(14,23), axes=FALSE, main="")
  lines(hx, col="blue")
  abline(h=0)
}
diag.hist = function(x, ...){
  usr = par("usr"); on.exit(par(usr)); par(usr=c(usr[1:2], 0, 1.5), new=TRUE)
  hist(x, freq=FALSE, xlim=c(14,23), ylim=c(0,.8), main="", axes=FALSE)
  lines(density(na.omit(x)))
}
lower = function(x, y){
  usr = par("usr"); on.exit(par(usr)); par(usr = c(0, 1, 0, 1), new=TRUE)
  plot( density(na.omit(x)), xlim=c(14,23),ylim=c(0,.5),main="",axes=FALSE, col="blue")
  lines(density(na.omit(y)), col="red")
}

windows()
  pairs(ud, upper.panel=upper, diag.panel=diag.hist, lower.panel=lower)

Comment: This would be fine if you want to compare the histogram one by one. But in my case, I only want to know the variability in this the 3 overlapping histograms (year 2000, 2005, 2010). So for me, overlapping them would be just enough.


Why Manage_fields and Manage_display tab are not shown in content type?

Question: Suddenly My dev site is not showing

Manage_fields and Manage_displays

in all content types. I am using contributed module admin_menu. I clear all cache but it happens same. This is multilingual site. I can't understand why it occurs? Can anyone solve this problem? I have enabled field_ui modules.
Answer: There is unchecked permission of field. After checked it shows the tabs. Make sure two things to solve this problem.
1. Enable Field UI (field_ui) module
2. Make sure the field in permission is checked

admin > people > permissions


dynamically allocate the id in the URI in the ng-resource

Question: I have a webpage created on the angularjs in which I have used the ng-resource and the ui-router module.
In this app The main requirement I want is that  in the navigation bar, I have created the ng-repeat="". which fetches the username from the database.
Now the navigation bar will be created
along with the ui-sref="{{username}}" and then now I have shown the app.js
this App.js is for the view which is going to be loaded and it will require the {{username}} as it id
so  here username is needed to dyanamically allocated for the  each get request

var app = angular.module('trendy', ['ngResource']);

app.controller('trendyWho',[ 'UserFactory', function ( UserFactory) {

  var self=this;

    UserFactory.get({}, function (userFactory){
       self.userdata = userFactory.user;

    });

}]);

app.factory('UserFactory', function ($resource) {

    return $resource('Trending/js/{{id:username}}', {}, {
        query: {
            method: 'GET',
            params: {},
            isArray: true
        }

    })

});

<!DOCTYPE html>

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">

  AngularUI Router

{{username}}

Answer: You are using ui-sref so I assume you are using ui-router?
The argument in ui-sref is different from the normal href, you pass in the state name instead of the URL itself.
For example your state is
.state('main.user', {
    url: "/user/{userId:[0-9]{1,}",
    template: ...,
    controller: ...
})

Then your sref will be
ui-sref="main.user({userId: username})"
Comment: creating dyanamic sref is correct but how to create the URI for the get of the different view going to opened
Comment: since I have to fetch the different data according to the different views loaded according to the username
Comment: the main problem is how to fetch the URI
Comment: If somehow we can alter the id of the URi according to the {{username}}
Comment: Do you mean the URI in `$resource`? You get username in that by using `$stateParams.userId`
Comment: can u link me with any good documentation apart for the github one or any fiddle for my clarity because being a newbie in angularjs and lack of correct resources i m not getting how to use the $stateParams
Comment: help is appreciated otherwise one way or other your first comment is still illuminating
Comment: $stateParams comes with ui-router, it stores the variable part in your state. You can console.log it to see what is inside.
Comment: So do I had to define my Uri like this "nest/account/$stateparams
Comment: `$stateParams.something`. Can you show your state configuration in case something is different there?
Comment: var app = angular.module('trendy', ['ngResource']);

app.controller('trendyWho'[ 'UserFactory', function ( UserFactory) {

  var self=this;

    UserFactory.get({}, function (userFactory){
       self.userdata = userFactory.user;

    });

}]);

app.factory('UserFactory', $stateparams, function ($resource,$stateparams) {

    return $resource('Trending/js/:Id',{Id: "$stateparams.id" } ,{}, {
        query: {
            method: 'GET',
            params: {},
            isArray: true
        }

    })

});   so can I inject the $stateparams in  fac. ike this
Comment: app.config(function config ($stateProvider, $urlRouterProvider){

$urlRouterProvider
        // The `when` method says if the url is ever the 1st param, then redirect to the 2nd param
        // Here we are just setting up some convenience urls.
        .when('/c?id', '/contacts/:id')
        .when('/user/:id', '/contacts/:id')

        // If the url is ever invalid, e.g. '/asdf', then redirect to '/' aka the home state
        .otherwise('/Settings/ResetPass');

$stateProvider.state("index",{

url:"/",
controller : "myCtrl as first",
templateUrl: "Feed/feed.html"
});
Comment: I'm not sure if you are suppose to use both normal routing (`.when`) and state routing (`.state`) together. Either way you'll need to get the username from the URL. The process goes: user select 1 user -> user id get passed in URL -> get user id from $stateParam or URL path -> load corresponding data.


Android handling clicks on parentView

Question: Click events handling does not work.
Click handling works with CheckBox and TextView, but doest not work with frameLayout.
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout  xmlns:android="http://schemas.android.com/apk/res/android"
          android:layout_width="match_parent"
          android:layout_height="56dp"
          android:background="@drawable/yellow_ripple"
          android:clickable="true"
         >
<TextView
        android:clickable="false"
        android:id="@+id/text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_vertical"/>

<CheckBox
        android:clickable="false"
        android:id="@+id/box"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_vertical|right"
        />

In create view:
 View resultView = LayoutInflater.from(context)
            .inflate(R.layout.filter_signle_view, parent, true);

    selectedBox = (CheckBox) resultView.findViewById(R.id.box);
    title = (TextView) resultView.findViewById(R.id.text);

    title.setText(m_filter.getTitle());

    selectedBox.setChecked(m_state.isSelected());

    selectedBox.setOnCheckedChangeListener((compoundButton, b) ->
                    m_state.setSelected(b)
    );

    resultView.setClickable(true);

    resultView.setOnClickListener(
    view -> m_state.setSelected(!m_state.isSelected())
    );
    );

    return resultView;

I want to handle clicks on FrameLayout. It is not happening.
(I use retrolamda)
Comment: android:focusable="false" on the views where you want the click to be passed to parent view ? tried it ?
Comment: @divyenduz it did not help
Answer: You are assigning the listener to the parent of your frame layout.
Please change last parameter of your inflation from true to false. For more - LayoutInflater.inflate(int, ViewGroup, boolean)
View resultView = LayoutInflater.from(context).inflate(R.layout.filter_signle_view, parent, false);

Comment: side note: that's because `inflate` returns the parent if `attachToParent` is `true`
Answer: 1) Add listener to frame layout. You are missing it and its the most important thing here.
2) Add
android:descendantFocusability="blocksDescendants"

to frame layout in xml. This will prevent child items clicks.
Answer: Ok, so after fixing numerous compile errors and other Lint issues, I did run your code (slightly modified). And it worked fine, here's what I have.
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="56dp"
    android:background="?attr/selectableItemBackground"
    android:clickable="true">

    <TextView
        android:id="@+id/text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_vertical"
        android:clickable="false" />

    <CheckBox
        android:id="@+id/box"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_vertical|end"
        android:clickable="false" />

</FrameLayout>

And the Java part...
@Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View resultView = LayoutInflater.from(getActivity()).inflate(R.layout.generator_personalization, container, false);

        CheckBox selectedBox = (CheckBox) resultView.findViewById(R.id.box);
        TextView title = (TextView) resultView.findViewById(R.id.text);

        title.setText("Title!");

        selectedBox.setChecked(true);

        selectedBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                Toast.makeText(getActivity(), "Changed!", Toast.LENGTH_SHORT).show();
            }
        });

        resultView.setClickable(true);
        resultView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(getActivity(), "CLICKED!", Toast.LENGTH_SHORT).show();
            }
        });

        return resultView;
    }

So basically, what I think is the biggest problem here is attaching the view to the parent in your inflate statement. Try changing that last parameter to false.
You should also note that setting click listeners from code also sets the clickable attribute when enabled.
Hope this helps!
P.S. Consider changing that layout to something more maintainable - like using a single CheckBox instead of FrameLayout + TextView + CheckBox without text.
Answer: When you infilating a layout, you supply this parameters to the inflator service:
public View inflate(int resource, ViewGroup root, boolean attachToRoot)

If you set attachToRoot true then the returned view is the root view that you suppilied.
In your example you set it to true and it is returning the "parent" view.
You then set a click listener to a parent viewgroup, however, the click event will be consumed on the child FrameLayout because you set the clickable to true. In your case this will do nothing because you set the click listener to the wrong view, and another view consumed the click event.
So you should set the attachToRoot to false, and the returned view will be your FrameLayout, and that will fix your problems.

Android handling clicks on parentView


Find a ring that contain $\mathbb{Q}$ as a group and has solution for $x^2 \equiv 2$ but no solution to $x^2 \equiv 3$

Question: I have the following question :
Find a ring that contain $\mathbb{Q}$ as a group and has solution for $x^2 \equiv 2$ but no solution to $x^2 \equiv 3$
Hint : Start from $\mathbb{Q}[x]$
I really don't know how to approach this, how to force that $x^2 \equiv 3$ has not solution???
This is what I did - I don't know if its right
Maybe if I choose $I=x^2-2$? I think its an ideal since no root since there is no such $x\in \mathbb {Q}$ such that $x^2-2=0$,
Yet how that implies solution for $x^2 \equiv 2$? what about no solutions for $x^2 \equiv 3$?
Any help will be appreciated.
Answer: Your attempt is indeed fruitful. If you define $R=\Bbb Q[x]/I$, where $I=(x^2-2)$, then $$(x+I)^2 = x^2+I = (x^2+I) - (x^2-2+I) =2+I$$ so you have solution to $x^2=2$. Note that $\Bbb Q$ is embedded in $R$ via $q\mapsto q + I$ and that this is "sort of cheating". We literally defined $R$ so it will have this root.
To show that there are no solutions to $x^2=3$, first note that every element of $R$ can be uniquely written as $ax + b+I$, $a,b\in\Bbb Q$. Existence follows from Euclidean division: if you have $f(x)+I\in R$, then $f(x) = q(x)(x^2-2) + r(x)$, with $\deg r \leq 1$ and $f(x)+I = r(x)+I$. Uniqueness follows from degree argument:
$$ax + b + I = a'x + b' + I \iff (a-a')x+(b-b')\in I$$
but there are no polynomials of degree $0$ or $1$ in $I$, thus $(a-a')x+(b-b)$ is zero polynomial.
Now,
$$(ax+b+I)^2 = a^2x^2+2abx+b^2 + I = 2abx+b^2+2a^2 + I$$
and you can easily check that system
\begin{align}
2ab &= 0\\
2a^2+b^2 &= 3
\end{align}
has no rational solutions.
Alternatively, you can prove that $R\cong \Bbb Q[\sqrt 2] = \{a+b\sqrt 2\mid a,b\in\Bbb Q\}$, which contains $\sqrt 2$, but does not contain $\sqrt 3$.
Comment: @JaVaPG, please see my edit.
Comment: Thank you for you'r answer two question if I may, Can you explain why $(x+I)^2 = x^2+I = 2+I \implies x^2 \equiv 2$? and as well why is element of $R$ can be uniquely written as $ax+b+I$, Did you use the first homomorphism theorem? How did you conclude this?
Answer: You have the right idea. The ideal $(x^2 - 2) \subseteq \mathbb{Q}[x]$ is maximal and so $R = \frac{\mathbb{Q}[x]}{(x^2-2)}$ is a field.
Note that $R \cong \{ a + b \sqrt{2} \ | \ a,b \in \mathbb{Q} \}$ and $\mathbb{Q} \subseteq R$.
Suppose that $\sqrt{3} \in R$. Then there exist $a,b \in \mathbb{Q}$ such that
$$\sqrt{3} = a + b\sqrt{2}.$$
We now seek a contradiction.

Case 1: $a = 0$
I'll leave this to you.

Case 2: $b = 0$
I'll leave this to you.

Case 3: $a,b \neq 0$
If you square both sides of that equation and rearrange, you get:
$$ 3 - a^2 - 2b^2 = 2ab \sqrt{2}.$$
This implies that $$\sqrt{2} = \frac{3-a^2-2b^2}{2ab} \in \mathbb{Q}_.$$
So we arrive at a contradiction.

Thus $\sqrt{3} \notin R$. Obviously neither is $-\sqrt{3}$. So $x^2-3$ has no roots in $R$.


How do I convert from binary base to decimal?

Question: I have a homework problem and I don't understand it. Here is the problem:
The base two number 11111(base 2) has the same digit in all places. The same
number can be written in different bases. Find two other bases where the
number has the same digit in all it's places.
I get that 11111 base 2 = 31, but I don't really understand what the question is asking me or how to "solve" it.
Comment: Want to know why $11111_2=31,$if want to know then you have the solution below
Answer: $$11111_2=1\cdot 2^0+1\cdot 2^1+1\cdot 2^2+1\cdot 2^3+1\cdot 2^4=1\cdot 1+1\cdot 2+1\cdot 4+1\cdot 8+1\cdot 16$$
$$=1+2+4+8+16=31$$
Answer: A number of the form $aaa$ in base $b$ represents $ab^2+ab+a$, with the number of terms matching the number of digits.  You are being asked to find two pairs $a,b$ (with some number of digits) so that it can represent $31_{10}$
Comment: So if I understand, a valid answer might be 1011 in base 3? And I would need to find one more, correct?
Comment: You are correct that $1011_3=31_{10}$, but it doesn't meet the requirement that all the digits be the same.
Comment: Oh ok. Would 111 base 5 work? But I can't even think of what the next one might be.
Comment: Yes, $111_5$ is one of the solutions.  There aren't too many choices left for the number of digits.  Bases can be larger than $10$
Comment: Ok I figured it out. I got 11 base 30. Thank you very much.
Comment: That is correct.  Good work.
Answer: The number is $31$. If $dd\dots dd_b = 31_{10}$, then $d$ divides $31$.  Only possibilities are $d= 1$ and $d=31$.  So for all bases $b \gt 31$ you have a single digit which clearly passes the requirement.  Now check all $11\dots 11_b$ for different bases $b$ and you have the rest.
Comment: I don't think a single digit solution was intended, though technically all the digits are the same.  There are two multidigit solutions.
Answer: The number in decimal is 31.  I think we've established that.
It appears that you're being asked for two other bases in which 31 is written with all the same digits.
Any base 32 or larger will work.  In this case, decimal 31 will be a single digit.  I guess they're all the same if there's only one, right?
Base 30 will work:
$$11_{30}=1\cdot 30^1+1\cdot 30^0$$
Since 31 is odd, the next possibility would be $33$, but that won't work because 28 isn't divisible by 3.
$55$ and higher won't work because the number would need to be at least base 6, and $55_6$ exceeds 31.
Let's go to $111$ then.  Is there a value for $n$ such that $n^2 + n = 30$ ?  Why, yes there is:
$$111_{5}=1\cdot 5^2+1\cdot 5^1+1\cdot 5^0$$
So there are the two (non-trivial single-digit) solutions.
Comment: Because $31$ is prime, the digit must be $1$ or $31$
Comment: Good point. That would have made things easier. :)


please help me. Command PhaseScriptExecution failed with a nonzero exit code

Question: please help me
i found that error while move to another developer device ,
previously i used windows laptop and it was fine, but when i move to mac mini m1 this problem appears
    Command PhaseScriptExecution failed with a nonzero exit code

flutter doctor
Answer: Got same issue, I solved that by changing "Any iOS SDK" to "Any iOS Simulator SDK" from Xcode in Excluded Architectures section.
Xcode screenshot
Answer: Try switching to Flutter master channel and then check to see if it work or not, then switch back to Flutter stable channel.
Comment: still same error


LilyPond: parenthesized hairpin

Question: I found LilyPond code to place a hairpin between parenthesis like this:

You can see that the result overlaps with the bar line. The code that does it is some hard-core Scheme hackery. One obviously has to know Scheme and the guts LilyPond to write it. I don't know how to modify it to avoid overlapping. Can somebody help?
\version "2.22.1"
\language "italiano"

common = {
    \key sol \minor
    \time 4/4
    \tempo "Largo [Широко]"
}

hairpinBetweenText =
#(define-music-function (parser location leftText rightText) (markup? markup?)
    #{
        \once \override Hairpin.stencil =
        #(lambda (grob)
            (ly:stencil-combine-at-edge
                (ly:stencil-combine-at-edge
                    (ly:stencil-aligned-to (grob-interpret-markup grob leftText) Y CENTER)
                    X RIGHT
                    (ly:stencil-aligned-to (ly:hairpin::print grob) Y CENTER)
                0)
                X RIGHT
                (ly:stencil-aligned-to (grob-interpret-markup grob rightText) Y CENTER)
             0))
   #})

parenthesizedHairpin = \hairpinBetweenText \markup{\larger\larger "("} \markup{\larger\larger ")"}

right = \relative do'' {
    \key sol \minor
    re8 mib re do sib la sol sib |
    mib, re fa mib re4. la8 |
    re8 mib re sib' re, fad la re |
}

left = \relative do' {
    \key sol \minor
    sib,8 (sib')  <fad la re>4 sol,8 (re') <sol sib re>4 |
    do,,8 (sol') <mib' sol>4 re,8 (re') <fad la re>4~ |
    8 r8 r4 r2 |
}

dynamics = {
    s8 s8 s8 \parenthesizedHairpin s8 \> s8 s8 s8 s8 \! |
}

\score {
    \new PianoStaff <<
        \new Staff = "right" \right
        \new Dynamics \dynamics
        \new Staff = "left" { \clef bass \left }
    >>
}

Answer: Just adjust the hairpin's span as needed using shorten-pair.
dynamics = {
    s8 s8 s8 \parenthesizedHairpin s8\tweak shorten-pair #'(0 . 0.9)\> s8 s8 s8 s8 \! |
}

See the snippet "Moving the ends of hairpins" in the documentation at http://lilypond.org/doc/v2.23/Documentation/notation/expressive-marks-attached-to-notes.html#dynamics.
By the way, note that out-of-the-box support for parenthesizing spanners is currently being added (https://gitlab.com/lilypond/lilypond/-/merge_requests/839). It does not solve the collision, though (even with the pending change https://gitlab.com/lilypond/lilypond/-/merge_requests/842, and it is not a problem with span bars specifically but spanners in general).
Comment: How am I supposed to extract the syntax of "out-of-the-box parenthesizing spanners" from a merge request? Is it supported in LilyPond 2.22.1?
Comment: A merge request is a proposed change to the source code by a developer, namely me in this case. The merge request was just merged (i.e. accepted). So, in the next version that will be released (2.23.4), you will be able to parenthesize hairpins with just \parenthesize\< without needing this Scheme function.
Comment: I know what a merge request is. I am just puzzled, why I need a link to it.
Answer: This is a very "low tech" fix (it maybe even is worthy of the name "kludge") but what about fooling with the spacer rests in the dynamics context?
dynamics = {
    s8 s8 s8 \parenthesizedHairpin s8 \> s8 s8 s16 s32 s64 \! s64 s8 |
}

Comment: It will do. Meanwhile, I started reading the Scheme tutorial.
Comment: I don't know which Scheme tutorial you're using, but [this](https://extending-lilypond.readthedocs.io/en/latest/) is a good place to start with extending LIlyPond once you know the basics.

LilyPond: parenthesized hairpin


Combination selecting a vocal group

Question: A vocal group consisting of alf,bill,cal,deb,eve, and fay (3 boys and 3 girls) are deciding how to arrange themselves from left to right on a stage.
How many way to do this if
A. The boys should be next to each other and so should the girls?
B. Just the boys sit next to each other?
For A I am having problem solving.
The seating I can come up with BBBGGG or GGGBBB. I think it would would be
$(3!)(3!)$ That is 36 possible ways.
For part B it would similar to A since there equal amount of boys and girls.
So the possibilities are
BBB GGG
But I am not sure.
Answer: Your first calculation is almost right. You need to multiply by $2$. For there are $36$ ways using the pattern BBBGGG, and $36$ for GGGBBB.
For boys all together, there are several patterns: BBBGGG, GBBBGG, and so on. Count the number of patterns and multiply by $3!3!$.
Comment: In BBGGBB which is probably a typo, there are too many boys, and they are not all together. There are $4$ "good" patterns in all, $0$ to $3$ girls on the left end.
Comment: Yes, that's right. Another way of thinking about it is that you have the clump $\mathfrak{B}$ of boys, and $3$ girls. The clump can be in any of $4$ places.
Comment: I see so you have to pay attention to the edges.
Comment: Both problems have the same basic structure. But if you only need the boys to be together, there are more "sex alternation" patterns than in the case boys are all together **and** girls are all together.
Comment: So  BBGGBB would not count as pattern, because in BBBGGG a boy and girl stand next to each other in the BG part, so I guess the main idea is that no boy can have a girl sitting to his left and right.
Comment: I see so the pattern are GGGBBB,GGBBBG,GBBBGG,BBBGGG. I think because all three boys have to be togheter.

Combination selecting a vocal group


Generalized form of the integral

Question: What is the generalized form of the integral $\int_0^2 x^3(1-x/2)^4dx$?
I have tryed to solve it using the formula with euler, but i dont quite understand it.
Answer: Note
$$\int_0^2 x^3\left(1-\frac{x}{2}\right)^4\mathrm{d}x= \frac{1}{16}\int_{0}^{2} x^3(2-x)^4 \mathrm{d}x$$
Now, substitute $x=2t$. The question becomes $$\frac{2^8}{16}  \times \int_{0}^{1} t^3(1-t)^4 \mathrm{d}t$$ Using the beta function, we can calcualte the result to be $$\frac{2^8}{2^4} \times \mathrm{B} (4,5)=\frac{3! \times 4!}{8!} \times 2^{4}=\frac{2}{35}$$
Answer: Using S.C.B.'s first steps, you have
$$\frac{2^8}{16}  \times \int_{0}^{1} t^3(1-t)^4 \,dt=16\int_0 ^1(t^7-4 t^6+6 t^5-4 t^4+t^3)\,dt$$ which seems to be quite simple.

Generalized form of the integral


Definition of derivative and cluster points

Question: The most general way to define the derivative of a real function is given as follows:
Definition$\;\mathbf{1}$. Let $X \subset \mathbb{R}$, $f: X \rightarrow \mathbb{R}$ and $a \in X$ a cluster point (point of accumulation or limit point) of $X$. We say that $f$ is differentiable at $a$ when exists the limit
$$
f'(a):=\lim_{x \to a} \frac{f(x)-f(a)}{x-a}. \tag{1}
$$
In affirmative case, the limit $f'(a)$ is said the derivative of $f$ at $a$.
Remark$\;\mathbf{1}.$ In Defintion $1$ the point $a \in X$ must be a cluster point of $X$ in order to ensure that the limit in $(1)$, if exists, is well-defined and unique.
On the other hand, for instance, in Definition $6.1.1$ (page $162$) of $[1]$,  Definition $1$ is considered for $X=I$ an interval. The reason for that, according the authors, is: the concept is most naturally apparent for functions defined on intervals. However, when $X$ is an interval is not considered $a \in X$ as a cluster point.
Question. Regarding this last affirmation: is this possible since every point in any interval is a cluster point?
$[1]$ Bartle, R. and Sherbert, S. Introduction to real analysis. 4th ed.
Comment: Definition 1, when considering functions defined on intervals (open or closed), there's no need to specify that $a$ is a cluster point because this is implied by the fact that you're working with an interval. The reason the authors of the book you mentioned may have omitted that detail is that it is a standard assumption in real analysis when dealing with intervals, and explicitly stating it for every point could be redundant. However, it's always a good practice to define your terms clearly if there's any potential for confusion.
Comment: I do not understand at all your "i[f] exi[s]ts, is well-defined and unique."
Comment: @TedShifrin The limit may not exist, but if it does, with $a$ being an accumulation point, then the limit is well-defined and is unique (by limit property).
Comment: The point is that there is no definition of limit at a non-accumulation point. Well-defined and unique mean the same thing, by the way.
Comment: @TedShifrin Yes I know. That's why I wrote it as an remark, just to reinforce the reason why we need it to be an accumulation point so that the reader doesn't need to consult the limit definition.
Answer: Given $X \subset \mathbb{R}$, denote by $X':=\{ x \in \mathbb{R} \: ; \: x \: \text{is a cluster point of} \: X\}$.
For $a,b \in \mathbb{R}$ with $a<b$, let $I \subset \mathbb{R}$ be any of the following bounded intervals: $(a,b), (a,b], [a,b)$ and $[a,b]$. According item $i)$ of Example $2.1.1$ of $[2]$, we have $I'=[a,b]$. Thus, in this case, since $I \subset [a,b]=I'$, we conclude that every point of $I$ is a cluster point of $I$.
Now, if $I \subset \mathbb{R}$ is one of the unbounded intervals $(a, \infty)$ or $[a, \infty)$, then according item $ii)$ of Example $2.1.1$ of $[2]$, we have $I'=[a, \infty)$. Thus, $I \subset [a, \infty)=I'$ and every point of $I$ is a cluster point of $I$.
Similarly, if $I \subset \mathbb{R}$ is one of the unbounded intervals $(-\infty,b)$ or $(-\infty,b]$, by item $iii)$ of Example $2.1.1$ of $[2]$, every point of $I$ is a cluster point of $I$.
In any case, namely for bounded or unbounded intervals, we can conclude that every point of any interval $I \subset \mathbb{R}$ is a cluster point of $I$.
$[2]$ NAIR, M. Thamban; NAIR. Calculus of one variable. Second Edition. Springer International Publishing, $2021$.


trouble in loop in R: matrix or data frame in the beginning?

Question: I have a data frame (new_t) with rows=strains (28 of them) and columns are genes (12559 of them) and the cells are the expression values for these genes. i want to see the correlation of each gene with the last one. so i want to compare each column like a vector to the last column vector..
> rr<-matrix()
> for (i in 1:ncol(new_t)) {
  bb<-cor(x=new_t[,i], method='spearman', y=new_t[,12559])
  rr<-cbind(rr, bb)
  }

my problem is that when the loop finishes, rr that is formed is all composed of bb's.. as in bb bb bb bb...
if i change rr into a data frame, it gives me error
Error in data.frame(..., check.names = FALSE) :
 arguments imply differing number of rows: 0, 1

any help is appreciated
Answer: You can use apply to avoid the for loop and get the same resutls.
A toy example
> set.seed(1)
> new_t <- matrix(rnorm(100, 100, 3), 10)
> apply(new_t, 2, cor, method="spearman", y=new_t[,10])
 [1] -0.30909091 -0.17575758  0.41818182 -0.36969697 -0.33333333  0.10303030 -0.18787879 -0.36969697
 [9]  0.01818182  1.00000000

I think that with your data it should be:
apply(new_t, 2, cor, method="spearman", y=new_t[,12559])

Or even simplier using just cor without apply and selecting the last column from the correlation matrix.
> cor(new_t, method="spearman")[, ncol(new_t)]
 [1] -0.30909091 -0.17575758  0.41818182 -0.36969697 -0.33333333  0.10303030 -0.18787879 -0.36969697
 [9]  0.01818182  1.00000000

Comment: thank you i used the apply function and solved the problem. thanks for the fast response.
Answer: From the help page of cbind (?cbind):

If there are several matrix arguments, they must all have the same
  number of columns (or rows) and this will be the number of columns (or
  rows) of the result. If all the arguments are vectors, the number of
  columns (rows) in the result is equal to the length of the longest
  vector. Values in shorter arguments are recycled to achieve this
  length (with a warning if they are recycled only fractionally).
When the arguments consist of a mix of matrices and vectors the number
  of columns (rows) of the result is determined by the number of columns
  (rows) of the matrix arguments. Any vectors have their values recycled
  or subsetted to achieve this length.
...
The cbind data frame method is just a wrapper for data.frame(...,
  check.names = FALSE). This means that it will split matrix columns in
  data frame arguments, and convert character columns to factors unless
  stringsAsFactors = FALSE is specified.

I suspect that you are mixing up the number of rows. I'm not sure why you are getting your error with matrix(), as you did not provide a reproducible example. Applying cbind to data.frame() throws an error because the number of rows do not match.
## this seems to work
cbind(matrix(),cor(1:10,2:11))
#      [,1] [,2]
# [1,]   NA    1

## this throws an error
cbind(data.frame(),1)
# Error in data.frame(..., check.names = FALSE) :
#   arguments imply differing number of rows: 0, 1

You'd be better off avoiding the for-loop altogether and using apply or sapply:
sapply(seq_len(ncol(new_t)), function(i)
  cor(x=new_t[,i], method='spearman', y=new_t[,12559]))


Showing $\min\limits_{j=1,\dots,n}|\lambda-\lambda_j|\le ||C||_p||C^{-1}||_p||B||_p$

Question: Let $A$ be a diagonalizable $n\times n$ matrix with eigenvalues $\lambda_1,\dots, \lambda_n$, $B$ an $n\times n$ matrix, and $\lambda$ an eigenvalue of $A+B$. Show that
$$\min\limits_{j=1,\dots,n}|\lambda-\lambda_j|\le ||C||_p||C^{-1}||_p||B||_p$$
where $C$ is a nonsingular matrix such that $C^{-1}AC$ is diagonal and $p=1,2,\infty$.
I'm having difficulty figuring out where to start. If given some guidance I'm sure I can easily get the rest. I know that under the assumption $A$ is diagonalizable gives $C^{-1}AC=diag(\lambda_1,\dots,\lambda_n)$, but I am failing to see how I will use the other assumptions. Any input would be greatly appreciated!
Comment: What is the context of this question? Is exercise contained any book? Or is it a problem whose solution contributes to some of your research? How do you know it's not a false statement? Please clarify these questions.
Comment: It is a problem in the book Numerical Analysis by Rainer Kress
Answer: Here's an argument for the $p=\infty$ case.
Suppose that $(A+B)v=\lambda v$. Since $C^{-1}AC$ is diagonal, we have $C^{-1}ACe_j=\lambda_je_j$, where $e_1,\ldots,e_n$ are the canonical basis. So $Av_j=\lambda_jv_j$, where $v_j=Ce_j$.
Assume $A$ is invertible (when $A$ is not invertible, we may tweak the eigenvalues slightly so that it is, and the we approximate the estimates). Then $v_1,\ldots,v_n$ are a basis. Write $v=\sum_jr_jv_j$ for some coefficients $r_j$. Now
\begin{align}
Bv&=\lambda v-Av=\sum_j r_j \lambda v_j-\sum_jr_j Av_j=\sum_jr_j(\lambda-\lambda_j)v_j\\ \ \\
&=\sum_jr_j(\lambda-\lambda_j)Ce_j.
\end{align}
Thus
$$\tag1
\sum_j r_j(\lambda-\lambda_j)e_j=C^{-1}Bv.
$$
Since $v\ne0$, $r_k=\max\{|r_j|:\ j\}\ne0$. Then
$$\tag2
|r_k|\,|\lambda-\lambda_k|\leq\left\|\sum_jr_j(\lambda-\lambda_j)e_j\right\|_\infty=\|C^{-1}Bv\|
$$
Also, since $v=\sum_jr_jv_j=\sum_jr_jCe_j$, we have that
$$\tag3
\|v\|=\left\| C\,\sum_jr_je_j\right\|\leq\|C\|\,\left\| \sum_jr_je_j\right\| _\infty=\|C\|\,|r_k|
$$
From $(2)$ and $(3)$,
$$
|\lambda-\lambda_k|\leq\frac1{|r_k|}\,\|C^{-1}Bv\|\leq\frac1{|r_k|}\,\|C^{-1}\|\,\|B\|\,\|v\|\leq\|C^{-1}\|\,\|B\|\,\|C\|.
$$
Comment: Thank you for the answer. How is it we know $|r_k|\ge1$?
Comment: We don't.  Look at $(3) $.