Probability of Rolling a number that changes over time on One Die

Question: I've seen the following question asked and answered many times on various forums:

Knowing that the odds of rolling a six with one die are one in six, what
  are the odds of rolling a six in two, three, four (etc.) consecutive rolls? 1/6 + 1/6 + ... wouldn't make sense as you'd have a 100% chance of rolling a six in six rolls.

The answer I've seen is that the odds of rolling a six after n rolls are 1 - (5/6)^n.
Now my question is this - lets say that instead of rolling for a six, we pick a number out of a fixed sequence of six unique numbers after each roll. So for example, lets say our sequence is 1, 2, 3, 4, 5, 6. At the first roll we're looking to roll a one, the second roll we're looking for a two, then a three etc. until finally at the seventh roll we go back to one. What are the chances of matching any of the numbers in the sequence in this way after n rolls?
Answer: Yes, if I understand your question correctly. In each roll there is one out of six numbers you consider a match, whether it is a six or any other number. Thus, $$P\{\text{At least one match in n rolls}\}=1-P\{\text{No match in n rolls}\}=1-P\{\text{No match in roll 1, no match in roll 2...}\}=1-(5/6)^n,$$ where the last step follows from independence of the rolls.
Comment: It's okay Karl, I upvoted for him. And he's a bit closer to 15 rep as well.
Comment: @RoyG, great! If you consider the question answered, you can indicate you are satisfied by clicking the accept answer button next to the answer, or you can wait and also see what other answers may come. When you find an answer useful, you can also use the up-vote next to it to indicate so. Cheers!
Comment: marked as answered and tried to up-vote but unfortunately it said I need at least a 15 reputation.
Comment: Yep, just FYI for future questions when your rep is higher.


Zurb Foundation base font size?

Question: I noticed the
 are 1rem and very leaded out. I've tried overriding this, by up to and including p {font-size: 14px !important}
No affect.
I am using the compiled Foundation 5 CSS and JS, enqueued in a Wordpress theme. All else works fine.
Answer: Usage of this code snippet
p {font-size: 14px !important}

is definitely the right solution in general. What's more, this one
p {font-size: 14px}

should work well too. Here you are a CodePen example (I have used 30px just to briefly demonstrate it's working).
If this isn't working in your project it is probably because of order of you CSS includes - compiled Foundation CSS should always come first and your own style after that.
Comment: The order of the CSS files were reversed. This being Wordpress, it wasn't immediately apparent

Zurb Foundation base font size?


Compute $\sum\limits_{k=1}^{9999}\frac1{2\sqrt k+1}$

Question: I'm in trouble when trying to calculate the following sum:
$$\frac1{2\sqrt 1+1}+\frac1{2\sqrt 2+1}+\frac1{2\sqrt 3+1}+\ldots+\frac1{2\sqrt {9999}+1}$$
Since there isn't any formula to calculate the series$\sum\frac1{n^{1/2}}$ and there are square root numbers in the sum, how do you solve this?
Please note that this problem was given in a tournament in which I participated, so it MUST be solvable.
Comment: Since $\frac{1}{2\sqrt{k}+1}\approx \sqrt{k}-\sqrt{k-1}-\frac{1}{4k-1}$ for large values of $k$, such sum belongs to the interval $(97,98)$.
Comment: Voted to close as this seems another incorrectly transcribed question from some source we cannot view.
Comment: @JackD'Aurizio your type of questions, right
Comment: You could try [Euler-Maclaurin summation](https://en.wikipedia.org/wiki/Euler%E2%80%93Maclaurin_formula).
Comment: `calculate the following sum` What was the exact wording of the question? It is not clear whether "*calculate*" means closed form (unlikely), or a numerical approximation, or the integer part etc.
Comment: @dxiv Most probably a "simpler" numerical exact value, may be by telescoping the original sum (I've tried some minutes but without success). Btw, I agree it is just vaguely related to the other thread.
Comment: [Turns out](http://www.wolframalpha.com/input/?i=sum+of+1%2F(2sqrt(x)%2B1)+from+x%3D1+to+9999) to be around $97.0708$.
Comment: Note that one can try rationalising the denominator to get $$2\sum_{k=1}^{9999}\frac{\sqrt k}{4k-1}-\sum_{k=1}^{9999}\frac1{4k-1}$$
Comment: wolfram alpha does not find a closed form, so you probably must be content with a numerical result.
Comment: The result is sufficiently ugly also with just three terms.. can you state what is the complete statement?
Comment: @JackD'Aurizio So, probably the task was to determine the integral part of this series.
Comment: @PaoloLeonetti Apparently. Jack often finds astonishing simple solutions to very difficult seeming questions. Fascinating!
Comment: There is no way there is a simple way to write this whole sum. For any prime $5000<p<10000$ there will be a term involving $\sqrt{p}$, and those terms will be linearly independent from each other and from remaining terms in the sum, so there will not be any cancellation involving them.
Comment: So ... perhaps the "tournament" question was in a multiple choice format?
Comment: @JackD'Aurizio ... probably the right way to do it.  The numerical value is $97.0707870752\dots$
Comment: @GEdgar: actually a variation of David Quinn's approach is more efficient than mine. The integral of $\frac{dx}{2\sqrt{x}+1}$ over $(1/2,9999+1/2)$ is $97.0794\ldots$  and by standard (convexity) inequalities the approximation error does not exceed $5\cdot 10^{-2}$.
Answer: You can get quite a good approximation by evaluating $$\int_1^{9999}\frac{1}{2\sqrt{x}+1}dx=\sqrt{9999}-1-\frac 12\ln\left(\frac{2\sqrt{9999}+1}{3}\right)\simeq96.89267844$$
Comment: "Quite good" In which (precise) sense?
Comment: Better to replace the LHS with $\int_{1/2}^{9999+1/2}\frac{dx}{2\sqrt{x}+1}$ and estimate the remainder through the Hermite-Hadamard inequality or similar techniques. To prove $S\leq 98$ is not difficult, to prove $S\geq 97$ is a bit more tricky.


pentaho report designer : extract 'month' from format date in Capital Letter

Question: The date column in my BD table is in date format like 2019-06-01.
To show this on the report, I used
$(date_n, date, MMMM)

to get the month in letters, 'june' for '2019-06-01'.
Now I want to make it in Capital letter,I know there's an option UPPER() on formula. But since this is a variable, don't have an idea how to formulate it.
I tried UPPER(date_n,date,MMMM), and it says syntax error.
It would be really nice if someone can share his/her idea.
Answer: You should use
UPPER( $(date_n, date, MMMM) )

Comment: it says it's syntax error. I did it on data-format, is it correct?
Comment: no, that should be the actual value of the field. Use a formula to create a new field based on the query value.
Comment: Sorry to bother you again but I still don't understand, what do you mean by "create a new field based on the query value" ? With my query, I get date_n in date format, what am I supposed to do on open formula?
Comment: on the RHS panel, under Data, you have the fields coming from your query, and also other options. One of them is formula. You create a new formula, put that formula there, and it gives you a new field you can drag to the canvas. See the Pentaho Report Designer documentation or training for examples of how to do that.
Comment: I created a new formula =UPPER($(date_n, date, MMMM)), syntax error. I tried with =UPPER("$(date_n, date, MMMM)"), this one has no syntax error, just gives
$(MOIS_N, DATE, MMMM) as result. So I think we need quotes to use UPPER function, but then it doesn't consider it as variable.
You really tried to explain, thanks for it, but I tried all you said and it doesn't resolve the prob. Wonder if I'm doing something wrong.
Comment: try semi-colon instead of comma. I don't recall the syntax by heart, tbh, and it's been a while since I last used pentaho report designer.
Comment: I actually tried =UPPER(TEXT([date_n];"MMM")) and it finally works!! thanks for all your answers !
Answer: I solved the prob. Just in case someone has the same issue:
=UPPER(TEXT([date_n];"MMM"))

If you don't use TEXT function, it will say it's syntax error.


Bootstrap issue with col-md-12

Question: I am encountering someting really weird.
I have this structure:

                <input type='text' class="form-control action" placeholder="Från" />

                <input type='text' class="form-control action" placeholder="Till" />

        <button class="btn btn-primary  btn-block col-md-12  ">Filtrera</button>

My problem:
The last div with class =
 col-md-12

is taking up the entire row and positioning itself over the two previous ones.
image in firebug:

I cant focus the two inputs because of this and I don't really understand it.
If I set this on the last div:
col-xs-6 col-sm-12 col-md-12

the issue dissapears but the question remeains.
When I add the class
 row

I get the same result
What am I doing wrong here?
Comment: I don't see the problem: https://jsfiddle.net/s2zwckgy/1/ But I guess you should wrap it in another `row` since a row should contain a max of 12 cols (i believe)
Comment: Cannot reproducce- http://codepen.io/Paulie-D/pen/GZydeP ...but without knowing what any ***extra*** CSS is doing (such as the `filterRes` class`0 we can't help diagnose.
Comment: Some bootstrap tips (I'm not saying you have done them wrong ;-] ):
(1) Never use rows and cols on the same element, they should be alternating.
(2) the lowst column is enought `col-xs-12` will do `col-sm-12 col-md-12 col-lg-12` as well, a different case would be `col-xs-12 col-md-6` which is necessary.
(3) Always include `col-xs-12` even if the element is supposed to be full width, this is to prevent floating issues
(4) `.form-group` acts as a `.row` be sure to use columns inside as well
Comment: fiddle: https://jsfiddle.net/8mfe3f3a/
Answer: You should have 2 rows instead of 1. A row is designed to have 12 divisions of space. You are filling 12 and thus breaking the functionality. Here's a working example
HTML

                <input type='text' class="form-control action" placeholder="Från" />

                <input type='text' class="form-control action" placeholder="Till" />

        <button class="btn btn-primary  btn-block col-md-12  ">Filtrera</button>

----------- EDIT -----------------
After having the plunk example, I saw that it had to do with relative positioning of the columns. Fixed plunkr: https://jsfiddle.net/8mfe3f3a/1/
Comment: It was per my understanding that when I fill the 12 spaces thats when i fill one row. I add another 12 to fill the next row inside of a row.
My reasnoning was have one row with two rows inside of it
Comment: @Ra3IDeN Correct...rows wrap if the content exceeds 12 columns
Comment: @Ra3IDeN You are correct... Do you have a defined height on the "filterRes" class?
Comment: @DanielHigueras no I don't. Your answer does solve my problem but I don't understand why this is even happening. I tried not including my own css file and just used the bootstrap.css and I still have this issue
Comment: @Ra3IDeN Create a plunkr reproducing the problem so it's easier to debug. Without that, all we can do is give ideas of what might be happening. Who knows, you might fix the issue yourself creating the plunkr...
Comment: @Ra3IDeN I see it working correctly on your jsfiddle
Comment: Then it must be a browser issue or something. For me it is not working and I am using chrome version 49.0.2623.110. EDIT: I just updated to 49.0.2623.112 m and i still cant focus the inputs
Comment: @Ra3IDeN Working now: https://jsfiddle.net/8mfe3f3a/1/ It's got to do with `position: relative` on the columns.
Comment: It works in the fiddle but in my project it remains the same. I will accept this since I don't want to waste more time but I am curious to why this is happening
Answer: Adding a row:
I might be wrong but this might be a problem:

    <button class="btn btn-primary  btn-block col-md-12  ">Filtrera</button>

change it to this, by adding a row:

        <button class="btn btn-primary  btn-block col-md-12  ">Filtrera</button>

each set of columns needs to be wrapped by a row, since rows clear the floating.

Removing the btn column
on the other hand your button does not need 12 columns, btn-block aready does that for you

    <button class="btn btn-primary btn-block">Filtrera</button>

Answer: Add a div with class Row

            <button class="btn btn-primary  btn-block col-md-12  ">Filtrera</button>

Bootstrap issue with col-md-12


RandomForestRegressor behavior when increasing number of samples while restricting depth

Question: I am relatively new to machine learning in general, especially random forests.
Currently I am training a random regression forest with the scikit-learn library. My dataset has 500 features, the model produces a multi-output.
When training the model on 2 million and 3 million samples respectively, using n_estimators=3, max_depth=18, without touching the rest of the parameters, the saved model trained on 2 million samples is 50% larger than the one trained on 3 million samples. But not only the model size is larger, the accuracy is higher as well. This only happens, when I restrict the depth of the trees. When training the model without restricting the depth, then the accuracy increases with increasing number of samples.
I have read that deeper trees reduce the bias, while more trees reduce the variance. Does this consequently mean, that my dataset is somewhat biased and thus increasing the number of samples, increases the bias of the model, but this does not happen, when the depth is not restricted?
Is this behavior to be expected? Can anybody give me a hint to what is happening in the tree building process of RandomForestRegressor that results in this behavior?
If any additional information is needed to answer my question, please do not hesitate to ask in the comments.
EDIT1:
I just fixed the seed as suggested by @RUser4512 and ran a test to reproduce the described behavior. All three test runs where trained with max_depth=15
n_samples=100,000: mean absolute error: 0.375; saved model size on disc: 4.6MB; Avg number of leaves per tree = 10,600
n_samples=200,000: mean absolute error: 0.312; saved model size on disc: 5.9MB; Avg number of leaves per tree = 12,610
n_samples=400,000: mean absolute error: 0.603; saved model size on disc: 1.3MB; Avg number of leaves per tree = 2,920
I thought about the nature of the prediction a little more. When doing inference, my model runs 2000 independent predictions which are later used to form a single final prediction. The 2000 single predictions have numerous outliers which are far from the ground truth. I am measuring the quality of a split with the criterion mean squared error, which penalizes outliers pretty heavily. Is there a chance, that this might be effected by increasing number of samples?

I further inspected my dataset and found out that about 2% of the samples had very large outliers which were created in the process of generating the dataset. After removing those outliers not only did the MAE go way down, the above described behavior also did not reoccur.
If anybody is willing to explain why and how big outliers result in such behavior, I am happy to except their answer.
Comment: Setting `n_estimators=3` means you're only training 3 trees. This is a very small number, and should be something more like 100.  Given the randomness of each tree, the measured accuracy of the overall model could fluctuate wildly from run to run. So, it seems hard to read too much into the accuracy here. "The saved model trained on 2 million samples is 50% larger" What exactly are you measuring that's larger?
Comment: I trained the forests with the same set of parameters 3-5 times without any noticeable difference in accuracy. The accuracy definitely gets worse with increasing number of samples while the `max_depth` is fixed. "The saved model trained on 2 million samples is 50% larger", I dump my model to a .pkl file using `joblib`. So I just stated that the size of the saved model decreases in size with increasing number of samples. But it is to be noted, that this only happens after around 2million samples with `max_depth=18`.
Answer: The number of trees in random forest is not something that you tune. You set it to some high value (like 100, 250, or more). Greater depth of the trees lets them learn more complicated patterns and eventually could lead to overfitting, so you could prevent this from happening by making it smaller.
Answer:
When training the model on 2 million and 3 million samples respectively, using n_estimators=3...

Tim's answer hits the nail on the head. See Do we have to tune the number of trees in a random forest? for some discussion.
Three trees will produce an ensemble with a very large variance, which is to say that there will be large variations in the model quality between alternative runs. You can verify this with a simple experiment: construct a holdout partition and fit several random forests with n_estimators=3 and then several random forests with n_estimators=1000. You'll find that the distribution of model statistics as measured by the holdout set will have a higher variance when n_estimators=3 than n_estimators=1000.

I further inspected my dataset and found out that about 2% of the samples had very large outliers which were created in the process of generating the dataset. After removing those outliers not only did the MAE go way down, the above described behavior also did not reoccur.
If anybody is willing to explain why and how big outliers result in such behavior, I am happy to except their answer.

The prediction of a single leaf of a random forest regression model is the average of the training samples in that node. If one of those samples is orders of magnitude larger in absolute value than the others, then the mean will obviously be sensitive to that single observation.
Moreover, the fewer samples in the terminal nodes, the larger this effect will be. For a fixed amount of training data, increasing the number of nodes in the tree will tend to decrease the number of samples in each leaf, so the sampling distribution of the sample mean for a leaf will tend to have a larger variance.
Another way to ameliorate this phenomenon is to set a minimum leaf size. This will force each leaf to have at least $k$ samples in it. Whenever this $k$ is larger than a leaf size when you are not setting this parameter, the sample mean of a leaf will be less sensitive to any single observation.
It's important to note that whether or not deleting outliers is a good strategy depends on what problem you're trying to solve. We have several threads on this topic such as Is it OK to remove outliers from data?
Answer:
I have read that deeper trees reduce the bias, while more trees reduce
  the variance. Does this consequently mean, that my dataset is somewhat
  biased and thus increasing the number of samples, increases the bias
  of the model, but this does not happen, when the depth is not
  restricted?

No. "my dataset is somewhat biased" is an assertion that needs to be clarified. On the other hand, a biased estimator is a notion that is clearly defined (Wikipedia definition). Therefore, the bias of the random forest is not related to a kind of bias in the data.

But not only the model size is larger, the accuracy is higher as well

Regarding the issue about accuracy of your model decreasing with the number of sample, it is quite hard to know where it comes from.
Was the sampling performed randomly ? If so, did you fix the seed you use ? (both before sampling and before training the random forest) ? Though they are not parameters of the model, they can impact the accuracy you measure.
Comment: I sampled the `n_samples` used for training out of a pool with 16 million samples. No, I did not fix the seed for sampling the training data, nor did I fix the seed before training the random forest. I will train the model on 2 million and 3 million samples respectively, with a fixed seed and post the results here, as soon as I have them.


How to continue running a python program in the background

Question: I'm writing a Python 3 program in Windows and I would like to be able to continue running the program in the background (not in the taskbar) to gather information.
I was able to create it as a service, but I need admin privileges to run and it stops immediately!
Answer: It sounds to me like what you want is to make your program a Windows service. There's a bunch of good information in this other question: Is it possible to run a Python script as a service in Windows? If possible, how?
Comment: Thanks for the reply! I tried the code in the link in my program and I got printed instructions that I Don't understand: I put the instructions I got in my question. You can probably tell that I don't really know what i'm doing!
Comment: Also. Keep in mind that i'm going to eventually compile my code into an executable.
Comment: @Luke: I'm guessing your script is LIP.py, correct? and you ran it from the command line like: python LIP.py? If so, the usage output is telling you that you need to pass in some options to start your script as a service, try: python LIP.py --install
Comment: Yes. But I actually run it from IDLE, and after that, it should be an executable.
Comment: @LukeDinkler I'm fairly certain that the command line arg's will be the same when you run it as an exe, so you'll just start it: LIP --install.
Comment: Ok. I've run it from the command line, and it runs, but I don't see it under 'services' in the task manager, and how do I see if it is running in the backround?
Comment: Wait. Now it shows in the command line "option --install  not recognized"!
Comment: @LukeDinkler try adding --startup="auto" startup defaults to manual, but I'm not enough of a Windows guru to tell you how to manually start a service
Comment: Now it starts in the command line, but I get an error in the log, "Error installing service: Access is denied. (5)"!
Comment: Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/60185/discussion-between-greg-chapman-and-luke-dinkler).


How to search multiple search engines with keywords from own website? Like comparison websites

Question: I'm building an app using Meteor.js and React. It incorporates the use of TextRazor's API (NLP) to extract keywords from a body of text. The keywords will then be used to query different websites to bring back results, like how price comparison websites work (although for now I will just incorporate Google and build out the other websites that I want to search within once I've got it working).
How would I go about building the search functionality?
Thanks
Comment: Is your question about how to query google using the keywords you have extracted? Or is it about building some search functionality within meteor/mongo?
Comment: Hi Cenk, sorry I didn't clarify, it's in regards to querying google (or any other searchable website like facebook, youtube etc.) with the keywords extracted.
Comment: Does the answer below help you? If you find it useful, please accept this answer, as it is how this website works.
Answer: I think for each external site that you want to search, you have to determine whether it exposes a search API or not. If it does, you would simply have to query via the API, using your local set of keywords, and hope that you don't exceed the API query limits of each site (if you query like that in real time, you might exceed limits at each site).
If the external site does not expose a search API, then you would have crawl it or download it's contents (presuming that you can legally do so... which presumes much), and then you would create a local index of the site's content. This means you would need a local search engine platform of some sort (e.g. SOLR, elasticsearch, whatever), and a fairly fat ETL pipeline to transform the website content into the necessary entries or documents in your local index. Then, you would query against your locally built index using your keywords.


Can this problem be solved using the implicit function theorem? If not, how?

Question: Let $f: \mathbb{R}^2 \rightarrow \mathbb{R}^2$ be defined as
$$f(x,y)=\begin{pmatrix} x^3+xy+1\\x+y+y^3+1 \end{pmatrix}$$
Show there is an open neighborhood $U$ of $(1,1)^T$, which is mapped bijectively to a neighborhood $V$ of $(3,4)^T$ by $f$. Find the derivative of the inverse $f^{-1}: V  \rightarrow U$ of f in the point $(3,4)^T$.
Explicitly calculating the inverse function is a mess.
My second attempt: define $g: \mathbb{R}^2\times \mathbb{R}^2 \rightarrow\mathbb{R}^2$ such that $g((1,1),(3,4)) = 0$. Then the implicit function theorem gives us that there exists a mapping $\phi$ from a neighborhood of $(1,1)$ to a neighborhood of $(3,4)$, and it tells us that map is continuously differentiable. Using this approach I don't know how to show $f=\phi$, let alone that $\phi$ is bijective.
Is my approach wrong? If not how do I continue?
Comment: Why use the implicit function theorem if you can use the inverse function theorem? You find it very difficult to apply the implicit function theorem. The inverse function theorem would be more straightforward.
Answer: Show that $f'(1,1)$ is invertible. This shows the  existence of the sets $U $ and $V $.
The derivative of the inverse at $(3,4)^T $ is given by $f'(1,1)^{-1}$.


Can't SSH into Amazon EC2

Question: This is my first Amazon EC2 instance but I'm having a hard time and google can't help me out. These are the steps I have taken:

Generate a keypair called aws
Download aws.pem and put in my /Users/Jim/Documents/sshkeys folder
CHmod both file and folder to 700
Create an instance from official Amazon Debian 6 AMI
Verify security settings include SSH on port 22 (TCIP 22 (SSH)   0.0.0.0/0)
Run this command:

ssh -v -i /Users/James/Documents/sshkeys/aws.pem root@myec2ip

This is the message I get:

OpenSSH_5.9p1, OpenSSL 0.9.8r 8 Feb 2011
debug1: Reading configuration data /etc/ssh_config
debug1: /etc/ssh_config line 20: Applying options for *
debug1: Connecting to myec2ip port 22.
debug1: Connection established.
debug1:identity file /Users/James/Documents/sshkeys/aws.pem type -1
debug1: identity file /Users/James/Documents/sshkeys/aws.pem-cert type -1
debug1:Remote protocol version 2.0, remote software version OpenSSH_5.5p1 Debian-6+squeeze3
debug1: match: OpenSSH_5.5p1 Debian-6+squeeze3 pat OpenSSH* debug1: Enabling compatibility mode for protocol 2.0
debug1:Local version string SSH-2.0-OpenSSH_5.9
debug1: SSH2_MSG_KEXINIT sent
debug1: SSH2_MSG_KEXINIT received
debug1: kex: server->client aes128-ctr hmac-md5 none
debug1: kex: client->server aes128-ctr hmac-md5 none
debug1: SSH2_MSG_KEX_DH_GEX_REQUEST(1024<1024<8192) sent
debug1: expecting SSH2_MSG_KEX_DH_GEX_GROUP
debug1: SSH2_MSG_KEX_DH_GEX_INIT sent
debug1: expecting SSH2_MSG_KEX_DH_GEX_REPLY
debug1: Server host key: RSA ef:06:a0:a3:26:9f:c5:e7:c0:a6:0d:9a:1a:24:27:ef
debug1: Host 'myec2ip' is known and matches the RSA host key.
debug1: Found key in /Users/James/.ssh/known_hosts:6
debug1:ssh_rsa_verify: signature correct
debug1: SSH2_MSG_NEWKEYS sent
debug1: expecting SSH2_MSG_NEWKEYS
debug1: SSH2_MSG_NEWKEYS received
debug1: Roaming not allowed by server
debug1: SSH2_MSG_SERVICE_REQUEST sent
debug1: SSH2_MSG_SERVICE_ACCEPT received
debug1: Authentications that can continue: publickey
debug1: Next authentication method:publickey
debug1: Trying private key: /Users/James/Documents/sshkeys/aws.pem
debug1: read PEM private key done: type RSA
debug1: Authentications that can continue: publickey debug1: No more authentication methods to try. Permission denied (publickey).

I've tried a few different things, can anyone help me work out where I am going wrong please?
Answer: Most likely you have this in your /etc/ssh/sshd_config:
PermitRootLogin no

This is a good thing, however.  If you want to perform privileged actions, you should do them with sudo or at least start a root shell with sudo -s.
There will likely be a reason for the failed login in /var/log/auth.log on the server.  It doesn't look like you put the public key in /root/.ssh/authorized_keys on your server, which is where it needs to be for root to log in.

Buried in the fine print here is the titbit that the default user is admin, not root in the Debian AMI.  That's where Amazon will have put the public key that matches the private key you downloaded.  Use this:
ssh -i /Users/James/Documents/sshkeys/aws.pem admin@myec2ip

The default user is ec2-user in the Amazon AMI and ubuntu in the Ubuntu AMI.  I don't know about any others.
Comment: Thank you for the reply. Amazon EC2 don't seem to have "public" keys though and by setting that as the  keypair on amazon does it not allow the EC2 to have this key authorised? I wish I could see var/log/auth.log but I can't access it, but I have updated my original message to include more details
Comment: The Red Hat AMI also uses ec2-user fyi.
Answer: Try using "ec2-user" instead of root.
email@example.com

And pem file is both public and private key. So, try saving it as a public key using puttygen.
Comment: `ec2-user` is for Amazon Linux. The [official Debian AMIs use `admin` as the username](https://wiki.debian.org/Cloud/AmazonEC2Image/Squeeze), and there's no need to modify the `.pem` file, they work fine.
Answer:
Download the .pem file anywhere
chmod 400 file.pem
ssh -i file.pem ec2-user@ip (Amazon AWS distrib) or admin@ip on a LInux system.

Can't SSH into Amazon EC2


Não consigo instalar o tomcat e não recebo mensagem ao acessar localhost:8080

Question: Estou iniciando com Java. Baixei o e-book e comecei a ler.
Estou paralisado, não consigo completar a instalação do Tomcat.
Baixei em http://tomcat.apache.org.
Na opção "tomcat 8.0.20 Released", optei por "apache-tomcat-8.0.20-windows-x86". Meu sistema é Windows 7 Profissional 32 bits. Após descompactar o arquivo, ele gerou um diretório e subdiretórios em "apache-tomcat-8.0.20-windows-x86".
Seguindo orientação do livro acessei o subdiretório bin e executo o arquivo startup.bat para iniciar o servidor. Não existe nenhuma ocorrência. Nada acontece.
Em seguida tento acessar o endereço http://localhost:8080, que deveria acessar uma página que retornaria confirmando e execução. O browser Google Chrome retorna mensagem informando que a página não esta disponível.
A propósito também baixei e instalei o JDK Development 8.
Como não existe nenhum retorno, nenhuma informação aparece no subdiretório log, estou realmente voando. Se alguém já passou por algo parecido e puder ajudar, seria ótimo.
Comment: Você tem algum outro serviço na porta 8080? Tenta trocar ela para outra porta. http://www.mkyong.com/tomcat/how-to-change-tomcat-default-port/
Comment: Por exemplo, o Skype usa a porta 8080.
Answer: Você se lembrou de setar as variáveis do sistema como JAVA_HOME e JRE_HOME? o Tomcat não ira funcionar sem elas.
para vericar vá até pasta bin do tomcat segure shift clique com o botão direito do mouse, e selecione abrir janela de comando aqui. digite no cmd startup.bat e verifique se ele retorna o erro.
Answer: Pré-Requisitos: Tenha o JDK instalado. (irei supor que o jdk está instalado no diretório C:\Program Files\Java\jdk1.8.0_45)
Passo 1: Faça o download (da versão desejada) do tomcat no site oficial http://tomcat.apache.org/, preferencialmente o .zip do tópico "Binary Distributions" e extraia no diretório desejado (Irei supor que extraiu no diretório C:\ e renomeou a pasta para tomcat). Sendo assim, o tomcat está instalado em C:\tomcat.
Passo 2: Crie as variáveis de ambiente necessárias para que o prompt de comando do windows reconheça o tomcat e o jdk nos seguintes passos:

2.1: Abra o "Painel de Controle" > Busque e abra a opção "Sistema" > Na lateral esquerda da janela clique na opção "Configurações Avançadas do Sistema" > Na aba "Avançado" da nova janela clique na opção "Variáveis de Ambiente".
2.2: Na janela que abriu, na área "Variáveis de Sistema" clique em "Novo".
2.3: Na nova janela que abriu terá o campo "Nome da Variável" e "Valor da Variável". No primeiro coloque CATALINA_HOME e no segundo campo coloque o caminho da pasta onde extraiu o tomcat (neste nosso exemplo foi C:\tomcat). Finalize clicando em OK.
2.4: Execute novamente os passo 2.2 e 2.3. Executando novamente o passo 2.3, insira desta vez no primeira campo o valor JAVA_HOME e no segundo campo coloque o caminho do seu jdk (neste exemplo está em C:\Program Files\Java\jdk1.8.0_45). Finalize clicando em OK.
2.5: Busque nessa mesma janela na área "Variáveis de Ambiente" a variável Path, selecione-a e clique em Editar.
2.6: Na nova janela que abriu e no campo "Valor da Variável" vá para o final do texto que já tem lá e adicione um ponto-e-vírgula (;) após todo o texto.
2.7: Adicione o seguinte texto após o ponto-e-vírgula que você colocou: %JAVA_HOME%\bin;%CATALINA_HOME%\bin
2.8: Finalize clicando em OK em todas as janelas abertas neste passo 2.
2.9: Abra um NOVO prompt de comando e execute o comando "java" (sem as aspas) e depois o comando "catalina" (sem as aspas). Se você não recebeu a mensagem "...is not recognized as an internal or external command, operable program or batch file." significa que você adicionou as variáveis de ambiente corretamente.

Passo 3: Adicione suas aplicações na pasta webapps.
Passo 4: No prompt de comando digite "catalina run" (sem as aspas) para iniciar o servidor tomcat. Se a configuração foi feita corretamente o servidor estará acessível em localhost:8080. E para acessar uma página que esteja na pasta webapps/teste, por exemplo teste.html, acesse localhost:8080/teste/teste.html


Finding a good parametric form for a model

Question: Hello
I am trying to model the relationship between two variables, say x and y.  I have a number of subjects - for each subjectm I have a number of x and corresponding y, both of which are always positive.  This data tends to be very sparse.  There are some problem specific constraints:
1) y(0) = 0 (or very close to it)
2) y is increasing as a function of x
3) y' is decreasing as a function of x
This is rather nebulous, but I have a feeling that the most important difference between subjects is in the height of the curve, not in the slope.  Because of the sparsity, I think I can get away with forcing each subject to have the same "slope" (perhaps at a specified x), but allowing the height to vary.  I have been playing around with various sorts of logistic functions, but the asymptote isn't really justifiable.  I have also been looking at things like a*log(x+b), but this doesn't really conform to the intuition delineated above.  Does anyone have any suggestions?
Comment: As non-expert said, if we could look at the graph we might be able to help more.
Answer: (This is supposed to be a comment.)
I would say that without knowing the physical process(es) that generated the $y$'s for each corresponding $x$'s, any number of functions would be admissible. Barring that, one usually graphs the data first before even thinking about models...
Comment: thank you for your reply.  I don't really know much about the physical process.  I have plotted the data, but for each subject it is extremely noisy.  This is why I am trying to just get something off the ground.  To clarify a bit - I am looking for a model that has maybe 1 parameter that controls steepness, 1 that controls height, and maybe one or two others.
Comment: Maybe you can edit your post to show that noisy graph you speak of, and then we can start from there.
Answer: First, draw a distinction between what you expect and what you measure.
Since the expectations can't sculpt a functional form, investigate a generic method like polynomial approximation. Then you can look at the result and see how well it matches your expectations.
Start with a set of $m$ measurements $\left\{ x_{k}, y_{k} \right\}_{k=1}^{m}$ and $d$th order approximation.
Model
$$
 y(x) = a_{0} + \sum_{\mu=1}^{d} a_{\mu} x^{\mu}
$$
Linear system
$$
\begin{align}
  \mathbf{A} a &= y \\
%
\left[ \begin{array}{cccc}
  1 & x_{1} & x_{1}^{2} & \dots & x_{1}^{d} \\
  1 & x_{2} & x_{2}^{2} & \dots & x_{2}^{d} \\
  \vdots & \vdots & \vdots & & \vdots \\
  1 & x_{m} & x_{m}^{2} & \dots & x_{m}^{d} \\
\end{array} \right]
%
\left[ \begin{array}{c}
  a_{0} \\ a_{1} \\ \vdots \\ a_{d}
\end{array} \right]
%
&=
%
\left[ \begin{array}{c}
  y_{1} \\ y_{2} \\ \vdots \\ y_{m}
\end{array} \right]
%
\end{align}
$$
Least squares solution
The least squares solution is
$$
 a_{LS} = \mathbf{A}^{+}b +
\left(
 \mathbf{I}_{d+1} - \mathbf{A}^{+} \mathbf{A}
\right) z, \quad z \in \mathbb{C}^{d+1}
$$


How to write a util function that takes map as an input iterate over all the keys and calls this function and returns a sanitized key value map?

Question: This is the function addorUpdateAddress instead of using this sanitizeXSS and decrypt_key again and again write a util function that takes map as an input iterate over all the keys and calls this function and returns a sanitized key value map.
addOrUpdateAddress : function (request, resolve)
    {
        const customerKey = sanitizeXSS(decrypt_key(request.customer_key));
        const lat = sanitizeXSS(decrypt_key(request.lat));
        const lng = sanitizeXSS(decrypt_key(request.lng));
        const line1 = sanitizeXSS(decrypt_key(request.line1));
        const line2 = sanitizeXSS(decrypt_key(request.line2));
        const city = sanitizeXSS(decrypt_key(request.city));
        const pincode = sanitizeXSS(decrypt_key(request.pincode));
        const state = sanitizeXSS(decrypt_key(request.state));

        const contact = sanitizeXSS(decrypt_key(request.contact));
        const landmark = request.landmark?sanitizeXSS(decrypt_key(request.landmark)):null;
     }
 sanitizeXSS: string => {
      const map = {
          '&': '&',
          '<': '<',
          '>': '>',
          '"': '"',
          "'": ''',
          "/": '/',
      };
      const reg = /[&<>"'/]/ig;
      return string.replace(reg, (match)=>(map[match]));
    }
function decrypt_key(message, action)
{
    var text = message;
    var encrypted = "";

    for(var i = 0; i < text.length; i++) {
    var ASCII = text[i].charCodeAt(0);
    var n = null;

    if(i % 2 == 0) {
      n = action == 'encrypt' ? ASCII + 4 : ASCII - 4;
    }

    else if(i % 2 == 1) {
      n = action == 'encrypt' ? ASCII + 3 : ASCII - 3;
    }

    var s = String.fromCharCode(n);

        encrypted += s;
    }
    return encrypted;
}

Answer: Yes, you can write such function.
function sanitizeXSS(string){
      const map = {
          '&': '&',
          '<': '<',
          '>': '>',
          '"': '"',
          "'": ''',
          "/": '/',
      };
      const reg = /[&<>"'/]/ig;
      return string.replace(reg, (match)=>(map[match]));
}

function decrypt_key(message, action)
{
    var text = message;
    var encrypted = "";

    for(var i = 0; i < text.length; i++) {
    var ASCII = text[i].charCodeAt(0);
    var n = null;

    if(i % 2 == 0) {
      n = action == 'encrypt' ? ASCII + 4 : ASCII - 4;
    }

    else if(i % 2 == 1) {
      n = action == 'encrypt' ? ASCII + 3 : ASCII - 3;
    }

    var s = String.fromCharCode(n);

        encrypted += s;
    }
    return encrypted;
}

function decryptAndSanitizeXss(obj){
  let newObj = {}
  for(const prop in obj)    {
    if(obj[prop]){
        newObj[prop] = sanitizeXSS(decrypt_key(obj[prop]));
    }
    }
    return newObj
}

function addOrUpdateAddress(request, resolve) {
   request = decryptAndSanitizeXss(request)
}

Comment: Can u please write what should be their in prop, obj in your decryptAndSanitizeXss function?
Comment: And also in addorUpdateAddress function how it is ensuring that all those query params will be passed here?
Comment: @neha For your first comment, please refer function call to decryptAndSanitizeXss, provided as last line. Here, decryptAndSanitizeXss function reads property from object which is passed  to the function and update it into the other object.
As an backup, you can also create clone of your original map and update properties into clone directly.


How do I display the submitted data in the same page?

Question: I created a custom form in Drupal 7. I need to display the submitted data in the same page showing the form, without using drupal_set_message(). Is it possible?
Answer: You can use $form_state['rebuild'];
If $form_state['rebuild'] = TRUE; has been set then a new copy of the form is immediately built and sent to the browser. Instead of a redirect to new page.
Example:
function example_form_submit($form, &$form_state)
{
  // we return the submitted value to the form
  // by storing it in $form_state['storage'] and rebuilding
  $form_state['storage']['some_value'] = $form_state['values']['some_value'];
  $form_state['rebuild'] = TRUE;
}

You can refer https://www.drupal.org/node/2171993
Another way store the "$form_state['values']" in session.
Take @clive answer How to display an HTML table after the form submission on the same page as the form? as reference.


Trying to integrate pagination on multiple isotope instance

Question: I've been trying integrate a filter functionality using a library called Isotope.js. Included with filter is a pagination functionality. I've been trying to solve the issue on how I can make the pagination work on multiple isotope instances. It seems that pagination is duplicating itself multiple times when using the filter and affecting other instances present when using the pagination
Below is a sample work in progress of what I'm currently working on

var itemSelector = ".products-item";
var $checkboxes = $('.filter-checkbox');
var $container = $('.products-container').isotope({
  itemSelector: itemSelector
});

//Ascending order
var responsiveIsotope = [
  [480, 3],
  [720, 5]
];
var itemsPerPageDefault = 5;
var itemsPerPage = defineItemsPerPage();
var currentNumberPages = 1;
var currentPage = 1;
var currentFilter = '*';
var filterAttribute = 'data-filter';
var filterValue = "";
var pageAttribute = 'data-page';
var pagerClass = 'isotope-pager';

// update items based on current filters
function changeFilter(selector) {
  $container.isotope({
    filter: selector
  });
}

//grab all checked filters and goto page on fresh isotope output
function goToPage(n) {
  currentPage = n;
  var selector = itemSelector;
  var exclusives = [];
  // for each box checked, add its value and push to array
  $checkboxes.each(function(i, elem) {
    if (elem.checked) {
      selector += (currentFilter != '*') ? '.' + elem.value : '';
      exclusives.push(selector);
    }
  });
  // smash all values back together for 'and' filtering
  filterValue = exclusives.length ? exclusives.join('') : '*';

  // add page number to the string of filters
  var wordPage = currentPage.toString();
  filterValue += ('.' + wordPage);

  changeFilter(filterValue);
}

// determine page breaks based on window width and preset values
function defineItemsPerPage() {
  var pages = itemsPerPageDefault;

  for (var i = 0; i < responsiveIsotope.length; i++) {
    if ($(window).width() <= responsiveIsotope[i][0]) {
      pages = responsiveIsotope[i][1];
      break;
    }
  }
  return pages;
}

function setPagination() {

  var SettingsPagesOnItems = function() {
    var itemsLength = $container.children(itemSelector).length;
    var pages = Math.ceil(itemsLength / itemsPerPage);
    var item = 1;
    var page = 1;
    var selector = itemSelector;
    var exclusives = [];
    // for each box checked, add its value and push to array
    $checkboxes.each(function(i, elem) {
      if (elem.checked) {
        selector += (currentFilter != '*') ? '.' + elem.value : '';
        exclusives.push(selector);
      }
    });
    // smash all values back together for 'and' filtering
    filterValue = exclusives.length ? exclusives.join('') : '*';
    // find each child element with current filter values
    $container.children(filterValue).each(function() {
      // increment page if a new one is needed
      if (item > itemsPerPage) {
        page++;
        item = 1;
      }
      // add page number to element as a class
      wordPage = page.toString();

      var classes = $(this).attr('class').split(' ');
      var lastClass = classes[classes.length - 1];
      // last class shorter than 4 will be a page number, if so, grab and replace
      if (lastClass.length < 4) {
        $(this).removeClass();
        classes.pop();
        classes.push(wordPage);
        classes = classes.join(' ');
        $(this).addClass(classes);
      } else {
        // if there was no page number, add it
        $(this).addClass(wordPage);
      }
      item++;
    });
    currentNumberPages = page;
  }();

  // create page number navigation
  var CreatePagers = function() {

    var $isotopePager = ($('.' + pagerClass).length == 0) ? $('

') : $('.' + pagerClass);

    $isotopePager.html('');
    if (currentNumberPages > 1) {
      for (var i = 0; i < currentNumberPages; i++) {
        var $pager = $('');
        $pager.html(i + 1);

        $pager.click(function() {
          var page = $(this).eq(0).attr(pageAttribute);
          goToPage(page);
        });
        $pager.appendTo($isotopePager);
      }
    }
    $container.after($isotopePager);
  }();
}
// remove checks from all boxes and refilter
function clearAll() {
  $checkboxes.each(function(i, elem) {
    if (elem.checked) {
      elem.checked = null;
    }
  });
  currentFilter = '*';
  setPagination();
  goToPage(1);
}

setPagination();
goToPage(1);

//event handlers
$checkboxes.change(function() {
  var filter = $(this).attr(filterAttribute);
  currentFilter = filter;
  setPagination();
  goToPage(1);
});

$('#clear-filters').click(function() {
  clearAll()
});
/* http://meyerweb.com/eric/tools/css/reset/
       v2.0 | 20110126
       License: none (public domain)
    */

html,
body,
div,
span,
applet,
object,
iframe,
h1,
h2,
h3,
h4,
h5,
h6,
p,
blockquote,
pre,
a,
abbr,
acronym,
address,
big,
cite,
code,
del,
dfn,
em,
img,
ins,
kbd,
q,
s,
samp,
small,
strike,
strong,
sub,
sup,
tt,
var,
b,
u,
i,
center,
dl,
dt,
dd,
ol,
ul,
li,
fieldset,
form,
label,
legend,
table,
caption,
tbody,
tfoot,
thead,
tr,
th,
td,
article,
aside,
canvas,
details,
embed,
figure,
figcaption,
footer,
header,
hgroup,
menu,
nav,
output,
ruby,
section,
summary,
time,
mark,
audio,
video {
  margin: 0;
  padding: 0;
  border: 0;
  font-size: 100%;
  font: inherit;
  vertical-align: baseline;
}

/* HTML5 display-role reset for older browsers */

article,
aside,
details,
figcaption,
figure,
footer,
header,
hgroup,
menu,
nav,
section {
  display: block;
}

body {
  line-height: 1;
}

ol,
ul {
  list-style: none;
}

blockquote,
q {
  quotes: none;
}

blockquote:before,
blockquote:after,
q:before,
q:after {
  content: '';
  content: none;
}

table {
  border-collapse: collapse;
  border-spacing: 0;
}

.centered-component {
  width: 100%;
  max-width: 1300px;
  margin: 0 auto;
  display: flex;
  flex-wrap: wrap;
  padding: 100px 0;
}

.centered-component .filter-sidebar {
  width: 100%;
  max-width: 250px;
  margin-right: 24px;
}

.centered-component .content-block {
  flex: 1;
}

.filter-sidebar {
  display: flex;
  flex-direction: column;
}

.products-container {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  grid-gap: 24px;
}

.isotope-container>h2 {
  margin-bottom: 48px;
}

.products-item {
  position: relative !important;
  top: initial !important;
  left: initial !important;
}

.products-container {
  height: initial !important;
}

.isotope-pager {
  margin-top: 42px;
}

.isotope-container+.isotope-container {
  margin-top: 64px;
}
<!doctype html>

  <title>Isotope</title>
  <link rel="stylesheet" href="style.css" />

                <input type="checkbox"  class="filter-checkbox" value="beige" />
                beige

                <input type="checkbox"  class="filter-checkbox" value="green" />
                green

                <input type="checkbox"  class="filter-checkbox" value="blue" />
                blue

                <input type="checkbox"  class="filter-checkbox" value="orange" />
                orange

                <input type="checkbox"  class="filter-checkbox" value="purple" />
                purple

                <input type="checkbox"  class="filter-checkbox" value="pink" />
                pink

                <input type="checkbox"  class="filter-checkbox" value="teal" />
                teal

                <input type="checkbox"  class="filter-checkbox" value="yellow" />
                yellow

                <input type="checkbox"  class="filter-checkbox" value="black" />
                black

Category 1

beige

green

blue

orange

purple

pink

teal

yellow

black

beige

Category 1

beige

green

blue

orange

purple

pink

teal

yellow

black

beige

Comment: what is the specific issue you are facing?
Comment: Trying to implement pagination properly on multiple `isotope` instances. It works when there is one instance but becomes an issue when there are multiple instances
Comment: How do you replicate the problem?
Comment: It's there in my snippet of code that I've provided
Comment: Each isotope should have its own pagination instance? Or all Isotopes should share one pagination?
Comment: @EliezerBerlin Each isotope should have it's own pagination instance.
Answer: It is not working because your code doesn't support multiple instances of pager. I have modified your code a bit to allow multiple pager instance.
This is something to start with and by no means is a clean solution, it needs clean up in quiet a few places, nevertheless it will give you an idea why your current code is not working.

var itemSelector = ".products-item";
var $checkboxes = $('.filter-checkbox');
var filterAttribute = 'data-filter';

class IsotopContainer {
  constructor(container) {
    this.container = $(container);
    //Ascending order
    this.responsiveIsotope = [
      [480, 3],
      [720, 5]
    ];
    this.itemsPerPageDefault = 5;
    this.itemsPerPage = this.defineItemsPerPage();
    this.currentNumberPages = 1;
    this.currentPage = 1;
    this.currentFilter = '*';
    this.filterValue = "";
    this.pageAttribute = 'data-page';
    this.pagerClass = 'isotope-pager';

    this.isotope = this.container.isotope({
      itemSelector: itemSelector
    });
  }

  // update items based on current filters
  changeFilter(selector) {
    this.container.isotope({
      filter: selector
    });
  }

  //grab all checked filters and goto page on fresh isotope output
  goToPage(n) {
    this.currentPage = n;
    var selector = itemSelector;
    var exclusives = [];
    // for each box checked, add its value and push to array
    $checkboxes.each((i, elem) => {
      if (elem.checked) {
        selector += (this.currentFilter != '*') ? '.' + elem.value : '';
        exclusives.push(selector);
      }
    });
    // smash all values back together for 'and' filtering
    this.filterValue = exclusives.length ? exclusives.join('') : '*';

    // add page number to the string of filters
    var wordPage = this.currentPage.toString();
    this.filterValue += ('.' + wordPage);

    this.changeFilter(this.filterValue);
  }

  // determine page breaks based on window width and preset values
  defineItemsPerPage() {
    var pages = this.itemsPerPageDefault;

    for (var i = 0; i < this.responsiveIsotope.length; i++) {
      if ($(window).width() <= this.responsiveIsotope[i][0]) {
        pages = this.responsiveIsotope[i][1];
        break;
      }
    }
    return pages;
  }

  setPagination() {
    var SettingsPagesOnItems = () => {
      var itemsLength = this.container.children(itemSelector).length;
      var pages = Math.ceil(itemsLength / this.itemsPerPage);
      var item = 1;
      var page = 1;
      var selector = itemSelector;
      var exclusives = [];
      // for each box checked, add its value and push to array
      $checkboxes.each((i, elem) => {
        if (elem.checked) {
          selector += (this.currentFilter != '*') ? '.' + elem.value : '';
          exclusives.push(selector);
        }
      });

      // smash all values back together for 'and' filtering
      this.filterValue = exclusives.length ? exclusives.join('') : '*';
      // find each child element with current filter values
      this.container.children(this.filterValue).each((i, child) => {
        // increment page if a new one is needed
        if (item > this.itemsPerPage) {
          page++;
          item = 1;
        }
        // add page number to element as a class
        var $child = $(child);
        var wordPage = page.toString();
        var classes = $child.attr('class').split(' ');
        var lastClass = classes[classes.length - 1];
        // last class shorter than 4 will be a page number, if so, grab and replace
        if (lastClass.length < 4) {
          $child.removeClass();
          classes.pop();
          classes.push(wordPage);
          classes = classes.join(' ');
          $child.addClass(classes);
        } else {
          // if there was no page number, add it
          $child.addClass(wordPage);
        }
        item++;
      });
      this.currentNumberPages = page;
    };

    // create page number navigation
    var CreatePagers = () => {
      var existingPager = this.container.siblings('.' + this.pagerClass);
      var $isotopePager = (existingPager.length == 0) ? $('

') : existingPager;

      $isotopePager.html('');
      if (this.currentNumberPages > 1) {
        for (var i = 0; i < this.currentNumberPages; i++) {
          var $pager = $('');
          $pager.html(i + 1);

          $pager.click(e => {
            var page = $(e.target).attr(this.pageAttribute);
            this.goToPage(page);
          });
          $pager.appendTo($isotopePager);
        }
      }
      this.container.after($isotopePager);
    };

    SettingsPagesOnItems();
    CreatePagers();
  }

}

var containers = $.map($('.products-container'), c => new IsotopContainer(c));

// remove checks from all boxes and refilter
function clearAll() {
  $checkboxes.each(function(i, elem) {
    if (elem.checked) {
      elem.checked = null;
    }
  });
  containers.forEach(c => {
    c.currentFilter = '*';
    c.setPagination();
    c.goToPage(1);
  });
}

containers.forEach(c => {
  c.setPagination();
  c.goToPage(1);
});

//event handlers
$checkboxes.change(function() {
  var filter = $(this).attr(filterAttribute);

  containers.forEach(c => {
    c.currentFilter = filter;
    c.setPagination();
    c.goToPage(1);
  });
});

$('#clear-filters').click(function() {
  clearAll()
});
/* http://meyerweb.com/eric/tools/css/reset/
       v2.0 | 20110126
       License: none (public domain)
    */

html,
body,
div,
span,
applet,
object,
iframe,
h1,
h2,
h3,
h4,
h5,
h6,
p,
blockquote,
pre,
a,
abbr,
acronym,
address,
big,
cite,
code,
del,
dfn,
em,
img,
ins,
kbd,
q,
s,
samp,
small,
strike,
strong,
sub,
sup,
tt,
var,
b,
u,
i,
center,
dl,
dt,
dd,
ol,
ul,
li,
fieldset,
form,
label,
legend,
table,
caption,
tbody,
tfoot,
thead,
tr,
th,
td,
article,
aside,
canvas,
details,
embed,
figure,
figcaption,
footer,
header,
hgroup,
menu,
nav,
output,
ruby,
section,
summary,
time,
mark,
audio,
video {
  margin: 0;
  padding: 0;
  border: 0;
  font-size: 100%;
  font: inherit;
  vertical-align: baseline;
}

/* HTML5 display-role reset for older browsers */

article,
aside,
details,
figcaption,
figure,
footer,
header,
hgroup,
menu,
nav,
section {
  display: block;
}

body {
  line-height: 1;
}

ol,
ul {
  list-style: none;
}

blockquote,
q {
  quotes: none;
}

blockquote:before,
blockquote:after,
q:before,
q:after {
  content: '';
  content: none;
}

table {
  border-collapse: collapse;
  border-spacing: 0;
}

.centered-component {
  width: 100%;
  max-width: 1300px;
  margin: 0 auto;
  display: flex;
  flex-wrap: wrap;
  padding: 100px 0;
}

.centered-component .filter-sidebar {
  width: 100%;
  max-width: 250px;
  margin-right: 24px;
}

.centered-component .content-block {
  flex: 1;
}

.filter-sidebar {
  display: flex;
  flex-direction: column;
}

.products-container {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  grid-gap: 24px;
}

.isotope-container>h2 {
  margin-bottom: 48px;
}

.products-item {
  position: relative !important;
  top: initial !important;
  left: initial !important;
}

.products-container {
  height: initial !important;
}

.isotope-pager {
  margin-top: 42px;
}

.isotope-container+.isotope-container {
  margin-top: 64px;
}

                <input type="checkbox"  class="filter-checkbox" value="beige" />
                beige

                <input type="checkbox"  class="filter-checkbox" value="green" />
                green

                <input type="checkbox"  class="filter-checkbox" value="blue" />
                blue

                <input type="checkbox"  class="filter-checkbox" value="orange" />
                orange

                <input type="checkbox"  class="filter-checkbox" value="purple" />
                purple

                <input type="checkbox"  class="filter-checkbox" value="pink" />
                pink

                <input type="checkbox"  class="filter-checkbox" value="teal" />
                teal

                <input type="checkbox"  class="filter-checkbox" value="yellow" />
                yellow

                <input type="checkbox"  class="filter-checkbox" value="black" />
                black

Category 1

beige

green

blue

orange

purple

pink

teal

yellow

black

beige

Category 1

beige

green

blue

orange

purple

pink

teal

yellow

black

beige

Comment: What colors and categories are supposed to show up when one color is selected?
Comment: @natel I am not sure as to what is supposed to show up, I kept original logic as it was.
Comment: @clestcruz did you get a chance to take a look?


How do I iterate through nested pandas dataframe by column?

Question: Problem: I have a 1 row dataframe dfA whose column length can vary, within each cell contains a json object. All fields in each json object are the same.
I'm trying to write code that loops through each cell, parses the JSON object, and loads ALL data into 1 single dataframe dfB, so if I have 5 columns in dfA then the final output of dfB should have 5 rows
I have the code written to where I can manually enter the column number of dfA and dfB outputs correctly:
dataA = dfA[0].values.tolist()
dfB = pd.json_normalize(dataA)
dfB

In the above example, the code pulls the 1st JSON object of dfA and correctly outputs a 1 row dataframe
I've Tried:
for column in dfA:
  dataA = dfA[column].values.tolist()
  dfB = pd.json_normalize(dataA)

This outputs just the last cell in dfA
I've tried different variations of this and either get the 1st cell, last cell, or the original dfA
Please help, thank you!
EDIT:
dfA:

0
1
2
3
4

0
{'id':'testID434556'...
{'id':'testID568912'...
{'id':'testID652154'...
{'id':'testID756298'...
{'id':'testID812362'...

dataA = dfA[0].values.tolist()
dfB = pd.json_normalize(dataA)
dfB

id
field2
field3
field4
field5

0
testID434556
field2data
field3data
field4data
field5data

Desired Output:

id
field2
field3
field4
field5

0
testID434556
field2data
field3data
field4data
field5data

1
testID568912
field2data
field3data
field4data
field5data

2
testID652154
field2data
field3data
field4data
field5data

3
testID756298
field2data
field3data
field4data
field5data

4
testID812362
field2data
field3data
field4data
field5data
Comment: Will you please provide a small sample of the dataframe?
Comment: Just updated with what it looks like now and what I'm trying to get to, thank you!
Comment: For each column you loop over with your for loop, you create a different dfB. You need to store it, for instance
`dfB = pd.DataFrame()
for column in dfA:
  dataA = dfA[column].values.tolist()
  dfB = pd.concat([dfB, pd.json_normalize(dataA)])
`
Answer: dfA[0] only gets the first column. You should convert you dataframe first row to list then feed the result to pd.json_normalize()
pd.json_normalize((dfA.iloc[0, :].values))


Want to post from a Apps Script form to another App Script

Question: I have an addon shared to all domain-users.
It opens a sidebar that contains a form.
I want the form to post to another Apps Script (implemented webapp) in a basic client-server fashion.
The other script (runs as admin) should do stuff with the user-submitted data.
Script1.html (in addon, any user can run it)
<form id="myForm" method="post" action="https://script.google.com/a/macros/<domain>/s/


How to read data from file containing variables

Question: I have a bash script for initializing iptables.
#!/bin/sh

EXTIF="eth0"
INTIF="eth1"

INTIP="192.168.0.1/32"
EXTIP=$(/sbin/ip addr show dev "$EXTIF" | perl -lne 'if(/inet (\S+)/){print$1;last}');

UNIVERSE="0.0.0.0/0"
INTNET="192.168.0.1/24"

/sbin/iptables-restore -v < iptables.rules

I have iptables.rules file containing something like this:
-A OUTPUT -o $EXTIF -s $UNIVERSE -d $INTNET -j REJECT

How can I pass those variables from bash script to iptables.rules or evaluate them?
Comment: Cross-posted from [here](http://stackoverflow.com/questions/5289665/use-external-file-with-variables).
Answer: Something like this:
while read line; do eval "echo ${line}"; done < iptables.rules | /sbin/iptables-restore -v

or more nicely formatted:
while read line
  do eval "echo ${line}"
done < iptables.rules | /sbin/iptables-restore -v

This forces the variable expansion stuff.  You definitely need to be sure you understand what's in those variables; I suspect that if somebody could set a variable to an arbitrary value they could use it to execute arbitrary code.
Comment: This works well for me
Answer: I would not want to trust this in general execution without a lot of content tests, at which point it becomes easier to feed it through a macro processor instead of trying to substitute shell variables into it.  I strongly recommend going that way instead.  That said, something like this should work:
f="$(mktemp)" || exit 1
{echo '/sbin/iptables-restore <<__EOF'; cat iptables.rules; echo '__EOF'} >"$f"
. "$f"
rm "$f"

Comment: In Bash (note that the question is tagged `[bash]`, but the shebang is `#!/bin/sh`), you can source something on the fly without a temporary file: `source <(echo '...'; echo "$(<iptables.rules)"; echo '...')`
Answer: If iptables.rules contains:
RULES="-A OUTPUT -o $EXTIF -s $UNIVERSE -d $INTNET -j REJECT"

And your script sources that file, then the variables will be evaluated.
#!/bin/sh

EXTIF="eth0"
INTIF="eth1"

INTIP="192.168.0.1/32"
EXTIP=$(/sbin/ip addr show dev "$EXTIF" | perl -lne 'if(/inet (\S+)/){print$1;last}');

UNIVERSE="0.0.0.0/0"
INTNET="192.168.0.1/24"
. iptables.rules

/sbin/iptables-restore -v < $RULES

Comment: no, unfortunately...
Comment: That wouldn't work anyway:  `$RULES` isn't the name of a file.  `echo "$RULES" | /sbin/iptables-restore -v` would work if `iptables.rules` were set up correctly.


Initializing a std::barrier with a class member function

Question: How do you initialize a std::barrier with a class member function?
class CMyClass {
private:
    void func() {
    }

public:
    void start() {
    }
}

void CMyClass::start() {
    std::barrier<??> barrier(threads_count, &func()); // ??
}

Answer: The completion function of a barrier has to be invocable with zero arguments, which means you can't just pass a pointer to non-static member function (such a function still needs an argument: the class instance). Instead, you have to provide a lambda:
std::barrier barrier(threads_count, [this]{ func(); });

Class template argument deduction (CTAD) will deduce the class template parameter from the type of the lambda, so you don't have to worry about it.
Comment: Thank you, tell me, how do I declare the `std::barrier` as a member of a class? (how use pointer to `std::barrier`)?
Comment: `Error C2338 N4861 [thread.barrier.class]/5: is_nothrow_invocable_v shall be true` :(


Using variables in a plpgsql function

Question: Ok so I used a string_agg like this.
select string_agg(DISTINCT first_name,', ' ORDER BY first_name) FROM person_test;

Then I wrote this to return the values to a table.
SELECT *
FROM person_test
where first_name = ANY(string_to_array('Aaron,Anne', ','));

Now I want to put this in a function so that instead of acturally putting names into the string_to_array, I can just call the string_agg.
I am new to postgres and am not finding any good documentation on how to do this online. I believe I would have to declare the the string_agg and then call it in string_to_array but I am having no such luck.
This was my attempt, I know this is now right but if anyone could add some feedback. I am getting an error between results and ALAIS and on the return.
create or REPLACE FUNCTION select_persons(VARIADIC names TEXT[]);
declare results ALIAS select string_agg(DISTINCT first_name,', ' ORDER BY first_name) FROM person_test;
BEGIN
return setof person_test LANGUAGE sql as $$
  select * from person_test
  where first_name = any(results)
end;
$$ language sql;

Answer: You can create a function with variable number of arguments.
Example:
create table person_test (id int, first_name text);
insert into person_test values
(1, 'Ann'), (2, 'Bob'), (3, 'Ben');

create or replace function select_persons(variadic names text[])
returns setof person_test language sql as $$
    select *
    from person_test
    where first_name = any(names)
$$;

select * from select_persons('Ann');
 id | first_name
----+------------
  1 | Ann
(1 row)

select * from select_persons('Ann', 'Ben', 'Bob');
 id | first_name
----+------------
  1 | Ann
  2 | Bob
  3 | Ben
(3 rows)

To use a variable inside a plpgsql function, you should declare the variable and use select ... into (or assignment statement). Example:
create or replace function my_func()
returns setof person_test
language plpgsql as $$
declare
    aggregated_names text;
begin
    select string_agg(distinct first_name,', ' order by first_name)
    into aggregated_names
    from person_test;

    -- here you can do something using aggregated_names

    return query
        select *
        from person_test
        where first_name = any(string_to_array(aggregated_names, ', '));
end $$;

select * from my_func();

Comment: Yes that works fine, but something that I would like to do is basically declare the string_agg as a variable so that way when I want to call multiple rows I can just call the variable and not have to input all their names.
Comment: That was exactly what I wanted!

Using variables in a plpgsql function


Transform this LINQ expression to SQL server query

Question: I have written this query using LINQ methods in Entity Framework:
var items = db.Items.ToList();

var unique_items = items.OrderBy(c => c.date)
              .GroupBy(c => c.title)
              .Select(group => group.First()).ToList();

Items returns this for example :
id   title  date
-----------------------
 1   car1   02-05-2019
 2   car2   02-06-2019
 3   car2   02-07-2019
 4   car4   02-05-2019
 5   car1   02-04-2019

and unique_items should return this :
1   car1   25-10-2019
3   car2   25-10-2019
4   car4   25-12-2019

I want only unique titles.
And I want now to do it using SQL Server query to create a view in the database, I tried to use Group By and Distinct but I couldn't do it because the use is different from LINQ queries can someone help please?
Comment: create view your_view_name as Select min(id) as id, title, min(date) as date from your_table group by title
Comment: @МаксимИванов That is only correct if every min(id) and every min(date) point to the same record.
Comment: The easy answer is to use the DbContext.Log to just catch the SQL that is being generated and use that.  https://learn.microsoft.com/en-us/ef/ef6/fundamentals/logging-and-interception
Comment: @Robert McKee Yes. But he wants unique titles - he gets unique titles. It is not pretty clear what date and id must be. I suggested to take mins.
Comment: @МаксимИванов He's getting unique titles, and for each unique title, he gets the earliest date, and the corresponding id with that earliest date.  That is what his code currently does.  Although, given that, his example result is wrong given his example input.
Comment: thank you guys for your help. sorry I wasn't that clear, the most important thing for me is id and title, date is just for ordering titles before taking the first one. The answer from Robert worked for me
Answer: Something like the following, but I would just use EF6's logging to capture the query and use that as is:
SELECT id, title, date
FROM (
  SELECT id,title,date, ROW_NUMBER() OVER (PARTITION BY title ORDER BY date) AS rn
  FROM Items
) t1
WHERE t1.rn=1
ORDER BY date


Adicionar um separador a cada item

Question: Olá,
Tenho o site exemplo.com, nele eu uso o Bootstrap, gostaria de adicionar uma / a cada item na navbar dele, como um breadcumb.

Como se fosse um breadcumb mas na navbar.
Obrigado desde já.
Comment: Podes explicar melhor o que já tens com código e/ou imagem para ficar mais claro?
Comment: @Sergio código eu não tenho, procurei na internet mas não achei nada que pudesse me ajudar.
Comment: Você nm tem nem o código da navbar ? Providencie algo para as pessoas poderem te ajudar... Uma imagem do que deseja ou um link...
Answer: Apesar de a sua pergunta estar meio confusa, veja se não é isso aqui que você precisa:

.nav .breadcrumb {
    margin: 0 7px;
}
@media (min-width: 768px) {
    .nav .breadcrumb {
        float: left;
        margin: 7px 10px;
    }
}

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

Home

Library

Data

            Hello George

Settings

Logout

 Help

 Exit

Fonte: Breadcrumb into a navbar in bootstrap 3.0.2.

Adicionar um separador a cada item


Informatica column concatenation

Question: I have 2 columns in a single  my input as given below :
Input :
Column1

A|B|C|D

Column2

1|2|3|4

And I need to get the single Output as shown below :
Column1

A.1 || B.2 || C.3 || D.4

Can anyone help me to get the output ?
Answer: You can split the columns into multiple parts based on delimitter and then concat.

1 find position of | in first column like this -

v_pos1 = InStr( col1, '|', 1, 1)
v_pos2 = InStr( col1, '|', 1, 2)
v_pos3 = InStr( col1, '|', 1, 3)
...

2 Create bunch of variable ports to capture actual values-

v_val1 = iif(v_pos1 =0,col1, SubStr( col1, 1, v_pos1 - 1))
v_val2 = iif(v_pos2 =0,'', SubStr( col1, v_pos1 + 1), SubStr( col1, v_pos1 + 1, v_pos2 - v_pos1 - 1))
v_val2 = iif(v_pos2 =0,'', SubStr( col1, v_pos2 + 1), SubStr( col1, v_pos2 + 1, v_pos3 - v_pos2 - 1))
...

3 Repeat above steps for column2 as well. Lets asseme they are v_val_col21,v_val_col22...
4 Once you have both set of columns, then concat both to get final values.

o_final = v_val1 ||'.' || v_val_col21 ||'||'|| v_val2 ||'.' || v_val_col22...

Informatica column concatenation


My MCMC do not overlap : Mixturemodel with JAGS and R

Question:
I fitted a JAGS model and I have those results :

My questions are: Why do my chains not overlap, and how can I fix that?
I used the following method:
My model is a mixture Gaussian model of two population with the same unknown variance $\sigma$. The proportion of the two population is $\pi_0$ also unknown and the mean of the two responses are obviously unknown: $\mu_0$ (associate with the proportion $\pi_0$) and $\mu_1$.
Mathematical model:
Let $ n \in \mathbb{N} $ , $\pi_0 \in \; ]0,1[ \,$ and $(\mu_0,\mu_1,\sigma) \in \mathbb R^2\times\mathbb R^+$.
I define the following function $\mu : x \in (0,1) \rightarrow (1-x)\times\mu_0 + x\times\mu_1 $
$(X_i)_{i \in [1,n]}$ and $(Z_i)_{i \in [1,n]}$ are two family of random variable defined by:
$$ Z_i \tilde\ Bernoulli(\pi_0) \quad \& \quad X_i|Z_i\tilde\ \mathcal{N}(mu(Z_i),\sigma) $$
Data:
I generate a dataset following the mathematical model above:
n   = 100 # number of points
pi0 = 1/4 # proportion of points in the class 1
pi1 = 1-pi0 # proportion of points in the class 2
mu0 = 1 # mean of the class 1
mu1 = 4 # mean of the class 2
sd0 = 1 # sd of the class 1
sd1 = 1 # sd of the class 2
Z = rbinom( n , size=1 , prob=pi0 ) # Hidden information
X = rep( 0 , n ) # Information
X[Z==1] = rnorm(sum(Z) , mean=mu1 , sd=sd1 )
X[Z==0] = rnorm(n-sum(Z) , mean=mu0 , sd=sd0 )
plot(X,rep(0,n),col=Z*2+2,pch=0)

Now with the only information in my vector X, I want to find my four parameters ($\pi_0$, $\mu_0$, $\mu_1$ and $\sigma$). To do that I used JAGS to compute a mixture model.
NB: I also used the package Mclust but I want to code my own model to be able to complexity it later.
R Code
I built the following jags model:
top = 2*qnorm(0.925,mean=mean(X),sd=1.5*sd(X))
bot = 2*qnorm(0.025,mean=mean(X),sd=1.5*sd(X))

write(
paste(
 'model
 {
  for(i in 1:',n,')
  {
   Z[i] ~ dbern(pi0)
   mu[i] <- Z[i]*mu1 + (1-Z[i])*mu0
   X[i] ~ dnorm(mu[i],1/sigma)
  }
  sigma ~ dunif(1,5)
  mu1 ~ dunif(',bot,',',top,')
  mu0 ~ dunif(',bot,',',top,')
  pi0 ~ dunif(0.2,0.8)
 }'
,sep=""), "basic_mixture.txt")

And I computed the model:
# Compilation of the model
d <- list(X=X)
jm <- jags.model("basic_mixture.txt",data=d,n.chains=3)

# Chain generation
thin = 4
jmc <- coda.samples(jm,c("pi0","mu1","mu0","sigma"), n.iter=5000*thin,
                    thin=thin)
plot(jm)

The result of the last plot creates the first graphical.
I haven't a great experience in MCMC and JAGS code so my problem can be probably obviously solved but if you have some references that can help me to have a better understanding of the problem I'm very interested too.
Comment: It is possibly a label switching problem (see http://stats.stackexchange.com/questions/152/is-there-a-standard-method-to-deal-with-label-switching-problem-in-mcmc-estimati) the "symmetric" differences between traceplots seem to suggest that.
Comment: Yes, this is exactly "the" label switching phenomenon. Both MCMC chains overlap in your case so it means MCMC works very well! Since the chain switches between the different modes of the posterior density. This is also illustrated by the fact that you get similar posteriors on $\mu_!$ and $\mu_2$.
Answer: Imagine you have a mixture of two normal distributions, the one on the left (L) and the one on the right (R) side of the plot presented below. To estimate $\mu_L$ and $\mu_R$ parameters you decide to use MCMC approach. Generally, in such case you would draw lots of random values so to substitute the $\mu_L$ and $\mu_R$ parameters and among those values you would look for the best candidates. The problem is that the sampler is dumb, it does not know that "obviously" $\mu_L$ < $\mu_R$, so sometimes it produces such values where $\mu_L$ < $\mu_R$ and sometimes the opposite. This is called the label switching problem and it is very common problem when estimating mixtures with MCMC. It is called label switching because what you get from such simulation is two vectors $\boldsymbol{\mu_1}$ and $\boldsymbol{\mu_2}$ and each of those vectors would contain samples for both $\mu_L$ and $\mu_R$ parameters, sampler would not "know" that it should save all $\mu_L$ in $\boldsymbol{\mu_1}$ and $\mu_R$ in $\boldsymbol{\mu_2}$, so from time to time (randomly!) it would switch.

What could be done about this problem? In such simple case there is an obvious solution: force an restraint that always $\mu_L$ < $\mu_R$ (e.g. having two values simply sort them before assignment to mu1 and mu2 variables, or using different informative priors for each value). There is more ways of dealing with this problem (see this thread), but unfortunately they not always work and not always are so simple as the one described.
In many cases the problem is pretty easy to spot on traceplots. For example, look at the traceplots that you provided. If you compare plots for mu0 and mu1, you will notice that until 3000th iteration the green chain was sampling for the "higher" $\mu$ and then switched to "lower" $\mu$, to make many more such exchanges during the whole simulation.


Multiple PHP email message function. (checkboxes)

Question: What should I type in PHP instead of I got now to receive in mail all of the answers typed in checkboxes by user. Now I have only one. Thanks
PHP:
$email_message .= "Sport: ".clean_string($_POST["sport"])."\n";
$email_message .= "Music: ".clean_string($_POST["music"])."\n";

HTML:

    <input type="checkbox" name="sport" value="Kosz" />koszykówka

    <input type="checkbox" name="sport" value="Zimowe" />sporty zimowe

    <input type="checkbox" name="sport" value="Konie" />jeździectwo konne

    <input type="checkbox" name="rozrywka" value="festiwal" />festiwale

    <input type="checkbox" name="rozrywka" value="wesole" />wesołe miasteczka

    <input type="checkbox" name="rozrywka" value="zespolowo"/>paintball,bilard,kręgle..

Edit:
Thanks but not exactly can type different 'names' cause I also have one checkboxe to set all on check at once and it works with JS like this:

<input type="checkbox" onClick="toggle2(this)" />

<input type="checkbox" name="rozrywka" value="club" />kluby

<input type="checkbox" name="rozrywka" value="puby" />puby

<input type="checkbox" name="rozrywka" value="koncert" />koncerty

<input type="checkbox" name="rozrywka" value="festiwal" />festiwale

<input type="checkbox" name="rozrywka" value="wesole" />wesołe miasteczka

<input type="checkbox" name="rozrywka" value="zespolowo" />paintball,bilard,kręgle...

Answer: I'm not 100% sure what it is you're asking here, but if you'd like to see if a checkbox is set you can do the following:
if(isset($_POST['checkbox-name-here'])){
   //it's set code here, maybe set a variable...
   $var = "checkbox value";}

That's a rough example, but you should get the drift.
If you're trying to get multiples - then give each checkbox a unique name:

    <input type="checkbox" name="sport1" value="Kosz" />koszykówka

    <input type="checkbox" name="sport2" value="Zimowe" />sporty zimowe

    <input type="checkbox" name="sport3" value="Konie" />jeździectwo konne

Then in PHP you can check if each value is set:
if(isset($_POST['sport1'])){$sport1="sport1";}
if(isset($_POST['sport2'])){$sport2="sport2";}
if(isset($_POST['sport3'])){$sport3="sport3";}

$email_message .= "Sports: ".clean_string($_POST["sport1"])."\n"
                            .clean_string($_POST["sport2"])."\n"
                            .clean_string($_POST["sport3"])."\n";

There are much tidier ways of doing it, but that should help you work it out?
Alternatively you could give each of the checkboxes the same name, and then construct an array out of them. This array can then be looped in the PHP email handler. Look at this SO answer for a great example: https://stackoverflow.com/a/4516887/3112128
Comment: 1.Thanks for answering
2.Please check edit.
3.Dont know much about PHP that's why I just copied some of the PHP contact form code and I'm trying to change it to work with my page
Comment: Okay I need just a little bit more clarification. There is a HTML form with checkboxes, and when the form is submitted, the HTML values are processed into a mail handler and emailed?
Comment: .I think so.. yes.
The form head is:
If you want to see it yourself www.2know.pl/formularz.html
The HTML and CSS are public
Comment: Webistes looking good! Well done. HTML isn't much use right now though, it's the PHP. I know what's going on now though and can give a better example above.
Comment: .Don't get scared of the mess there in code. it's my first website
Comment: I'm afraid even though the answer is GOOD with my knowledge of PHP I can't adapt the code to my file. But I'll try. Thanks!


Bootstrap Datepicker and Disable C#/JSON array of dates,

Question: I have a list of dates that I want to disable in my bootstrap date picker.  I cannot get the datesDisabled function to work with the array of dates returned from JSON.  It does work with a hard coded array of dates.
Is there something that I need to do format the dates returned from JSON in order to get it to work?
Query:
var DatesBooked= JsonConvert.SerializeObject(db.Calendar.Where(x =>  x.CalLocation != "OFF")).Select(x => x.CalDate).Distinct().ToList());

In my view:
@Html.TextBox("AddedDates", null, new { @class = "form-control small", @Value = ViewBag.SelDate, autocomplete = "off" })

@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")

unavailableDates value
var unavailableDates = "[\"2016-05-01T00:00:00\",\"2016-05-02T00:00:00\",\"2016-05-03T00:00:00\",\"2016-06-24T00:00:00\",\"2016-06-25T00:00:00\"]"

If I hardcode thisfor unavailableDates, everything works fine.
var unavailableDates = ["05/25/2016", "05/26/2016"]

How do I need to format the dates in order to get this to work?
TIA!
Answer: Well after many attempts and more research, I was able to solve this by doing the following:
I reformatted the date using C#:
var checkdates = db.Calendar.Where(x => x.CalLocation != "OFF")).Select(x => x.CalDate).Distinct().ToList()

var DatesBooked= JsonConvert.SerializeObject(checkdates, Formatting.None, new IsoDateTimeConverter() { DateTimeFormat = "MM/dd/yyyy" });

Then in the view, I stripped the "\" characters returned by JSON and created an array:
var unavailableDates = @Html.Raw(Json.Encode(Model.DatesBooked));
        var formatDates = unavailableDates.replace(/\\/g, "");
        var trimDate = formatDates.slice(1, -1);  // to remove " at beginning and end
        var finalDates = JSON.parse("[" + trimDate + "]");
        $input = $("#AddedDates");
        $input.datepicker({
            multidate: true,
            multidateSeparator: ',',
            datesDisabled: finalDates,
            todayHighlight: true
    });


Have all promoted teams from one season of the united German Bundesliga ever been relegated in the following season?

Question: Have all the promoted teams in one season ever been relegated in the following season?
The most recent season when this "almost" happened was 2012/13, when two previously promoted teams got relegated. But in this season there was a third promoted team, which didn't get relegated.
Comment: @F1Krazy The first one!
Comment: By "united German Bundesliga", do you mean since the Bundesliga replaced Germany's regional leagues in 1963-64, or since the East German league was folded into it in 1991-92?
Answer: This has happened four times, although on all but one occasion, only two teams had been promoted the previous season:

In 1966/67, when Fortuna Düsseldorf and Rot-Weiss Essen were both immediately relegated. (Only two teams were promoted and relegated in those days.)
In 1978/79, when Arminia Bielefeld, 1.FC Nürnberg, and SV Darmstadt 98 were all immediately relegated.
In 1982/83, when FC Schalke 04 and Hertha BSC were both immediately relegated. Only two teams had been promoted in 1981-82, as Bayer Leverkusen had won a play-off and got to keep their place; Schalke ended up in the relegation play-off in 1982/83 but lost and were relegated along with Hertha and Karlsruhe.
In 1992/93, when Bayer 05 Uerdingen and 1.FC Saarbrücken were both immediately relegated. The Bundesliga had temporarily expanded to 20 teams in 1991/92 to include two East German teams as part of the reunification; only two teams were promoted that year while four were relegated.

Honourable mention goes to 1986/87: of the two promoted clubs, Blau-Weiß 90 Berlin were relegated, while FC Homburg went into the play-off (but won and kept their place).
There have also been nine occasions in which 2/3 of the promoted clubs were relegated: 1975/76, 1977/78, 1985/86, 1991/92 (though as mentioned above, four teams were relegated that year), 1999/2000, 2003/04, 2005/06, 2007/08, and 2012/13.
Comment: @SnackExchange There's generally a significant gap in quality between a country's first and second leagues. Some promoted teams are able to bridge that gap through clever recruitment and tactical nous, and some aren't.
Comment: What was the reason for these immediate relegations?


Matthews correlation coefficient - how much is a good classifier

Question: I'm comparing performance of different classifiers on the data sets derived from financial markets, getting different accuracy and precision measures but Matthews correlation coefficient and Kappa statistic seldom exceeds 0.2. My data sets are quite big like 20000x170
so it should not be a problem with not enough of data.
So my question is: what value of MCC and Kappa can be considered as a 'good classifier' on such data.
Answer: I presume your are from Poland?
I do not think it is possible to answer for your question. Even in some statistics books about measures like AUC it is said it will be domain specific.
My classification models had recently their MCC in range of 0.2-0.25 with AUC bit over 0.7.
MCC can be calculated only if you specify a cutoff point when you have a probabilistic prediction.
But besides measures of accuracy for classification you might have a explicit cost/benefit measures for false positives and false negatives which might change cutoff point taken from the purely information point of view.
Comment: Yes, I'm from Poland. You said 'MCC can be calculated only if you specify a cutoff point when you have a probabilistic prediction.' What you mean by that and why probalistic prediction ?? According to Wikipedia is just a way to describe confusion matrix and as an input uses TN,TP,FN,FP
Comment: There are two possibilities 1) you have a classification method which gives directly class labels 2) you have a classification method which gives a probability to belong to a class. Personally I prefer probabilistic prediction because you can have an estimate of variation and costs/benefits related to making a decision on different levels of probability to belong to a class. With only class labels, you cannot do that.
Comment: But there might not be an answer for your question related to the level of these measures which you like to report. Some processes can easily be so difficult to predict with information only available publicly. Of course if you have inside information, then I think it could be possible to improve classification... :)
Comment: thanks for info but i still don;t understand why you said 'MCC can be calculated only if you specify a cutoff point when you have a probabilistic prediction. ' My data sets are generated by high frequency FOREX rates (1min sampling) so no inside information. It seems that performance of classifiers is very unstable on this data i.e one day they perform great and another very bad
Comment: Hi Analyst, please don't sign your posts with "Analyst". See [this section of the help](http://stats.stackexchange.com/help/behavior), under the heading "*Do not use signature, taglines, or greetings.*" for an explanation of why. I have removed it for you in this case.  Krzysztof, I have done the same with yours.
Comment: There is a related topic here: https://stats.stackexchange.com/questions/118219/how-to-interpret-matthews-correlation-coefficient-mcc?rq=1
There is a table resuming what is a good value for Pearson correlation coefficient. MCC has the same meaning for binary class.


Stuck on a probability question about pairs of socks

Question: The question is as follows:

You have 10 pairs of socks (i.e., 20 socks in total) with each pair in a different color.  You put all the socks into the washing machine but it "eats" four of the 20 socks at random.

What  is  the  expected  number  of  complete  pairs  left  in  the  washing machine?

I approached this question like this:
There are 3 possible outcomes:

8 pairs of socks survive
7 pairs of socks survive
6 pairs of socks survive

I then tried to find the probability of each of these events occurring.
The ways that 8 pairs of socks survive is:

Eating 2 different colour socks then eating their pairs

Eating first sock, then eating it's pair, Eating the second sock, then eating its pair

P(8 pairs) = $1*\frac{18}{19}*\frac{2}{18}*\frac{1}{17}\\+1*\frac{1}{19}*1*\frac{1}{17}$
The ways that 7 pairs of socks survive is:

Eating three socks of different colours, then eating any one of their pairs
Eating two socks of different colours, then eating any one of their pairs, then drawing another sock of a different colour
Eating any sock, eating another sock of the same colour, then eating two other socks of different colours

P(7 socks)=$1*\frac{18}{19}*\frac{16}{18}*\frac{3}{17}\\+1*\frac{18}{19}*\frac{2}{18}*\frac{16}{17}\\+1*\frac{1}{19}*1*\frac{16}{17}$
The ways that 6 pairs of socks survive is:

Eating 4 socks of different colours

P(6 pairs)=$1*\frac{18}{19}*\frac{16}{18}*\frac{14}{17}$
I am confident that my solution is incorrect.
First of all, the probabilities sum to $\frac{2906}{2907}$ when it should sum to 1.
Secondly, I simulated the process in the question on my computer and the probabilities that I obtained were:
P(8 pairs)=$0.0269986$
P(7 pairs)=$0.4319539$
P(6 pairs)=$0.5410475$
Compared to my answers which were:
P(8 pairs)=$0.0093$
P(7 pairs)=$0.2972$
P(6 pairs)=$0.6935$
Would there be another simpler way of solving the question?
Comment: Assign an indicator variable to each pair of socks.  Use Linearity of Expectation.
Comment: Your own result adds up to one. Maybe you might also try checking your simulation.
Comment: I tried implementing a simulation myself and got $P(\text{6 pairs}) = 0.693988$, $P(\text{7 pairs}) = 0.296513$, $P(\text{8 pairs}) = 0.009499$.
Answer: There are $\binom{20}{16}$ ways to select the $16$ remaining socks, all of which we assume are equally likely.  Let $$X_i = \begin{cases}
1 \qquad \text{if pair i survives intact} \\
0 \qquad \text{otherwise}
\end{cases}$$
for $1 \le i \le 10$.   So
$$P(X_i = 1) = \frac{\binom{18}{14}}{\binom{20}{16}} =\frac{3060}{4845}$$
By linearity of expectation, the expected value of the number of surviving pairs is
$$E \left( \sum_{i=1}^{10} X_i \right) = \sum_{i=1}^{10} E(X_i) = 10 \times \frac{3060}{4845} = \boxed{6.31579}$$
Comment: An elegant approach.
Answer: I would go for more direct approach.
All possibilities of four socks being eaten is of type $abcd$ (six pairs survive), $aabc$ (seven pairs) and $aabb$ (eight pairs). Here each symbol stands for one of left or right sock of a pair.
Then expected number of survivals is
$$ \left[ 6 \cdot \binom{10}{4} \cdot 2^4  + 7 \cdot \binom{10}{3} \cdot \binom{3}{1} \cdot 2^2 + 8 \cdot \binom{10}{2} \right] \Big/ \binom{20}{4} $$
$$=\frac{120}{19} $$
which is roughly $6.316$ pairs.
Comment: What do the powers of 2 represent in your answer?
Comment: @FarmerZee We're treating every sock as distinct. Of any pair, we have two distinct socks : left and right. Powers of $2$ are to account for selecting either of these according to the mentioned possibilities.
Answer: The order of selection does not matter, just which socks are selected.
There are $\binom{20}{4}$ ways to select the four socks which are "eaten".
Eight pairs of socks survive if two full pairs are eaten.  There are $\binom{10}{2}$ ways to select two full pairs of socks.  Hence, the probability that eight pairs of socks survive is
$$\frac{\dbinom{10}{2}}{\dbinom{20}{4}}$$
Seven pairs of socks survive if one full pair of socks is eaten and one sock each from two of the other nine pairs are eaten.  There are $\binom{10}{1}$ ways to select which pair of socks is eaten, $\binom{9}{2}$ ways to select which two of the other pairs lose a sock, and two ways to select a sock from each of those pairs.  Hence, the probability that seven pairs of socks survive is
$$\frac{\dbinom{10}{1}\dbinom{9}{2}\dbinom{2}{1}^2}{\dbinom{20}{4}}$$
Six pairs of socks survive if one sock each from four of the ten pairs is eaten. There are $\binom{10}{4}$ ways to select the four pairs from which a sock is eaten and two possible choices for each of those pairs.  Hence, the probability six pairs of socks survive is
$$\frac{\dbinom{10}{4}\dbinom{2}{1}^4}{\dbinom{20}{4}}$$
Thus, the expected number of pairs of socks which survive is
$$\frac{6 \cdot \dbinom{10}{4}\dbinom{2}{1}^4 + 7 \cdot \dbinom{10}{1}\dbinom{9}{2}\dbinom{2}{1}^2 + 8 \cdot \dbinom{10}{2}}{\dbinom{20}{4}}$$


When user clicks on the add to cart, the items should get stored inside the table

Question:

<input type = "text" name ="color" id="color">
<input type = "text" name ="paint" id="paint">
<input type = "text" name ="build" id="build">
<input type = "text" name ="combine" id="combine">
<input type = "button" onclick="addto()"value="add to cart"/>`

these are the text field disbled in the webpage. When user types the value and click in the add to cart button the value of this should store in the table space provided below.

<input type="text">
<input type="text">
<input type="text">
<input type="text">`

This is the code for table when user fills the details and click on the display button the value should store in this table values.
Comment: can you show your code for `addto()` ?
Comment: actually i need a code to that function only i did not written any code yet to that addto().
Comment: do you need to save data in db or just show that in another table ? what you need to achieve?
Comment: i just want to store that in the another table .were user can cross verify  whether the entered value are right or not that's it
Answer: You firstly need to get all data from input box in jquery/js using .val() and then use .append(..) to add the data inside your table as a new row .So your jquery  code will look like below :
function addto() {
    //getting value from input box
      var color = $("#color").val();
      var paint = $("#paint").val();
      var build = $("#build").val();
      var combine = $("#combine").val();
      var appends = '
<input type="text" value=' + color + '>	<input type="text" value=' + paint + '>	<input type="text" value=' + build + '>	<input type="text" value=' + combine + '>
'
    //appending new row inside table
      $("#abc").append(appends);
    }

Demo Code :

function addto() {
  //getting value from input box
  var color = $("#color").val();
  var paint = $("#paint").val();
  var build = $("#build").val();
  var combine = $("#combine").val();
  var appends = '
<input type="text" value=' + color + '>	<input type="text" value=' + paint + '>	<input type="text" value=' + build + '>	<input type="text" value=' + combine + '>	<button type="button" onclick="remove(this)" >Remove</button>
'
  //appending new row inside table
  $("#abc").append(appends);
}

function remove(ele){
//Removing

ele.closest('tr').remove();
}
button{
color:black;
background:red;
}

    Color : <input type="text" name="color" id="color">

    Paint : <input type="text" name="paint" id="paint">

     Build : <input type="text" name="build" id="build">

     Combine : <input type="text" name="combine" id="combine">

    <input type="button" onclick="addto()" value="Add to cart" />

Your Typed Data Will Display Here :

      Color
      Paint
      Build
      Combine
      Remove

Comment: glad i helped :) don't forget to set this answer as accepted
Comment: In future if i need to add this row of table cart in to data base what changes should i make please help me for this
Comment: that depend on what you use , if you use ajax then onclick event you can you get all value from input and then insert the value in db or form is other option.
Comment: In   var color =$("#color").val(); #color  is value of id right???
Comment: yes that is `id` of input .. you need to use `#` with id name to get value  of a particular input .


Retirar apenas um valor na array

Question: Tenho uma array desta forma
$arr = array('10', '12', '10', '15', '18', '18', '7', '18', '18', '15');

Quatro vezes o valor 18. Preciso retirar dela apenas um valor, exemplo um 18, e ela continuar assim:
$arr = array('10', '12', '10', '15', '18', '7', '18', '18', '15');

E isso com qualquer outro numero até zerar e não possuir mais nenhum numero, exemplo o 18, não tem limite de números.
Como se fosse uma logica de carrinho de compras
Tenho 10 produtos numero 18, se eu retirar um de cada vez, o numero 18 vai saindo da array
Espero que tenha ficado mais claro agora
Comment: Possível duplicata de [Removendo um elemento específico em um array](https://pt.stackoverflow.com/questions/27445/removendo-um-elemento-espec%c3%adfico-em-um-array)
Comment: Pra zerar é facil, deleta o array :)   Relacionada https://pt.stackoverflow.com/questions/27445/removendo-um-elemento-espec%C3%ADfico-em-um-array
Comment: Você quer tirar o último?
Comment: Como assim até zerar? Cada número só pode aparecer até 3 vezes? Não está clara a lógica.
Comment: Até zerar seria o array não ter mais elementos? Qual a lógica para determinar qual elemento deve sair? Aquele que se repetir mais? Por favor, [edit] a pergunta e seja claro na sua dúvida.
Comment: Talvez seja o caso de array_unique — Remove o valores duplicados de um array
Comment: @AndersonCarlosWoss Ate zerar seria o caso, se tenho quatro números na array, vou retirando de um em um ate zerar, entendeu, como se fosse um carrinho de compras
Comment: @bfavaretto - Os números não tem limite, apenas preciso de retirar uma de cada vez se necessário, ou ate mesmo retirar todos porem tem que ser de um em um, ate zerar
Comment: Ok, retirar um a um enquanto houverem números. Isso ficou claro. Agora, como definir a ordem que devem ser retirados? Isso você ainda não explicou.
Comment: @AndersonCarlosWoss, retirar apenas um, independente da quantidade de vezes que ele repete, toda vez que eu chamar a função ele retiraria um numero que eu determinasse da array
Comment: @MarcosPaulo e como devem ficar os índices do array após a remoção do valor? Devem permanecer os mesmos ou reajustá-los?
Comment: @AndersonCarlosWoss não importa como retornam, basta apenas a remoção de cada um
Answer: Para isso acha-se a posição com a função array_search:
$posicao = array_search('18',$arr);

E de seguida elimina-se essa posição com a função unset:
unset($arr[$posicao]);

Ou fazendo tudo junto:
unset($arr[array_search('18',$arr)]);

Exemplo
Comment: Perfeito, deu certo aqui da forma que eu precisava

Retirar apenas um valor na array