How to split a string (based on a variety of delimiters) but without keeping whitespace?

Question: I have Java strings which are boolean expressions with parentheses, &, |, and ! as operators, and I want to split them into tokens.  For example:
((!A1)&(B2|C3)) should become "(","(","!","A1",")","&","(","B2","|","C3",")",")"
Following this answer I found that I can use Java's String.split() with a regex that includes lookahead and lookbehind clauses:
List<String> tokens = "((!A1)&(B2|C3))".split("((?<=[!&()|])|(?=[!&()|]))")

My only problem is that whitespace will be included in the list of tokens.  For example if I were to write the expression as ( ( !A1 ) & ( B2 | C3 ) ) then my split() would produce at least four strings like " " and there'd be padding around my variables (e.g. " A1 ").
How can I modify this split expression and regex to tokenize the string but not keep any of the witespace?
Comment: Remove the spaces first, then split?
Comment: `"( ( !A1 ) & ( B2 | C3 ) )".replaceAll("\\s+", "")` What about this before `split`?
Answer: Instead of split you can use this this regex to match what you want:
[!&()]|[^!&()\h]+

RegEx Demo
RegEx Details:

[!&()]: Match ! or & or ( or )
|: OR
[^!&()\h]+: Match any characters that is NOT !, &, (, ) and a whitespace

Code:
final String regex = "[!&()]|[^!&()\\h]+";
final String string = "((!A1)&( B2 | C3 ))";

final Pattern pattern = Pattern.compile(regex);
final Matcher matcher = pattern.matcher(string);

List<String> result = new ArrayList<>();
while (matcher.find()) {
    result.add(matcher.group(0));
}

System.out.println(result);


SQL query, who visited in the past year

Question: I am having problems with SQL querys. Specialy with this one, it goes like this.
I have 2 tables, patients and visits.
CREATE TABLE patients (
   ID_patients INTEGER NOT NULL,
   Name VARCHAR NOT NULL
);

and
CREATE TABLE visit(
    ID_visit INTEGER NOT NULL,
    DATE_visit DATE NOT NULL,
    FK_patients INTEGER NOT NULL
);

Now I would like to make a query, that would tell me which patients visited in the past year? And I don't mean in 2015 for instance but as in BETWEN(today-365 days) AND ( today -  730 days). I hope someone can give me some usefull tips.
Comment: Which column defines the relation between `patients` and `visit` table?
Comment: Sorry, my mistake, there should be a third colum by
 FK_patients INTEGER NOT NULL
Answer: select * from visit
where DATE_visit between
CURRENT_DATE - interval 2 year and CURRENT_DATE - interval 1 year;

Comment: This works fine, but you need to add  interval '2' and internval '1' , otherwise it wont work. Thank you for your answer.
Comment: But: `select CURRENT_DATE - interval 2 year` return `2014-04-18`... it should works...
Answer: Try this to fetch all the patients names:
SELECT patients.name
  FROM patients, visit
 WHERE patients.id = visit.fk_patients
   AND DATE_visit BETWEEN CURRENT_DATE - interval '2' year AND CURRENT_DATE - interval '1' year;

SQL query, who visited in the past year


Rodar dois serviços no mesmo domínio em portas distintas

Question: Preciso configurar uma aplicação que possui dois serviços distintos rodando na porta 80 e outro na 8080, porém no mesmo domínio. Pergunto a vocês se é possível e como poderia configurá-los dessa forma?
Exemplo:
meuunicodominio.com.br:80 caminho: /var/www/appfrontend
meuunicodominio.com.br:8080 caminho: /var/www/appbackend
A questão para essa façanha é o uso de duas tecnologias, na 80 roda PHP e na 8080 roda node.js, não tenho opção de criar subdomínios ou adicionar outro domínio, no máximo posso usar o IP da máquina pra apontar o backend.
Comment: sem acesso a modificar a configuração do nginx não é possível.
Comment: Eu tenho acesso root ao server. O problema que não posso usar outro domínio, por isso tenho que se virar com o mesmo usando portas diferentes para duas apps.
Answer: Na documentação há exemplos de como configurar: http://nginx.org/en/docs/http/server_names.html
Exemplo de configuração:
server {
    listen       80;
    server_name  foo.bar  www.foo.bar;
    root         /var/www/foo.bar/
}

server {
    listen       8080;
    server_name  bar.foo  www.bar.foo;
    root         /var/www/bar.foo/
}

Comment: Obrigado camarada, funcionou!


Multichannel recordings with computer

Question: I'd be interested to hear about the possibilities of recording more than 8 multiple channels simulaneously with a computer, the limitations involved and what is the state-of-the-art way to go. I am not interested in recording software, but only the audio interfaces and their connections to the computer.
I am aware of firewire audio interfaces and mixing consoles, but firewire seems to be going extinct, judging by the number of motherboards which still have a FW port and the number of FW audio interfaces on the market.
I've been searching for USB interfaces, but the number of channels seems to be limited to 8in 8out and there seem to be problems with duplex mode. Other USB interfaces use proprietary protocols (e.g Tascam). This concerns USB 2.0 interfaces. I have not yet seen any USB 3.0 interfaces
I've also seen thunderbolt interfaces, but they may be difficult to use on non-apple machines.
I am not even considering using multiple soundcards, because they will be difficult to sync and require a lot of extra gear (phantom power etc.)
In short:

Technology (FW, USB ...)?
Limitations (number of channles)?
proprietary protocol?
Linux comptabile?
cheap/expensive?

As a side note, I'd be interested in learning what the pros use. I cannot imagine that the eqipment I've seen so far is used in professional music production.
Comment: Pros - [SSL](http://www.bhphotovideo.com/c/product/657030-REG/Solid_State_Logic_726902XB_XLogic_Alpha_Link_MADI_AX.html) The rest of us mere mortals, something like the [MOTU](https://www.google.com/shopping/product/8374591758758039690?q=24-channel+audio+interface&safe=off&rls=en&biw=1137&bih=1035&prds=paur:ClkAsKraX7wtEOotDJu8C4pz0hKUxonpmWwYkGTDbE3pdWmhrP2I_x83QIR1QSrHFI-25rlfP1AkZsYDqn9jZM82BRaq6oUvVuYvs1Y-HYwH1gpMEnOuozVb8BIZAFPVH71ej-guu4ykvXbSSTApIT_c81wkzw&sa=X&ei=XtijVLiEN8j9UMuSgJgL&ved=0CLkBEPMCMAU)
Answer: Your question is fairly broad, so I'll do my best to cover what I can in general terms.
Technology:
Firewire is indeed going extinct. It was a proprietary hunk of tech made by Apple and is being replaced by Thunderbolt. If you're looking for non-Apple, the only way to go is USB 2.0 currently. I've heard good things about the Roland M-16DX which would allow you to record 16 channels concurrently.
Limitations:
It all depends on what you're going to do with it. The M-16DX is a nice hunk of tech for a home studio, but might not be suitable depending on space, cost, number of channels, or features. If you're running a professional studio, you'll probably want something more along the lines of a Yamaha 01V. Really, the only limits are space & budget. Sweetwater would probably be the best place to go to find mixers & audio interfaces to suit your needs no matter what they might be.
Proprietary-ness:
I have not personally run into any issues with proprietary protocols on mixers. If you have an issue with Tascam, don't buy 'em. Really, the only proprietary issues I've ever come across in recording gear was "Firewire" and "Thunderbolt". Just keep an eye on what the ad says it supports and you should be golden. I have nothing but good things to say about Focusrite, if that helps.
Linux:
Heh. There is a very steep learning curve with audio production on Linux. There isn't a single notable company (that I know of) that is actively making software/hardware for Linux. First time I tried migrating over I was disheartened by the lack of decent audio software. Second time I got everything up and running (Ardour as my DAW), and even recorded a few things, but in the end I felt that I could do everything in a Windows environment with a lot less tinkering. In the end I feel Linux is far better suited for a hobbyist than a professional studio. If you were to insist on going this route, the Linux community tends to be very supportive and helpful. There's loads of information on what's compatible, what works, what doesn't, and sometimes even 'how to make something that doesn't work, work'.
Mildly related.
Cheap/Expensive:
Always remember: "You get what you pay for". A pair of studio monitors might have a good set of reviews, but if they're $50, don't expect Genelec-quality. I would personally expect to pay somewhere in the neighborhood of $2000 to get every essential bit for a home studio (including an okay-ish computer and four channel interface). If I wanted to outfit a professional studio in tech (so, not including soundproofing and building the actual space) I could easily see spending $20k.
Comment: About the number of channels: I do a lot of Midi stuff and I have 2 stereo devices plus an old DX7. With just a single microphone and a lonely guitar I end up with 7 channels. Is that an unusual style of recording? Or how come there are so many devices with less than 8 input channels. And oh BTW - my Phonic helixboard just blew its PSU. I felt this coming, which is why I asked this question in the first place. If it was more robust, the Phonic would suit all my needs.
Comment: I've certainly heard of more bizarre setups. I don't think yours is terribly outrageous.

For channels: It's usually cheaper to grab an interface that only handles 2 to 4 channels than one that can get 8+. Moreover: for some setups, the space requirement is essential. I have a [Scarlett 2i2](http://us.focusrite.com/usb-audio-interfaces/scarlett-2i2) that works great for my purposes since I tend to record guitar & vocals as a sketch, and then elaborate with more tracks later.
Answer: You can add a multichannel recording card to the desktop computer same way as the high end graphic cards are added (though PCI-Express interface). I know esi-audio MAYA44 XTe can record 4 channels at once and should cost about $200 with software. SSL MadiXtreme 64 can record 64 channels, much more than you need, but already expensive (about $900).
If you really need a laptop, RME HDSPe MADIface may work (64 channels). It uses ExpressCard slot that most of laptops have. It is, however, also an expensive solution ($1475 or about).
Comment: $200 gets you a [Delta 1010LT](http://www.m-audio.com/products/view/delta-1010lt#.VcB_mLWH3To).  8+2 in\out (x's up to 4) AFAIK, still (beware, this product's like 20yo) the cheapest way to get more than 4 analogue inputs into a computer.

Multichannel recordings with computer


where query after context has been disposed

Question: i am using this in my data layer
public static IQueryable<Permission> ListAll()
{
    using (InventorySystemEntities context = new InventorySystemEntities(new ConfigurationManager().ConnectionString))
    {
        IQueryable<Permission> result = context.Permissions;
        return result;
    }
}

it should put all rows inside the result variable. however doing something like this, and it will result to context has been disposed..
permissionList = PermissionModel.ListAll();
chkListGeneral.DataSource = permissionList.Where(p => p.Parent == "General");

is there a way to filter the IQueryable without a context?
Comment: No. You need the provider for the IQueryable.
Answer: The connection is accessible only as long as the context that wraps it. Your method returns IQueryable, so the filter is trying to be "translated" to a DB query, but the underlying query provider no longer exists. You either need to specify the where condition while the context still exists, or force eager load (e.g. by calling ToList() on the result variable), return IEnumerable and filter the results in memory.
Comment: i have tried this already, calling Where from an IEnumerable or List returns method or operation not implemented.
Comment: Even when you simply change the return type to `IEnumerable` and call `ToList()` on the `result`?


What is the simplest way to do this combinatorics problem?

Question: Question: Bob is about to hang his eight shirts in the wardrobe. He has 4 different styles of shirt, two identical ones of each particular style. How many different arrangements are possible if no two identical shirts are next to each other?
Here are the solutions:
In this case, we take the first case of all possible combinations: $\frac{8!}{2^4}$
But we see that we counted the possibilities with at least one pair together
so we have to subtract $\frac{7!}{2^3}\cdot \binom{4}{1}$ if we tie the two offending shirts together.
^This I don't get - why and what is being double-counted?
However, we see now that we double subtracted ones that have two pairs thus we must add the chance of two pairs so we must add $\frac{6!}{2^2}\cdot \binom{4}{2}$ and so on
Thus the final answer is equal to $864$
Is there a better way that doesn't involve BOTH adding AND subtracting?
Comment: The Inclusion-Exclusion is used to count the union of a set of events or the complement of the union.  In this case, the events are the four sets of arrangements in which adjacent identical shirts occur.  Let me know if you want a detailed explanation of why the Inclusion-Exclusion Principle works here.
Comment: When you count cases in which a particular pair of identical shirts is adjacent, you count each case in which there are two pairs of adjacent identical shirts twice, once for each way of designating one of those pairs as the pair of adjacent identical shirts.  To compensate for subtracting too much, we use the Inclusion-Exclusion Principle,
Comment: How can you intuitively know when to use the inclusion-exclusion principle?
Comment: @user71207: We use PIE, the principle of inclusion-exclusion, when it's (relatively) easy to calculate *at least* information, but hard to calculate *exact* information. I've added some related info in the comment section of my answer.
Answer: The method in your solutions is actually the Inclusion–exclusion principle. Since $${\displaystyle \left|\bigcup _{i=1}^{n}A_{i}\right|=\sum _{i=1}^{n}|A_{i}|-\sum _{1\leqslant i<j\leqslant n}|A_{i}\cap A_{j}|+\sum _{1\leqslant i<j<k\leqslant n}|A_{i}\cap A_{j}\cap A_{k}|-\cdots +(-1)^{n-1}\left|A_{1}\cap \cdots \cap A_{n}\right|.}$$ the additions and substractions you see are exactly the coefficients $\pm1$ in the formula.
To avoid substractions, you may need to divide the orginal problem into distinct ones, and the number of conditions could be really large. I don't think it's a better way tho.
Comment: The correct spelling is subtractions.
Comment: @N.F.Taussig:  The [variant spelling](https://www.merriam-webster.com/dictionary/substraction) used by the OP is fairly common, and closer to its late Latin root *substractus*.
Answer: We denote with $a,b,c,d$ the four different types of shirts. We are looking for words of length $8$ built with all letters from the multiset $\{a,a,b,b,c,c,d,d\}$ which do not contain the bad words in $\{aa,bb,cc,dd\}$.

This answer is based upon a generating function of generalized Laguerre polynomials
\begin{align*}
  L_k^{(\alpha)}(t)=\sum_{i=0}^k(-1)^k\binom{k+\alpha}{k-i}\frac{t^i}{i!}
  \end{align*}
The Laguerre polynomials have some remarkable combinatorial properties and one of them is eminently suited to answer problems of this kind. This is nicely presented in Counting words with Laguerre series by Jair Taylor. We find in section $3$ of this paper:

Theorem: If $m_1,\ldots,m_k,n_1,\ldots,n_k$ are non-negative integers, and $p_{m,n}(t)$ are polynomials defined by
\begin{align*}
  \sum_{n=0}^\infty p_{m,n}(t)x^n=\exp\left(\frac{t\left(x-x^m\right)}{1-x^m}\right)
  \end{align*}
then the total number of $k$-ary words that use the letter $i$ exactly $n_i$ times and do not contain the subwords $i^{m_i}$ is
\begin{align*}
   \int_0^\infty e^{-t}\prod_{j=1}^k p_{m_j,n_j}(t)\,dt\tag{1}
  \end{align*}

Here we consider a $4$-ary alphabet $\{a,b,c,d\}$ and words built with all letters from the multiset $\{a,a,b,b,c,c,d,d\}$ and the bad words $\{aa,bb,cc,dd\}$.
Following the theorem above we have $m_j=2, n_j=2, 1\leq j\leq 4$ and the wanted number of valid words is according to (1)
\begin{align*}
 \int_0^\infty e^{-t}\left(p_{2,2}(t)\right)^4\,dt\tag{2}
\end{align*}
We obtain with some help of Wolfram Alpha
\begin{align*}
p_{2,2}(t)&=[x^2]\exp\left(\frac{t\left(x-x^2\right)}{1-x^2}\right)\\
&=[x^2]\left(1+tx+\frac{1}{2}t(t-2)x+\cdots\right)\\
  &=\frac{1}{2}t(t-2)
\end{align*}

According to (2) and recalling $\int_0^{\infty}e^{-t}t^{n}\,dt=\frac{1}{n!}$ we obtain as wanted number
\begin{align*}
&\int_0^\infty e^{-t}\left(\frac{1}{2}t(t-2)\right)^4dt\\
&\qquad=\frac{1}{16}\int_{0}^{\infty}e^{-t}t^4\left(t^4-8t^3+24t^2-32t+16\right)dt\\
&\qquad=\frac{1}{16}\left(8!-8\cdot7!+24\cdot 6!-32\cdot 5!+16\cdot 4!\right)\\
&\,\,\qquad\color{blue}{=864}
\end{align*}
in accordance with OPs statement.
Answer: Comment: I think inclusion-exclusion may be the
"best" solution. That is a frequently used combinatorial method.
By whatever method, I'm pretty sure that the number
of allowable arrangements is $864$ out of $8!/16,$ as you say.
Simulating in R, one can use
shirts = c(1,1,2,2,3.3.4,4) and randomly permute
them with the sample procedure:
shirts = c(1,1,2,2,3,3,4,4)
sample(shirts)
[1] 2 2 4 1 3 1 4 3
sample(shirts)
[1] 2 2 1 4 3 1 3 4
sample(shirts)
[1] 3 2 3 1 4 2 4 1
sample(shirts)
[1] 2 3 1 4 4 1 2 3

Some are legal arrangements and some are not.
If you take successive differences, then 0s will
show illegal ones.
s = sample(shirts);  s;  diff(s)
[1] 4 1 1 3 2 3 4 2
[1] -3  0  2 -1  1  1 -2        # illegal
s = sample(shirts);  s;  diff(s)
[1] 2 3 1 4 3 2 4 1
[1]  1 -2  3 -1 -1  2 -3        # legal
s = sample(shirts);  s;  diff(s)
[1] 1 2 1 4 3 2 4 3             # legal

We can count the 0s in each iteration,
and see what proportion of iterations is 'legal' (the ones with no 0s.)
shirts = c(1,1,2,2,3,3,4,4)
set.seed(2020)
nr.adj = replicate(10^7,
                   sum(diff(sample(shirts))==0))
mean(nr.adj==0)
[1] 0.3428441

So about 34.28% of the iterations are legal, suggesting
that there must be about 864 legal arrangements.
 mean(nr.adj==0)*(factorial(8)/16)
[1] 863.9671

Comment: @hardmath :  Thanks for mentioning typos. Fixed them. Maybe Santa will bring new glasses. Also (+1) for your Answer.
Answer: Because the problem involves rather small numbers, we can count by hand without using inclusion/exclusion.
Assume the first style of shirt that appears, left-to-right, is A, and that the next style is B, followed (disregarding any more A,B) by one of style C (so that the last style to appear in this sequence is D).  Any permutation of those four styles produces a distinct, but still valid, arrangement.  By counting the sequences with that fixed order of appearance, we will get a number that multiplied by $4!$ gives the answer to the original problem.
Accordingly the sequence resembles AB_C_D_ with the stipulation that underscores represent the combined locations of the four remaining shirts.  An underscore might correspond to zero or more of the four shirts, but with certain restrictions.  The first underscore cannot hold C or D styles, and the second underscore cannot hold a D style.
In consequence the final D has to go into the spaces represented by the last underscore, splitting it into two parts.  Furthermore we cannot leave the two D's adjacent, so something has to be put between them.  Let's represent this with an asterisk:
A B _ C _ D * D _

Since something (rather than nothing) has to replace that asterisk, it makes sense to consider the seven cases of non-empty subsets $\mathscr S$ of the remaining styles A,B,C which might go there:
Case 1: $\mathscr S =$ {A,B,C}
If we put all the remaining shirts in the asterisk place (between the two D's), then the only choice we have is how to order them.  Thus this case leads to $3!=6$ possible outcomes.
Case 2: $\mathscr S =$ {A,B}
If we put the pair of shirts styled A,B in the asterisk place, we must choose the ordering of them and where else the last shirt, styled C, should go.  But the only valid place for that C is after the last D, so this case leads to $2!=2$ possible outcomes.
Case 3: $\mathscr S =$ {A,C}
If we put the pair of shirts styled A,C in the asterisk place, we must choose the ordering of them and where else the last shirt, styled B, should go.  As there are two valid places for that B, after the last D or between C and the first D, this case leads to $2! \times 2 = 4$ possible outcomes.
Case 4: $\mathscr S =$ {B,C}
If we put the pair of shirts styled B,C in the asterisk place, we must choose the ordering of them and where else the last shirt, styled A, should go. But that shirt A can go in three valid places (any of the three underscores will do), so this case leads to $2! \times 3 = 6$ possible outcomes.
Case 5: $\mathscr S =$ {A}
If we put shirt A in the asterisk place, then we must choose whether the remaining shirts B,C will be placed together or into separate underscore locations.

If together, then the first underscore is not valid (because the second C must go in the second or third underscore location), and if C goes into the second underscore, it would have to be preceded by B (either order works in the third underscore).  So that gives us $1+2 = 3$ possible outcomes.

If separately, then the first underscore is not valid (the two B's must not be adjacent) for either shirt, and the second underscore is not valid for the C shirt by itself.  So the only way to separate them is putting B into the second underscore and C into the third underscore, for only $1$ possible outcome.

Case 6: $\mathscr S =$ {B}
If we put shirt B in the asterisk place, then we must choose whether the remaining shirts A,C will be placed together or into separate underscore locations.

If together, then the first underscore is not valid (because the second C must go in the second or third underscore location), and if C goes into the second underscore, it would have to be preceded by A (either order works in the third underscore).  So that gives us $1+2 = 3$ possible outcomes.

If separately, then only the third underscore is valid for the C shirt by itself.  So if we separate them, we can choose to put A into the first or second underscore and C into the third underscore, for $2$ possible outcomes.

Case 7: $\mathscr S =$ {C}
If we put shirt C in the asterisk place, then we must choose whether the remaining shirts A,B will be placed together or into separate underscore locations.

If together, then in the first underscore location they would have to be ordered AB (to avoid adjacent B's),  but either order works in the second and third underscores.  So that gives us $1+2+2 = 5$ possible outcomes.

If separately, then only the second or third underscore is valid for the B shirt by itself, and then we can choose to put A in either of the two remaining underscore locations.  We get $2\times 2 = 4$ possible outcomes.

Finally we add up all the possible case outcomes:
$$ 6 + 2 + 4 + 6 + (3+1) + (3+2) + (5+4) = 36 $$
and multiply that by $4!$ to get the answer: $36 \times 24 = 864$.
Answer: We denote with $a,b,c,d$ the four different types of shirts. We are looking for words of length $8$ built with all letters from the multiset $\mathcal{V}=\{a,a,b,b,c,c,d,d\}$ which do not contain the bad words in $\mathcal{B}=\{aa,bb,cc,dd\}$.

Here we use PIE the inclusion-exclusion principle to count the number of valid words.

In order to do the job some kind of bookkeeping is helpful. We consider
\begin{align*}
&\left(.\ .\ .\ .\ .\ .\ .\right)\tag{1}\\
&\quad-\left(aa\ .\ .\ .\ .\ .\ .|bb\ .\ .\ .\ .\ .\ .\ .|cc\ .\ .\ .\ .\ .\ .|dd\ .\ .\ .\ .\ .\ .\right)\tag{2}\\
&\quad+\left(aa\ bb\ .\ .\ .\ .|aa\ cc\ .\ .\ .\ .|aa\ dd\ .\ .\ .\ .\right.\\
&\quad\qquad \left.|bb\ cc\ .\ .\ .\ .|bb\ dd\ .\ .\ .\ .|cc\ dd\ .\ .\ .\ .\right)\tag{3}\\
&\quad-\left(aa\ bb\ cc\ .\ .|aa\ bb\ dd\ .\ .|aa\ cc\ dd\ .\ .|bb\ cc\ dd\ .\ .\right)\\
&\quad+(aa\ bb\ cc\ dd)
\end{align*}
Comment:

In (1) we count all $8$-letter words from $\mathcal{V}$ indicated by eight dots which gives $\frac{8!}{2!2!2!2!}$ words.

In (2) we subtract all words which contain at least one bad word. Note that the first pattern
\begin{align*}
aa\ .\ .\ .\ .\ .\ .
\end{align*}
represents all words which have two adjacent $a$'s and which gives $\frac{7!}{1!2!2!2!}$ words. In fact it counts all words which contain at least $aa$ besides possibly, occurrences of other adjacent letters e.g. $bb$ represented by two of the other dot's. Such words are counted more than once, because they are also counted with $(bb\ .\ .\ .\ .\ .\ .)$.
In oder to compensate this we add the words which contain at least twice occurrences of adjacent letters in (3).

In (3) we add words containing two bad words as compensation for those which we've subtracted twice in (2), which gives $\frac{6!}{1!1!2!2!}$ words. We  continue in the following lines accordingly.

No more cases are left to consider, since words containing five or more bad words have length greater than $8$.

We obtain according to (1) to (3):
\begin{align*}
&\frac{8!}{2!2!2!2!}-\binom{4}{1}\frac{7!}{1!2!2!2!}+\binom{4}{2}\frac{6!}{1!1!2!2!}\\
&\qquad-\binom{4}{3}\frac{5!}{1!1!1!2!}+\binom{4}{4}\frac{4!}{1!1!1!1!}\\
&\quad=2\,520-4\cdot 630+6\cdot 180-4\cdot 60+1\cdot 24\\
&\quad\,\,\color{blue}{=864}
\end{align*}
in accordance with OPs statement.


Let users download and set induvidual blog themes Drupal 7

Question: I want to enable users customize their own blog appearance and theme the same way it is being done in multi-user blogging sites such as wordpress.com, tumblr.com, typepad.com, etc.

Users can set a theme to their blog
Users can manage some settings regarding ther blog appearance (background color, fonts, etc.)
Users can download themes or even make their own themes available for others.
The theme setting only affects the user blog page (but not the general site layout).

Any possible suggestions to make part of those requirements implemented quickly?
Answer: Letting them download and put up whatever theme that they want sounds like it might be a major security issue for your site, since they could put whatever PHP that they want into the theme files and it would run. I'd suggest making a specific set of themes you have picked available and letting users choose from those. There are modules like Theme key to enable using different themes: http://drupal.org/project/themekey
Comment: That was very helpful... theme key is a nice solid solution and very easy for implementing. After a very long search I did not find any ready made solution for letting users downloading their own theme or altering their own blog appearance - this is probably the most you can get without having to create your own module :-)


Pyqt5 not installing

Question: So basically ive been trying to install pyqt5 using pip in visual studio code and it  always comes back with this error preparing wheel metadata... Error
<code> Using cached PyQt5-5.14.1.tar.gz (3.2 MB)
  Installing build dependencies ... done
  Getting requirements to build wheel ... done
    Preparing wheel metadata ... error
    ERROR: Command errored out with exit status 1:
     command: 'C:\Users\97152\AppData\Local\Microsoft\WindowsApps\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\python.exe' 'C:\Users\97152\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\pip\_vendor\pep517\in_process\_in_process.py' prepare_metadata_for_build_wheel 'C:\Users\97152\AppData\Local\Temp\tmpzk3hpkso'
         cwd: C:\Users\97152\AppData\Local\Temp\pip-install-n92hbnur\pyqt5_823c0736297343559d66d8215f79e2c8
    Complete output (29 lines):
    Traceback (most recent call last):
      File "C:\Users\97152\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\pip\_vendor\pep517\in_process\_in_process.py", line 143, in prepare_metadata_for_build_wheel
        hook = backend.prepare_metadata_for_build_wheel
    AttributeError: module 'sipbuild.api' has no attribute 'prepare_metadata_for_build_wheel'

    During handling of the above exception, another exception occurred:

    Traceback (most recent call last):
      File "C:\Users\97152\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\pip\_vendor\pep517\in_process\_in_process.py", line 349, in <module>
        main()
      File "C:\Users\97152\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\pip\_vendor\pep517\in_process\_in_process.py", line 331, in main
        json_out['return_val'] = hook(**hook_input['kwargs'])
      File "C:\Users\97152\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\pip\_vendor\pep517\in_process\_in_process.py", line 147, in prepare_metadata_for_build_wheel
        whl_basename = backend.build_wheel(metadata_directory, config_settings)
      File "C:\Users\97152\AppData\Local\Temp\pip-build-env-5j8h2xca\overlay\Lib\site-packages\sipbuild\api.py", line 51, in build_wheel
        project = AbstractProject.bootstrap('pep517')
      File "C:\Users\97152\AppData\Local\Temp\pip-build-env-5j8h2xca\overlay\Lib\site-packages\sipbuild\abstract_project.py", line 83, in bootstrap
        project.setup(pyproject, tool, tool_description)
      File "C:\Users\97152\AppData\Local\Temp\pip-build-env-5j8h2xca\overlay\Lib\site-packages\sipbuild\project.py", line 479, in setup
        self.apply_user_defaults(tool)
      File "C:\Users\97152\AppData\Local\Temp\pip-install-n92hbnur\pyqt5_823c0736297343559d66d8215f79e2c8\project.py", line 62, in apply_user_defaults
        super().apply_user_defaults(tool)
      File "C:\Users\97152\AppData\Local\Temp\pip-build-env-5j8h2xca\overlay\Lib\site-packages\pyqtbuild\project.py", line 70, in apply_user_defaults
        super().apply_user_defaults(tool)
      File "C:\Users\97152\AppData\Local\Temp\pip-build-env-5j8h2xca\overlay\Lib\site-packages\sipbuild\project.py", line 225, in apply_user_defaults
        self.builder.apply_user_defaults(tool)
      File "C:\Users\97152\AppData\Local\Temp\pip-build-env-5j8h2xca\overlay\Lib\site-packages\pyqtbuild\builder.py", line 66, in apply_user_defaults
        raise PyProjectOptionException('qmake',
    sipbuild.pyproject.PyProjectOptionException
    ----------------------------------------
WARNING: Discarding https://files.pythonhosted.org/packages/3a/fb/eb51731f2dc7c22d8e1a63ba88fb702727b324c6352183a32f27f73b8116/PyQt5-5.14.1.tar.gz#sha256=2f230f2dbd767099de7a0cb915abdf0cbc3256a0b5bb910eb09b99117db7a65b (from https://pypi.org/simple/pyqt5/) (requires-python:>=3.5). Command errored out with exit status 1: 'C:\Users\97152\AppData\Local\Microsoft\WindowsApps\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\python.exe' 'C:\Users\97152\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\pip\_vendor\pep517\in_process\_in_process.py' prepare_metadata_for_build_wheel 'C:\Users\97152\AppData\Local\Temp\tmpzk3hpkso' Check the logs for full command output.
</code>
how can I fix this I have installed the Microsoft C++ buildtools and tried downloading It using the pyqt5 wheel file (gives me a this file is not a supported wheel on this platform
Comment: Does this answer your question? [AttributeError: module 'sipbuild.api' has no attribute 'prepare\_metadata\_for\_build\_wheel' for PyQt5 5.15.0](https://stackoverflow.com/questions/65447314/attributeerror-module-sipbuild-api-has-no-attribute-prepare-metadata-for-bui)
Answer: Please, try:

Download file PyQt5-5.15.4-cp36.cp37.cp38.cp39-none-win_amd64.whl from the page
https://pypi.org/project/PyQt5/#files

Rename it to PyQt5-5.15.4-py3-none-win_amd64.whl

Run pip install PyQt5-5.15.4-py3-none-win_amd64.whl

I was able to install it into Python 3.10 virtual environment, then was able to run example from https://zetcode.com/gui/pyqt5/firstprograms/
Comment: Thank you Andrew.  I banged my head on this topic for a long while before stumbling upon your answer.  I didn't realize the file needed to be renamed.  "I didn't get the memo."
Comment: Additionally, 5.15.5 will be released soon, but you can download it from https://www.riverbankcomputing.com/pypi/

Pyqt5 not installing


How important is to reach the bottom limit of the key when pressed?

Question: When practicing, I noticed that in forte scale runs I always reach the bottom limit of every key I press, but when playing the same run piano or pianissimo I don't always reach the bottom limit.
So, my question is: How important is to reach the bottom limit of the key when pressed? Should the distance vary depending on dynamic (piano, forte, etc)? Is there an ideal/optimal height the key should end when pressed?
This happens on both MIDI keyboard and acoustic piano.
Comment: Just out of curiosity, do you have a digital piano (or keyboard) or an acoustic piano?
Comment: @Dom Both, and this happens on both.
Answer: The let-off on an acoustic piano is adjustable.  Your tuner can show you how to do it.  It determines how softly you can play.
The answer to your question is:  it depends on how the let-off is adjusted.
Comment: I see! So, it's all about taste? From a technique context, there is no recommended distance from the bottom to be in when pressing keys? It just doesn't matter?
Comment: It's more about whatever works for you, given what your piano can do.  If you can play pianissimo by pressing the key just until the escapement flings the hammer, you will be using less motion in your fingers and you can play faster.  I don't have that much finger control.
Answer: An interesting thought !On all of my acoustic pianos, so it's not just one, a key can be pressed down less than a quarter of the way to make the note sound.HOWEVER, if that key is pressed in the conventional way, straight downwards, it may or may not make a sound.Pressed all the way gently, no sound. Pressed with more force, sound. Mostly with volume commensurate with the force applied.By using a different technique to depress a key, rather like a claw-like movement, thus giving more impetus to the key and hammer, the key only needs to be depressed by 25% for the note to sound.This movement is to touch a key and slide the finger off the end of the key, quickly.I blocked under the edge of the key so it could not go down more than stated.Range of volume is available.
It's not so much the depth that is important, than the velocity to start the hammer moving. Once it starts to move, the extra depth the key goes to has little effect.
Digital pianos usually have a completely different mechanical arrangement, so there is no simple direct comparison.
Comment: Interesting! Is it recommended to always push the key until all the way to the bottom limit? Are there technique recommendations regarding this?
Comment: My acoustics came without instructions. Sorry !Having set up a Roland pno., it would appear that the same phenomenon occurs with that.Press gently and no sound comes out, but not necessary to press fully down if some velocity is used.
Comment: Haha I mean from a pianist point of view, technique as context. To me it seemed like something that can influence technique. Is this just not taken into consideration by teachers when carving technique?
Comment: Not my teachers, but that was 40 odd yrs ago, and only just past grade VIII. Maybe it doesn't get addressed by most until one is quite an advanced player, by which time, one has formed one's own techniques anyway.
Answer: If you find that sometimes the notes don't sound when not hitting the bottom, then it's important to hit the bottom.  If this isn't the case, then it doesn't matter - unless you're interested in playing unfamiliar pianos regularly.
The way to play softly is with a slower action, or with the soft pedal, or both.  Different pieces may require different methods of playing softly, but not pressing all the way down is not a recognised technique for playing softly, probably because that's pretty difficult to do deliberately and consistently.
I'm not one to suggest there's a right or wrong way, but when I do it, the keys go all the way down, except by mistake (which occasionally happens with very short notes, regardless of whether trying to play soft or loud).
Answer: Playing to the bottom of the keys no matter how loud or soft makes for a solid and consistently even tone that you can control much better than one created by haphazardly pressing notes at various pressure levels.
When playing it's important to use more than just your fingers to produce the tone, and this is done by putting some force behind the moving using your arms and shoulders. By doing this, you'll find it's very easy to play both loudly and softly without working too hard at it.
Keep in mind that this won't happen instantly and like everything else with the piano, you need to practice and use it all the time so the movements become natural.


Related Content with References in Drupal 7

Question: I have made this website using Drupal 7 a year ago, where the References module plays a key role.
Say I have two content types movie and actor, and the content type movie has a references field which references actor nodes. Now, how do I have a block which lists other movies which the actors in this movie are referenced?
Something seems to be here: http://drupal.org/node/370227 but that doesn't seem to work for Drupal 7.
Also, as I have more than 1000 nodes in content type movie, I prefer not to move from References field also, my all my urls are like example.com/content-example
Thanks!
Answer: I am sure you could do all of this in one view using a contextual filter and using that as a relationship to point to the movies in question, but, if you don't mind some php coding, you can do all of this pretty easily yourself and one simpler view.
1.  create a view that has a contextual filter using the actor reference field, eg,
it returns just the movies that contain that actor, and in fields, just nid of the
movie node should be sufficient.  Make sure that this will reference any actor in the
movie, eg, all of the values of this field, not just the first one.

Then in your block hook, put in something along the lines of:
$node=menu_get_object();

$movies=array();
foreach ($node->NAME_OF_ACTOR_REFERENCE_FIELD as $actor) {
   $view=views_get_view('NAME_OF_VIEW_ABOVE');
   $view->set_arguments(array($actor['nid']));
   $view->execute();
   foreach ($view->result as $result) {
      $movies[$result->nid]=$result->nid;
   }
}

Assuming this is displayed on a page that is displaying a movie of course, what this does is grab the actors referenced in that node and then loops through them, grabbing each movie that has referenced them as well, and then stores that in an array.  Since we key this array to the movie's nid, we also create a unique list of movies.
So, now we have a list of movie nids so we can do something like:
foreach ($movies as $nid) {
  $node=node_load($nid);
  $content.='
' . l($node->title, $node->path) . '
';
}

and return $content as the content of the block and style it however you want with css.
Caveat:  I am just learning D7 and a lot of times D6isms creep into play, and most of the above is just typed in from memory, so there may be subtle things you'll need to adjust (drupal_set_message() and print_r() are your friends) but this hopefully will help out.


Dúvida sobre treinamento openCV

Question: Em um aprendizado de máquina deve-se separar os dados em 3 conjuntos, um para treinamento, outro pra validação e outro pra testes com quantidade relativa a 70%, 15% e 15% respectivamente.
Contudo minha dúvida é em relação a quantidade real de imagens/dados para um treinamento ideal de reconhecimento.
Tenho usado o opencv trainscascade para fazer o treinamento, mas infelizmente para o meu projeto eu não possuo um número consideravel de imagens tanto positivas quanto negativas então precisaria de um número mínimo para esses dois tipos de imagens, qual seria?
E quanto aos estágios, estou a par de que quanto mais estágios é colocado como parâmetro mais específico se torna o reconhecimento, o que pode gerar até um treinamento excessivo, então o número de estágios ideal se dá também por volta de 10 e 20 ?
E por último, caso eu faça um treinamento gerando um cascade.xml de data, e em seguida faça outro que complemente esse primeiro cascade é possível anexá-los de alguma forma sem ter que retreinar tudo de novo?
Segue abaixo um exemplo de código para facilitar a visualização dos parâmetros para treinamento:
<code> opencv_traincascade -data 'diretório do cascade' \
-vec 'diretório das imagens POS.vec' \
-bg 'diretório das imagens NEG.txt' \
-numPos x \
-numNeg y \
-numStages z \
-w 24 -h 24 \
-mode ALL
</code>
Answer: Não existe uma formula exata para se calcular qual a quantidade de treinamento que um modelo precisa receber para cair em um "treinamento excessivo" ou overfitting que apesar de ser um termo em inglês é o nome mais difundido por aqui, é necessário testa-lo de forma gradual para saber qual deles obteve o melhor desempenho.
Imagino que a sua duvida tenha surgido, por medo de gerar overfitting, que é basicamente o nome dado a um modelo que se "acostumou" tanto ao padrão de amostras do seu dataset de treino que tem dificuldades em identificar ou predizer qualquer amostra que esteja fora do seu dataset.
No seu caso é fácil identificar qual a quantidade ideal de treino pois como você mencionou a própria biblioteca separa 15% das amostras para fins de testes ou seja são amostras que não estarão presentes em seu dataset de treino, isso assegura que os valores retornados nos resultados não estão sendo influenciados pelas amostras do treino ( desde que as amostras de testes não sejam iguais as amostras de treino), portanto, você pode começar treinando com 10 estágios e depois comparar os resultados com um treino feito com 20, caso o resultado com 20 tenha melhorado ainda pode haver espaço para melhora então tente 30, agora caso o resultado com 10 tenha sido melhor tente encontrar entre 10 e 20 qual o melhor resultado, e assim até se dar por satisfeito com os resultados.
Obs: Usei como exemplo 10 e 20 estágios pois eles foram mencionados na pergunta, o ideal é se trabalhar com um range bem maior e ir afunilando conforme os resultados forem aparecendo.

Dúvida sobre treinamento openCV


is F# to IronPython/IronRuby as C# is to VB.NET?

Question: I just listened to podcast of Chris Smith talking about F# in which he talks about how F# is a language which allows you to approach problems in a different way than in C#/VB.NET, i.e. instead of "pushing bits around" you "chain together data transformations", and that how F# will "become like XML", something that you use in addition to your language of choice (C# or VB.NET) in order to solve certain problems in a more efficient way.
This got me to thinking about the relationship of the .NET languages, here's how I understand them:

C# and VB.NET are syntactically but not substantially different, i.e. a C# programmer would not learn VB.NET in order to "approach problems in a new way"
however, a C# or VB.NET programmer would learn F# in order to "approach programming problems in a functional way"

But what about IronPython and IronRuby? Chris mentioned that "F# learned a lot from Ruby and Python" so I would think that F# has a similar relationship to IronRuby/IronPython and C# has to VB.NET. However, a little googling around tells me that IronRuby and IronPython are both built on the DLR but F# is not.
How are the relationships between F#, IronRuby and IronPython to be best understood?
Comment: F# has roots in OCaml which is far from IronPython and IronRuby... I don't see any *direct* relationships.
Comment: Isn't IronPython (just) an implementation of Python in .NET? F# is a new language altogether....
Comment: I think you mean Chris Smith not Chris Sells.
Comment: @Robert, thanks, right: Chris Smith.
Answer: F# and IronPython/IronRuby are light years apart from a language perspective.   F# is a functional, highly typed compiled language.  IronRuby/IronPython are dynamically typed, interpreted languages.
I believe IronPython does additionally support compilation but I'm not 100% sure, and less about ruby.
The relationship between VB.Net and C# is much closer.
Comment: I'd go so far as to say that F# is much closer to VB.NET and C# than IronRuby/IronPython.
Comment: F# is just a different paradigm, as our friends said, its compiled, and that makes it very different to the Iron family.
If you look arroung, you will see Haskel, Charity, Clean as exemples of pure functional programming. Then there are others that allow function programming but they have their own main paradigm, C/C++/C#, List, Matematica, Python are exemples of that.
Comment: Depends on what you mean by "compilation" -- both IronRuby and IronPython really are compilers.
Comment: By compilation most people mean you have a distinct compile step and emit some sort of binary like an exe, dll, or java class file.
Answer: In many ways F# and Ruby/Python are superficially similar.  All three languages allow you to concisely express ideas without littering your code with many types.  However, F# is actually very different from Ruby and Python, since F# is a statically typed language, while Ruby and Python are dynamically typed.  Idiomatic F# code rarely mentions types, but the compiler infers types and any type errors will be flagged by the compiler during compilation.  For Ruby and Python, using a value at the wrong type will only generate errors at run-time.  Ruby and Python's dynamism means that both are more amenable to metaprogramming than F# is (types can be modified at runtime, for instance).  On the other hand, F# is going to be more performant for most tasks (comparable to C#), and offers many nice functional abstractions such as discriminated unions with pattern matching.  It's certainly true that learning any of these languages well will lead you to think about problems differently than you do in C# or VB.NET, but your approach will probably vary a lot between F# and Python/Ruby as well.
Answer: I'd say F# learned a whole lot more from OCaml than it did from Ruby and Python combined.  The only real comparison is that F# is brings ML to .NET in the same way that IronPython/Ruby bring Python/Ruby to .NET.
Comment: I think they often get because F# and IronPython/Ruby both have concise syntax where you don't explicitly need to state they type of each identifier.
Comment: I can see that, but even so they each have concise syntax for different reasons and don't need explicity identifiers for different reasons.  The similarities are very superficial.
Answer: F# is more of a "tool" language where there are specific problems that are best tackled with a functional approach.  F# is inherently thread safe which gives hope that it will be helpful in scaling an application to use multiple processors.  I see F# being used to build components that will be used in VB.NET or C# to handle specific problems.
Comment: F# is inherently thread safe is - unfortunately - just not true. F# provides mecanisms which facilitate thread safe code, but it doesn't just magically, or automatically, happen out of the box.
Comment: Having completely replaced C# with F# in a project, I don't see how it's a narrow "tool" language that just steps in when C# doesn't cut it. Apart from a few remaining interop issues (and lack of tool support), F# is pretty much a superset of C#, functionality-wise.
Comment: WOW, that's interesting perspective.  I've heard the main concern about F# is that business apps lend themselves to OO and imperative programming and those apps traditionally aren't approached with a functional language.  The "tool" comment implies that a developer would divide the problem into domains and best apply F# where it made sense.
Comment: It takes a bit to get the hang of it, but you can do classes and all of that in F#, and they are usually more succinct.
Answer: There are aspects of F# that are similar to dynamic languages; however, JaredPar's answer sums it up really.  F# is in it's own category of functional programming where as IronRuby and IronPython are dynamic languages and C#/VB OO Languages.  They can all do the same things and just depends on how you want to do it.  Each has it's pros and cons for a given problem.
Answer: NOTE: This is mostly a compilation of my thoughts and observations on the subject. I'm a C# programmer by day and Python by night.
Yeah I agree with some of the stuff that has been said, but I have some time and feel like elaborating and sharing my thoughts.
F# is a functional language. Which means you are really more concerned with the verbs so to speak. It is still statically typed and runs on the CLR, but you structure your code differently and work through problems differently. Usually people think that functional languages are more mathematical in structure and easier to prove formally. Of course that is generally regarded as mostly academic.
C# and other statically typed OO languages are really more focused on the nouns to further my analogy. So you structure your code and work through problems in regards to that. Of course there are also natural problems with maintaining state and having non-deterministic methods on objects that tend to come up more often in OO languages.
And of course F# has some features and ideas borrowed from OO languages while C# has ideas and features borrowed from functional.
Comparing Python and C# is more about the difference between dynamic and static typing (although python does offer some functional features that C# still does not). Dynamic typing usually being far easier to handle introspection/reflection activities and run-time modification while adding the risk of run-time errors due to typos or incorrect objects used in "regular" code.
Static languages usually have some developer overhead that dynamic languages do not have. The overhead seems to usually be due to having to create layers to abstract things away and creating inheritance hierarchies and interfaces to work with the needed/wanted abstraction. Since you are trying to avoid dependencies to types.
It seems like statics languages can be much easier to manage in larger teams. Plus you get the advantages of refactoring very easily with all the checking and tools out there.
Comment: Nice thoughts. I am working on some Python projects that are growing pretty large and the lack of automated refactoring definitely creates extra work.


How do we interpret the "natural log of income"

Question: I'm just confused as to how we interpret a natural log in relation to a regressor, say years of training
thanks
Answer: Let $y$ be income and $x$ be years of training.  It sounds like you are thinking about
$$ \log(y)  = \beta_0 + \beta_1 x $$
Exponentiating both sides yields
$$ y = B_0 \exp(\beta_1 x) $$
Where $B_0 = \exp(\beta_0)$ is the median income when individuals have 0 years of training (why median and not mean?  I will get to that).
So how do we interpret this regression.  When $x$ increases by $1/\beta_1$ units, then the median income increases by a factor of $e$.  Consider someone with 0 years of training and compare then to someone with $1/\beta_1$ years of training.
The median income of the latter person is $y_1 = B_0 \exp(\beta_1 \times \frac{1}{\beta_1}) = B_0 \exp(1)$.  The median income for the former person is $y_0 = B_0 \exp(0) = B_0 = y_1/\exp(1)$.  Hence, the median income has increased by a factor of $e$
Why The Median And Not The Mean?
OLS does not require the residuals to be normally distributed (or even independent of one another).  That being said, some assumptions on the conditional distribution can give us some insight.
If we assume the conditional distribution is normal, then this means $\log(y) \vert x$ is normal and hence $y \vert x$ is lognormal.  According to some results about the log normal, if $\mu$ is the expectation of the underlying normal random variable, then $\exp(\mu)$ is the median of the lognormal not the mean.  To get the mean, we would have to estimate the residual variance and multiply our prediction by a factor of $\exp(\sigma^2/2)$.  The relationship between changes in the predictor and changes in the expectation of the log normal random variable are the same as the median since the effects are multiplicative.
Comment: thanks, how about if we used dummy variables instead, how would that affect interpretation
Comment: @king34  A dummy variable would change the median income by a factor of $\exp(\beta)$, where $\beta$ is the estimated coefficient.


How many connected components does the following infinite graph have?

Question: Consider the undirected infinite graph whose nodes are the positive integers $1,2,3,4,...$, and where there is an edge between two nodes $n$, $m$ if and only if $\frac{n^2+n}{2} = m$. How many connected components does this graph have? How might we characterize them?
Comment: Why is that? Is there some number theoretic reason? That seems like the intuitive answer to me, given the relative sparseness of edges, but I can't give myself a concrete reason why.
Comment: Find the Laplacian of the graph and then find eigendecomposition and number of zero eigenvalues are the number of connected components
Comment: Yes, sorry. It's been awhile since I've done any graph theory, so my terminology was off. What I meant was connected components, i.e. maximal connected subgraphs.
Answer: As far as I can tell, your graph is the disjoint union of infinitely many half-infinite paths and one isolated vertex $1$ (or a loop if you want, because $(1^2+1)/2=1$). Each vertex $n$ has at least one, but also at most two neighbors, namely $(n^2+n)/2$ and maybe an $m$ with $(m^2+m)/2= n$. So there are infinitely many connected components, all but one being one of the paths.
Why are there infinitely many such paths? Choose some prime $p>2$. Every number that follows on $p$ in its path will be a multiple of $p$. So no prime $q>p$ will be part of this path. You see that every path can contain at most one (odd) prime, hence there must be infinitely many paths.
Answer: There will be infinitely many.
Note that $m$ is the sum of the numbers $1$ through $n$.
Hence, $1$ is connected to $1$, and $1$ only, so one subgraph is:
$1 \rightarrow 1$
$2$ is connected to $3$ (since $3$ is sum of $1$ and $2$), which is connected to $6$ (sum of $1$ through $3$), which is connected to $21$, etc., so you get:
$2 \rightarrow 3 \rightarrow 6 \rightarrow 21 \rightarrow ...$ (this one will go on forever of course)
But, you just skipped $4$, so you also get:
$4 \rightarrow 10 \rightarrow 55 \rightarrow ...$
and then you have:
$5 \rightarrow 15 \rightarrow 120 \rightarrow ....$
In fact, there will always be number that you skipped, since not every number is the sum of numbers $1$ through $n$, and hence that number will start yet another subgraph that consists of just one long linear infinite path. So, you get infinitely many of such infinitily long subgraphs, together with the $1 \rightarrow 1$ subgraph.


Calculating standard error of the mean from multiple files in a directory in R

Question: I have multiple text files (hundreds of them) in a directory. Each text has dimensions 225 rows and 50 columns (all the same row names and column names). All text files are numbers and I need to generate one data-frame that takes the standard error of the mean of each cell of all of these text files.
There is plenty of code to calculate one master data-frame that has the average in each cell of all text files in a directory but none for calculating one master data frame that just shows standard error of the mean in every cell.
For example, this will bring in all text files, read them, and generates one master data frame that has the average each cell for each text file.
txt <- lapply(list.files(pattern = ".txt"), read.delim)
Z <- Reduce("+", txt) / length(txt)

Which gives one data frame that looks like this:
>head(Z)
      C1   C2  C3
Row_1 20   22  25
Row_2 14   9   22

But these are averages of all text files combined into one data frame. I would like this to be standard errors of the mean instead, and unfortunately I haven't found posts that can generate this result. There are plenty of posts that take the standard error of columns of one data-frame, just not this many stored in a directory.
I have tried this, but unfort. it does not work:
SE <- Reduce("sd", txt) /sqrt(length(txt)

Any help would be greatly appreciated. Thank-you.
Answer: One option would be to unlist, create an array and use one of the custom functions that calculate standard error
library(plotrix)
dim1 <- c(dim(txt[[1]]), length(txt))
apply(array(unlist(txt), dim1), 1:2, std.error)
#          [,1]      [,2]     [,3]      [,4]
#[1,] 1.666667 1.2018504 1.452966 1.7638342
#[2,] 2.081666 1.5275252 1.527525 2.3333333
#[3,] 2.027588 0.8819171 1.855921 0.8819171

which is also equal to the function OP showed for calculating
apply(array(unlist(txt), dim1), 1:2,  function(x) sd(x)/sqrt(length(x)))
#        [,1]      [,2]     [,3]      [,4]
#[1,] 1.666667 1.2018504 1.452966 1.7638342
#[2,] 2.081666 1.5275252 1.527525 2.3333333
#[3,] 2.027588 0.8819171 1.855921 0.8819171

It can also be used to calculate the mean
Reduce(`+`, txt)/length(txt)
#        V1       V2       V3       V4
#1 5.333333 6.333333 5.333333 4.666667
#2 4.000000 3.000000 4.000000 5.333333
#3 4.666667 4.666667 6.666667 6.666667

apply(array(unlist(txt), dim1), 1:2, mean)
#         [,1]     [,2]     [,3]     [,4]
#[1,] 5.333333 6.333333 5.333333 4.666667
#[2,] 4.000000 3.000000 4.000000 5.333333
#[3,] 4.666667 4.666667 6.666667 6.666667

apply(array(unlist(txt), dim1), 2, rowMeans)

data
set.seed(24)
txt <- lapply(1:3, function(i) as.data.frame(matrix(sample(1:9, 3 * 4,
      replace = TRUE), 3, 4)))

Comment: Thank you very much! This worked beautifully! Just as a side note, this replaced all of my column names with the generic "V1, V2, V3", etc. in the final data-frame. After looking at my data, I think this code preserves the column order, so I can just rename them with the same column name as the txt files (they all have the same column names in the same order).


is includePadding not recommended as PlatformTextStyle is deprecated in jetpack compose?

Question: I'm developing with jetpack compose.
When I use includePadding = false,
in compose, the feature is used like below
platformStyle = PlatformTextStyle(includeFontPadding = false)

But the jetpack compose docs say like below,
includeFontPadding was added to Android in order to prevent clipping issues on tall scripts.
However that issue has been fixed since Android 28.
Jetpack Compose backports the fix for Android versions prior to Android 28.
Therefore the original reason why includeFontPadding was needed in invalid on Compose.
This configuration was added for migration of the apps in case some code or
design was relying includeFontPadding=true behavior and will be removed

As above mentioned, I'm confused with whether to use includePadding.
Is there other way to use includePadding = false or Is it not recommended to use includePadding = false?
Comment: @ADM Nope, in 1.2.0-beta01 in is turned ON by default again.
https://developer.android.com/jetpack/androidx/releases/compose-ui#1.2.0-beta01

PlatformTextStyle, however, id marked as deprecated - and it is really confusing.
Comment: The doc says everything . the clipping was fixed a while ago https://developer.android.com/jetpack/androidx/releases/compose-ui#1.2.0-alpha05 .
Comment: @ADM fixed what exactly? see the example https://stackoverflow.com/questions/75832996/jetpack-compose-platformtextstyle-includefontpadding-is-deprecated-so-what-is-t
Comment: Is confusing for me as well, I need to remove the padding included by default, my implementation has nothing to do with the coment and the deprecation coment also don't tell what should we use instead
Answer: Based on what is relevant at the time of the answer, if you are using a version less than 1.6.0-alpha01, then you can use it without problems and not think about the deprecation signature

Update June 2023: Compose ui 1.6.0-alpha01 is the first version with includeFontPadding switched to false by default.

Use PlatformTextStyle API from Compose 1.2.0 to configure includeFontPadding. For few compose versions it was deprecated on purpose to indicate that it is a compatibility API, but has been undeprecated in compose 1.5 to encourage developers to use it.

or you can simply upgrade to the latest version and be happy
read more here


Fitting of a sum of vectors $Y \alpha = X \beta + \epsilon$

Question: Related question / Motivation
This question is related to the question here. But the difference in this question is that the weights can be different on both sides of the equation.

This question
This question is an extension of linear regression where we find coefficients $\beta$ relating to the model
$$y = X \beta  + \epsilon = \hat{y} + \epsilon$$
The solution that minimizes $\epsilon$ is also maximizing the correlation between $y$ and $\hat{y}$.
What if $y$ is now containing some flexibility as well and we have a model like
$$ Y \alpha = X \beta  + \epsilon$$
To minimize the $\epsilon$ the trivial answer is $\alpha$ and $\beta$ being equal to $0$ but say that we exclude this option? Ie. we could add the restriction that $\sum \alpha_i  = 1$
Find coefficients $\alpha$ and $\beta$ such that we maximize the correlation between $Y \alpha $ and $X\beta $.
We can assume that the columns in $X$ and $Y$ have zero mean.
Answer: If the correlation between $Y \alpha $ and $X \beta$ is maximized then the $\beta$ are such that it is the OLS solution of $\alpha Y$ (where we either translate the columns in $X$ such that the column means are zero, or we add an intercept to the OLS regression).
So we have $$X \beta = X(X^T X)^{-1}X^TY \alpha = Y_{\parallel} \alpha$$
the difference is
$$X \beta  - Y \alpha = (X(X^T X)^{-1}X^T-I)Y \alpha = Y_{\perp} \alpha$$
The image below illustrates this in 3 dimensions.

The possible solutions $Y\alpha$ and $X\beta$ are in a surface spanned by the vectors $Y_1, Y_2, ... Y_n$ and $X_1, X_2, ... X_n$. For a given $\alpha$ the solution of $\beta$ that minimizes the correlation is the OLS solution, ie. the perpendicular projection of $Y\alpha$ onto the surface spanned by $X$.
In this example with 3D coordinates we see that the planes intersect and $\alpha$ can be changed such that the vector $Y\alpha$ is entirely in the plane spanned by $X$. And the correlation can be made equal to 1. But in more dimensions, the hyper-surfaces might not need to intersect (except in the point zero where the planes always intersect).

Solution with optimization using a Lagrangian function
Maximizing the correlation between $X \beta $ and $Y \alpha$ is like minimizing the ratio of the length of the vectors $Y_{\perp} \alpha$ and $Y_{\parallel} \alpha$ or $Y \alpha$. The correlation is larger for a smaller remainder $Y_{\perp} \alpha$ while keeping the projection $Y_{\parallel}\alpha$ or total vector $Y \alpha$ the same size.
We can solve this by minimizing the Lagrangian
$$L(\alpha, \lambda) = \alpha^T \, M_{\perp} \, \alpha + \lambda(\alpha^T \, M \, \alpha - 1)$$
where $M_{\perp} = Y_{\perp}^TY_{\perp}$ and $M = Y^TY$
whose gradient must be zero leading to the equations
$$ \begin{array}{}
(M_{\perp}+\lambda M) \alpha &=& 0 \\
 \alpha^T\,M \, \alpha  &=& 1
\end{array}$$
To solve the first equation,  we are looking for a constant $\lambda$ and vector $\alpha$ such that
$$M_{\perp}\alpha = -\lambda M \alpha $$
or
$$(M^{-1}M_{\perp}) \alpha = -\lambda \alpha $$
Which makes the $-\lambda$ and $\alpha$ the eigenvalues and eigenvectors of $(M^{-1}M_{\perp})$.
The solution with the maximum correlation will be related with the smallest eigenvalue $\lambda_v = -\lambda$. This is because we can compute the correlation as
$$\rho = \sqrt{1-\frac{\alpha^T \, M_{\perp} \, \alpha }{\alpha^T \, M \, \alpha }} = \sqrt{1-\frac{\alpha^T \, \lambda_v M \, \alpha }{\alpha^T \, M \, \alpha }} = \sqrt{1-\lambda_v} $$
So an algorithm to find $\alpha$ and $\beta$ is to compute the eigenvectors of that matrix and select the one with the smallest absolute value of the eigenvalue.
Code example
<code>library(MASS)
set.seed(1)
### create X and Y
X = t(mvrnorm(3,mu = rep(0,10), Sigma = diag(10) ))
Y = t(mvrnorm(3,mu = rep(0,10), Sigma = diag(10) ))

### subtract the means (without loss of generality)
X = X - rep(1,10) %*% t(colMeans(X))
Y = Y - rep(1,10) %*% t(colMeans(Y))

### compute matrices
P = X %*% solve(t(X) %*% X) %*% t(X)  ### projection matrix
Ypar = P %*% Y                        ### Y projected on X
Yperp = Y-Ypar                        ### residual of projection
M = t(Y) %*% Y               ### quadratic form to compute square length
Mperp = t(Yperp) %*% Yperp

### solve with eigenvectors
eV = eigen(solve(t(M)) %*% Mperp)$vectors

### compute Xbeta and Yalpha
### when putting alpha equal to the last eigenvector
### the last eigenvalue is the one with the lowest eigenvalue
alpha = alpha = eV[,length(eV[1,])]
yfit = Y %*% alpha
xfit = P %*% yfit
corrV = cor(yfit,xfit)

### optimization of correlation
f<-function(p){
  a1 = p[1:3]
  a2 = p[4:6]
  rho = cor((Y %*% a1),(X  %*% a2))
  d = abs(sum(a1^2)-1)^2
  return(-rho+d)
}

a = rep(1,6)
### optimize correlation
mod <- optim(a,f, method = "BFGS",control = list(maxit=1*10^5,trace=1,reltol=10^-16))
mod

### check results of models
yh = Y %*% mod$par[1:3]
xh = X %*% mod$par[4:6]

### correlation from optimization
### 0.69886626
cor(yh,xh)

### correlation from eigenvectors
### 0.6988626 (it's the same)
max(corrV)
</code>
Intuition
The correlation in terms of the vector $\alpha$ is the ratio of the length of the vectors
$$\rho = \frac{\Vert Y_{\parallel} \alpha \Vert}{\Vert Y \alpha \Vert} = \sqrt{\frac{\alpha^T \, M_{\parallel} \, \alpha}{\alpha^T \, M \, \alpha}} =\sqrt{\frac{\alpha^T \, M^{-1} M_{\parallel}  \alpha}{\alpha^T\alpha}}$$
If we restrict the $\alpha$ to be of a specific size then the alpha that maximizes this product $\alpha^T \, M^{-1} M_{\parallel}  \, \alpha$ is directed along the eigenvector with the largest eigenvalue.


Adding more fields to the registration process

Question: In Drupal 7, is there a way to add more fields to the registration process? I was thinking along the lines of birthday, fullname, gender, twitter, etc. Also how do I access this data once it's in, so I can output it to my template files?
Answer: Since D7, field management is included in the core. Almost every kind of content has now the ability to be managed with fields.
You can go to admin/config/people/accounts/fields to manage user fields. There is also a tab for managing the display.
Comment: @Dewsworld you need to check mark at 'Display on user registration form.' at the field edit page, e.g for Date of birth field(field_dob) the url is admin/config/people/accounts/fields/field_dob.
Comment: Where is this *admin/config/people/accounts/fields?* I can't find it in D7.
Comment: You need to go to :
Configuration > People (first block in default admin) > Account settings. In the account settings page there is a "Manage Fields" tab.
Comment: I'm able to add new fileds, but cannot make them visible on the registration process!
Comment: I have been able to do all of the above, but my fields don't show up on the edit account pages for the users, only for the admin. Any ideas? I would be very grateful!
Comment: @reptilex, I found the problem that caused this issue for me, it was that I had the Organic Group Field Access module enabled.  Once I disabled it, everything works again for my users.  More details at: https://www.drupal.org/node/1201582
Answer: Administration » Configuration » People » Account settings » Manage fields
Make sure once again by edit the new fields and its check box for  Required field and
Display on user registration form will be enabled.


Find X509 certificate from store based on Thumbprint

Question: I am trying to find a certificate from store using its Thumbprint. I am having very hard time to find what is the problem with my code.
Top section shows my code with debugger stopped at that position. Then I have copied that statement into Immediate Window and the count is zero.
There are two certificates in the location that I am trying to find and second certificate is what i am interested in. So I have modified the statement to use the thumbprint of that certificate rather than typing it manually in. Now the count is 1.
Then I just printed Thumbprint and copied to previous statement and count is 1. So I thought there is a typo. but I you see the last two statements, there is no typo. only difference is spaces, which does not matter. But I tried making both statements look exactly same but result always differ.
Not sure what is going on... either i am missing very simple thing or i am too stupid.
Answer: Your original string might contain invisible Unicode characters. If the thumbprint string from Certificate[1].Thumbprint works fine, copy it from debug window and use that one instead.
Comment: this one helped http://stackoverflow.com/questions/11115511/how-to-find-certificate-by-its-thumbprint-in-c-sharp
Comment: i have this problem again. Previously i was able to solve it by copying from debugger but I cannot do that for prod deployment. Copying the thumbprint to notepad also did not help. Any other suggestions?


Card game Probability: Having a second war after a first war

Question: I was wondering about the probability of getting two wars.  The way the game works is, both players get $26$ cards, and flip one card over, whoever has the largest card value, takes both cards and puts them underneath the deck.
Now the tricky part comes when the two cards flipped over have an equal value, this is called a "war".  At a war, the players each flip another card on the top of their deck over, and whoever has the highest value card gets all the cards on the table.  My question is, what is the chance that these two cards also have equal value?  So, the probability of having two cards out of $52$, be equal, then the next two cards be equal.
I keep arriving at this number: $\frac{3}{49} + \frac{1}{49} = \frac{4}{49} = 0.0816$.
Thanks for the help!
Answer: I think you can ignore everything except for the two flips that result in war. Given that there was a war on the first flip, the deck has lost two cards of equal rank.
Then $50$ cards remain. There are $12$ complete ranks of $4$ cards each. Each of those ranks has $\binom{4}{2}=6$ possible pairs. The $13$th rank is the one that was drawn for the first war, and there is only $1$ remaining pair of that rank.
Overall there are $(12\cdot6)+1=73$ pairs left in the deck of $50$ cards.
So the probability of a second war is $\frac{73}{\binom{50}{2}}=\frac{73}{1225}\approx5.96\%$
Comment: Ah I see, thanks!  I was wondering what was wrong with my calculation though, do you by any chance know?
Comment: Can you say a bit more about where the numbers in your calculation came from?
Comment: Yes.  After the first war, I assume 2 cards have been lost.  So, instead of 52 cards, there are now 50 cards.  When one person flips a card over, there are now 49 cards, with 3 cards able to match its rank.  Giving 3/49.  However, there is the chance that the person gets the card of the same rank as the first war.  And the chance to match that is 1/49.  So I have 3/49 + 1/49.
Comment: Ah, got it. So, you need to assign weights to each of those fractions. There is a $\frac{48}{50}$ probability that the first card flipped was not another of the same rank from the first war, and a $\frac{2}{50}$ probability it was one of the same rank from the first war. So the calculation should be $\frac{48}{50}\cdot\frac{3}{49}+\frac{2}{50}\cdot\frac{1}{49}$. This results in the same answer I got the other way.
Comment: @DreiCleaner, sorry, I didn't see your comment here until just now, after posting an answer saying the same thing.
Comment: Great minds think alike!
Comment: @DreiCleaner, I was thinking much the same!
Answer: This answer is in response to the OP's request, in comments below DreiCleaner's answer, to explain what is wrong in their (mis)calculation ${3\over49}+{1\over49}$.
The OP is quite right that if the third card flipped is matches the rank of the cards in the first war, then there is only a $1/49$ chance the fourth card will match the third. But this (the third card matching the first to) only happens with probability $2/50$ -- that is, the third card must be one of the $2$ cards of the same rank from the first war, out of $50$ cards available. Similarly, if the third card is different from the rank of the first war, which happens with probability $48/50$, then the fourth card will match it with probability $3/49$. So a correct calculation of the probability of a second war is
$${48\over50}\cdot{3\over49}+{2\over50}\cdot{1\over49}={24\cdot3+1\over25\cdot49}={73\over1225}$$
as in DreiCleaner's answer.
Comment: Ah, I see DreiCleaner said all this in a reply to the OP's comment.


able to access only the / route in Laravel 5.2

Question: I am able to access only the '/' route and all my other routes are returning 404.
I have installed laravel on a new EC2 instance and I have ensured that my php, Mysql and apache2 are all running
My Laravel version is 5.2.45
my 000-default.conf is as follows
<VirtualHost *:80>

        ServerAdmin webmaster@localhost
        DocumentRoot /var/www/html/testing/public

        ErrorLog ${APACHE_LOG_DIR}/error.log
        CustomLog ${APACHE_LOG_DIR}/access.log combined

</VirtualHost>

my apache2.conf file is as follows
<Directory />
        Options FollowSymLinks
        AllowOverride None
        Require all denied
</Directory>

<Directory /usr/share>
        AllowOverride None
        Require all granted
</Directory>

<Directory /var/www/html/testing/public>
        Options Indexes FollowSymLinks
        AllowOverride None
        Require all granted
</Directory>

my folder structure is /var/www/html/testing
But I am getting a 500 when trying to hit the ip..Any help will be highly appreciated.
routes.php
**********Physiotherapist******/
Route::get('/home-request/physiotherapist', 'HomeController@physiotherapist');
Route::post('/physiotherapist', 'ServicesController@requestPhysio');
Route::post('/physiotherapist/getPhysioRates', 'ServicesController@getPhysioRates');

/********** Doctor *************/
Route::get('/home-request/doctor', 'HomeController@doctor');
Route::post('/doctor', 'ServicesController@requestDoctor');
Route::post('/doctor/getDoctorRates', 'ServicesController@getDoctorRates');

/********** Patient Attendant *************/
Route::get('/home-request/patient-attendant', 'HomeController@patient');
Route::post('/patient', 'ServicesController@requestAttendant');
Route::post('/patient/getPatientAttendantRates', 'ServicesController@getPatientAttendantRates');

/public/.htaccess file
<IfModule mod_rewrite.c>
    <IfModule mod_negotiation.c>
        Options -MultiViews
    </IfModule>

    RewriteEngine On

Options -Indexes

RewriteCond %{REQUEST_FILENAME} !-f
 RewriteRule ^([^\.]+)$ $1.php [NC,L]
# RewriteRule ^([^\.]+)/([^\.]+)$ /$2.php  [L]
    # Redirect Trailing Slashes If Not A Folder...
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^(.*)/$ /$1 [L,R=301]

    # Handle Front Controller...
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^ index.php [L]

    # Handle Authorization Header
    RewriteCond %{HTTP:Authorization} .
    RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]

</IfModule>

<ifmodule mod_expires.c>
  ExpiresActive On
  AddType image/x-icon .ico
  ExpiresByType image/gif "access plus 60 days"
  ExpiresByType image/jpeg "access plus 60 days"
  ExpiresByType image/png "access plus 60 days"
  ExpiresByType image/ico "access plus 60 days"
  ExpiresByType image/x-icon "access plus 60 days"
  ExpiresByType text/css "access plus 60 days"
  ExpiresByType application/javascript "access plus 60 days"
  ExpiresByType application/x-javascript "access plus 60 days"
  ExpiresByType text/javascript "access plus 60 days"
  ExpiresByType application/json "access plus 7 minutes"
</ifmodule>
## EXPIRES CACHING ##

<IfModule mod_deflate.c>
  # Compress HTML, CSS, JavaScript, Text, XML and fonts
  AddOutputFilterByType DEFLATE application/javascript
  AddOutputFilterByType DEFLATE application/rss+xml
  AddOutputFilterByType DEFLATE application/vnd.ms-fontobject
  AddOutputFilterByType DEFLATE application/x-font
  AddOutputFilterByType DEFLATE application/x-font-opentype
  AddOutputFilterByType DEFLATE application/x-font-otf
  AddOutputFilterByType DEFLATE application/x-font-truetype
  AddOutputFilterByType DEFLATE application/x-font-ttf
  AddOutputFilterByType DEFLATE application/x-javascript
  AddOutputFilterByType DEFLATE application/xhtml+xml
  AddOutputFilterByType DEFLATE application/xml
  AddOutputFilterByType DEFLATE font/opentype
  AddOutputFilterByType DEFLATE font/otf
  AddOutputFilterByType DEFLATE font/ttf
  AddOutputFilterByType DEFLATE image/svg+xml
  AddOutputFilterByType DEFLATE image/x-icon
  AddOutputFilterByType DEFLATE text/css
  AddOutputFilterByType DEFLATE text/html
  AddOutputFilterByType DEFLATE text/javascript
  AddOutputFilterByType DEFLATE text/plain
  AddOutputFilterByType DEFLATE text/xml
    Header append Vary User-Agent
</IfModule>

Comment: Could you share the `routes.php` and the `/laravel/public/.htaccess` file?
Comment: Various ways are mentioned here, check
https://stackoverflow.com/questions/13514990/laravel-4-all-routes-except-home-result-in-404-error
Comment: I have updated the same..please check and advise
Comment: Does your apache2 log give any clues to what the error is?
Comment: where will I find this log file in Ubuntu 16.04?
Comment: I have the default .htaccess file in the public folder so do I need to do anything in the .htaccess file?
Answer: You need to allow override in Your appache conf. Try this:
<Directory /var/www/html/testing/public>
        Options Indexes FollowSymLinks
        AllowOverride All
        Require all granted
</Directory>


How many solutions for $37+\frac{3(x-1)x}2+3^{x+2}=y^2\,$?

Question: How many solutions does the following exponential diophantine equation have in the positive integers?
$$37+\frac{3(x-1)x}2+3^{x+2}=y^2$$
The solutions $\,(x,y)\,$ I have found are: $\;(1,8),\;(2,11),\;(3,17),\;(4,28)$.
Are the only solutions?
Many thanks.
P.S. The equation has been built noting that:
$$27+37+0=64=8^2$$
$$81+37+3=121=11^2$$
$$243+37+9=289=17^2$$
$$729+37+18=784=28^2$$
Comment: Not all such equations involving both exponential and non-exponential terms will have easy solutions, in fact these problems will generally be very hard unless we are lucky that special tricks exist to solve them (e.g. modular arguments happen to work).
Comment: @Mastermind817 I'd like to buy a vowel.  I've worked on it for 15 minutes, and got nowhere.  If no protocol violation, request hint or online (e.g. pdf) pertinent reference.
Comment: Those are indeed the only positive integral solutions to the equation. But you haven't shown as to how you got them. And if you only want to check if they are the only ones, you could easily have searched WolframAlpha. However if you want a method then that's a different case.
Comment: No Wolfram. It's not difficult to build exponential diophantine equations giving squares for few positive integers. For example: $x2^x+57=y^2$ for $x=3, 4, 6$.
Comment: Usually, modulo arithmetics does not work if a solution exists. It would be interesting to see a proof here. Already the "usual" diophantine equations are not solvable in general (Hilbert's tenth problem) , exponential equations are in general even more difficult. What is the trick in this case ?
Comment: In general, if Wolfram Alpha presents a solution, there is no guarantee that the solution is complete. It might be able to do it in this case.
Comment: I wonder if one could reverse engineer a proof that those are the only solutions by looking at the algorithm(s) used by WA to compute those specific solutions.
Comment: Case 1: $x$ is even
Let $a = 3^{(\frac{x+2}{2})}$
 $3^{x+2} = a^2$
Now the minimum difference between $l^2$ and $m^2$ is $2l+1$ where $l$ is the smaller one

Therefore, $y^2 - a^2 = 37+ \frac{3(x-1)(x)}{2} \ge 2a+1$
Since $a$ is exponential it will rise very very quickly and so you can try putting smaller values of $x(2,4)$. It is clear that for $x \ge 6$, $2a+1$ is greater.
Comment: Equivalent to no solutions to $81^{1+X}=12Y^2+4Y-8X^2-10X-15$ where $X,Y\ge0$.
Answer: The following can be found with the 15-digit precision of Excel.
$$
(1,8)\quad
(2,11)\quad
(3,17)\quad
(4,28)\quad
(36,1162261467)\quad
(38,3486784401)\quad
(40,10460353203)\quad
(42,31381059609)\quad
(44,94143178827)\quad
(46,282429536481)\quad
(48,847288609443)\quad
(50,2541865828329)\quad
(52,7625597484987)\quad
(54,22876792454961)\quad
(56,68630377364883)\quad
(57,118871300538602)\quad
(58,205891132094649)\quad
(59,356613901615807)\quad
(60,617673396283947)\quad
$$
But WolframAlpha disagrees with the $x\ge36$ as seen here so, if there are other pairs, it would take software with arbitrary precision to find them.
Comment: I used Python and Sympy library. I did not find any other solution except for the first four.


Segurança em formulário

Question: Eu tenho o seguinte código:
PHP (servidor):
if(isset($_POST['subdate']) && !empty($_POST['date'])) {

   $daysOff = array();
   $get_date = explode(',', $_POST['date']);
   foreach ($get_date as $date) {
     $date = explode('-', $date);
     $day = $date[0];
     $month = $date[1];
     $year = $date[2];
     $time_Stamp = mktime(0,0,0,$month,$day,$year);
     $daysOff[] = strftime('%d-%m-%Y', $time_Stamp);
   }

   $daysOff = json_encode($daysOff);
   echo "dates off: " .$daysOff;
}

else {
   $daysOff = json_encode(array("23-09-2015", "15-09-2015"));
   echo "dates off: " .$daysOff;
}

HTML (cliente)
...
<link rel="stylesheet" href="https://code.jquery.com/ui/1.11.4/themes/pepper-grinder/jquery-ui.css">

...
<form method="POST">
    <input id="datepicker" type="date" name="date" autocomplete="off" readonly>

    <input type="submit" name="subdate">
</form>
...

Javascript (cliente)
function datePicker() {

   <?php echo "var datesOff = JSON.parse('" .$daysOff. "');"; ?>
   var daysSelected = [];

   var datepickerOpts = {

      beforeShowDay: function(date){

         var day = $.datepicker.formatDate('dd-mm-yy', date);
         var checkDate = datesOff.indexOf(day);

         if(checkDate == -1) {
             // not found, data available
             return [true, "", "available"];
         }
         else {
            return [false, "", "not available"];
         }
      },
      onSelect: function(date) {

         var index = daysSelected.indexOf(date);

         if(index == -1){
            daysSelected.push(date);
            console.log(daysSelected);
         }
         else {
            daysSelected.splice(index, 1);
            console.log(daysSelected);
         }
         $('input[type="date"]').val(daysSelected);
         // prevent from closing datepicker when clicking date
         $(this).data('datepicker')['inline'] = true;
      },
      onClose: function() {
         $(this).data('datepicker')['inline'] = false;
      },
      dateFormat: 'dd-mm-yy',
      showOn: "both",
      buttonImage: "http://icons.iconarchive.com/icons/icons8/ios7/256/Time-And-Date-Calendar-icon.png",
      buttonImageOnly: true,
      buttonText: "Select date",
      showAnim: "slideDown",
   };

   $('#datepicker').datepicker(datepickerOpts);
}

datePicker();

Tudo funciona muito bem, partindo do príncipio que não vão mudar manualmente o valor do input como mostro na imagem abaixo, o que faz disparar um erro no servidor, mais especificamente com a função explode. Eu queria evitar isso, gostava que houvesse uma simples verificação (já tentei com try/catch), ex: se os inputs fossem este formato: "dd-mm-aaa,dd-mm-aaaa" é que avançamos para os explodes etc... Tendo em mente que tem de resultar também se só houver uma data: "dd-mm-aaaa". Outras sugestões para evitar que sejam disparados erros neste caso também são bem vindas. Exemplo do que acontece:
Antes de submeter, mudar manualmente o valor:

Depois de submeter:

Erros surgem quando tentamos aceder aos indexes (keys) de $date, dentro do ciclo que temos no código do lado servidor.
Answer: A maioria dos seus problemas serão resolvidos com algumas simples validações, exemplo:
<?php

if(isset($_POST['subdate']) && !empty($_POST['date'])) {

   $daysOff = array();
   $get_date = explode(',', $_POST['date']);
   foreach ($get_date as $date) {

      // Validação com Expressão Regular
      // Apenas com essa validação você pode resolver a maioria dos seus problemas
      if(!preg_match('/^([0-9]{2}\-[0-9]{2}\-[0-9]{4})$/', $date)){
         // Não está no formato NN-NN-NNNN
         // Tome qualquer providencia aqui
      }

      $date = explode('-', $date);

      // Validando a quantidade de elementos retornados pelo explode
      if (count($date) == 3){
         $day = $date[0];
         $month = $date[1];
         $year = $date[2];
         $time_Stamp = mktime(0,0,0,$month,$day,$year);
         $daysOff[] = strftime('%d-%m-%Y', $time_Stamp);
      } else {
         // O explode não resultou em 3 elementos
         // Tome qualquer providencia aqui
      }
   }

   $daysOff = json_encode($daysOff);
   echo "dates off: " .$daysOff;
} else {
   $daysOff = json_encode(array("23-09-2015", "15-09-2015"));
   echo "dates off: " .$daysOff;
}

Comentei o código mostrando as validações. Tenha em mente uma coisa, sempre que receber dados do usuário/cliente, mesmo que por uma biblioteca javascript é crucial validar esses dados. Qualquer dado de entrada deve ser validado pelo sistema, ainda mais quando o processo depende desses dados.
Ainda poderia fazer outras validações, pra verificar se os dados realmente são datas: Correctly determine if date string is a valid date in that format
Comment: Já está a resultar, enganou-se em `[0-2]{4})$` devia ser também `[0-9]...`. Já agora que quer dizer o `^`, `/`, "\", `$` no preg match? Obrigado mais uma vez
Comment: Verdade, me enganei ali no `[0-2]{4}`, já corrigi. `^` quer dizer "início", `/` são delimitadores da expressão regular, `$` quer dizer "fim" e `\ ` é o escape para o carácter literal `-` que contém na data, essa barra não é absolutamente necessária, mas é bom para evitar possíveis bugs e erros @Miguel
Comment: Obgado, era uma solução como ess que procurava, simples e capaz de ter o trabalho feito. mas não está a aceitar as datas certas também, mas creio que com um pouco de correção consiga
Answer: Bem, como você trabalha com formulários e não sabemos o que o cliente vai passar seria bom para evitar varios erros, adicionar uma mascara de date no seu input.
Outra coisa que costumo fazer no meu codigo é sempre usar DateTime do php, uma dica para você trabalhar com a data seria mais ou menos assim no parametro de entrada.
Ex:
$newDate = implode('-', array_reverse(explode('/', $date)));
$newDate = new DateTime($newDate);
E no parametro de saida você adiciona um tratamento para o date.
Comment: Jose seja bem vindo ao StackOverflow em Português, [leia esse tópico](http://pt.stackoverflow.com/editing-help) para conhecer melhor o modelo de formatação de perguntas do SOpt, assim melhora a qualidade da sua resposta e de toda a comunidade no geral.

Segurança em formulário


why my image gallery is not closing

Question: I am making a image gallery with fancy box with title, but when i click on image, the image is opening but can not close the image or can not find a close button. I am using html , css and javascript . I am uploading a image to show what is my problem.

$(document).ready(function(){
    //FANCYBOX
    //https://github.com/fancyapps/fancyBox
    $(".fancybox").fancybox({
        openEffect: "none",
        closeEffect: "none"
    });
});

html
<link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/fancybox/2.1.5/jquery.fancybox.min.css" media="screen">

                        Image Title

                        Image Title

                        Image Title

                        Image Title

                        Image Title

                        Image Title

css
.gallery
{
    display: inline-block;
    margin-top: 20px;
}

Comment: Any JS errors in Developer Console?
Answer: You have links pointing to images in your html, which should be causing the issue. It's opening the image in a new page, not the desired gallery

try using other element or removing the href attribute

why my image gallery is not closing


Uniqueness of the result of rewritting an algebraic expression using distributivity rule

Question: Let $expr$ be an algebraic expression involving natural numbers, addition operator and multiplication operator, e.g.,
$$(1+2)\cdot(3+4 \cdot 5)+6.$$
By iteratively applying the distributivity of multiplication over addition to $expr$, that is, transforming subexpressions of the form $(expr_1 + expr_2)\cdot expr_3$ into the form
$(expr_1\cdot expr_3) + (expr_2 \cdot expr_3)$, until it is no longer possible, at each iteration applying the distribituvity rule to the first (the "leftmost" one) subexpression that it can be applied to, one obtains a sum of products. No other rules are applied, no addition and no multiplication is actually performed. For the above example, the result would be
$$1\cdot 3 + 1\cdot 4 \cdot 5 + 2 \cdot 3 + 2\cdot 4 \cdot 5 + 6.$$
Is the obtained sum of products unique?
If yes (as I believe is the case), is there a general result that this fact follows from?
$\textbf{Edit:}$

the distributivity rule $expr_1 \cdot (expr_2+ expr_3) \rightarrow (expr_1 \cdot expr_2 )+ (expr_1 \cdot expr_3)$ can also be applied

$\textbf{Solution:}$
By formalizing properly the reduction rules that I had in mind, I got a reduction system that is both locally confluent and terminating. Now the uniqueness of the normal form follows from the Newman's lemma.
Comment: Do you know about [Newman's diamond lemma](https://mathoverflow.net/questions/289300/newmans-lemma-or-diamond-lemma)? I suspect it leads to a fairly straightforward proof of this once you have formalized the question (there are a few choices to be made in formalizing it, such as whether you encode sums $a_1+a_2+\cdots+a_k$ as multisets or as tuples, and likewise for products).
Comment: I'm just seeing you are trying to tie-break your rewrite system by applying the rewrite rule to the leftmost pattern at each step. But then there is nothing to prove!
Comment: Alternatively, you can work in the polynomial ring over $\mathbb{Z}$ in a bunch of variables (as many as there are numbers in your original expression). Replace the numbers in your original expression by the variables. All rewriting steps you make still work after this replacement, since you are never actually simplifying the numbers. But the result is clearly unique, since it is the expanded form of the polynomial.
Comment: @darij grinberg: will have a look at the lemma, thanks!

And yes, I tried to make things easier by applying the rules to the leftmost patterns. I see that in such a case it is somewhat "obvious" that the result is unique, but I fail to provide even a simplest formal justification for that.
Answer: Let $N$ be a language for natural numbers. The set $E$ of algebraic expressions is inductively defined by the following rules:

If $n \in N$, then $n \in E$.
If $e, e' \in E$, then $(e + e') \in E$.
If $e, e' \in E$, then $(e \cdot e') \in E$.

In order to define a function $f \colon E \to E$ transforming an expression $e$ into another expression $f(e)$, one just needs to use structural recursion. In your case, the function $f$ is defined by the following rules:

 If $n \in N$, then $f(n) = n$.
  If $e, e' \in E$, then $f((e + e')) = (f(e) + f(e'))$.
  If $e \in E$, then:

 If $n \in E$, then $f((n \cdot e)) = (f(n) \cdot f(e))$.
       If $e', e'' \in E$, then $f(((e' + e'') \cdot e)) = ((f(e') \cdot f(e)) + (f(e'') \cdot f(e)))$.
       If $e', e'' \in E$, then $f(((e' \cdot e'') \cdot e)) = ((f(e') \cdot f(e'')) \cdot f(e))$.

With these rules the function $f$ is well-defined, so for a given expression $e$ the rewritten expression $f(e)$ is clearly unique.
Now, if you only allow expressions of the form $((e' + e'') \cdot e)$ to be transformed into $((e' \cdot e) + (e'' \cdot e))$, then an expression such as $(2 \cdot (3 + 4))$ won't be transformed into a sum of products. In order to apply left-distributivity as well, you need to adjust the definition of $f$. (Hint: in rule 3, instead of three cases there will be nine cases to handle).
Comment: IMHO the OP is not looking for a deterministic tie-breaking rule, but for a proof that *every* order of rewritings leads to the same result. While your $f$ is probably helpful for that, in itself it is not the answer. Note that if I'm not mistaken, you need associativity and commutativity of addition for the confluence to hold.


Using HAproxy to redirect incoming traffic to docker

Question: We are currently using HAproxy to redirect incoming traffic to our domain example.domain to our containers, which are only accessible via the local interface (e.g. 127.0.0.1:12000:8080
To achieve this our current config looks something like this:
defaults
    mode http
    timeout connect 5000
    timeout check 5000
    timeout client 20000
    timeout server 20000

frontend domain
    bind *:80
    bind *:443 ssl crt /etc/haproxy/certs/domain.cert
    bind *:11000-11199 ssl crt /etc/haproxy/certs/domain.cert
    http-request redirect scheme https unless { ssl_fc } # ssl_fc returns true if the request is already using SSL
    http-request set-header X-Forwarded-Port %[dst_port]
    http-request add-header X-Forwarded-Proto https if { ssl_fc }

    # Ports 11000-11099 are reserved for secure traffic
    acl secure_0_host dst_port 11000
    acl secure_1_host dst_port 11001

    # Ports 11100-11199 are reserved for insecure traffic
    acl insecure_0_host dst_port 11100
    acl insecure_1_host dst_port 11101

    # Secure Backends
    use_backend secure_0 if secure_0_host
    use_backend secure_1 if secure_1_host

    # Insecure Backends
    use_backend insecure_0 if insecure_0_host
    use_backend insecure_1 if insecure_1_host

    # Fallback Backend
    default_backend fallback_backend

backend fallback_backend
    http-request redirect location https://example.domain code 302

# Secure Backends
backend secure_0
    server secure_0 127.0.0.1:12000 ssl verify none

backend secure_1
    server secure_1 127.0.0.1:12001 ssl verify none

# Insecure Backends
backend insecure_0
    server insecure_0 127.0.0.1:12100

backend insecure_1
    server insecure_1 127.0.0.1:12101

This setup does work but it is really tedious to manually add each port-mapping and also it kinda bugs me, that I have to use different ports (12000-12099) for the docker containers, than I am listening on with HAproxy.
Is it somehow possible to just tell the config, that a given portrange (11000-11099) should be passed through to 127.0.0.1:11000-11099?
Comment: https://stackoverflow.com/questions/26794547/how-to-configure-haproxy-port-range-to-range-one-by-one
Answer: can try this https://www.haproxy.com/documentation/hapee/latest/configuration/binds/syntax/ which is slightly different than using the port range for acls ... or just have different front ends for each port range like that docs shows
Comment: Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer).