Cannot use the alias "/libraries"

Question: I am trying to make a node have the alias "/libraries" but I get a Page Not Found error which looks to be returned before Drupal has fully bootstrapped (I don't get the usual Drupal 404).
I checked a few other sites and they seem to have the same issue. Is there some reason why I cannot use this alias in Drupal? Would it have anything to do with a "libraries" folder in the root of the project?
Edit: It does appear to be because I have a "libraries" directory in the docroot which contain various JS libraries for CKEditor and other modules that need them.
So what is the fix here? I assume if I change the directory to anything else, those plugin paths will break. I could add Libraries API maybe, but I don't know the status of that module, but it still means any module that has a libraries.yml file that looks for /libraries..../file.js still won't work.
In this actual case, /libraries is a View (or could wind up being a node with a View block on it) that lists all libraries in the system, and thats what I want the URL to be.
Comment: @Kevin This worked for me some years back: https://drupal.stackexchange.com/questions/52882/using-profiles-in-a-url-alias
Comment: this is happening before Drupal is bootstrapped in .htaccess, `RewriteCond %{REQUEST_FILENAME} !-d` excludes existing directories getting to index.php
Comment: Makes sense. So, am I stuck here?
Comment: I tried to implement a rule that matched `^libraries/$` which resulted in an endless redirect loop - how did you get around that with profiles? Note that I only want to allow the alias `/libraries` for a node that lists all library locations in the city - other nodes have a Pathauto pattern of `/libraries/[node:title]` and seem fine as-is.
Answer: For anyone looking in the future, this will solve it.
Add this to your htaccess file:
# Allow the alias "/libraries" to work without breaking actual assets in the libraries directory.
RewriteRule ^libraries$ /index.php [L]

Just before this block:
  # Pass all requests not referring directly to files in the filesystem to
  # index.php.
  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteCond %{REQUEST_FILENAME} !-d
  RewriteCond %{REQUEST_URI} !=/favicon.ico
  RewriteRule ^ index.php [L]

I also had to add an .htaccess file to the libraries directory. Inside of that, I had to do:
DirectoryIndex ../index.php
DirectorySlash off

Now I can create an alias for /libraries and not introduce and endless redirect loop, and physical assets (CKEditor plugins) can still be loaded correctly from this directory.

Cannot use the alias "/libraries"


Round-robin assignment

Question: I have a Customers table and would like to assign a Salesperson to each customer in a round-robin fashion.
Customers
--CustomerID
--FName
--SalespersonID

Salesperson
--SalespersonID
--FName

So, if I have 15 customers and 5 salespeople, I would like the end result to look something like this:
CustomerID -- FName -- SalespersonID
1 -- A -- 1
2 -- B -- 2
3 -- C -- 3
4 -- D -- 4
5 -- E -- 5
6 -- F -- 1
7 -- G -- 2
8 -- H -- 3
9 -- I -- 4
10 -- J -- 5
11 -- K -- 1
12 -- L -- 2
13 -- M -- 3
14 -- N -- 4
15 -- 0 -- 5

etc...
I've been playing around with this for a bit and am trying to write some SQL to update my Customers table with the appropriate SalespersonID, but am having some trouble getting it to work.
Any ideas are greatly appreciated!
Answer: In SQL Server:
WITH    с AS
        (
        SELECT  *, ROW_NUMBER() OVER ORDER BY (customerID) AS rn
        FROM    customers
        ),
        s AS
        SELECT  *,
                ROW_NUMBER() OVER ORDER BY (SalespersonID) AS rn
        FROM    salesPersons
        )
SELECT  c.*, s.*
FROM    с
JOIN    s
ON      s.rn =
        (с.rn - 1) %
        (
        SELECT  COUNT(*)
        FROM    salesPersons
        ) + 1

Comment: is there a typo (customerID instead of SalesID) ?                 ---------------------->                           SELECT  *,
                ROW_NUMBER() OVER ORDER BY (customerID) AS rn
        FROM    salesPersons
Answer: Any particular platform?
In SQL Server 2005 and up, you can use ROW_NUMBER (OVER) to assign row numbers and then use your ROW_NUMBER from the customers modulo the number of salespeople to determine the salesperson ROW_NUMBER.

Round-robin assignment


Public access to Jenkins on Cloudbees

Question: I have been trying to setup a link between github and cloudbees to show the status of the build.  But the URL requires authentication to retrieve the data.  I have read the documentation and it is ambiguous as to whether this can work -

Unless you have a FOSS account, Jenkins instances on DEV@cloud are only accessible to users > you have added to your CloudBees account. However, you may have jobs (or folders) which you > want to make public.

What does this mean?  Does it mean that you need a cloudbees account to get access to my Jenkins instance (without me setting up that user within Jenkins) or that this allows public access without a cloudbees account?
I have tried following the instructions but they aren't working as I thought so maybe it is the first answer above.
Comment: I have a FOSS account, but even there it's not public.
Answer: The wiki about public jobs discusses how to make your job publicly visible; by default it is accessible only to people in your CloudBees account after login. Currently your Jenkins instance is not set up to allow anonymous access (see the section Flipping the Switch in the wiki).
If you wanted to make the build status icon be anonymously visible even when the job or your Jenkins instance generally are not, that would require a change to the associated plugin: BadgeAction would need to be refactored into an UnprotectedRootAction.

Public access to Jenkins on Cloudbees


avoid List.Sort resort if sort indicator remains the same

Question: I have a List<Foo> fooList; where Foo is defined as
class Foo
{
    public int Importance { get; set; }

    public string Name { get; set; }
}

Now i add three objects to fooList
fooList.Add(new Foo { Name = "Foo1", Importance = 1 });
fooList.Add(new Foo { Name = "Foo2", Importance = 1 });
fooList.Add(new Foo { Name = "Foo3", Importance = 1 });

Now i sort by importance
fooList.Sort((a, b) => a.Importance.CompareTo(b.Importance));

and dump the list, i get
Foo3, Foo2, Foo1

doing a sort again gives me
Foo1, Foo2, Foo3

Both results are correct, but they are confusing to my users.
Is there a way to avaoid resorting?
Comment: Have something like created time. If `Importance` is equal sort with `createdtime`
Answer: If the comparison of the field that you want to sort on falls out as equal, then compare on something else, for example the objects themselves:
fooList.Sort((a, b) => {
  int result = a.Importance.CompareTo(b.Importance);
  if (result == 0) {
    result = a.CompareTo(b);
  }
  return result;
});

Answer: Maybe using OrderBy and ThenBy
fooList = fooList.OrderBy(x=>x.Importance).ThenBy(x=>x.Name).ToList();

It will sort first after Importance then after Name so results will be the same. See demo below:
http://ideone.com/jf6Am9
EDIT:
here you can find comparision between OrderBy and Sort so you can consider chaning to OrderBy C# Sort and OrderBy comparison. In short: OrderBy is comparably fast and this solution looks cleaner :)
Comment: +1 for the LINQ suggestion, but the comment that `OrderBy` is faster is highly dependent on the situation. On my machine (i7 3rd gen Release build on 64bit .NET 4.5), `Sort` outperforms `OrderBy` around in all cases mentioned in that Darin's [answer](http://stackoverflow.com/a/1832713/69809) by up to three times. Since `OrderBy` creates three additional arrays of length of the `IEnumerable` and then runs Quicksort (check the source for `OrderedEnumerable`), I don't see how it could possibly be faster. LINQ *is* a much cleaner solution, however, and one that should be preferred in most cases.
Comment: The code in the answer (or the demo) doesn't change the list. You have to use something like `.ToList()` to realise the result so that the code does anything at all, and assign the result back to the variable (or a new variable).
Comment: @Groo really? I thought it's faster, but thanks for clarification. I'll change my answer and suggest that it's cleaner and comparably fast ;) I'll keep your suggestions in mind :)


Finding a definite integral of an algebraic fraction

Question: I need to find the definite integral $\displaystyle\int_0^4 \frac{x^3}{(x^2+1)^{1/2}} dx$.
I first tried to manipulate the fraction algebraically and did not succeed down that path. I then chose to use the substitution $x=\tan y$ and after a series of manipulations I used a second substitution $u=cost$ and things got worse. I feel I am doing something wrong. I need a hint here.
Answer: Note that $x^3 = x\cdot x^2$. Now, put $$u = x^2 + 1 \implies du = 2x\,dx \iff \dfrac{du}{2} = x\,dx$$ and $$x^2 = u-1.$$
We can't forget the bounds: you can simply change the bounds from $x = 0 \implies u = 1$ to $x = 4 \implies u = 17$. Then there's no need to back substitute.
That gives you $$\begin{align}\int_0^4 \frac{x^3\,dx}{(x^2+1)^{1/2}} & = \frac 12 \int_1^{17} \frac {(u-1)\,du}{u^{1/2}}\\ \\& = \frac 12 \int_1^{17} \left(u^{1/2} - u^{-1/2}\right)\,du\end{align}$$
Can you take it from here?
Comment: Yes, thank you amWhy, that is flawless.
Answer: There's an extremely useful (but apparently rarely taught) tactic for handling integrals involving square-roots of quadratic functions known as Euler substitutions. The appropriate Euler substitution can convert any integral of an algebraic function of the form $R{(x,\sqrt{ax^2+bx+c})}$, where $R$ is a rational function, into just an integral of a pure rational function.
Applying the technique to your problem, we could use the type-I Euler substitution.
$$\sqrt{x^2+1}=-x+t,$$
$$\implies t=x+\sqrt{x^2+1},~x=\frac{t^2-1}{2t},~$$
$$\implies \mathrm{d}x=\frac{t^2+1}{2t^2}\,\mathrm{d}t.$$
Thus,
$$\begin{align}
\int_{0}^{4}\frac{x^3}{\sqrt{x^2+1}}\,\mathrm{d}x
&=\int_{1}^{4+\sqrt{17}}\frac{(t^2-1)^3}{4t^2(t^2+1)}\cdot\frac{t^2+1}{2t^2}\,\mathrm{d}t\\
&=\frac18\int_{1}^{4+\sqrt{17}}\frac{(t^2-1)^3}{t^4}\,\mathrm{d}t.\\
\end{align}$$
From there, the rest of the problem should be very straightforward, though perhaps algebraically tedious.
Comment: I like this one. You used type 1 Euler substitution, could you link me to where I can find the other types?
Comment: @2good4this The wikipedia link I provided in my answer nicely describes all three types.
Answer: For this particular integral, you could try trigonometric substitution.
First substitute $x = \tan t,$
then substitute $\sec t = u.$
You should then have
$$\int_0^\sqrt{17} (u^2 - 1) du.$$
(As a check, Wolfram Alpha evaluates this to the exact same value as the original integral.)
Answer:
$\qquad$ I then chose to use the substitution $x=\tan y$ and after a series of manipulations I used a second substitution $u=\cos t$ and things got worse. I feel I am doing something wrong.

$x=\tan u~=>~dx=d(\tan u)=\dfrac{du}{\cos^2u}.~$ At the same time, $1+x^2=1+\tan^2u=\dfrac1{\cos^2u}$.
Thus, $~I=\displaystyle\int_0^a\dfrac{\tan^3u}{\bigg(\dfrac1{\cos u}\bigg)}\dfrac{du}{\cos^2u}=\int_0^a\dfrac{\sin^3u}{\cos^4u}du=-\int_0^a\dfrac{1-\cos^2u}{\cos^4u}d(\cos u),~$ which is
trivial. $~$ Now, $a=\arctan4$, and, after letting $t=\cos u$, the upper limit becomes $\cos(\arctan4)$,
which, by definition, is the cosine of the angle whose tangent is $4.~$ So, $\tan a=\dfrac{\sin a}{\cos a}=4.~$ But
$\sin a=\sqrt{1-\cos^2a}.~$ This yields a quadratic equation, whose solution is $\cos a=\dfrac1{\sqrt{17}}$.

Alternately, if you are familiar with hyperbolic functions, let $x=\sinh y.~$ Since $\sinh'y=\cosh y$
and $1+\sinh^2y=\cosh^2y$, you will be left with $\displaystyle\int_0^b\sinh^3y~dy=\int_0^b\Big(\cosh^2y-1\Big)~d(\cosh y)$,
which is also trivial. Here, $b=\sinh^{-1}4$, and, after letting $z=\cosh y$, the new upper limit will be
$\cosh(\sinh^{-1}4)$, which, by its very definition, is the hyperbolic cosine of the arc whose hyperbolic
sine is $4.~$ In other words, $\sinh b=4.~$ But $\cosh^2b-\sinh^2b=1\iff\cosh b=\sqrt{1+\sinh^2b}=$
$=\sqrt{1+4^2}=\sqrt{17}$.
Comment: I hadn't thought that a trigonometric substitution would work here. Thank you
Answer: $\newcommand{\angles}[1]{\left\langle\, #1 \,\right\rangle}
 \newcommand{\braces}[1]{\left\lbrace\, #1 \,\right\rbrace}
 \newcommand{\bracks}[1]{\left\lbrack\, #1 \,\right\rbrack}
 \newcommand{\ceil}[1]{\,\left\lceil\, #1 \,\right\rceil\,}
 \newcommand{\dd}{{\rm d}}
 \newcommand{\ds}[1]{\displaystyle{#1}}
 \newcommand{\expo}[1]{\,{\rm e}^{#1}\,}
 \newcommand{\fermi}{\,{\rm f}}
 \newcommand{\floor}[1]{\,\left\lfloor #1 \right\rfloor\,}
 \newcommand{\half}{{1 \over 2}}
 \newcommand{\ic}{{\rm i}}
 \newcommand{\iff}{\Longleftrightarrow}
 \newcommand{\imp}{\Longrightarrow}
 \newcommand{\pars}[1]{\left(\, #1 \,\right)}
 \newcommand{\partiald}[3][]{\frac{\partial^{#1} #2}{\partial #3^{#1}}}
 \newcommand{\pp}{{\cal P}}
 \newcommand{\root}[2][]{\,\sqrt[#1]{\vphantom{\large A}\,#2\,}\,}
 \newcommand{\sech}{\,{\rm sech}}
 \newcommand{\sgn}{\,{\rm sgn}}
 \newcommand{\totald}[3][]{\frac{{\rm d}^{#1} #2}{{\rm d} #3^{#1}}}
 \newcommand{\ul}[1]{\underline{#1}}
 \newcommand{\verts}[1]{\left\vert\, #1 \,\right\vert}$
\begin{align}
&\color{#66f}{\large\int_{0}^{4}{x^{3} \over \pars{x^{2} + 1}^{1/2}}\,\dd x}
=\int_{x\ =\ 0}^{x\ =\ 4}x^{2}\,\dd\pars{x^{2} + 1}^{1/2}
\\[5mm]&=\left.x^{2}\pars{x^{2} + 1}^{1/2}\,\right\vert_{\, 0}^{\, 4}\ -\
\overbrace{\int_{0}^{4}\pars{x^{2} + 1}^{1/2}\pars{2x}\,\dd x}
^{\ds{\color{#c00000}{x^{2}\ \mapsto\ x}}}\ =\
16\root{17} - \int_{0}^{16}\pars{x + 1}^{1/2}\,\dd x
\\[5mm]&=16\root{17} - \left.{2 \over 3}\pars{x + 1}^{3/2}\right\vert_{0}^{16}
=16\root{17} - {2 \over 3}\pars{17^{3/2} - 1}
=\pars{16 - {2 \over 3}\,17}\root{17} + {2 \over 3}
\\[5mm]&=\color{#66f}{\large{14\root{17} + 2 \over 3}}
\approx {\tt 19.9078}
\end{align}
Comment: Nice, I hadn't realised I could integrate by parts here.
Comment: @2good4this I'm glad it was useful for you. Thanks.


Specifying mixed-linear model in lme() for pre-/post-treatment design

Question: Dear crossvalidated community!
I am analyzing a data of a study in which every participant's performance in a memory task was measured twice (once under placebo, once under drug treatment in random order).  Moreover every subject was tested in a blood test measuring the level of stable blood marker. I would like to analyze the data with respect to drug-effects and blood marker effects using lme() from the nlme() package.
'treatment' codes placebo/drug
'session' codes the first or second testing in order to account for learning/re-test effects
'blood' codes for the blood marker level (continous variable), which should be entered as a covariate in the analysis
'id' codes for the subjects
Would the following equation correct for the described data:
# some data
data <- structure(list(id = structure(c(1L, 12L, 14L, 15L, 16L, 17L,
18L, 19L, 20L, 2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L, 10L, 11L, 13L,
1L, 12L, 14L, 15L, 16L, 17L, 18L, 19L, 20L, 2L, 3L, 4L, 5L, 6L,
7L, 8L, 9L, 10L, 11L, 13L), .Label = c("1", "10", "11", "12",
"13", "14", "15", "16", "17", "18", "19", "2", "20", "3", "4",
"5", "6", "7", "8", "9"), class = "factor"), sess = structure(c(1L,
2L, 2L, 1L, 1L, 2L, 2L, 1L, 1L, 2L, 2L, 1L, 1L, 2L, 2L, 1L, 1L,
2L, 2L, 1L, 1L, 2L, 2L, 1L, 1L, 2L, 2L, 1L, 1L, 2L, 2L, 1L, 1L,
2L, 2L, 1L, 1L, 2L, 2L, 1L), .Label = c("a", "b"), class = "factor"),
    treat = structure(c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
    1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L,
    2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L
    ), .Label = c("drug", "placebo"), class = "factor"), memory = structure(c(2L,
    12L, 17L, 18L, 1L, 20L, 19L, 15L, 14L, 16L, 8L, 7L, 5L, 9L,
    4L, 6L, 10L, 3L, 11L, 13L, 2L, 12L, 17L, 18L, 1L, 20L, 19L,
    15L, 14L, 16L, 8L, 7L, 5L, 9L, 4L, 6L, 10L, 3L, 11L, 13L), .Label = c("1",
    "10", "11", "12", "13", "14", "15", "16", "17", "18", "19",
    "2", "20", "3", "4", "5", "6", "7", "8", "9"), class = "factor"),
    blood = structure(c(3L, 11L, 17L, 18L, 20L, 19L, 9L, 10L,
    6L, 16L, 5L, 2L, 12L, 15L, 4L, 13L, 14L, 8L, 7L, 1L, 3L,
    11L, 17L, 18L, 20L, 19L, 9L, 10L, 6L, 16L, 5L, 2L, 12L, 15L,
    4L, 13L, 14L, 8L, 7L, 1L), .Label = c("1", "100", "17", "25",
    "38", "39", "40", "44", "55", "6", "62", "66", "70", "77",
    "81", "83", "85", "86", "89", "94"), class = "factor")), .Names = c("id",
"sess", "treat", "memory", "blood"), row.names = c(NA, -40L), class = "data.frame")

# the model
m1 <- lme(memory~sess*treat*blood, random=~1|id/treat, data=data)
summary(m1)

Comment: Is there a particular reason you're using `nlme` rather than its successor, `lme4`?
Comment: I was hoping to get some p-values and pvals.fnc() will only work with the most simple random effects structure.
Answer: A few notes:

If you look at your data you obtain:
> str(data)
'data.frame':   40 obs. of  5 variables:
$ id    : Factor w/ 20 levels "1","10","11",..: 1 12 14 15 16 17 18 19 20 2 ...
$ sess  : Factor w/ 2 levels "a","b": 1 2 2 1 1 2 2 1 1 2 ...
$ treat : Factor w/ 2 levels "drug","placebo": 1 1 1 1 1 1 1 1 1 1 ...
$ memory: Factor w/ 20 levels "1","10","11",..: 2 12 17 18 1 20 19 15 14 16 ...
$ blood : Factor w/ 20 levels "1","100","17",..: 3 11 17 18 20 19 9 10 6 16 ...

The dependent variable memory and the covariate blood shouldn't be factors, but numeric:
> data$memory <- as.numeric(data$memory)
> data$blood <- as.numeric(data$blood)

I am no expert for regression designs, but why do you add the covariate and all it's interactions? Wouldn't it be sufficient to have something like memory ~ sess*treat + blood? I think everything on top of this needs justification.
The random effect needs to be stratified for both within-subjects factor sess and treat something that is cumbersome in lme and lme4 is preferable (for the cost of loosing straight forward p-values, but you can still get them via bootstrap). Something between the following extremes should work:
lmer(memory ~ sess*treat + blood + (1|id), data = data)
lmer(memory ~ sess*treat + blood + (1+sess*treat|id), data = data)

Have a look at the paper from Baayen and Milin (2010) for different random effects structures. And to obtain p-values from a lmer model you can use the pvals.fnc function from the languageR package.

Baayen, R. H., & Milin, P. (2010). Analyzing Reaction Times. International Journal of Psychological Research, 3(2), 12–28.
Comment: Thanks for your helpful answer! I was hoping to find a way to use lme() in order to report p-values. Unfortunately it seems that pvals.fnc() will only work with a lmer() model 'when there is more than one random intercept in the model'(R Documentation). So the only random effects specification I would be left with is the first one you mention: lmer(memory ~ sess*treat + blood + (1|id), data = data). So it seems I have to give up on p-values and use likelihood ratio tests instead?
Comment: You probably mean will NOT work with more than one random intercept. But why not use the most simple model?


Gerar uma profissão aleatória para os Jogadores Online

Question: Eu estou a criar um pequeno jogo (Android) para jogar eu mais uns amigos meus. O jogo chama-se "Polícias e Ladrões". Pelo menos é necessário ter 4 jogadores em que um deles será o POLÍCIA, outro será o CRIMINOSO, outro será a DAMA e os restantes serão CIVÍS (Pessoas Normais).
Eu atualmente tou a usar o Socket.IO para fazer a ligação entre os jogadores e a comunicação. Mas na altura de dar uma profissão para cada jogador, deparei-me com um problema. Esta é a parte do código em que ele cria e envia para o jogador a sua profissão:
    var PoliceAlready,CriminalAlready,DamaAlready = false;
    for(var SI in clients) {
        var socket = clients[SI];
        var profissaoT;

        if(!PoliceAlready){
                profissaoT="POLÍCIA";
                PoliceAlready = true;
        }else if(!CriminalAlready){
                profissaoT="CRIMINOSO";
                CriminalAlready = true;
        }else if(!DamaAlready){
                profissaoT="DAMA";
                DamaAlready = true;
        }else{
                profissaoT="CIVÍL";
        }
        socket.emit('profissao', profissaoT);
 }

Mas obrigatoriamente terá que ter um Polícia, Criminoso e Dama e estes não se podem repetir. Apartir do código acima ele irá fazer isso mesmo, porém a função for() vai executando os dados do array "clientes" por ordem, o que faz com que sempre tenha a mesma profissão e o objetivo é sempre que voltar a executar esta função de dar a profissão, sempre seja aleatoriamente!
var clients = {'/#53h2bn324buh234', '/#h32h324h5234uh2', '/#3pm3b4ij234'};

Agradeço desde já quem se disponibilizar a ajudar-me, ou pelo menos tentar.
Answer: O ideal seria explicar a forma que proponho desenhando, mas tentarei ilustrando. Para garantir que cada jogador terá um papel válido e que tenha somente 1 Policial,  1 Dama e 1 Criminoso vamos imaginar 5 crianças brincando.
Elas pegam uma caixa e colocam 5 papeis escritos as profissões disponíveis, tal que depois que elas terminam a caixa terá 1 Policial, 1 Criminoso, 1 Dama e 2 Cívis. Elas chacoalham a caixa para embaralhar e então cada uma tira um papel. No final, cada criança saberá a sua profissão e não haverá o risco de não ter saído nenhum policial ou ter dois policiais.
O que fiz nesse código é isso. Existe um array chamado papeis, onde possuem números associados a profissões, que são:
1 = Policial
2 = Criminoso
3 = Dama
4 = Cívil
Caso tenha mais de 4 jogadores, o array é preenchido de cívis, por isso o push(4). Então para cada cliente é removido uma profissão aleatóriamente da "caixa".

// deixar os papéis fixos
var papeis = [1, 2, 3, 4];

// Clientes em formato de array de objetos, para que cada cliente possua uma profissao
var clients = [{
  'id': '/#53h2bn324buh234',
  'profissao': null
}, {
  'id': '/#h32h324h5234uh2',
  'profissao': null
}, {
  'id': '/#3pm3b4ij234',
  'profissao': null
}, {
  'id': '/#3pm3b4ij222',
  'profissao': null
}];

// Se houver mais de 4 jogadores os demais serão civis
if (clients.length > 4) {
  for (var i = 0; i < clients.length - 4; i++) {
    papeis.push(4);
  }
}

// elegendo o papel para cada jogador
clients.forEach(function(cliente) {
  var aux = Math.floor(Math.random() * papeis.length);
  // splice remove o papel do array de papeis. Isso para
  // para que tenha somente 1 Policia, Dama e Criminoso.
  var papel = papeis.splice(aux, 1);
  cliente.profissao = obterProfissao(papel[0]);

  adicionarTela(cliente);
});

function adicionarTela(cliente) {
  var div = document.getElementById("papeis");
  var span = document.createElement("span");
  span.innerHTML = " O jogador: " + cliente.id + " é: " + cliente.profissao + "
"
  div.appendChild(span);
}

function obterProfissao(escolha) {
  //var socket = clients[SI];
  var profissaoT;

  if (escolha == 1) {
    profissaoT = "POLÍCIA";
    PoliceAlready = true;
  } else if (escolha == 2) {
    profissaoT = "CRIMINOSO";
    CriminalAlready = true;
  } else if (escolha == 3) {
    profissaoT = "DAMA";
    DamaAlready = true;
  } else {
    profissaoT = "CIVÍL";
  }
  return profissaoT;
  //socket.emit('profissao', profissaoT);
}

PS: Eu adorava esse jogo!
Comment: Lucas, posso ter percebido mal a pergunta e o jogo, mas eu acho que também jogava este jogo :P . Mas assim a alguém que fica a saber as profs de todos, certo? Não deveria ser cada um só saber o seu? De qualquer maneira +1
Comment: Funcionou Lucas, fiz os respectivos testes e está exatamente como queria!
Comment: Na vida real sim @Miguel! Você diz isso por achar que deveria ser alocado no servidor as profissões?
Comment: Sim, pelo menos pensei que sim. Para não haver conflitos e cada um só saber o seu... Bem logo se vê
Comment: Você está certo. Na verdade exibi no HTML somente para ficar visível a distribuição dos papéis. E fiz no javascript para para monstrar a lógica :) no caso é só passar para o node, ou PHP para ficar mais adequado.
Comment: http://image.prntscr.com/image/74c41261bcb64f92bf2e1aa2862ddcec.png
Comment: Que legal cara! Fico feliz por ajudar :)
Comment: Miguel, a profissão escolhida irá ser enviada apenas para esse mesmo jogador com um Socket Emit. O jogo que estou a criar é baseado em Sockets (Socket.IO,NodeJS,...) com um aplicativo Android (Java)!
Answer: O que tens de fazer é guardar do lado servidor as profissões que já saíram, neste caso vou escolhendo ao acaso uma das 3 princípais e depois apago a escolhida, quando alguma socket (jogador) sai do jogo essa prof fica de novo à disposição.
Isto é um exemplo funcional dessa funcionalidade, apesar do teu lado cliente ser diferente podes testar isto no browser. Sendo que index.html e server.js estão na mesma pasta.
server.js:
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var jogadores = {}; // serve para guardar as sockets e respetiva profissões
var profs = ['POLÍCIA', 'CRIMINOSO', 'DAMA'];

app.get('/', function(req, res){
    res.sendfile('index.html'); // enviar ficheiro para o browser
});

io.on('connection', function(socket){
    socket.on('chose_prof', function () {
        if(!(socket.id in jogadores)) {
            var prof = 'CIVIL'; // civil por default
            if(profs.length > 0) { // se ainda existirem as profissões princípais
                prof = profs[Math.floor(Math.random()*profs.length)]; // escolher prof ao acaso
                profs.splice(profs.indexOf(prof), 1); // apagar prof sorteada do nosso array de profs
            }
            jogadores[socket.id] = prof; // guardar socket e prof no obj jogadores, fazer console.log(jogadores); para perceberes
            io.to(socket.id).emit('new_prof', {prof: prof}); // enviar profissão sorteada
        }
    });
    socket.on('disconnect', function() {
        if(socket.id in jogadores) {
            if(jogadores[socket.id] != 'CIVIL') {
                profs.push(jogadores[socket.id]); // profissão de quem saiu do jogo fica de novo à disposição para outros que entrem
            }
            delete jogadores[socket.id]; // apagar jogador do nosso obj
        }
    });
});

http.listen(3000, function(){
    console.log('listening on *:3000');
});

index.html:

<button id="gera_prof">Gerar Prof</button>

Comentei o que acho que deve ser esclarecido, caso tenhas duvidas diz.


Path to the file Python

Question: I've made a code that reads files from the folder and saves their paths.
sample_directory = []
sample_files = []
for (dirpath, dirnames, filenames) in walk('./Samples'):
    sample_files.extend(filenames)
    break
paths = []
for i in range(len(sample_files)):
    path = os.path.realpath(sample_files[i])
    paths.append(path)

sample_directory.append(sample_files)
sample_directory.append(paths)
print(sample_directory)

[['smpl1.xlsx', 'smpl2.xlsx', 'smpl3.xlsx', 'smpl4.xlsx', 'smpl5.xlsx'], ['/Users/Graygood/Desktop/Science comput/Application/smpl1.xlsx', '/Users/Graygood/Desktop/Science comput/Application/smpl2.xlsx', '/Users/Graygood/Desktop/Science comput/Application/smpl3.xlsx', '/Users/Graygood/Desktop/Science comput/Application/smpl4.xlsx', '/Users/Graygood/Desktop/Science comput/Application/smpl5.xlsx']]

The problem is that it skips one folder and the true path is:

/Users/Graygood/Desktop/Science comput/Application/Samples/smpl1.xlsx

Why is that and how to fix it?
Answer: your first loop only stores the filenames, without the root directory. After that, using realpath (or abspath) doesn't solve anything: the directory path information is already lost.
You don't need recursion, since you break at first iteration, so the best way would be to use os.listdir and append the path (and use abspath to convert to absolute path):
the_dir = "Samples"
paths = [os.path.abspath(os.path.join(the_dir,filename)) for filename in os.listdir(the_dir)]

alternative with glob.glob:
import glob
paths = glob.glob(os.path.abspath("Samples/*"))

also note that instead of abspath/realpath, most of the time the Samples directory is relative to your python file. In that case, just do:
the_dir = os.path.join(os.path.dirname(__file__),"Samples")

and drop all absolute/real path conversion. The advantage is that you can change directory/run the app from another directory and the "resource" files are still reachable.
Comment: Thanks, it helped!
Answer: The realpath returns a relative filepath to path either from the current directory or from an optional start point.
Since you want the actual path of the file, use:
path = os.path.realpath(os.path.join(dirpath,sample_files[i]))

Path to the file Python


Get Last Order ID and Date Per Customer in Oracle

Question: It's an orcale database and I'm trying to get the last order ID and its date for each customer. I'm familiar enough with MySQL to be able to write something like the following in a MySQL system:
https://www.w3schools.com/SQL/trysql.asp?filename=trysql_select_all
SELECT CustomerID, COUNT(OrderID), MAX(OrderDate) as Last_Order_Date,
    (SELECT OrderID FROM Orders O2
    WHERE O2.CustomerId = O1.CustomerId
    ORDER BY OrderDate DESC LIMIT 1)
    AS LAST_ORDER_ID
FROM [Orders] O1
GROUP BY CustomerID
ORDER BY CustomerID

However I haven't been able to write the equivalent for an Oracle database. The part that trips me up is I have to write a subquery for the order by, then pick the top 1... but that also need to go into my bigger query of getting the last order for each customer.
Answer: Use MAX( ... ) KEEP ( DENSE_RANK LAST ... ):
SELECT CustomerID,
       COUNT( OrderID ),
       MAX( OrderDate ) AS Last_Order_Date,
       MAX( OrderID ) KEEP ( DENSE_RANK LAST ORDER BY OrderDate ) AS Last_Order_ID
FROM   Orders
GROUP BY CustomerID
ORDER BY CustomerID;

or use analytic functions:
SELECT CustomerID,
       Num_Orders,
       OrderDate AS Last_Order_Date,
       OrderID AS Last_Order_ID
FROM   (
  SELECT o.*,
         COUNT( OrderID ) OVER ( PARTITION BY CustomerID ) AS Num_Orders,
         ROW_NUMBER() OVER ( PARTITION BY CustomerID
                             ORDER BY OrderDate DESC, OrderID DESC ) AS rn
  FROM   orders o
)
WHERE  rn = 1
ORDER BY CustomerID;


Another enum value by default in stripes

Question: I have enum field in my JSP looks as:

        <stripes:select name="answer" id="answer" tabindex="530">
            <stripes:options-enumeration enum="com.enums.YesNoEmpty"/>
        </stripes:select>

And of course YesNoEmpty.java
public enum YesNoEmpty {
    NO,
    YES;

    public String toString() {
        switch (this) {
            case YES:
                return "Yes";
            case NO:
                return "No";
            default:
                return null;
        }
    }
}

The problem is i see "No" by default on my page, but need "Yes". How can i manage it without changing order NO, YES in YesNoEmpty.java.
Thank you.
Answer: According to the API:

The options will be generated in ordinal value order (i.e. the order they are declared in the enum).

It looks like the best(only) way would be to change the order of the enum.
Comment: Thank you for your answer. I thought the same, but it will change logic for all sources which use the enum. Found other, just initialized in db entity the field as "Yes".              @Column(name = "Item")
    @Enumerated(EnumType.ORDINAL)
    private YesNoEmpty Item = YesNoEmpty.YES;


How to: Bootstrap Prediction Intervals for Regression Models with non IID noise?

Question: Question:
Consider a regression model $Y=m(X)+\epsilon$ for which $\epsilon$ is neither independent of $x$ nor identically distributed.
How would we go about generating prediction intervals in such a scenario? I'm specifically asking in a non-time series context, though if the method is equally applicable there – then even better.
(I.e. A $1-\alpha$ prediction interval $[l,u]$ for $Y|X = x$ such that $\mathbb{P}(l\leq Y \leq u | X=x) = 1-\alpha$.)
Personal Attempt at Finding Answer:
My usual approach would be (for IID noise): generate $N$ bootstrapped samples. For each bootstrapped sample, fit the model and compute the residuals. Make a prediction with the fitted model, and randomly sample from the residuals and add this to the prediction. (This is the approach also used in the video in bullet 3).
However, in the non-IID case, I've done a lot of reading and can't seem to find a concrete answer:

The method offered here, based on Section 6.3.3 of Davidson and Hinckley (1997), I believe requires an OLS model and i.i.d,

Other proposals require transforming the data (such as with heteroskedasticity) – however this would only work in certain circumstances.

The approach provided in this video makes the most intuitive sense and works for i.i.d noise, but on testing on my own synthetic data that does not have i.i.d noise it's not able to capture the true population distribution.

The most potentially promising bootstrap method I can find is in Cosma Shalizi's Bootstrap Lecture Notes, see page 13, section 5.4. He describes the "Case Bootstrap" (aka. "Pairs bootstrap", "x-y bootstrap" or "rows bootstrap").

Resampling cases makes only very weak assumptions about the
data-generating distribution, that all data points ($(x, y)$ pairs)
are independent and identically distributed. It does not assume that
any $m(x)$ is correct, or that the noise is independent of $x$, or has
constant variance.

Now, as Shalizi mentions this x-y pairs method is extensively described by Buja et al (2014).
However, in neither Shalizi or Buja's can I find a description of the actual method (in Shalizi's case, I struggle to understand the R code), and more specifically in the context of prediction intervals.
Summary:
Does anyone know how to do the xy bootstrap for prediction intervals and/or know how to actually do prediction intervals for non iid noise?
Answer: You are correct that the case bootstrap is appropriate here. The algorithm itself is very simple. Assuming that your data set consists of n rows (observations), you want to repeat the following steps:

Sample with replacement n rows from your original data set, to obtain a new data set of the same size. Shalizi does this with the resample.data.frame function, which outputs df[resample(1:nrow(df)),]. He previously defines the resample function as sample(x, size=length(x), replace=TRUE), i.e. a sample of size x from the numbers {1,...,x} with replacement.

Fit your regression model to this new data set. In Shalizi's code, this is re.lm(cats.lm, resample.data.frame(cats)). The re.ml function just takes the equation from cats.lm (which is Hwt ~ Sex*Bwt) and fits it to the resampled data.

Every repetition will produce a different set of estimates for the model coefficients, and you can use these to approximate their sampling distribution.
Comment: I think you'll have to move beyond standard bootstrap techniques, because you're trying to predict what will happen when you plug in a new (unseen) value of x, but ϵ depends on x.

Have you looked at (split sample) conformal prediction intervals?
Comment: Just coming back to this to say that this last month I've taken a full dive into conformal prediction thanks to your comment — it's definitely the solution to the question I was asking. If you're able to submit that as an answer, happy to give you the tick :) Thanks
Comment: Hi Doctor Milt, thanks for taking the time to respond and the explanation. Isn't the case bootstrap method as you describe it though only going to provide confidence intervals around the model coefficients? I'm interested in a prediction interval around a new observation
Comment: No I can't say I have, I'll definitely look into that. Do you have any helpful resources or know where I might find a step by step of the process? Thanks again
Comment: Try this: https://www.stat.cmu.edu/~ryantibs/papers/conformal.pdf
Comment: Start with Algorithm 1 (page 8).
Comment: That's great! I'll write up an answer as soon as I have a moment.
Comment: Conformal prediction is a really handy tool, isn't it?
Comment: Honestly it really is, you've opened a whole new world of prediction intervals to me haha


How do I access an airflow rendered template downstream?

Question: Airflow version: 1.10.12
I'm having trouble passing a rendered template object for use downstream. I'm trying to grab two config variables from the Airflow conf.
from airflow import DAG
from airflow.operators.bash_operator import BashOperator

from datetime import datetime

with DAG(
    dag_id="example_trigger_target_dag",
    default_args={"owner": "airflow"},
    start_date=datetime(2021, 6, 24),
    schedule_interval='@once',
    tags=['example'],
) as dag:

    bash_task = BashOperator(
        task_id="bash_task",
        bash_command='echo "{{ conf.test }}:{{ conf.tag }}"',
        xcom_push=True
    )

Basically what it passes to xcom is just : without the variables present.  The full rendered string does show up however in the rendered tab.  Am I missing something?
Edit: the variables exist in the conf, I just replaced them with test and tag for security reasons.
Comment: Can you test `bash_command='echo "{{ dag_run.conf["test"] }}:{{ dag_run.conf["tag"] }}"',`?
Answer: I just tested this code (I'm using Airflow 2.1.0) and got that result.
BashOperator(task_id='test_task',
                     bash_command='echo " VARS: {{ conf.email.email_backend '
                                  '}}:{{ conf.core.executor }}"',
                     do_xcom_push=True)


How are convolution layer/max-pool layer operations carried out

Question: I understand the concept behind why convolution layers / max pool operations work, but I cannot conceptualize how they are applied in typical neural network model.
For example if I had a NN model that looked like this:
[inputs] -(weights 0)-> [conv. layer / max-pooling] -(weights 1)-> [dense layer] -(weights 2)-> [output]
where exactly would the operations for apply filters/averaging take place? During the weights section or the [conv. layer / max-pooling] section itself
Assuming the inputs take in a 28 * 28 pixel, how would I take a 2 * 2 filter and change the original matrix, would I have to split the inputs into 2 * 2 chunks and recombine them?
If I wanted to preform max-pooling on the same inputs would I also have to also split the image into 2x2 chunks to downscale the image and add all of those little chunks together to form a new matrix?
[2][3]
[5][4] ---> [5]
I'm currently at the phase of transitioning from theory to practice.
Answer:
where exactly would the operations for apply filters/averaging take
  place? During the weights section or the [conv. layer / max-pooling]
  section itself

Weights actually belong to filters, i.e. the convolutional layer. Pooling occur afterwards and doesn't relate to the weights.

Assuming the inputs take in a 28 * 28 pixel, how would I take a 2 * 2
  filter and change the original matrix, would I have to split the
  inputs into 2 * 2 chunks and recombine them?

You convolve the input image and the filter. You can convolve different sized images (signals), no need to split the larger one into smaller chunks. This step sometimes can slightly differ from the usual convolution, in which zero-padding can be used, or reversal of filter (which isn't important in learning) is not performed etc.

If I wanted to perform max-pooling on the same inputs would I also
  have to also split the image into 2x2 chunks to downscale the image
  and add all of those little chunks together to form a new matrix?

After the conv. layer, you divide the image into 2x2 non-overlapping chunks, choose the max amongst the 4 pixels, and form a new image. Yes, this is a form of downscaling, but not in the usual sense in signal processing, where you apply, for example, low-pass filters and subsample.
Comment: Ah that explains a lot, so just to clarify, where the weights normally are exists a function that's job it is to apply a filter for convolutions, while the max pooling takes place within the max-pooling layer itself? At this max pooling layer, are weights and activation functions also applied or do the layers only preform max-pooling and convolutions without preforming any of the dense layer functions.
Comment: Pooling layer doesn't contain weights/activations, just pooling (mean, max or whatever you choose) Conv. layer has filters (i.e. weights) and sometimes activations.
Comment: Oh sorry, I tend to forget to do that


Solving definite integrals with periodic integrand

Question: So, the question  is:
If $f(2-x) = f(2+x)$ and $f(4-x) = f(4+x)$ where $f(x)$ is a function for which
$$\int_{0}^{2}f(x)dx =5$$ ,
then prove that :
$$\int_{0}^{50}f(x)dx =125$$
$$\int_{-4}^{46}f(x)dx =125$$
$$\int_{2}^{52}f(x)dx =125$$
also comment whether $\int_{1}^{51}f(x)dx =125$ is true or false.
My approach:
since $f(2-x) = f(2+x)$ , replace $x$ by $x+2$
and we get $f(x) = f(4+x)$ hence  period of
$f(x)$ is $4$
now,
$$\int_{0}^{50}f(x)dx = \int_{0}^{48}f(x)dx +\int_{0}^{2}f(x)dx  $$
hence
$$\int_{0}^{50}f(x)dx =12* \int_{0}^{4}f(x)dx +\int_{0}^{2}f(x)dx  $$
which becomes
$$\int_{0}^{50}f(x)dx =12*( \int_{0}^{2}f(x)dx+\int_{0}^{2}f(x+4)dx) +5  $$
so,we get $$\int_{0}^{50}f(x)dx =125$$
similarly for
$$\int_{-4}^{46}f(x)dx $$,substitute $x+4=t$
therefore,
$$\int_{-4}^{46}f(x)dx =\int_{0}^{50}f(t)dt  =125 $$
however I am not able to prove on the final part and comment on  whether $\int_{1}^{51}f(x)dx =125$ is true or false.Kindly help me out.
Answer: Hint: $\int_2^{52} f(x)dx=\int_0^{52} f(x)dx -\int_0^{2} f(x)dx=(13)\int_0^{4} f(x)dx-5$.
Comment: yes, got it what about comment part
Comment: There is not enough information to evaluate $\int_1^{51}f(x)dx$. @Gingerbread
Comment: alright it's fine
Comment: @Kavi Rama Murthy, it can be evaluated.
Answer: $$\begin{align} \int_{1}^{51} f(x) dx &=\int_{1}^{3} f(x) dx+\int_{3}^{51} f(x) dx\\ &=\int_{0}^{2} f(x+1) dx+120\\&\ne 125\tag{$\because\int_{0}^{2}f(x)dx=5$}\end{align}$$
Comment: How do you know that $\int_0^{2}f(x+1)dx \neq 5$?
Comment: @Kavi Rama Murthy, because the graph will shift on left side by $1$ unit and so the area will change as function has period $4$.


Jquery consumindo Web Service Rest

Question: Gostaria de listar os ceps desse json, segue ele:
 [
  {
    "id": 1,
    "nome": "Hospital Da Mulher",
    "cep": "60508090"
  },
  {
    "id": 2,
    "nome": "Hospital Maria jose",
    "cep": "2"
  }
]
E esse é onde eu to chamando:
 $.getJSON('/MinhaDoenca/rest/hospital/get',
                    function(data) {

                        alert("O cep é:  " + data.cep);

                    });

Gostaria que listassem todos os ceps do meu json, como devo prosseguir?
Answer: Uma solução feita com jquery usando o $.each para percorrer o objeto.
Exemplo:

var dados = [{
  "id": 1,
  "nome": "Hospital Da Mulher",
  "cep": "60508090"
}, {
  "id": 2,
  "nome": "Hospital Maria jose",
  "cep": "2"
}];

$.each(dados, function(key, val) {
  alert('id=' + val.id + ' nome=' + val.nome + ' cep=' + val.cep);
});

Answer: Você deve percorrer os itens do array pegando cada cep dos objetos. Segue:
for( var index in data ) {

  alert( data[ index ].cep );

}

Jquery consumindo Web Service Rest


funcao usando char e vetor em c

Question: Boa noite, estou enfrentando um problema.
estou tentando fazer o preenchimento de um vetor em C dessa forma.
int a[5];
void lerValor(char grupo, int posicao, int valor) {
    grupo[posicao] = valor;
    printf("%i", grupo[posicao]);
}

estou passando como paramentro esse exemplo:
lerValor('a',1,10);
porque nao funciona dessa maneira? desde já agredeco a atencao de todos.
Na minha lógica ficaria: a[posica] = valor; que por sua vez ficaria: a[1]=10;
Comment: No código acima grupo não é um vetor.
Comment: mas a variavel grupo num é do tipo char? que recebe a, entao na minha lógica ficaria:

a[posica] = valor; que por sua vez ficaria: a[1]=10;
Comment: Se a variável é do tipo char então ela tem espaço para um único caractere. Note que char grupo e diferente de char grupo[].
Comment: Qual é o resultado obtido e qual é o resultado esperado?
Comment: ele retorna um erro: error: subscripted value is neither array nor pointer nor vector.

realmente ele informa que nao é um array, matriz e nem vetor, mas como resolver essa questao? preencher varios vetores usando uma funcao, sem usar if e switch.
Answer: Primeiro, a variável grupo precisa ser um vetor para poder utilizar o operador de colchetes []. Além disso deve ser um vetor de valores inteiros.
Segundo, se você quer passar o vetor a como parâmetro da função lerValor() deve utilizar o nome da variável sem aspas, ou seja, a ao invés de 'a'.
Assim, a definição da função fica da seguinte forma:
void lerValor (int grupo[], int posicao, int valor) {
    grupo[posicao] = valor;
    printf("%i", grupo[posicao]);
}

E a chamada da função, assim:
lerValor(a, 1, 10);

Comment: não é bem isso o que eu quero, no caso eu vou ter outros vetores: a[5], b[5]...
minha ideia era que essa funcao ficasse responsavel por preencher valores nesses vetores. da forma como voce apresentou estarei criando um outro vetor.

o que quero é passar para essa funcao o nome do meu vetor(a, b...) e ela preencher meu vetor já existente. sem usar if e switch.
Comment: Não sei se entendi direito, mas nesse caso, você pode passar o endereço do seu vetor no parâmetro da função, e ir caminhar com o pointer até a posição que foi passada pra função e atribuir o valor a essa posição de memória, assim o seu vetor original terá recebido aquele valor na posição especificada.
Comment: Como funcionária? Pode postar um código por favor?
Answer: São alguns problemas. O principal é que seu exemplo lerValor('a',1,10); não ajuda a entender o que você quer fazer.
1) A variável grupo precisa ser um array para inteiros. Se você pretende inicializar com um valor inteiro, não pode copiar um char.
2) Você precisa passar o tamanho do array que quer inicializar e não a posição. Se você quer atualizar apenas uma posição do array, basta usar o comando certo, não precisa de um método.
grupo[posicao] = valor;

Para  seu exemplo, bastaria:
a[1] = 10;

3) Se você quer que o método inicialize o array inteiro, precisa mudar os argumentos e o nome.
lerValor dá a impressão de que você quer recuperar o valor do array.
Neste caso, uma chamada de initArray(a,1,10) colocaria o valor "10" na posição 0 e na posição 1 do array "a".
    void initArray(int grupo[], int tam, int valor)
    {
            for(int i = 0; i < tam; i++)
            {
               grupo[i] = valor;
               printf("[%i]", grupo[i]);
            }
    }

4) Não sei o que você estaria tentando imprimir ali com o seu printf.
Comment: Na verdade o que a função do OP se resume em: `char grupo`, é o nome da variável do vetor a ser alterado, `int posicao`, que é a posição do vetor a ser modificada e `int valor`, que é o valor a ser colocado nessa posição. Ou seja, suponhamos que você tenha uma array de inteiros chamada `vet`. A função `lerValor('vet', 2, 10)` alteraria a posição 2 do vetor `vet` para o valor 10. O OP só não soube se expressar.
Comment: exatamente.  isso mesmo que eu quero

funcao usando char e vetor em c


Show that the mapping is one to one iff $|f(S)|=|S|$, and the two definitions for being onto are equivalent.

Question: Definition: $f(X)=${$f(x)|x\in X$}, "$|A|$"represents the number of elements in the set A.
In the title, $f:S\to T$, "$iff$" means "if and only if".$S$and $T$ are finite sets.
Two definitions for being onto:
1.If for every element $ t$ in $T$, there exists some $s\in S$, such that $f(s)=t$, then it's onto.
2.$f(S)=T$
Answer: Saying, about a function $f\colon S\to T$,

for every $t\in T$ there exists $s\in S$ such that $f(s)=t$

or

$f(S)=T$

is exactly the same, because, by definition,
$$
f(S)=\{t\in T: \text{there exists $s\in S$ such that $f(s)=t$}\}.
$$
Now, when $S$ is finite, saying $|f(S)|=|S|$ is equivalent to $f$ being one-to-one.
($\Leftarrow$) If $f$ is one-to-one, it defines a bijection $f'\colon S\to S$, so $|f(S)|=|S|$ by definition of having the same cardinality. (Note that this doesn't require $S$ is finite.)
($\Rightarrow$) Suppose $|f(S)|=|S|$ and that $f(s_1)=f(s_2)$, with $s_2\ne s_1$; set $S'=S\setminus\{s_2\}$; then $f(S')=f(S)$. Now, for every function $g\colon X\to Y$, $|g(X)|\le |X|$ (why?), so
$$
|S|=|f(S)|=|f(S')|\le|S'|=|S|-1
$$
which is absurd.
Comment: by definition: f(S) should be {f(s)|$s\in S$}
Comment: $S'=S\setminus\{s_2\}$, what do you mean by that? the notation is hard to follow
Answer: To show that the two definitions for being onto is equivalent:
1. If for $\forall t\in T$, $\exists s\in S|f(s)=t$, then $T\subseteq f(S)$, and for $\forall a\in f(S), a\in T$,so $f(S)\subseteq T$. Therefore $f(S)=T$
2. If $T=f(S)$, then for $\forall t\in T,t=f(s)$ for some $s\in S$.
To show that $f$ is one to one iff $|f(S)|=|S|$:
1.when  $f$ is one to one, for $\forall s\in S$, $f(s)$ is distinct, therefore there do not exist $f(s_1)=f(s_2)|s_1\neq s_2$. Thus if $|S|=n$, there are n distinct elements in $f(S)$, therefore$|f(S)|=|S|$.
2.If $|f(S)|=|S|,|S|=n$, assume that $\exists f(s_1)=f(s_2)|s_1\neq s_2$. Then for $n$ representations of elements in $f(S)$, some of them are equal, and therefore $|f(S)|<n=|S|$, a contradiciton. Therefore for $\forall s_1,s_2,f(s_1)\neq f(s_2)$, thus $f$ is one to one.
Answer: $f(S)=T\Leftrightarrow f\text{ is onto.}$ This is the very definition for "onto".
We'll show now that if $|f(S)=|S|$, then $f$ is one to one. This is obvious if $|S|=1$, so suppose $|S|\geq2$. If $|f(S)|=|S|=m$, and $f(x)=f(y)$ for some $x,y\in S$, consider the set $S_x=S-\{x\}$. It has $m-1$ elements. If $x\neq y$, $f(S_x)$ has $m$ elements, since it still contains the element $f(x)=f(y)$. But the image of a set of $m$ elements cannot have more than $m$ elements, hence we have a contradiction, so $x=y$ and we conclude that $f$ is one to one.
Suppose now that $f$ is one to one, and that $|f(S)|\neq |S|$. Since the image of a set cannot have more elements than this set, we have $|f(S)|<|S|$. WLOG, we can suppose that $S=\{1,\ldots,m\}$. For each $j\leq m$ consider the set $S_j=f(\{1,\ldots,j\})$. Let be $k$ the least integer such that $|f(S_k)|<k$ and $|f(S_{k-1})|=k-1$. Hence, $f(k)\in f(S_{k-1})$, so $f$ is not one to one, a contradiction.


How do I change jquery_update version for a custom theme?

Question: There are two options in jquery_update module's configuration: Jquery to be used in frontend theme, and Jquery to be used in admin themes. I set another theme to be used by a specific role (say, manager).
How do I change jquery_update version of that theme that is used by manager role.
Is it possible to do this with template.php, if yes, how so?
I already followed a patch here, but I am not sure if I should apply that old patch.
Answer: No need for a patch, jquery_update 7.x-3.0-alpha5 works great and it already includes functionality to specify jquery version per theme (as per this issue) on configuration page admin/config/development/jquery_update

For specifying a theme per role you can try any of the following modules role_theme_switcher Themes By Role (TBR)


How to limit a number of characteres in txt using PHP

Question: I would like a way to break the line when it gets to 360 characters in a txt file.
Example:
In my script my output

I'd like this output

My code to write in file
<code>$string = $data.'*'."\n";

$fp = fopen( 'registro.txt', 'a+' );
if( !$fp ){
  echo 'Erro inesperado, não foi possivel abrir o arquivo';
  exit;
}else{
   fwrite( $fp, $stringSEFIP."\n");
}
</code>
Comment: Possible duplicate of [PHP newline not working in text file](https://stackoverflow.com/questions/4858443/php-newline-not-working-in-text-file)
Comment: Split your string by 360 characters, add `\n` to each element then join the array. Write that to your file.
Comment: Yes, I do that, but when I write in txt file the information not write line by line. I like in this form:  line 1: info 1 \n line 2: info 2, but in my script the data in the same line like this info1 info 2 info 3.
Comment: If you are already doing that why won't you show us that PHP code then? You may want to use `\r\n` depending on your OS.
Comment: $teste  = substr($string,0,360);
Comment: In linux the data were formatted in the right way, when I ran this script in windows the formatation broke
Answer: Try something like this:
<code>$string = $data.'*'."\n";

$skip = 360;

$fp = fopen( 'registro.txt', 'a+' );
if( !$fp ){
  echo 'Erro inesperado, não foi possivel abrir o arquivo';
  exit;
}else{
    $pos = 0;
    while ($pos < strlen($str)) {
        fwrite( $fp, substr($stringSEFIP, $pos, $skip) . PHP_EOL);
        $pos += $skip;
    }
}
</code>


Why does a mixed design using R's aov() need the between subject factors specified more than once?

Question: An R cookbook http://www.cookbook-r.com/Statistical_analysis/ANOVA/ has an example of using aov() for mixed design ANOVAs.
I'll copy it here:
data <- read.table(header=T, con <- textConnection('
 subject sex   age before after
       1   F   old    9.5   7.1
       2   M   old   10.3  11.0
       3   M   old    7.5   5.8
       4   F   old   12.4   8.8
       5   M   old   10.2   8.6
       6   M   old   11.0   8.0
       7   M young    9.1   3.0
       8   F young    7.9   5.2
       9   F   old    6.6   3.4
      10   M young    7.7   4.0
      11   M young    9.4   5.3
      12   M   old   11.6  11.3
      13   M young    9.9   4.6
      14   F young    8.6   6.4
      15   F young   14.3  13.5
      16   F   old    9.2   4.7
      17   M young    9.8   5.1
      18   F   old    9.9   7.3
      19   F young   13.0   9.5
      20   M young   10.2   5.4
      21   M young    9.0   3.7
      22   F young    7.9   6.2
      23   M   old   10.1  10.0
      24   M young    9.0   1.7
      25   M young    8.6   2.9
      26   M young    9.4   3.2
      27   M young    9.7   4.7
      28   M young    9.3   4.9
      29   F young   10.7   9.8
      30   M   old    9.3   9.4
'))
close(con)

Then reshape it:
library(reshape2)

# Make sure subject column is a factor
data$subject <- factor(data$subject)

# Convert it to long format
data.long <- melt(data, id = c("subject","sex","age"), # keep these columns the same
              measure = c("before","after"),       # Put these two columns into a new column
              variable.name="time")                # Name of the new column

# subject sex   age   time value
#       1   F   old before   9.5
#       2   M   old before  10.3
#...

Now analyze using a mixed anova:
aov.after.age.time <- aov(value ~ age*time + Error(subject/time), data=data.long)
summary(aov.after.age.time)

But when there are more than two predictor variables, the R examples show that the between subject factors are added again after the error term:
#e.g., from R cookbook
#aov.bww <- aov(y ~ b1*b2*w1 + Error(subject/(w1)) + b1*b2, data=data.long)

# which would translate in our case as:
aov.bww <- aov(value ~ sex*age*time + Error(subject/time) + sex*age, data=data.long)
summary(aov.bww)

But why is b1*b2, or in our case sex*age, specified twice? It doesn't seem to make a difference when we remove them after the Error() term:
aov.bww2 <- aov(value ~ sex*age*time + Error(subject/time), data=data.long)
summary(aov.bww2)

Can anyone explain why the examples have those extra terms? The R manual just has this example, where the between factors are not specified twice:
# fm <- aov(yield ~ v + n*p*k + Error(farms/blocks), data=farm.data)

Edit:
I have checked the references from the R Cookbook and found other web sites also specify the terms twice in their mixed design examples. See here:
http://www.personality-project.org/R/r.anova.html
where they have the example:
aov.ex5 = aov.ex5 = aov(Recall ~ (Task*Valence*Gender*Dosage) +
Error(Subject/(Task*Valence)) + (Gender*Dosage), data.example5 )

and see here
http://www.statmethods.net/stats/anova.html
with their example:
# Two Within Factors W1 W2, Two Between Factors B1 B2
fit <- aov(y ~ (W1*W2*B1*B2) + Error(Subject/(W1*W2)) + (B1*B2),
data=mydataframe)

Which is presumably where the cookbook got their info from.
Comment: Minor fix that may change some results: `subject` needs to be made a factor in `data.long`, not `data`: `data.long$subject <- factor(data.long$subject)`
Comment: A better fix would simply be to make `subject` a factor in `data` before melting.  Then `subject` will automatically be a factor in `data.long`.
Answer: No, it is not necessary to specify those terms twice.  I suspect it was either a copy/paste typo, or that the author wanted to denote separately the terms that use the subject term for the denominator in the F test and the terms that use the subject/time term.  As you note, when the code is run, however, the terms are absolutely unnecessary.
In this case, also notice that the /time part of the Error call is unnecessary; the subject:time interaction is the lowest level, which is always included in the model.  So using Error(subject) and Error(subject/time) give the same result; the only difference is that in the output, that level of results is called "Within" for the first and is called "subject:time" for the second.
Comment: Good to have it checked by an expert, thanks! Strange that a couple of web sites have this in their examples.
Comment: (+1) I am not sure I understand your last point about `Error(subject)` and `Error(subject/time)` being the same. Are they always equivalent? I have posted [a related question](http://stats.stackexchange.com/questions/232109) (and came across this one while researching this topic) and would greatly appreciate your input over there. Thanks.
Comment: They are equivalent if there is one data point for each subject/time combination, because if so, adding Error(subject/time) adds nothing to the model, it just names the lowest level of variation "subject:time" variation instead of "Within" subject variation. Your other question is longer than I have time to look at right now, I see you've found a couple of my answers already, plus the more recent very excellent answer by Robert Long on crossed vs. nested.


Puppet vcsrepo git checkout branch

Question: I am using puppet to clone a repo on an agent node. My site.pp contains
node foobar{
   vcsrepo{"home/user1/gitrepo1":
     provider=>git,
     source=>"https://github.com/foobar/foo.git",
     revision => "remotes/origin/bar",
   }
}

On the agent when I do git branch after the catalog has been applied, it shows
*(no branch)
master

When I do git branch -a it shows
master
remotes/origin/HEAD -> origin/master
remotes/origin/bar

I want to be able to checkout the remote "bar" branch. Only specifying the revision=>bar gives the following error. The documentation is not too clear on this either.
err: /Stage[main]//Node[foobar]/Vcsrepo[/home/user1/gitrepo1]: Could not evaluate: Execution of '/usr/bin/git rev-parse bar' returned 128: fatal: ambiguous argument 'bar': unknown revision or path not in the working tree.
Use '--' to separate paths from revisions
bar

EDIT: There was a typo in what I had initially posted. I had in fact specified revision=>bar in my site.pp
Thank you.
Comment: What happens if you clone the repository on the command line and manually run `git checkout bar`?
Comment: This works fine. It just says switched to new branch "bar". I was wondering if there was way to this using vcsrepo only. It seems it would be best to clone the repo using vcsrepo, and then do exec{'checkout': command=>"git checkout -b bar origin/bar" } to checkout the branch.
Answer: The branch can be specified with 'revision' (can be a commit SHA, tag or branch name):
vcsrepo { "/path/to/repo":
    ensure => present,
    provider => git,
    source => 'git://example.com/repo.git',
    revision => '0c466b8a5a45f6cd7de82c08df2fb4ce1e920a31'
}

vcsrepo { "/path/to/repo":
    ensure => present,
    provider => git,
    source => 'git://example.com/repo.git',
    revision => '1.1.2rc1'
}

vcsrepo { "/path/to/repo":
    ensure => present,
    provider => git,
    source => 'git://example.com/repo.git',
    revision => 'development'
}

https://github.com/puppetlabs/puppetlabs-vcsrepo/blob/master/README.GIT.markdown
Comment: I had a typo in my initial posting. I was in fact using the revision attribute. In my case the 'development' branch is a remote branch, and I want to do a checkout. Doing a revision=>'foo' is giving me an error ambiguous argument 'foo': unknown revision or path not in the working tree.
Comment: What happens if you change 'revision => "remotes/origin/bar"' to 'revision => "bar"'?
Comment: err: /Stage[main]//Node[foobar]/Vcsrepo[/home/user1/gitrepo1]: Could not evaluate: Execution of '/usr/bin/git rev-parse savi-1.1' returned 128: fatal: ambiguous argument 'bar': unknown revision or path not in the working tree.
Use '--' to separate paths from revisions
bar
Comment: It seems it would be best to clone the repo using vcsrepo, and then do exec{'checkout': command=>"git checkout -b bar origin/bar" } to checkout the branch.

Puppet vcsrepo git checkout branch


Finding eigenvalues of a matrix using λ

Question: $$
\begin{pmatrix}
-2 &  0  & 1 \\
-6  &  -2 & 0 \\
19 &  5  & -4 \\
\end{pmatrix}
$$
The main I have is if I'm doing my algebra right because the back of my book has λ = -8 (Sorry I misread back of the book) I still don't know how they got one answer.
I end up getting:
(-2 - λ)[(-2 - λ)(-4 - λ)] + 1[- 30 -( 19 (-2 - λ))] = 0
after simplifying:
λ^3 + 8λ^2 + λ - 8 = 0
Factoring:
(λ + 1)(λ - 1)(λ + 8)
What am I doing wrong? I see what I did wrong I forgot the negative when I added -16 to 8.
Answer: I got -8, $\pm i$ with Mathematica.  The characteristic polynomial is
$-8 - x - 8 x^2 - x^3$
(or you could do all positive coefficients, but it just means you messed up the sign of the -8)  By the way, I don't think $\lambda + 8$ is a factor of your polynomial, so you made 2 different mistakes.
If you throw away the negative sign and factor out an x+8, you are left with $x^2 + 1$.
By the way, if the book got 8 and 2:
1. The book is wrong, or
2. You typed it in wrong, or
3. I typed it in wrong but I checked a few times so I don't think so.
Comment: Sorry I the book got -8 but I'm still not getting the right answer
Comment: Like I said, it looks like you were right at

λ^3 + 8λ^2 + λ - 8 = 0

except for the -8, which should be +8.  So, look at all the constant terms in the previous step.  There is -2*-2*-4-30-19*-2=-16-30+38=-8.  And, then, you moved everything to the other side of the equation (I can tell because you have $+\lambda^3$, for example, so the -8 becomes +8 when you do this.  So, maybe your problem was just that you forgot to change the sign when you moved it to the other side.

Finding eigenvalues of a matrix using λ


Validar CPF usando WPF

Question: Como posso verificar se um número de CPF é valido usando o WPF em C#?
É preciso criar alguma classe?
Comment: O que você já tentou? Fica muito vago a pergunta assim.
Comment: Relacionado: http://pt.stackoverflow.com/q/11470/101
Answer:
Como posso verificar se um número de CPF é valido usando o WPF em C#? [...]

Primeiramente, usar ou não WPF não faz diferença nenhuma. A linguagem é C# e é isso que importa. Para saber se um CPF é válido, existe um algoritmo que pode ser facilmente encontrado na internet.
Perceba que o algoritmo apenas pode verificar se um CPF é válido segundo a regras estabelecidas pelo país e não se ele é um CPF ativo ou não.

[...] É preciso criar alguma classe?

Depende da sua organização, tanto faz. Eu tenho uma classe Valida que uso para fazer algumas validações num dos meus projetos.
Abaixo o código que uso para validar CPF's, o algoritmo foi retirado daqui.
Talvez sejam necessárias algumas modificações, mas a base é essa e ele está completamente funcional dessa maneira.
Veja que o algoritmo pede um inteiro como parâmetro, se você salva o CPF com pontos e traço, é necessário removê-los e converter para inteiro antes de tentar validar (ou adaptar a função para receber no formato que você salva).
using static System.Convert;

public static class Valida
{
    public static bool Cpf(int cpf)
    {
        string strCpf = cpf.ToString().PadLeft(11, '0');

        if (strCpf.All(x => x == strCpf[0]))
            return false;

        var listCpf = strCpf.Select(num => ToInt32(num.ToString())).ToList();

        if (listCpf[9] != Mod11Cpf(listCpf, 10))
            return false;

        if (listCpf[10] != Mod11Cpf(listCpf, 11))
            return false;

        return true;
    }

    internal static int Mod11Cpf(List<int> elementos, int @base)
    {
        int soma = 0;
        for (int i = 0; i < (@base - 1); i++)
            soma += (@base - i) * elementos[i];

        int dv1, resto = soma % 11;

        if (resto < 2)
            dv1 = 0;
        else
            dv1 = 11 - resto;

        return dv1;
    }
}

Validar CPF usando WPF


$\mathbb{Z}\bigl[1+\sqrt{-7}\bigr]$ is not Euclidean

Question: The similarly looking ring $\mathbb{Z}\Bigl[\dfrac{1 + \sqrt{-7}}{2}\Bigr]$ actually is Euclidean (see here).

Now I want to show that $\mathbb{Z}\bigl[1 + \sqrt{-7}\bigr]$ is not Euclidean.

Proof: First we note that $\mathbb{Z}\bigl[1 + \sqrt{-7}\bigr] = \mathbb{Z}\bigl[\sqrt{-7}\bigr]$. Assume that $1 + \sqrt{-7}$ is reducible, that means there exist $k, l, m, n \in \mathbb{Z}$ so that $$\bigl(k + l \sqrt{-7}\bigr)\bigl(m + n \sqrt{-7}\bigr) = k m - 7 l n + (k n + l m)\sqrt{-7} = 1 + \sqrt{-7}.$$ Do
the equations
$$k m - 7 l n = 1 \\
k n +   l m = 1$$ have a solution?
In the case $k m \leq 0 \land l n \geq 0$ there is obviously no solution. The case $k m \geq 0 \land l n \leq 0$ only has the solutions $k = m = \pm 1$ and $(l = 0 \land n = k) \lor (l = 1 \land n = k)$, which is just a unit times an associated element of $1 + \sqrt{-7}$.
In the other two cases (that is $k m$ and $l n$ have the same sign) $k n$ and $l m$ must have the same sign, so the only two solution of the second equation would be $k n = 1 \land l m = 0$ or $k n = 0 \land l m = 1$, which again gives us just a unit times an associated element. So $1 + \sqrt{-7}$ is irreducible.
Since $\bigl(1 + \sqrt{-7}\bigr)\bigl(1 - \sqrt{-7}\bigr) = 8 = 2^3$ the ring $\mathbb{Z}\bigl[1+\sqrt{-7}\bigr]$ is not even an unique factorization domain, so it can't be Euclidean. $\square$
Everything ok?
The irreducibility proof of $1 + \sqrt{-7}$ was pretty cumbersome... perhaps using the norm is faster?
Thank you!
Answer: This can be shown without having to deal directly with any kind of factorization. A Euclidean domain is a UFD, and every UFD is integrally closed, which means something like the rational roots theorem holds: an integral domain $R$ with fraction field $K$ is called integrally closed if any root in $K$ of a monic polynomial in $R[x]$ lies in $R$.
The ring $\mathbf Z[\sqrt{-7}]$ is not integrally closed because $x^2 - x + 2$ is monic with coefficients in $\mathbf Z[\sqrt{-7}]$ but it has a root in the fraction field $\mathbf Q(\sqrt{-7})$ that is not in $\mathbf Z[\sqrt{-7}]$. The same argument shows $\mathbf Z[\sqrt{d}]$ is not integrally closed if $d$ is any integer that is not a perfect square and $d \equiv 1 \bmod 4$: the polynomial $x^2 - x + (1-d)/4$ is monic with coefficients in $\mathbf Z[\sqrt{d}]$ and has root $(1+\sqrt{d})/2$, which is in the fraction field $\mathbf Q(\sqrt{d})$ but is not in $\mathbf Z[\sqrt{d}]$. Therefore $\mathbf Z[\sqrt{d}]$ for such $d$ is not Euclidean or a UFD.
Answer: No,you are wrong  to prove this just show any one property of Euclidean domain is violated.Here $2|(1+\sqrt7i)(1-\sqrt 7i)$ but $2$ does not divide either $(1+\sqrt7i)$ or $(1-\sqrt 7i)$ hence $2$ is not prime but $2$ is irreducible as
$2=(a+b\sqrt7i)(c+d\sqrt 7i)$
Taking conjugate and multiplying
$\implies 4=(a^2+b^2)(c^2+d^2)$
either $(a^2+b^2)=1or (c^2+d^2)=1$
i.e either $(a+b\sqrt7i)$ is a unit or $(c+d\sqrt 7i)$ is so .Thus $2$ is irreducible but not prime which cant happen in a ED


Dynamically update menu contents with jQuery

Question: I have a drop-down menu that I would like to dynamically update using jQuery. Is this possible, or will I need something like PHP to pull in the data from the backend?
Answer: It is possible with a mix of AJAX and jQuery
HTML:
<select name="foo" id="foo">
   <option value="1">one</option>
   <option value="2">two</option>
   <option value="3">three</option>
   <option value="4">four</option>
</select>

JavaScript/jQuery:
$.ajax({
  url: "resource.php",
  success: function(d){
    $('#foo').append('<option value="' + d.value + '">' + d.description + '</option>');
  }
});

Comment: Okay, so if I stored the info to update as JSON for example, and then pulled this through with AJAX?
Comment: Correct, note that if the data that your going to get from the server is minimal you could store that in the HTML as an object literal on the load of the page - saving an `AJAX` request to the server...


How to find an Integrable upper bound for a sequence of functions?

Question: I am trying to use the Lebesgue dominated convergence theorem. I need to show $|f_n|$ has an integrable upper bound on $[1,a]$ for some $a>0$. How does one get rid of the $n$'s so that we obtain the Integrable upper bound function independent of $n$?
$$f_n(x)= \frac{n^2+n\sin(nx)}{(n+1)^2x+ n\cos(nx)}$$
Comment: Think about the worst case scenarios for $\sin$ and $\cos$.  The numerator cannot be any larger than $n^2+n$, and the denominator cannot be any less than $(n+1)^2 - n$ (assuming that $a > 1$).  Therefore...
Answer: For all $x \in [1,a]$ we have
$$\frac{n^2+n\sin(nx)}{(n+1)^2x + n\cos(nx)} \leq \frac{n^2 + n}{(n+1)^2 - n}.$$
Now since $\frac{n^2 + n}{(n+1)^2 - n}$ converges, it must be a bounded sequence and therefore there must exist a $K$, such that $\frac{n^2 + n}{(n+1)^2 - n} \leq K$ for all $n\in \mathbb{N}$. The constant function $g(x) = K$ is integrable on $[1,a]$.
Comment: More concretely:  $$\frac{n^2+n}{(n+1)^2 - n} = \frac{n^2 + n}{n^2 + n + 1} \le \frac{n^2 + n}{n^2+n} = 1. $$  This bound is sharp, too, as the fraction tends to $1$ as $n \to \infty$.


Package PyGObject Python 3 program with pynsist?

Question: I would like to package a Python3-PyGObject program with pynsist. The repository has an example for PyGTK and it made me think that it shouldn't be too hard to change the example.
The example can be found here:

https://github.com/takluyver/pynsist/tree/master/examples/pygtk

In this file (https://github.com/takluyver/pynsist/blob/master/examples/pygtk/grab_files.sh) I think one just has to grab the files targeting GTK 3 (http://www.gtk.org/download/win32.php):
wget -O gtkbundle.zip http://win32builder.gnome.org/gtk+-bundle_3.6.4-20130921_win32.zip
wget -O pygobject.exe http://sourceforge.net/projects/pygobjectwin32/files/pygi-aio-3.14.0_rev12-setup.exe/download
wget -O pycairo.zip http://ftp.gnome.org/pub/gnome/binaries/win32/dependencies/cairo_1.10.2-2_win32.zip

I am not sure what to do with the fourth line, because it is my current understanding that those bindings should already be inside the gtk or pygobject bundle:
 wget -O pygtk.exe http://ftp.gnome.org/pub/GNOME/binaries/win32/pygtk/2.24/pygtk-2.24.0.win32-py2.7.exe

I then tried to customize this file (https://github.com/takluyver/pynsist/blob/master/examples/pygtk/installer.cfg) to include (use gi instead of gi.repository):
[Include]
packages=gi

This resulting error is:
raise ExtensionModuleMismatch(extensionmod_errmsg % ('Windows', path))
nsist.copymodules.ExtensionModuleMismatch: Found an extension module that will not be usable on Windows:
/usr/lib/python3/dist-packages/gi/_gi.cpython-34m-x86_64-linux-gnu.so
Put Windows packages in pynsist_pkgs/ to avoid this.
Does anyone know what the correct approach for a program (like e.g. one of these: https://python-gtk-3-tutorial.readthedocs.org) would be?
Edit 1
After packaging and installing the program on Windows, starting the test-program produces the following traceback:
Traceback (most recent call last):
  File "C:\Program Files (x86)\hellogtk\hellogtk.launch.pyw", line 31, in <module>
    from gtk_test import main
  File "C:\Program Files (x86)\hellogtk\pkgs\gtk_test.py", line 3, in <module>
    from gi.repository import Gtk
  File "C:\Program Files (x86)\hellogtk\pkgs\gi\__init__.py", line 42, in <module>
    from . import _gi
ImportError: DLL load failed: The specified module could not be found.

It is odd that this ImportError occurs because there is a _gi.pyd-file in the same directory (gi) as the __init__.py
This is the current layout:
 - directory
 |- pynsist_pkgs
 |-- cairo
 |--- _cairo.pyd
 |--- __init__.py
 |-- gi
 |--- _gobject
 |--- overrides
 |--- repository
 |--- __init__.py
 |--- _gi.pyd
 |--- ...
 |-- gtk
 |--- bin
 |--- etc
 |--- lib
 |--- manifest
 |--- share
 |-- dbus
 |--- __init__.py
 |--- ...
 |-- gnome
 |--- ...
 |-- pygtkcompat
 |--- ...
 |-- _dbus_bindings.pyd
 |-- _dbus_glib_bindings.pyd
 |-- ...
 |- gtk_test.py
 |- grab_files.sh
 |- installer.cfg
 |- gtk_preamble.py

And I used the py-3.4-64 folder of the pygobject bindings. The Linux I am creating the package on is 64 bit, and the Windows I am running the program is also 64 bit.
Edit 2:
Using Dependency-Walker I can see that 2 DLLs are missing: GPSVC.DLL and IESHIMS.DLL.
Edit 3:
I found those 2 DLLs on the system and copied them in different directories of the test-program, but it didn't work.
Edit 4:
This might be useful for the import-error:

import gtk/glib produces ImportError: DLL load failed
Comment: Yep. The idea is that you run `./grab-files.sh` beforehand, and it puts the Windows versions of those libraries in `pynsist_pkgs`, where they'll be used instead of your Linux libraries. I've worked out that that pygi installer can be unpacked using `7z` (`apt-get install p7zip-full` on an Ubuntu system). That unpacks 1.5 GB in several directories (!) - it looks like you'll need to work out which bits you need and then do a second round of unpacking archives to get the actual files.
Comment: If you manage to install and try to run the application, and it crashes, it should be writing the traceback to a log file in `%APPDATA%`. On a Windows 7 system, that's typically `C:\Users\{username}\AppData\Roaming`. That should help tell you what's going wrong. Or you can start a command prompt, cd to the installed directory in Program Files and run `py MyApp.launch.pyw`.
Comment: Try putting just `gi` in packages - it's supposed to be top-level importable names. I'm downloading the pygobject bundle to see if that's the right thing.
Comment: It appears that `pygi-aio-3.14.0_rev12-setup.exe` is not a self executing zip file like the pygtk installer I used before, so calling unzip on it won't work. I'm not sure how best to extract the files from it.
Comment: @ThomasK: Just using `gi`seems to be the right approach. Now I get a more meaningful error message: `raise ExtensionModuleMismatch(extensionmod_errmsg % ('Windows', path))
nsist.copymodules.ExtensionModuleMismatch: Found an extension module that will not be usable on Windows:
/usr/lib/python3/dist-packages/gi/_gi.cpython-34m-x86_64-linux-gnu.so
Put Windows packages in pynsist_pkgs/ to avoid this.`
Comment: @ThomasK: I tried all kinds of combinations but could only get the installer working. The resulting program does not show the window. I can only get the PyGTK example to work properly. It is a little hard for me to grasp what is going wrong.
Comment: That error message ('DLL load failed') means it's failing to find another DLL that that one (.pyd files are Python DLLs) requires. [Dependency walker](http://www.dependencywalker.com/) might help you figure it out.
Comment: (BTW, thanks for your patience working this out. Pynsist is quite new, and you're probably the first person to try it with the new pygobject interface)
Comment: @ThomasK: I found 2 missing dll's using dw. Still have to read up why they are missing. It is actually a lot of fun to figure things out, but packaging is somehow very difficult for me. I should have taken more programming courses in college :)
Comment: TBH, I think that packaging pygobject apps for Windows is difficult for anyone. Did you find the DLLs you need? [This example](https://wiki.gnome.org/Projects/PyGObject?action=AttachFile&do=view⌖=setup.py) of a script to freeze the app with cx_Freeze might be informative.
Comment: @ThomasK: I added the missing DLLs to my question, but I am still reading what they are about. This question seems to be similar: http://stackoverflow.com/questions/1877098/nunit-missing-gpsvc-dll-on-windows-7-64
Comment: Aha. From that question, it sounds like a 64/32 bit distinction may be relevant. If your test system is 64-bit, maybe it's worth packaging with 64-bit Python and pygobject, at least to get the kinks worked out.
Comment: @ThomasK: I tried but it didn't change the problems and DW is till looking for those 2 packages.
Comment: If you copy those DLLs into the same folder as `_gi.pyd`, does it find them?
Comment: @ThomasK: Still not luck. The DLLs still show up as missing, and from different discussion I found, it might also be a false warning by dependency walker? In any case the traceback now complains about non-valid Win32 application.
Comment: I think that error (about a non-valid Win32 application) can mean that you've got 64-bit and 32-bit binaries mixed. But there may also be other causes for it. Possibly the best way forwards would be to install Python and pygobject on a Windows system, make sure it works and find out how it fits together.
Comment: @ThomasK: I installed the PyGobject bundle for Python 3.4 64 bit and that at least works. I can start Gedit and Glade. The bundle also includes GTK I think, but I am not sure about Cairo. I will see if I can get it working with that bundle as my only requirment.
Comment: @ThomasK: I now filed a bug at https://bugzilla.gnome.org/show_bug.cgi?id=745818
Comment: Now that you've [worked this out](https://github.com/takluyver/pynsist/tree/master/examples/pygi_mpl_numpy), do you want to answer your own question, so future people reading this can quickly see the result?
Comment: Was a little busy this week catching up from the flu. Answer is done, and thank you again for very much helping out along the way!
Comment: Thanks! Sorry to hear you were ill; I hope you're fully recovered now.
Answer: I worked together with Thomas K, the author of pynsist, to solve this. And I do want to advertise that it is a great tool, with very good support, and it makes packaging orders of magnitudes easier in my opinion.
There were a number of mistakes in my approach (see question), so it might be easier to just describe the correct approach:
Download dependencies
The only dependency needed for a program that only imports:
 from gi.repository import Gtk

is the most recent pygi-aio (currently pygi-aio-3.14) bundle that can be downloaded here (The example in the pynsist-repository has a download script, but i might need to be updated for newer releases):

https://sourceforge.net/projects/pygobjectwin32/files/

Extract dependencies
The PyGObject/PyGI example that has now been merged into the pynsist-repository, comes with a script that extracts the necessary dependencies from the bundle (See: https://github.com/takluyver/pynsist/tree/master/examples/pygi_mpl_numpy).
Most importantly it extracts the contents of the bindings zip file (Modify the script for the targeted Python version and bitness) and copies them into the pynsist_pkgs folder:
  - cairo
  - dbus
  - gi
  - gnome
  - pygtkcompat

Then it extracts and copies the subdependencies into the pynsist_pkgs/gnome/ folder. As lazka pointed out, the minimum requirements for a typical minimal Gtk-program are (each library has a pygi/noarch and pygi/[TargetedArchitecture] zip file):
 - ATK
 - Base
 - Gdk
 - GDKPixbuf
 - GTK
 - JPEG
 - Pango
 - WebP
 - TIFF

Build the installer
The installer was then build in my case using:
 python3 -m nsist installer.cfg

The installer.cfg is also in the repositories example folder. It only requires gnome to be listed (The subdependecies in the gnome folder behave as one unit).
Note about the pygi-aio bundle
When the pygi-aio is installed on a Windows-machine, the installer performs some post-installation compiling steps. This might become an issue if you are using this approach, because it only extracts the dependencies. In some cases you might need to run an exe file (comes with the bundle) and copy the compiled files back into your build directory. I describe the only problem I had here:

https://github.com/tobias47n9e/innsbruck-stereographic/issues/1

And there is a bug report with more information here:

https://sourceforge.net/p/pygobjectwin32/tickets/12/

Working example
You can get the example here:

https://github.com/takluyver/pynsist/tree/master/examples/pygi_mpl_numpy


What are the new ways to pass functions as template arguments in C++11?

Question: In the question Function passed as template argument, it was asked and explained that there are two traditional ways of passing a function as a template argument in C++, they're:

Declaring the function as a "functor" (e.g. an object with an overridden () operator). But it requires modifying the target function first.
Using function pointer as the parameter, and taking the address of the function with the & operator to use the template. But this can possibly inhibit compiler optimization, especially inlining, since the compiler may be unable to figure out the target of the naked pointer.

I have read and conceptually understood both methods. However, in a comment by user pfalcon under the answer, it was claimed that:

Fast forward to few years later, situation with using functions as template arguments much improved in C++11. You no longer bound to use Javaisms like functor classes, and can use for example static inline functions as template arguments directly. Still far cry comparing to Lisp macros of 1970s, but C++11 definitely has good progress over the years.

But no explanation or example is given. What are the supposedly "much improved" ways of doing that in C++11 that pfalcon was referring to? I tried to search "function as template argument C++11" but I didn't see any usable result.
Comment: See : https://en.cppreference.com/w/cpp/17 and lookup the templates section and lambdas
Comment: C++11 didn't so much change mechanisms to pass functions - it introduced new/extended ways to create function objects, such as lambdas (a shorthand to define a function object [aka functor] which is [if no data is captured] convertible to a function pointer), parameter packs (support templates with variable arguments).  It also extended the standard library with means to invoke functions (e.g. `std::invoke`) and with wrappers for functions and their arguments (e.g. `std::function`, reference wrappers) which deprecating some older binders and adaptors (which were later removed from C++17).
Comment: related https://stackoverflow.com/questions/10876930/should-one-never-use-static-inline-function
Comment: It actually sound like my comment from Quora or someone\somebot repeating me out of context. It was related lambdas and their further evolution, generic lambdas
Answer: Up until C++11, it was not possible to use functions internal linkage as arguments for NTTPs (non-type template parameters). For example, compiling the following code with -std=c++98 fails:
template <void(*fun)()>
void call() {
    fun();
}

// removing static is necessary in C++98
static void callback() {}

void foo() {
    call<callback>();
}

<source>:9:19: error: 'callback' is not a valid template argument
      |                for type 'void > (*)()' because 'void callback()'
      |                does not have external linkage
      |
    9 |     call<callback>();
      |     ~~~~~~~~~~~~~~^~

This is due to this section:

14.3.2 Template non-type arguments
1 A template-argument for a non-type, non-template template-parameter shall be one of:

[...]
the name of an object or function with external linkage, including function templates and function template-ids but excluding non-static class members, expressed as id-expression; or
[...]

- [temp.arg.nontype] §1
This restriction was lifted in C++11, allowing you to use functions with internal linkage for NTTPs as well. Before, callback would require external linkage, which is problematic if this code all written in a source file, because other source files containing their own callback would conflict with our callback.
In C++11, you are still not allowed to use lambda expressions as template arguments, and creating your own callable types is more verbose, so the above code is as concise as it gets.
Comment: @CloudCho it means that if there is another source file which also defines a `callback` with external linkage, you can have conflicting definitions and get linker errors. If this code is all written in a source file, you also have no way of controlling what other source files define, contrary to using headers to exchange some information between them.
Comment: Would you elaborate "which is problematic if this code all written in a source file"?


Device selection on Apple Pay In-App provisioning

Question: I work in a fintech company that offers support to Apple Pay in our cards, i.e. our users have the option add their cards to Apple Pay using our app (in-app provisioning). Our company already got the proper In-App provisioning entitlements from Apple and the entire in-app provisioning process is working as expected.
When an user taps on the button "Add to Apple Wallet" in our app to provision his card, we call the following code below:
let config = PKAddPaymentPassRequestConfiguration()
config.cardholderName = "\(firstName) \(lastName)"
config.localizedDescription = "MyApp Card"
config.primaryAccountSuffix = String(cardSuffix)
config.paymentNetwork = .visa

// Present the Apple Pay ViewController
let controller = PKAddPaymentPassViewController(requestConfiguration: config, delegate: self)
UIApplication.shared.delegate?.window??.rootViewController?.present(controller!, animated: true)

If the user has an Apple Watch paired, he is greeted with a screen asking him to select on which device he wants to add the card: on his iPhone or on the Apple Watch (please see the screenshot attached). After the user selects the device, the provisioning process continues successfully as expected.
However, if the user taps on the "Add to Apple Wallet" button and he already has the card added to one of the devices (the Apple Watch, for example), then the code above is called again, but he is once again greeted with the same screen asking him to select on which devices he wants to add the card, on his iPhone or on his Apple Watch, even though the card is already added on the Apple Watch.
The way I understand it, since the card is already added on the Apple Watch, only iPhone should appear as a valid option to have the card added.
Is there anything else that I need to do in the code above to make sure only the available devices (I mean, only the devices that don't have the card added on Apple Pay yet) are listed in the device selection?
Answer: I found the answer to this so I'm answering my own question:
After you create the PKAddPaymentPassRequestConfiguration object you need to set the field primaryAccountIdentifier with an unique identifier for the customer's bank account (you will probably get this information from the bank).
If you look at the code that I posted in my question, you will notice that I set many fields in the PKAddPaymentPassRequestConfiguration object, but not the primaryAccountIdentifier. That's why it was not working for me.
Here is the correct code, with the primaryAccountIdentifier added in the end:
let config = PKAddPaymentPassRequestConfiguration()
config.cardholderName = "\(firstName) \(lastName)"
config.localizedDescription = "MyApp Card"
config.primaryAccountSuffix = String(cardSuffix)
config.paymentNetwork = .visa
config.primaryAccountIdentifier = "some unique identifier"

With this update after you add a device to Apple Pay, it will no longer appear as a provision option when you want to add a second device with the same account.


Basic problem on topology $( James Dugundji)$

Question: Consider $(X, \tau)$ be a topological space . Then

$Fr[Fr\{Fr(A) \}] = Fr[Fr(A)]$, where $Fr(A) =\overline A \cap \overline{A^c}$ is the frontier of the set $A$
Assume that $Fr(A) \cap Fr(B) = \phi$. Then $ (A \cup B)^{\circ}= A^{\circ} \cup B^{\circ}$ and $Fr(A \cap B) = [\overline A \cap Fr(B)] \cup [\overline B \cap Fr(A)]$
Assume that $\mathfrak B$ be a subbasis for $X$ and $D \subset X$ such that $U \cap D \neq \phi $ for each $U \in \mathfrak B$. Does this imply $D$ is dense in $X$

I have tried

we know that $Fr(A) =\overline A \cap \overline{A^c}$

$\therefore Fr \{Fr(A)\} =\overline{ \overline A \cap \overline{A^c}} \cap \overline {(\overline A \cap \overline{A^c})^c} =  \overline A \cap \overline{A^c} \cap (\overline A^c \cup \overline {A^c}^c) $
Further how to proceed

I can easily  prove that $A^{\circ} \cup B^{\circ} \subseteq (A \cup B)^{\circ}$. Please give me hint of its converse  and $Fr(A \cap B) = [\overline A \cap Fr(B)] \cup [\overline B \cap Fr(A)]$
I think $D$ may not be dense. Please give me counter example.

Any help would be appreciated. Thank you
Answer: Some HINTS:
$\newcommand{\cl}{\operatorname{cl}}\newcommand{\fr}{\operatorname{Fr}}\newcommand{\int}{\operatorname{int}}$You know that $\fr A$ is closed. Suppose that $U\subseteq\fr(\fr A)$ is open. Then $U\subseteq\cl(\fr A)=\fr A$, so $U\cap(X\setminus\fr A)=\varnothing$, and therefore $U\cap\cl(X\setminus\fr A)=\varnothing$. But $U\subseteq\cl(X\setminus\fr A)$, so $U=\varnothing$. Thus, $\fr(\fr A)$ is nowhere dense. To finish the first problem, show that if $C$ is a nowhere dense closed set, then $\fr C=C$.
For the first part of the second question suppose that $x\notin(\int A)\cup\int B$. Then $x\notin\int A$, so $x\in\cl(X\setminus A)$, and $x\notin\int B$, $x\in\cl(X\setminus B)$. Now show that if $x\in\int(A\cup B)$, then $x\in\cl A$ and $x\in\cl B$. Conclude that $x\in(\fr A)\cap\fr B$ to get a contradiction.
Note that if $(\fr A)\cap\fr B=\varnothing$, then $\big(\fr(X\setminus A)\big)\cap\fr(X\setminus B)=\varnothing$, so the first part of the second question implies that
$$\begin{align*}
X\setminus\big(\cl(A\cap B)\big)&=\int\big(X\setminus(A\cap B)\big)\\
&=\int\big((X\setminus A)\cup(X\setminus B)\big)\\
&=\big(\int(X\setminus A)\big)\cup\int(X\setminus B)\\
&=(X\setminus\cl A)\cup(X\setminus\cl B)\\
&=X\setminus\big((\cl A)\cap\cl B\big)\;,
\end{align*}$$
and hence that $\cl(A\cap B)=(\cl A)\cap\cl B$. Now apply this to the second part of the second question
$$\begin{align*}
\cl(A\cap B)\cap\cl\big(X\setminus(A\cap B)\big)&=(\cl A)\cap(\cl B)\cap\cl\big((X\setminus A)\cup(X\setminus B)\big)\\
&=(\cl A)\cap(\cl B)\cap\big(\cl(X\setminus A)\cup\cl(X\setminus B)\big)\\
&=\ldots
\end{align*}$$
Your conjecture for the third question is correct: $D$ need not be dense in $X$. Let
$$\mathfrak{B}=\{(\leftarrow,a):a\in\Bbb R\}\cup\{(a,\to):a\in\Bbb R\}\;,$$
the set of all open rays in $\Bbb R$. Verify that $\mathfrak{B}$ is a subbase for the usual topology on $\Bbb R$. Then find a set $D\subseteq\Bbb R$ such that $D\cap U\ne\varnothing$ for each $U\in\mathfrak{B}$, but $D$ is not dense in $\Bbb R$. (It's possible to choose $D$ to be a countable, closed, discrete set.)


How to Specify POST with JSON body in Swagger Editor

Question: i have a POST method REST API  with request body as json, which has
<code>{
    "name": "5-Star",
    "vendor": "Cadbury",
    "description": "More almonds with chocolate",
    "price": 5,
    "primaryImage": "http://cdn.shopify.com/s/files/1/0219/2362/products/Front_a8743e5a-c6a3-4042-9cb2-834332af77d5_large.jpg?v=1377892407",
    "variants":
        [
          { "name" : "size",
            "type" : null,
            "defaultValue" : "8",
            "values" :[ "8","8.5"]
          },
          { "name" : "color",
            "type" : "COLOR",
            "values" :[ "Milky White","Chocolate"]
          }
       ],
    "tags":
       [ "Chocolate", "Cadbury"  ]
    }
</code>
I need to know how to set parameter for variants in the above json in swagger 2.0 editor, also referenced documentation and petstore sample from swagger but i cant find any clue.
Answer: Maybe this will get you started:
<code>properties:
 ... // other stuff
  variants:
    type: array
    description: variants description
    items:
      properties:
        name:
          type: string
          description: the name
 ... // the rest
</code>


What is the equivalent of regularization in optimization theory?

Question: I'm using a coordinate search to find an optima in a noisy search space. I'm wondering whether there's a notion of regularization in optimization to help mitigate avoid the noise? Regularization seems to be a topic exclusive to machine learning.
Thanks for any pointers!
Comment: It's not.  If you've studied any optimization theory, there is a duality between constrained optimization problems and unconstrained problems.  In this context the constrained problem is called "primal" and the unconstrained is called "dual".  The duality gives a way of passing between the domains.  When this is done, the constraints in the primal problem turn up as penalties in the dual problem, just like in regularization.  I'm not sure this is applicable to your case, but these ideas are worth having seen.
Comment: Here's a wiki on the topic: https://en.wikipedia.org/wiki/Duality_(optimization)
Comment: If you want to minimize a noisy objective function, the thing to look into is 'stochastic optimization' (e.g. see [here](https://stats.stackexchange.com/questions/226554/minimizing-approximate-function)). Some techniques that can be used for stochastic optimization can incorporate regularization (e.g. Bayesian optimization, which involves fitting an approximation to the noisy function).
Answer: Answer  copied from comments by Matthew Drury:  It's not. If you've studied any optimization theory, there is a duality between constrained optimization problems and unconstrained problems. In this context the constrained problem is called "primal" and the unconstrained is called "dual". The duality gives a way of passing between the domains. When this is done, the constraints in the primal problem turn up as penalties in the dual problem, just like in regularization. I'm not sure this is applicable to your case, but these ideas are worth having seen.
See https://en.wikipedia.org/wiki/Duality_(optimization)


why solution of $f''(x)+af'(x)+bf(x)=0$ is a vector space of dimension $2$?

Question: Let $V=\mathcal C^2(\mathbb R^2)$ and $$W=\{f\in V\mid f''+af'(x)+bf(x)=0\}.$$
I proved that $W$ is a subspace of $V$, but how can I prove that it has dimension $2$ ?
Comment: Are you sure it is $C^2(\mathbb R^2)$ and not $C^2(\mathbb R)$?
Answer: Sketch: If you assume it to be known (from ODE theory) that the solution of the initial value problem is unique, then every solution is determined by the initial values $f(0)=c_1$ and $f'(0)=c_2$, and is in fact equal to $c_1 g_1 + c_2 g_2$, where $g_1$ is determined by the initial values $g_1(0)=1$ and $g_1'(0)=0$, and the other way around for $g_2$.
Comment: Is it possible to prove that ?
Comment: Isn't the fact that any solution to the IVP unique usually deduced from the fact that this space is 2 dimensional?
Comment: @user657324: Prove what? The existence and uniqueness follows from the Picard–Lindelöf theorem, if you write the equation as a system of two first-order ODEs by letting $x_1=f$, $x_2=f'$. Proving the other claim (as well as linear independence of $g_1$ and $g_2$) is not more than a rather straightforward exercise.
Answer: Hint Let $u,v$ be any two solutions. Define
$$W(t):= u'v-uv'$$
Then
$$W'=u''v+u'v'-u'v'-uv''=(-au'-bu)v-u(-av'-bv)=-au'v+auv'=-aW$$
Solving this separable ODE you get $W(t)=Ce^{-at}$ for some $C$.
Now, pick any three solutions $u,v,w$. By the above, there exists some constants $C_1,C_2$ such that
$$u'v-uv'=C_1 e^{-at} \\
u'w-uw'= C_2e^{-at}$$
If $C_1=C_2=0$ then $u'v=uv'$ and $u'w=uw'$ are separable ODE which are easy to solve.
Otherwise
$$C_2(u'v-uv')=C_1(u'w-uw')\\
C_2\frac{u'v-uv'}{u^2}=C_1\frac{u'w-uw'}{u^2}\\
-C_2 \left( \frac{v}{u} \right)'=-C_1 \left( \frac{w}{u} \right)' \\
C_2 \frac{v}{u}=C_1 \frac{w}{u}+C_3 \\
C_2v=C_1w+C_3u
$$