10-fold cross validation, why having a validation set?

Question: I have my data stratified in 10 folders. So far I was using 9 of them to train the model, and the remaining one for testing it. A sudden thought just crossed my mind saying "you might be cheating". Authors of previous papers related to my problem used "10-fold cross validation with a single training fold used as an intermittent validation set". So they used 8 folders for training, 1 for validating and 1 for testing. I don't understand what is the purpose of the validation folder used in each of the 10 "iterations" of their cross validation proccedure.

Would it be reasonable to think that they changed the hyperparameters in each of the 10 iterations (where at the same time they were also changing the training and validation data, since that is what K-fold cross validation does), and then they went with the set of hyperparameters that gave the best test accuracy during that process?

Another general thing that I don't quite understand is, why setting the hyperparameters to best fit the validation set is right, and doing that for the test set is wrong, if they both come from the same distribution? Both are the same way of cheating the way I see it.
Comment: Possible duplicate of [What is the difference between test set and validation set?](https://stats.stackexchange.com/questions/19048/what-is-the-difference-between-test-set-and-validation-set)
Comment: Can you link the paper with "intermittent validation set"? I've never encountered the term (and a google search for me just turns up your question).
Answer: If you use a single set of parameters, then CV is enough.
If you also have to optimize hyperparameters, then you need a stacked approach.

Choose a test set, and put it aside.
Split the remaining data ("development set") into train and validation, for example using CV.
Optimize hyperparameters on this set only. You are now overfitting by model selection, and the performance estimate of CV is too optimistic.
Choose the final hyperparameters.
Get the test set you put aside before.
Train the model on the entire development set using the final hyperparameters, and test it on the test set, to get a more accurate prediction of your classifier performance.

By changing parameters until you get the best CV performance, you are indeed "cheating". You optimize parameters based on the evaluation score.
The reason why you need a clean (unused) test set is to really estimate how good it will work on new data. This is very important for business users (and researchers frequently are too sloppy here, as they won't lose money). If the new model is falsely-evaluated to improve sales by 5%, but it actually decreases sales by 5% because of overfitting hyperparameters, this can cost you money. Keeping a clean test data set helps getting a more reliable prediction of what could happen in the future.
It is even better if you can test on data that did not even exist at training time yet (fresh users). And in some cases it is beneficial to take time into account: always train on the older data, test on the newer data, because your future data is probably more similar to the newer data.
Comment: In $n$-fold cross validation, step 2 involves spitting the remaining data ("development set") into $n$ subsets ("folds"), and performing step 3 $n$ times for each attempt (with each fold in turn being a validation set and the other $n-1$ folds being the corresponding training set)
Answer: Let me chime in from a different point of view:
"Cross validation" and "validation set" are concepts that are orthogonal/independent in the sense that:

Validation set is about asking how many/which separate data subsets do I need?
Whereas cross validation is one possible answer to the question how do I generate/split my data to produce these subsets?

The original purpose of validation sets (1.), was, well, validation (or rather verification), i.e. measuring the generalization performance of the already trained model.
In that sense, yes, you do need a validation set. Note though, that this validation set I'm talking about has a totally different purpose of @Jai's validation set (see below).
Cross validation (2) is one very widely applied scheme to split your data so as to generate pairs of training and validation sets. Alternatives range from other resampling techniques such as out-of-bootstrap validation over single splits (hold out) all the way to doing a separate performance study once the model is trained.
At some point, there was the necessity to do some fine-tuning of hyperparameters. Unfortunately, instead of saying: fine, our new training algoritm internally does an optimization on generalization error, and therefore we split the training set again into a hyperparameter optimization set and a normal parameter fit set, the former valiation set was used for optimization. Because that is really part of the training, another set to estimate the final model's performance was needed. I.e. a set that does what the validation set used to do. This needed another name, and bekame known as test set.
In my experience this historic naming scheme train-validate-test creates a lot of confusion, particularly in fields where verification and validation were already established terminology for studying/demonstrating the predictive performance of methods.
Personally, I therefore prefer to speak

either of training-optimization-verification or
of training and verification/validation pointing out that inside your training you can do whatever further splits you like.
This point of view has the advantage, that it is much easier to see which set of hyperparameters should be used when doing the final training with the whole data set.
Maybe this also helps to explain:

why setting the hyperparameters to best fit the validation set is right, and doing that for the test set is wrong, if they both come from the same distribution? Both are the same way of cheating the way I see it.

The idea is that during training you are allowed (and supposed) to find out as much as possible about this distribution. Validation/verification then is to prove how much about this distribution was actually learned. And hyperparameter tuning really is part of the training.
Another analogy to the training-optimization-verification splitting is school: training when a concept is explained to you. You then may do some test exams to to challenge and fine-tune your understanding of the concept. Finally there is an exam to demonstrate the learned ability. Even if you do another round of fine-tuning your concept after the exam, the mark is set. The same with a model, just that we know for many practically relevant situations that there is much higher danger of overfitting with our models, so we just don't accept any claim of improvement over the validation (exam) without proof (another validation, re-taking the exam).

Now for each of these splitting steps, you need to decide how to do this. Doing single splits leads to the fixed train-optimize-verify (aka train-validate-test) approach. Doing cross validation for both is called nested or double cross validation. Your intermittent cross validation corresponds to doing cross validation for the (train+optimize) vs. verify split, and a single split for train vs. optimize.

Would it be reasonable to think that they changed the hyperparameters in each of the 10 iterations (where at the same time they were also changing the training and validation data, since that is what K-fold cross validation does), and then they went with the set of hyperparameters that gave the best test accuracy during that process?

No, this is not a good idea
A valid approach would be in each fold to optimize training, and record the test results. This basically corresponds to a cross validation of a training procedure that does a single split into train and optimization data sets internally.
Answer: The key thing you want to acces is how well your model can generalize.
Let's take a look at the usual workflow:
You have a training set which you use to continuously update the internal parameters of your model to minimize some error/loss function. Your model usually does very well after a certain time to give very good results for the training data, which is not suprising since that is the set used for setting the parameters. It does thereofre not make sense to use the error on the training data to judge your model.
To acces if you are done training yet you normally use a testing dataset. After a certain amount of updating steps you run your model on your test dataset. This will give a first impression of how well your model generalizes. If you have 0 error during training and a high error on this test dataset, then you are overfitting and need to rethink.
If everything goes well however you train until the error on your test dataset satisfies you or is not improving anymore.
However by doing so, the test dataset was part of the training process and using the error on your test dataset would be (as you say) "cheating" as the test dataset does not contain data that is completely unseen by your model.
That is why you need data that is completely new and unseen to truly acces how well your model actually does when given data that it has never seen before. The error on this validation set is what you want to be as low as possible which is why you would update the hyper parameters to give the lowest error on the validation set.
Appendix: comming back to your second question. why is it not cheating to use a validation set that comes from the same distribution than the rest of the data?
Think about it this way: You want your model to learn a relationship between input data and output data. Let's  assume you have an image classifier that classifies images into the categories "cat", "dog" and "mouse". Now when you have a large set of images and then are able to perform well on both training and validation set, then you can assume, that your classifier has learned a relationship between the images and the correct classification.
The kind of problmen that is probably also in your head is another one:
What if all cat pictures come from my mother who has a black cat, all dog pictures are from my brother that has an albino dog and the mouse pictures are all of grey mice. Then you would have a problem because since your model will just learn to look for black, grey or white content in the image.
But that is a problem of biased data and cross validation does not claim to be able to detect it.
Comment: But then, coming back to my second my question, why using the validation set for setting the hyperparameters is not "cheating" , if we somehow are setting them to perform well on the test set (since test and validation set come from the same distribution)?
Answer: In general, the idea is to have 3 sets: one each to train, validate and test your data.
The test set, you really don't wanna touch before all other parameters and hyperparameters are fixed.
You use the training data to fit your model and the validation set to see how different hyperparameter settings play out - meaning that you still compare different settings.
Only once you settle for a model and setting, it makes sense to evaluate it.
If you optimize hyperparameters on the test set, you falsify your performance evaluation.
As for the k-fold cross validation, this still makes sense for the training | validation split. Just keep the test data out of it.
Answer:
It is essential to have validation set
Here are the reasons of why is it essential to have validation set:
1] It does not waste training time because after few steps if the model does not perform well on validation set then you can just stop the training instead of waiting for the whole training to get completed
2] It is so obvious that if your model does not do good on validation set then it will definitely won't work on test set so it kind of tells you in advance whether the model overfit or not and the model's performance
3] The hyper-parameter tuning should always be done by evaluating model on validation set and not test set. If you used your testing set for hyper parameter tuning even though the test set was not included in training still it will be considered that you cheated because you used your testing set as training set
4] Now if hyper-parameter tuning is done seeing the testing set then the model will work on that particular testing set very well but won't generalize to other data in the real world or any other test set
5] To avoid test set to be a part of training set the idea of validation set came up
Why to use k-fold-cross validation set?
1] K-fold cross validation is usually used when the data is very less
2] Suppose you only have 18 training samples then in this case you can not afford to make a validation data set because already your training set is very less
3] In such cases k-fold cross-validation is used
4] In K-fold Cross-validation for every step the validation set changes
Just keep in mind that during training stage for any reason you used any information from the test set then you have cheated and if you have done so there is no guarantee how well your model will perform in the production even though the model performed well on the particular test set
So yes, you can tune your hyper-parameters according to the validation set even though the validation set changes in k-fold cross validation
But let's just consider what you said that is it really fine on tuning your hyper-parameterrs based on validation set that changes after every step ?
So, for k-fold cross validation suppose your k value is 10 and the number of steps for training is 100
So for every step the validation set chosen will be different but remember after the 11th step the validation set that was used in the 1st step will be repeated
Which means after every 10 step of training the validation set will be repeated and hence it is fine to tune your hyper-parameter based on validation set even in k-fold cross validation settings
And it really does not matter both validation set and test set comes from the same distribution
Remember that your model will only see the data samples coming from the same distribution. By this what I mean is that even in production the model will be used to classify from the distribution it was trained on
So the training, validation and testing all of them belong to the same distribution and the idea is to make your model learn that distribution based on only training set because you do not have all the samples in the world that belong to that particular distribution
Comment: Okey, thanks for the answer. But then, regarding my first question, when doing K-fold cross validation, does it makes sense to change the hyperparameters according to the validation set, if in the next "iteration" the validation set is going to be a different one?
Comment: @Santiago I updated my answer ... Anything else that you want to know ??


Hiding link from anonymous users

Question: How can I hide a particular link in the main menu from anonymous users without making the whole menu invisible?
Comment: What version of Drupal is this for?
Comment: If that page is not visible to anonymous user then the link will be automatically removed.
Comment: And how can I configure who views the page?
Comment: I'm using Drupal 7. Version 7.14 to be precise.
Answer: You don't so much configure the visibility of links directly, but rather you configure the permissions of specific content types, and any link to content of a particular type will either be visible or invisible depending on the permissions of the content the link points to.
You can configure the permissions on any given piece of content by going into the Permissions section in Administration and finding the content type you want to restrict permissions on, and configure those permissions (check boxes for view, create, edit, etc..) based on role appropriately.
If you need to configure access to specific nodes/content, then you might have a look at Content Access.
Comment: That's the very nature of the problem. I need some pages to be visible to anonymous users, so I can't simply block them by content type. Isn't there a way to configure the menu block so it only shows certain links to people who are logged in?
Comment: Updated my answer with a link to a module that should be able to help you out.
Comment: @Lester I don't think this allows for access control at node level, I could be wrong but it seems one would need to create a specific content type for the nodes needing access control. But this is already built-in in Drupal, so I'm a bit confused as to what this module does?  I will have to try this out. Thanks for sharing bro.
Comment: If you click on the thumbnail for the project, there's a "per content node access settings" item that you can check off.  It sounds like it adds another tab next to 'View', like 'Permissions' or something similar where you can configure perms just for that node.  But yeah, I'd need to try it myself too before I could actually confirm it.
Comment: Sick, I'll have to tuck this one away in my little bag of tricks going forward.
Answer: You can do this easily with a little bit of elbow grease!
There are two hooks for this depending on if your menu is generated by a module or by Drupal itself. In a custom module you would use either hook_menu or hook_menu_alter.
These two hooks have a parameter, access callback where you can give it a function that returns a BOOL. If the function returns TRUE, access is allowed and menu link is shown. If FALSE is returned, access is not allowed and menu link not displayed.
//Small example
function <your_module>_menu_alter(&$items) {
  // Example - disallow access for anonymous to node 15 from custom module
  $items['node/15']['access callback'] = '_accessCheck';
}

Then, further down you define the callback:
function _acccessCheck(){
  global $user;
  if ($user->uid) { // user is logged in
    return TRUE;
  } // Anonymous
    return FALSE;
}

Hope this helps, happy coding!
Answer: you could restrict users to see some of the menu links by using Menu per role module.
It allows you to restrict access to menu items based on user roles. So you could hide a particular menu link from a particular role and show it to others.
Comment: Hiding a menu item without restricting access has legitimate use cases, however hiding is no substitute for restricting if you need restricted content. That's bad. It's not just users guessing the URL (which by the way is an easy thing to do), it is also search engines indexing your pages if they are not restricted. If your content is sensitive this is very important. - That said, the question never stated that content access be restricted.
Comment: Does it hide the menu link or does it restrict access to the page it points to as well?
Comment: @LesterPeabody It hides the menu link. And hiding the menu link is as good as keeping the users to visit that page. I'm not sure if users might just guess the URL to visit the page ;-)
Comment: I just have serious issues with that from a security standpoint.  I don't understand the benefit to just hiding a link when they can still access the page it points to, just doesn't make any sense to me.
Answer: You can do it manually. Maybe, it isn't the best form, but it may fix you problem temporarily.
You can add a JavaScript file to you main .tpl.php. In this file you can play with the parent and children elements of you code (http://api.jquery.com/parent), by JavaScript methods. So, first you have to get your element, by something like #idelement (it may be positioned in the menu code between all the leafs of the menu) and then hide the element by .hide(). Also, you have to add to your code that the JavaScript file added to the .tpl.php only if the user is logged in. Like:
if(user_is_logged_in()){
   drupal_add_js(yourjSFile);
}

I repeat that is a temporary solution.
If you modified your code or element in the menu, this solution also must be modified.
This will only hide a menu item, and not the content types.
Answer: http://drupal.org/project/content_access works really well for me with Drupal 7.22.
It even hides the main menu links pointing to restricted content.

Hiding link from anonymous users


one ball is drawn at random from each box, what is the probability that both the balls are of the same colour?

Question: Boxes 1 and 2 contain 4 white, 3 red and 3 blue balls; and 5 white, 4 red and 3 blue balls respectively. If one ball is drawn at random from each box, what is the probability that both the balls are of the same colour?
Answer: This problem is a short calculation. Since both of the draws from the boxes are independent events, the probability of drawing a color from one box and the same color from the other box can be multiplied to find the probability of both events happening. Since the probability of drawing each color is disjoint from the other, the probability of the same color is the sum of the probability of drawing each color.
$P(\mbox{A and B})$ $=$ $P(A)P(B)$ if the events are independent.
$P(\mbox{A or B})$ $=$ $P(A)+P(B)$ if the events are disjoint.
$P(\mbox{2 whites}) = P(\mbox{white from the first box}) P(\mbox{white from the second box}) = \frac{4}{10} * \frac{5}{12} = \frac{20}{120}=\frac{1}{6}$
Similarly, $P(\mbox{2 reds}) =\frac{3}{10} * \frac{4}{12}=\frac{1}{10}$ and $P(\mbox{2 blues}) =\frac{3}{10} * \frac{3}{12} = \frac{3}{40}$
$P(\mbox{same color})=P(\mbox{2 whites})+P(\mbox{2 reds})+P(\mbox{2 blues})=\frac{41}{120}$
Edited for answer twice.
Comment: ThanQ for the answer, but how we get 3/8 when we add 1/4+1/10+3/40 which is 17/40, plz correct me
Comment: ThanQ for the update.
Comment: Is P(white from first box) = 4/10?  If so the final answer I'm getting is 41/120, please correct me.
Comment: Yeah, I rushed the calculation at first, but the steps are right.
Answer: HINT:
Probability of both balls to be white
$$\frac4{4+3+3}\cdot\frac5{5+4+3}$$


Can you make your own guitar capo with things around the house?

Question: I have lost my capo. Does anybody know of any easy DIY guitar capos one can make from items around the house?
Comment: WWM[cGyver]D ?   me, I'd waste hours designing one in CAD and 3D printing it. :-)
Answer: A pencil and an elastic band is a classic.
Wikipedia demos one at https://en.m.wikibooks.org/wiki/Guitar/Guitar_Accessories

Attribution: Lovenotmakewar at English Wikipedia
Comment: If you keep the same set on for years, possibly!
Comment: wouldn't that wear out the strings?
Answer: A plastic pen (parallel sided), a bolt inside plastic tubing, short length of dowling, rubber band for tension, a scrunchie can work, maybe with an eraser behind the neck for more tension.
Works better on flat or large radius fingerboards.
The ubiquitous index finger has also been used on occasions...
Answer: any flat object that's not to big around.ie 1/4 " tree branch and to keep it in place any string tied at each end keepinp it tight to the neck.I have done this while camping out.i also made drum sticks from tree branches
Answer: For this kind of things, the fastest is to look it up on  Instructables.
Besides the pencil and rubber band, there are also capos that need more effort to make:


How to play with a blues backing track in A

Question: I found this backing track here: https://www.learningguitarnow.com/free-blues-backing-tracks/free-blues-backing-track-slow-blues-in-a/
Now I try playing it with this scale:

Will this work out? Because as a beginner I do not know if the backing track is in A Blues as well. It only says its in the key of "A".
How to figure out if this will work?
Comment: If it says the backing track is a "slow blues in A" then with all likelihood you'll be alright with the blues scale in A that your diagram shows. How to figure it out - well, use your ears. Play the tones in the scale over the backing track, focusing on the roots of the chords of the progression (A-A-A-A-D-D-A-A-E-D-A-A). If it sounds good, keep doing it.
Answer: It should work fine. Just make sure your guitar is tuned well (use tuner). If you need a sanity check play the lowest A note on your guitar (open 5th string or 5th fret on low E string) and it should be the same note, the bass guitar plays at the beginning of the track.
Now, how to make a blues scale sound like a blues is another thing. Blues scale is only a selection of notes that fit well to basic blues chord progression and work well more or less throughout the whole progression. But these notes are more like a letters of blues alphabet and blues is a language that, as all languages, starts from words.
The best way to start playing the blues is simply by learning and copying existing vocabulary of phrases, licks ect. Then as an afterthought you might think about how they fit into blues scale. Sometimes they won't as the blues scale is not the only scale that works well in blues. But to sum it up: don't "use" scales - they're not for using, they just are. Learn the language instead. And if you're not sure if something sounds right or not, devote lots of time to training your ear, active listening, copying from recordings. It will get you much further at this stage than studying the scales.
Answer: Backing track says Blues in A. It should be using the dominant sevenths of each chord. The order ought to be
<code>                  A7  A7  A7  A7

                  D7  D7  A7  A7

                  E7  D7  A7  E7
</code>
the E7 being the turnaround chord to get to the next verse.
The guitar neck pattern is the minor blues scale in A, so notes will fit.
Don't just play up and down the scale - it sounds awful - you want awesome!
Try to play the chord notes on the first beat of each bar to start with. Then add some of the other notes between. Use your ears more than anything else. You'll find some notes just won't sound good over certain chords, and others will sound bad in a good way.Short notes will fit almost anywhere, so it's the longer notes you need to be careful with - vibrato will sound good with them.
Comment: I think I have a good example of "Don't just play up and down the scale". Here is my first try on the backing-track: https://vocaroo.com/i/s1QLhj1KtjI3
As far as I am sane I was surely in the A Blues Scale but still it sounded "bad" at some places!
Comment: @xetra11 I thought that was pretty good - dissonance is okay, as long as you don't hold it for too long before resolving to something else. Very brave of you to post it.
Comment: That's a nice try for the first! Well done.On the A7 bars, if you hold on to a C note(e.g.3rd string 5th fret) It sounds better bent up, or wobbled strenuously, to C# (maj3), as it fits what the band is playing better. An old trick - it works!
Answer: I struggled with this, and "use your ears" isn't always the right answer if you're not Eric Clapton and unblessed with prodigious natural talent, rather just a willingness to learn.
There are lots of variations on the blues chord progression too. You need to know the chord progression and so which chords come along in which sequence. However I never knew a way to pick which notes would sound good. This guide (admittedly for bass guitar) shows you which elements of each chord to use heavily and which to leave alone, or to use sparingly. It was this article that demystified it all for me.
Jarek is right to say that you do need to learn the vocabulary of phrases and their rhythms to sound "authentic" but its good to start by sounding musically literate first. Its a huge confidence boost and every learner needs that.
See also here simple discussion of note choices in another answer for an excellent answer from Michael Martinez.
Bass guitar for dummies article on note choices for chord progressions
Comment: You're right, use your ears is not a great suggestion if we can't rely on them. But on the other hand I have quite strong opinion about pointlessness of studying any theory without being able to "aurally recognize" any of the material we're studying. Do I actually know lydian scale if I can't sing it in my head or recognize in recording? Ear training is the elephant in the room and it can be trained and perfected as any other ability. And somehow it is extremely neglected in something we could call modern rock, blues, pop education
Comment: Agreed, but as a non-talented player, I think that "I'm making progress, and its coming from me" feeling is worth gold. Understanding follows with "so why does that work, exactly" later). I do think recognising intervals should be a practice topic in its own right.
Comment: If you can't 'use your ears' what other senses *can* you use?  It's of paramount importance that we listen - both to what we play and what others play. What goes on when trying to play along to a backing track. Don't tell me, or anyone, that we don't *'use our ears*'!! Otherwise we're not listening to either the track, or what we're trying to play to it.
Comment: I'm not saying that @Tim.Obviously no other senses would do instead What I'm saying is that's an easy response to give someone who has acquired a degree of competence and so doesn't have to wonder what choices to make, or has natural talent to make it easier. If you do not know innately, then you need some **pointers to make things easier**. Lots of people give up on instruments because no one shows them the bare bones and they give up hope. Its all about feeling confidence that you are making progress. Even if its only little gains, its still another valuable step down the road.
Comment: "use your ears" is tantamount to saying "well you should **just know**". If you don't magically "just know" then you feel a failure. Some people need to take smaller steps, or understand the steps better as they take them, or need it explained in a different way.
Comment: 'Use your ears' means in my world exactly that - 'listen'. I don't expect anyone, especially raw beginners, to 'just know'. How could they. The phrase isn't trotted out willy-nilly. It's an order to pay attention to all the sounds - the backing track and your contribution over it. Listen for the good bits that occur serendipitously, remember what you did. The bad bits, remember not to do them again! Obviously pointers and encouragement help, but using your ears is still at the forefront of any music making.


EXTNET MVC. Use a Store to send data to a page

Question: I am trying translate a web page dinamically.
The web is done with MVC, and EXTNET framework.
I am using a store in the web. I am trying to load into the X().Store the information of the resources file.
When load the web, the store call an action, who créate an dictionary with the data (key,value).
And then, with a listener, i call a JavaScript function.
But on this JavaScript function, i don't find the array with the values.
The code of the cshtml is:
@using (Html.BeginForm())
{
    var X = Html.X();
    @(
    X
    .Store()
    .ID("dsTranslate")
    .AutoLoad(true)
    .Fields(field =>
        {
            field.Add("key");
            field.Add("value");
        }
    )
    .Listeners(lis=>lis.Load.Fn="TranslateLoaded")
    .Proxy(p =>
        {
            p.Add(
                X.AjaxProxy()
                .Url("/extnet/Translate")
                .Reader(
                        reader => reader.Add(X.JsonReader().RootProperty("data").TotalProperty("total").IDProperty("key"))
                       )
                );
        }
        )
    )

The controller code for method /extnet/Translate:
public StoreResult Translate()
{

        var lang = "es-ES";

        if (Request.Cookies.Count > 0)
            lang = Request.Cookies["cultureCode"].Value;

        CultureInfo cult = Thread.CurrentThread.CurrentCulture;

        try
        {
            cult = new CultureInfo(lang);
        }
        catch (Exception ex) { }

        ResourceSet res = Resources.ResourceAdministracion.ResourceManager.GetResourceSet(cult, true, false);
        IDictionaryEnumerator trav = res.GetEnumerator();
        Dictionary<string, string> dict = new Dictionary<string, string>();

        while (trav.MoveNext())
        {
            if (trav.Key.ToString().Length > 2)
                dict.Add(trav.Key.ToString(), trav.Value.ToString());
        }

        var q = from c in dict
                select new { key = c.Key, value = c.Value };

        return new StoreResult(q, dict.Count);
    }

And where i have the problem. The script js:
var TranslateLoaded = function (objGrid, gridRecords, objOptions) {
        for (var i = 0; i < gridRecords.length; i++) {
            alert('Clicked');
        }
}

The object gridRecords have only one ítem, but i send 12 or more into the storeresult of the action.
Any idea about the problema with the code?
Need more parameters into the cshtml?
Debuging the script, i can see the variable total count with the number of records i have, but i don't know where is the array.
I am trying to do like this example:
http://sodeve.net/2011/10/how-to-enable-multi-language-translations-in-ext-net-mvc-part-2/
But it is not in cshtml, and i don't know if all my cshtml code is correct and like the example.
Answer: Ok.
All the previous code is correct.
Only rebuild the Project, and work perfect.
Sorry about the question.


Probability that 2 numbers will occur exactly 4 times.

Question: A die is rolled 10 times, what is the probability that 2 numbers will occur exactly 4 times? So I know that the probability of rolling any one number exactly 4 times would be
$$\frac{10!}{4!6!}\cdot \left(\frac{1}{6}\right)^4 \cdot\left(\frac{5}{6}\right)^6,$$
so would the probability that two numbers occur exactly four times be?
$$\frac{10!}{8!2!}\cdot\left(\frac{1}{6}\right)^4\cdot\left(\frac{1}{6}\right)^4\cdot\left(\frac{4}{6}\right)^2$$
Comment: Are you asking for the probability that, given two numbers which are fixed from the beginning, you get numbers which are either one or the other, exactly four times?
Comment: Copy and paste typo. Fixed
Comment: @fuglede no what I want to know is the probability if you roll the die ten times one number shows up four times and another number shows up four times.
Comment: What about the remaining two ? Are they identical ? Or Different ?
Comment: I am assuming that the remaining two can take any value
Answer: No, you have ignored two effects.  The first is that you seem to be trying to calculate the probability that two specific numbers occur four times each, and the problem asks for any two numbers.  The second is that once one number is given to have occured exactly four times, the odds of the other number also doing so are different that the original odds.
The easy way to do this is to ask how many ways to arrange to get two four-timers are there, and divide by $6^{10}$. So:

There are $\binom{6}{2}$ ways to choose the two numbers.
There are $\binom{10}{4}$ ways to choose  which of the dice landed on the specific first number.
There are then $\binom{6}{4}$ ways to choose  which of the dice landed on the specific second number.
There are then $4^2$ ways to choose the rolls of the remaining two dice.

The net probability is
$$
\frac{1}{6^{10}} \cdot \frac{6!}{2!4!}\cdot\frac{10!}{6!4!}\cdot \frac{6!}{4!2!}\cdot 4^2
$$
Comment: +1, and respectfully, I totally see your calculation, but I was wondering if the wording for the $\binom{10}{4}$ line is clear to everyone. I know what you mean.
Comment: Is your solution for one or two dice?
Answer: After your clarifications, here's an approach to compute favorable ways:
[ Choose faces to come up ] $\times$ [ Permute ]
There are two possibilities:
$4-4-2\;of\;a\;kind: [\binom62\binom41] \times [\frac{10!}{4!4!2!}]$
$4-4-1-1\;of\;a\;kind: [ \binom62\binom42] \times [\frac{10!}{4!4!1!1!}]$
Add up to get favorable ways, and divide by $6^{10}$ to get the final result
Answer: We can ask about the more  general problem of rolling an $n$-sided die
$m$ times and observing exactly $p$  values that occur $q$ times. This
corresponds to the marked combinatorial species
$$\mathfrak{S}_{=n}(\mathfrak{P}_{=0}(\mathcal{Z})
+ \mathfrak{P}_{=1}(\mathcal{Z}) + \cdots
+ \mathcal{U} \mathfrak{P}_{=q}(\mathcal{Z})
+ \mathfrak{P}_{=q+1}(\mathcal{Z}) + \cdots).$$
What we have here is a  sequence of sets containing the positions from
among  the $m$  rolls  where  a value  from  the  $n$ possible  values
occured, where instances of sets of  $q$ positions are marked. We then
obtain the mixed generating function
$$G(z, u) =
\left(\exp(z) - \frac{z^q}{q!} + u\frac{z^q}{q!}\right)^n.$$
On extracting the coefficient on $[u^p]$ we get
$$m! [z^m] [u^p] G(z, u) =
m! [z^m] {n\choose p} \frac{z^{pq}}{(q!)^p}
\left(\exp(z) - \frac{z^q}{q!}\right)^{n-p}
\\ = m! [z^m] {n\choose p}
\frac{z^{pq}}{(q!)^p} \frac{z^{(n-p)q}}{(q!)^{n-p}}
\left(\frac{q!\exp(z)}{z^q} -1\right)^{n-p}
\\ = m! [z^m] {n\choose p}
\frac{z^{nq}}{(q!)^n}
\sum_{k=0}^{n-p} {n-p\choose k} (-1)^{n-p-k}
\frac{(q!)^k \exp(kz)}{z^{kq}}
\\ = m! [z^m] {n\choose p}
\frac{1}{(q!)^n}
\sum_{k=0}^{n-p} {n-p\choose k} (-1)^{n-p-k}
(q!)^k \exp(kz) z^{nq-kq}
\\ = m! {n\choose p}
\frac{1}{(q!)^n}
\sum_{k=0}^{n-p} {n-p\choose k} (-1)^{n-p-k}
(q!)^k [z^{m+kq-nq}] \exp(kz)
\\ = m! {n\choose p}
\frac{1}{(q!)^n}
\sum_{k=0}^{n-p} {n-p\choose k} (-1)^{n-p-k}
(q!)^k \frac{k^{m+kq-nq}}{(m+kq-nq)!}.$$
Taking into  account that we must  have $m+kq-nq\ge 0$ we  obtain that
$k\ge n -  m/q.$ The problem definition tells us  that $m\ge pq$ (zero
possibilities  otherwise) and  hence  $m/q \ge  p.$  Thus  we  finally
obtain the probability
$$\bbox[5px,border:2px solid #00A000]{
\frac{m!}{n^m} {n\choose p}
\sum_{k=\lceil n - m/q\rceil}^{n-p}
{n-p\choose k} \frac{(-1)^{n-p-k}}{(q!)^{n-k}}
\frac{k^{m+kq-nq}}{(m+kq-nq)!}.}$$
Observe that this will yield $${\frac {875}{69984}}$$ for the question
posed by the OP ($n=6, m=10, p=2, q=4$) which incidentally matches the
answer by @MarkFischler.  Here we have used that ${n-p\choose k}$ will
be zero should $\lceil n - m/q\rceil \lt 0$ and $k$ is negative at the
lower end of the range.
There is  some very basic Maple  code to verify the  correctness of
the formula.

PROB :=
proc(n, m, p, q)
    option remember;
    local ind, digits, rolls, res, valset, match;

    if m < p*q then return 0 fi;

    res := 0;

    for ind from n^m to 2*n^m-1 do
        digits := convert(ind, base, n);

        rolls := digits[1..m];
        valset := convert(rolls, `multiset`);

        match := select(ent->ent[2] = q, valset);

        if nops(match) = p then
            res := res + 1;
        fi;
    od;

    res/n^m;
end;

PROB2 :=
proc(n, m, p, q)
    option remember;
    local ind, digits, rolls, res, valset, match;

    if m < p*q then return 0 fi;

    res := 0;

    for ind from n^m to 2*n^m-1 do
        digits := convert(ind, base, n);

        rolls := digits[1..m];
        valset := convert(rolls, `multiset`);

        match :=
        add(`if`(ent[2] = q, 1, 0), ent in valset);

        if match = p then
            res := res + 1;
        fi;
    od;

    res/n^m;
end;

X := (n, m, p, q)->
m!/n^m*binomial(n,p)
*add(binomial(n-p,k)*(-1)^(n-p-k)/(q!)^(n-k)
     *k^(m+k*q-n*q)/(m+k*q-n*q)!, k=ceil(n-m/q)..n-p);


how can i change the type of storing Dict from row to column using Python

Question: I have a simple question. I am using this code to store dictionary of dictionaries in csv file.
data = dataA,dataB, dataC, dataD
w = csv.writer(open("test.csv", "w"))
for x in data:
    for field, possible_values in x.items():
        print(field, possible_values)
        w.writerow([field, possible_values])

The stored values which I got in csv are stored in rows but I want them to be stored as column.
My actual result in csv:
name: Alex
Old: 22

My target in csv is should be like this:
Name  Old
Alex  22

How can I change it?
Update1:
the clue is for key in x.keys(). After many hours of hard work i updated my code like that and it works better than before but i still have a small issue to get a new line at the end of storing all values and keys x.keys() and y.values(). of my dictioanries in csv file
 if not os.path.isfile(filename):
    outfile = open(filename, "w")
    #outfile.write("#Sequence,,,,")
    for x in data:
        print(x.keys())
        for key in x.keys():
            print(key)
            store_key= key + ","
            outfile = open(filename, "a")
            outfile.write(store_key)
            outfile.close()

    for y in data:
        print(y.values())
        for value in y.values():
            print(value)
            store_value = value + ","
            outfile = open(filename, "a")
            outfile.write(store_value)
            outfile.close

Now i need to seperate maybe with "\n" between keys and values to get the the values od arays under the line of keys.
Any help yill be appreciated.
Comment: post the expected output for multiple dictionaries
Answer: You can write a row of the dictionary keys, then a row of the values.
for x in data:
    w.writerow(x.keys())
    w.writerow(x.values())

Comment: thank for answering. your tip works but i got all entities in one column. My goal, that next entity should be writen in the next column.
Name
Alex
Old
22
------------
Name  Old
Alex      22

my target is:
Name  Old
Alex     22
Answer: If you try to access and write to file, this will slow down your code. Hold the output text in a string, delete last comma(,) and add a newline character to end of the string. It will speed up your code, and new line will be added. You can do same for the second for loop too.
line = ""
for x in data:
    for key in x.keys():
        line += key + ","

line = line[:-1]+"\n" # Delete last character and add new line
outfile = open(filename, "a")
outfile.write(line)
outfile.close()

Comment: i can't use the function because i need to store  list of disionaries in csv file yithout [ ] and ' "
for x in data:
    outfile = open(filename, "a")
    outfile.write(str(x.keys()))
    outfile.close()
the problem which i have now that i got in csv file all the symbols of dictionary because iam using str().
When i dont use str() i got an error that yrite argument must be a str not dic_keys
Comment: @AhmyOhlin Can you add your expected result to your question for `data = [{"name": "Alex", "age": "22", "sex": "male"}, {"name": "Alice", "age": "19", "sex": "female"}]`
Comment: If you stick with your first code and use `w.writerow(x.keys())` like @Dustin said, you don't have to use `str()`. Use `data` that I gave previous comment. You'll see, it works.
Comment: thank you for the answer @Alperen . how can i add a new line in last element of dict of for loop?
Comment: That works. i got exactly what i wanted. but to be honest i feel bad because i really don't understand your code line += key + "," line = line[:-1]+"\n" : Could you please explain what line[:-1] means.
I think you have changed entities of my dict to list and you stored it every time in a line  . correct me please if iam wrong?
my question is: what does -1 means? you wrote als comment "delete last character" which characted will be deleted?
Thank you for your help and i will be happy if you could make me understand the code.
Comment: Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/157401/discussion-between-alperen-and-ahmyohlin).


SVD of row matrix using QR

Question: I want to reach to full SVD in faster way.
Since this involves hardware implementation, rather than designing things from scratch I want to use already available blocks:
a) QR decomposition
b) Matrix multiplication and basic  manipulations
Since QR do have role of householder there should an optimal way to reach it.
Answer: Hints: Let $A=QR$. Then $AA^T = RR^T$ and $A^TA=R^TR$. Now the singular vectors are given by eigenvectors of these matrices. Also singular values are given by eigenvalues of any of them (both will have same eigenvalues). There are really efficient methods to find eigenvalues from the cholesky decomposition of a matrix (since $AA^T=RR^T$ where $R$ is uppertriangular, you essentially have cholesky decomposition). Once you find the eigenvalues, it boils to solving linear system of equations. Say that you have a linear system of the form $CC^Tx=b$ for any given triangular matrix $C$ and vector $b$. Now you can solve the linear system $Cy=b$ first. Since $C$ is triangular, this can be done very fast by back-substitution. Then you can solve for the system $C^Tx=y$.
Comment: Solving equations will be a task itself in hardware.  Can having a block to do SVD of square matrix help?
Comment: @JayPrakash sorry didn't get you. You said you wanted to use QR decomposition to calculate SVD right?. Solving systems of equations with triangular matrices is very straightforward via back-substitution and is the standard approach. Please look up on that.
Comment: @JayPrakash feel free to reach out to me on my username.at.gmail if you need more clarity
Comment: https://math.stackexchange.com/questions/2271901/svd-of-row-matrix/2273002#2273002
This method worked for me for a vector.
Comment: SVD is a highly non-trivial concept compared to orthogonalization of a set of given vectors which is what is explained in the question you pointed.
Comment: yes but hardware design asks for loads of simplicity and I not being expert in RTL need to use available resources.

SVD of row matrix using QR


How to update only one field using Views?

Question: Is it possible to update only one field using Views? Say, you use Views to list all property items. Property content type has one field called 'Position' with option values as 'Featured', 'Hot', 'Sold', 'Vacant', etc.. For each item in a row listed you have what looks like the following:
Views Display:
<code>ID   Title     Type       Address       Total Size (sq Ft)     Position        Action
123  Bay View  Apartment  Moroco        1245                   (combobox)      Update
</code>
There are other fields for this content type that will not be included, hence, only those relevant fields are shown in this particular Views. So when you click 'Update' button the item will be updated accordingly, that is, only the 'Position' will be updated.
And maybe for other instances, a few fields - instead of one as above - can also be updated. The above is only an example with one field.
Any ideas?
Comment: try Editable Fields module, but I'm not sure you can allow only 1 field of the view to be editable offhand. The module page is at: https://www.drupal.org/project/editablefields
Answer: You might try the module Editable fields It is an old module that hasn't been updated in a long time, but I did get it working recently on a new project.
Another option is to build your own with rules, and rules links
With rules links you can set a path that sets a rule to activate. You can have that rule update the content with whatever setting you wish.


How can I post webform block values to another form?

Question: I have a capture form in a block on a panel, and I am trying to get it to post the values to another form, once it is submitted.
How can I achieve this?
First name, last name, and email get posted to example.com/page?fname=XXX&lname=YYY&email=ZZZ.
I am using Drupal 6, and the Webform module version 3.9.
Comment: What module handles what you call, "another form"?
Comment: Yes, i have a module that is rendering a join form ...
Comment: I mean which one: a custom module, a Drupal core module, or a module that can be downloaded from Drupal.org. In the last two cases, knowing exactly which module is could be relevant.
Comment: It is a custom module ... and here is an example of how i am building the form ... http://pastie.org/3490496
Answer: You should be able to use one of the webform hooks to pass $_GET values via redirect.
function YOURMODULE_webform_submission_insert($node, $submission) {
  if ($node->nid == XXX){
    // Grab the values we need and create our get url parameter string.
    $queryString = 'f1=' . $submission['value']['myfield'] . '&f2=' . $submission['value']['myfield2'] . '&f3=' . $submission['value']['myfield2'];
    drupal_goto('PATH/TO/FORM', $queryString);
  }
}

Or you can use a hook_form_alter for that form, add a new submit callback, and in the new function set the form's #redirect with the same syntax.
$queryString = $form_state['value']['myfield'] . '&f2=' . $form_state['value']['myfield2'] . '&f3=' . $form_state['value']['myfield2'];
$form['#redirect'] = array('PATH/TO/FORM', $queryString);

Then in your custom form, check for the $_GET values, and set them as the defaults to the appropriate fields, if they exist.
Answer: You could set the #value property of the relevant elements based on the $_GET values.
Comment: Right, but how to i get the webform to post those value to the url?
Comment: I shouldn't have talked about `$_GET`, but about `$_POST`, which is the variable used. It may not be usable though, given your sample code above. Maybe setting variables in `$_SESSION` would be a better way to go.


Can't recieve emails with Postfix/Dovecot telnet returns status0

Question: I try sending emails to my address and I can't find any record of them, even in the logs. I can send to myself on the server just fine.
When I try telneting onto my server I get the following answer

When I telnet onto port 587 it works as expected.
Within the logs I get
warning: unexpected end-of-input from smtp socket while reading input attribute name
smtp socket: wanted attribute: flags
warning: deliver_request_get: error receiving common attributes

This is my postconf -M
smtp       inet  n       -       n       -       -       smtp -v
submission inet  n       -       n       -       -       smtpd -v -o syslog_name=postfix/submission -o smtpd_tls_security_level=encrypt -o smtpd_tls_cert_file=/etc/let                                                  sencrypt/live/gamesleeve.io/fullchain.pem -o smtpd_sasl_auth_enable=yes -o smtpd_reject_unlisted_recipient=no -o smtpd_relay_restrictions=permit_sasl_authenticated,rej                                                  ect -o milter_macro_daemon_name=ORIGINATING
pickup     unix  n       -       y       60      1       pickup
cleanup    unix  n       -       y       -       0       cleanup
qmgr       unix  n       -       n       300     1       qmgr
tlsmgr     unix  -       -       y       1000?   1       tlsmgr
rewrite    unix  -       -       y       -       -       trivial-rewrite
bounce     unix  -       -       y       -       0       bounce
defer      unix  -       -       y       -       0       bounce
trace      unix  -       -       y       -       0       bounce
verify     unix  -       -       y       -       1       verify
flush      unix  n       -       y       1000?   0       flush
proxymap   unix  -       -       n       -       -       proxymap
proxywrite unix  -       -       n       -       1       proxymap
smtp       unix  -       -       y       -       -       smtp
relay      unix  -       -       y       -       -       smtp -o syslog_name=postfix/$service_name
showq      unix  n       -       y       -       -       showq
error      unix  -       -       y       -       -       error
retry      unix  -       -       y       -       -       error
discard    unix  -       -       y       -       -       discard
local      unix  -       n       n       -       -       local
virtual    unix  -       n       n       -       -       virtual
lmtp       unix  -       -       y       -       -       lmtp
anvil      unix  -       -       y       -       1       anvil
scache     unix  -       -       y       -       1       scache
maildrop   unix  -       n       n       -       -       pipe flags=DRhu user=vmail argv=/usr/bin/maildrop -d ${recipient}
uucp       unix  -       n       n       -       -       pipe flags=Fqhu user=uucp argv=uux -r -n -z -a$sender - $nexthop!rmail ($recipient)
ifmail     unix  -       n       n       -       -       pipe flags=F user=ftn argv=/usr/lib/ifmail/ifmail -r $nexthop ($recipient)
bsmtp      unix  -       n       n       -       -       pipe flags=Fq. user=bsmtp argv=/usr/lib/bsmtp/bsmtp -t$nexthop -f$sender $recipient
scalemail-backend unix - n       n       -       2       pipe flags=R user=scalemail argv=/usr/lib/scalemail/bin/scalemail-store ${nexthop} ${user} ${extension}
mailman    unix  -       n       n       -       -       pipe flags=FR user=list argv=/usr/lib/mailman/bin/postfix-to-mailman.py ${nexthop} ${user}

this is the postconf -n
alias_database = hash:/etc/aliases
alias_maps = hash:/etc/aliases
append_dot_mydomain = no
biff = no
broken_sasl_auth_clients = yes
compatibility_level = 2
home_mailbox = Maildir/
inet_interfaces = all
inet_protocols = ipv4
mailbox_size_limit = 0
mydestination = $myhostname,gamesleeve, gamesleeve.io,eiric.com, localhost.members,localhost
mydomain = gamesleeve.io
myhostname = mail.gamesleeve.io
mynetworks = 127.0.0.0/8 [::ffff:127.0.0.0]/104 [::1]/128
myorigin = gamesleeve.io
readme_directory = no
recipient_delimiter = +
relayhost =
smtp_sasl_auth_enable = yes
smtp_sasl_password_maps = hash:/etc/postfix/sasl/sasl_passwd
smtp_sasl_security_options =
smtp_tls_cert_file = /etc/letsencrypt/live/gamesleeve.io/fullchain.pem
smtp_tls_key_file = /etc/letsencrypt/live/gamesleeve.io/privkey.pem
smtp_tls_security_level = may
smtp_tls_session_cache_database = btree:${data_directory}/smtp_scache
smtp_use_tls = yes
smtpd_banner = $myhostname ESMTP $mail_name (Ubuntu)
smtpd_recipient_restrictions = permit_sasl_authenticated,permit_mynetworks,reject_unauth_destination
smtpd_relay_restrictions = permit_mynetworks reject_unauth_destination
smtpd_sasl_auth_enable = yes
smtpd_sasl_local_domain =
smtpd_sasl_path = private/auth
smtpd_sasl_security_options = noanonymous
smtpd_sasl_type = dovecot
smtpd_tls_CAfile = /etc/letsencrypt/live/gamesleeve.io/chain.pem
smtpd_tls_cert_file = /etc/letsencrypt/live/gamesleeve.io/fullchain.pem
smtpd_tls_ciphers = high
smtpd_tls_key_file = /etc/letsencrypt/live/gamesleeve.io/privkey.pem
smtpd_tls_loglevel = 1
smtpd_tls_received_header = yes
smtpd_tls_security_level = may
smtpd_tls_session_cache_database = btree:${data_directory}/smtpd_scache
smtpd_use_tls = yes
virtual_alias_domains = eiric.com
virtual_alias_maps = hash:/etc/postfix/virtual

I've doubled checked the MX records and it points to mail.gamesleeve.io with dig
Comment: If your MX record points to mail.gamesleeve.io you should telnet to that DNS name, not to gamesleeve.io. Also check your firewall rules and ``ss -lnt`` to verify the port is open.
Answer: You are not running an smtp server (smtpd). You probably introduced a typo in the first non-comment line of your master.cf file.
What it looks like in your case (only looking at the lines starting with smtp):
smtp       inet  n       -       n       -       -       smtp -v
smtp       unix  -       -       y       -       -       smtp

My defaults were - a smtp daemon is supposed to be started as the inet/smtp service:
smtp       inet  n       -       y       -       -       smtpd
smtp       unix  -       -       y       -       -       smtp

I suspect this happened when you added the non-default -v flag. Your smtpd_banner indicates you are running Ubuntu, there you should find a template in /etc/postfix/master.cf.proto that you can use to compare your edited settings to the distributors defaults.
Comment: OMG that fixed it. Thank you so much!


Javascript/jQuery: programmatically follow a link

Question: In Javascript code, I would like to programmatically cause the browser to follow a link that's on my page. Simple case:
something

function goToBar() {
   $('#foo').trigger('follow');
}

This is hypothetical as it doesn't actually work. And no, triggering click doesn't do it.
I am aware of window.location and window.open but these differ from native link-following in some ways that matter to me: a) in the presence of a <base /> element, and b) in the case of mailto URLs. The latter in particular is significant. In Firefox at least, calling window.location.href = "mailto:email@example.com" causes the window's unload handlers to fire, whereas simply clicking a mailto link does not, as far as I can tell.
I'm looking for a way to trigger the browser's default handling of links, from Javascript code.
Does such a mechanism exist? Toolkit-specific answers also welcome (especially for Gecko).
Comment: why not just use a target="_blank" attribute in your mailto: link?
Comment: I can, but that leaves a blank window open, whereas without that my mail client opens but my browser stays as is, which is what I want.
Comment: Your jsFiddle examples work for me with Firefox Aurora 14.0a2 (2012-06-04).
Answer: As far as I know, window.location does exactly what you are looking for, triggering the browser's default link clicking behavior.
Some browsers notice the protocol before any events are fired or the actual href is changed.
window.location = "mailto:firstname.lastname@example.com";

Trying the fiddle demo mentioned below I get the following results:

Chromium: fires onbeforeunload with the button and link
Firefox fires onbeforeunload only for the button
Safari: never fires onbeforeunload
Opera: same as Safari

So a good way to prevent the unload event from being fired is by returning false in beforeunload.
Comment: Fair enough, I tested this in multiple browsers now and it seems behavior is quite different. I'll update my answer to reflect this.
Comment: No, not quite the same. See http://jsfiddle.net/eyS6x/2/. "Click me" calls the `beforeunload` handler, the link itself doesn't.
Comment: Well, you may be on to something here. In my real code it's _only_ `beforeunload` and not `unload` that I have. I messed that up in my OP. Is there a way _inside_ my `beforeunload` handler that I can detect whether it's a mailto?
Comment: The OP is not asking how to mimic the link behavior, he is asking how to produce the exact same behavior as clicking the link. Even if it wasn't firing a `onbeforeunload` it would still be wrong because it wouldn't trigger the `click` event on the link.
Comment: No, actually the OP is specifically asking how "to trigger the browser's default handling of links". Which in my opinion doesn't mean the actual click of a link but mainly what happens after the click, such as following URLs or triggering associated events.
Comment: @Dan, you can't really query the location object since it only returns the current state, which is the current url. However, you could use a variable to store which link you just called. I extended your fiddle a little bit to show this. Of course for production code you wouldn't use a global variable but it shows the basic principle.
Answer: METHOD 1 click method
HTMLElements have a method click() https://developer.mozilla.org/en/DOM/element.click
function goToBar() {
   document.getElementById('foo').click();
}

Method 2 Firing synthetic events
I wonder why saluce deleted his answer. That solution is what I've used in the past (when click was an IE only thing). That is, firing a synthetic browser event (not a fake one like jQuery's click()). Let me post a solution using that idea...
DEMO: http://jsfiddle.net/eyS6x/3/
/**
 * Fire an event handler to the specified node. Event handlers can detect that the event was fired programatically
 * by testing for a 'synthetic=true' property on the event object
 * @param {HTMLNode} node The node to fire the event handler on.
 * @param {String} eventName The name of the event without the "on" (e.g., "focus")
 */
function fireEvent(node, eventName) {
  // Make sure we use the ownerDocument from the provided node to avoid cross-window problems
  var doc;
  if (node.ownerDocument) {
    doc = node.ownerDocument;
  } else if (node.nodeType == 9 /** DOCUMENT_NODE */){
    // the node may be the document itself
    doc = node;
  } else {
    throw new Error("Invalid node passed to fireEvent: " + +node.tagName + "#" + node.id);
  }

  if (node.fireEvent) {
    // IE-style
    var event = doc.createEventObject();
    event.synthetic = true; // allow detection of synthetic events
    node.fireEvent("on" + eventName, event);
  } else if (node.dispatchEvent) {
    // Gecko-style approach is much more difficult.
    var eventClass = "";

    // Different events have different event classes.
    // If this switch statement can't map an eventName to an eventClass,
    // the event firing is going to fail.
    switch (eventName) {
      case "click":
      case "mousedown":
      case "mouseup":
        eventClass = "MouseEvents";
        break;

      case "focus":
      case "change":
      case "blur":
      case "select":
        eventClass = "HTMLEvents";
        break;

      default:
        throw "JSUtil.fireEvent: Couldn't find an event class for event '" + eventName + "'.";
        break;
    }
    var event = doc.createEvent(eventClass);
    var bubbles = eventName == "change" ? false : true;
    event.initEvent(eventName, bubbles, true); // All events created as bubbling and cancelable.

    event.synthetic = true; // allow detection of synthetic events
    node.dispatchEvent(event);
  }
};

document.getElementById('button').onclick = function() {
   fireEvent( document.getElementById('link'), 'click');
}

Comment: It works on Chrome (19.0.1084.52 m), Firefox (10.0.3) and IE (8.0.7600) on Windows. It may be a Mac problem.
Comment: Indeed it doesn't. Try http://jsfiddle.net/eyS6x/1/ and click "Click Me". This is in Firefox 5.0 for MacOS.
Comment: That may be. I'll test a couple of more places.
Comment: @Dan Try out the new solution I posted, I don't have a mac to test it
Comment: Well, I have learned something new from  your post, so +1 for that, but unfortunately it doesn't work, at least in jsFiddle. Chrome throws the error "Refused to display document because display forbidden by X-Frame-Options." and Firefox 5 appears not to do anything at all.
Comment: @Dan, I had a friend try it. Doesn't work for FF/Chrome on the Mac, it does work for Safari on the Mac.


Regular expression for password validation without whitespaces C#

Question: Password must contains minimum of 8 symbols.
min 2 digits in any order,
min 1 special in any order character and
must not allow whitespaces.
I have something like this:
(?=.*\d.*\d)(?=.*[$/@:?{~!^`\[\]]{1,}).{8,}

UPD solution:
(?=[^\s]*\d){2}(?=[^\s]*[$/@:?{~!^`\[\]]){1,}[^\s]{8,}

Comment: exactly 2 digits or min 2 digits? and the same for the special character
Comment: Sorry,min 2 digits, updated
Comment: refer: http://stackoverflow.com/questions/19491670/regular-expression-for-password-at-least-2-digits-and-one-special-character-and
Comment: Possible duplicate of [Strong password regex](http://stackoverflow.com/questions/3131025/strong-password-regex)
Answer: I would change the . into \S, if your language supports negated classes
(?=\S*\d){2}(?=\S*[$/@:?{~!^`\[\]]){1,}\S{8,}

or into [^\s], if it does not
(?=[^\s]*\d){2}(?=[^\s]*[$/@:?{~!^`\[\]]){1,}[^\s]{8,}

Comment: @Chase Since `\S{8,}` will whatever check for whitespaces, no need to use `\S` in the lookaheads. The `^` and `$` anchors are also missing.
Answer: Here is another one:
^(?=(?:.*\d){2})(?=.*[$/@:?{~!^`\[\]])\S{8,}$

Debuggex Demo
Answer: ^(?!.*\s.*)(?=.*\d.*\d)(?=.*[$/@:?{~!^`\[\]]{1,}).{8,}$

Anchoring it to the start and end, with a negative lookahead for the whitespace
Answer: here is my suggestion:
^(?!\d+$)(?![$/@:?{~!^`\[\]]+$)[$/@:?{~!^`\[\]\d]{8,}$

NOTES: you need find another way to check at least 2 digits
Answer:  (?!.*?\s+.*?)

Just add this to your existing regex.A negative lookahead detecting one or multiple spaces.


How to configure mysql database connection with a different socket

Question: I have a Drupal 6 site that I ran for years before walking away about three years ago. I would like to resurrect the site in a more modern CMS and am first considering Drupal 8.
I run my site on a shared server where I have my own mysql socket. In Drupal 6, I connected to the database successfully in settings.php through the following syntax:
ini_set('mysqli.default_socket', '/path/to/my/mysql/socket');
ini_set('mysql.default_socket', '/path/to/my/mysql/socket');
$db_url = 'mysqli://dbuser:dbpass@localhost/dbname';

Looking at Drupal 8's settings.php it's a completely different syntax, and I am stumped on how to configure it correctly either there or on the Database configuration screen during install.php. Googling things like "drupal 8 mysql socket" brings up old articles that aren't relevant anymore.
PHP 7.0 is provided and I don't have write access to the ini, so I can't override the socket there.
I have confirmed that the database is running with this command:
mysqladmin --socket=/path/to/my/mysql/socket --user=dbuser -p status

Any help would be greatly appreciated on how to get the database setup in Drupal 8, thank you.
Edit: from Clive's suggestion I added the ini_set() lines above to Drupal 8's settings.php to no avail. I'm assuming it's user error at this point so I'm still trying things.
Comment: What happens if you just specify "localhost" as the hostname? On our setup this causes the Unix socket to be used. For true localhost TCP connection we need to specific 127.0.0.1.
Comment: I tried every variation of the advanced options. This was with the ini_sets in place so I'm not sure what was going on. But then I made a very simple test.php that did the ini_set and then a new PDO() passing it my socket string and that worked fine.
Answer: According to this Drupal issue, setting the socket in the UI is just not possible right now: (at least in 8.6.10)
https://www.drupal.org/project/drupal/issues/793200
I also could not figure out how to set the socket in sites/default/settings.php.
I had to resort to hardcoding my socket in this file:
core/lib/Drupal/Core/Database/Driver/mysql/Connection.php

This block of code:
    // The DSN should use either a socket or a host/port.
    if (isset($connection_options['unix_socket'])) {
      $dsn = 'mysql:unix_socket=' . $connection_options['unix_socket'];
    }
    else {
      // Default to TCP connection on port 3306.
      $dsn = 'mysql:host=' . $connection_options['host'] . ';port=' . (empty($connection_options['port']) ? 3306 : $connection_options['port']);
    }

I could not find any way to set "unix_socket" value on $connection_options, so I resorted to hardcoding it before this block like:
$connection_options['unix_socket'] = '/path/to/my/mysql/socket';


restapi lookup column sharepoint

Question: I am trying to fetch an additional lookup column. From List A I have a field which is looked up in list B, and I have added an additional column from list A.  How to fetch from the additional column using the REST API?
<code>/_api/web/lists/getbytitle('ListB')/items?$select=Title,ListA/ProjectName,ListA/OM&$expand=ListA
</code>
I am getting "invialid column OM".
Comment: Write a separate request for ListA /_api/web/lists/getbytitle('ListA')/items?$select=Title and ListB ListA /_api/web/lists/getbytitle('ListB')/items?$select=Title
Answer: Rest api $expand support below lookup additional fields only.

Single line of text
Date and Time
Number

For example:
Comment: What's the OM referenced from lista field type? belongs to above 3 field type?
Comment: also how to refer this lookup columns. I amm trying to display it in datatable tableContent += '' + objArray[i].DM_x002f_TL + ''; but it is returning undefined.

restapi lookup column sharepoint


Prove that a half-open line is uncountable - corrected

Question: I have to provide a proof that a halfopen line $L_a:={ ∈ ℝ:x > a}$ is uncountable.
I have used Schröder-Bernstein-Cantor and tried to show that an injection exists between $L_a$ and $ℝ$ an injection between $ℝ$ and $L_a$ to conclude that a bijective function exists between $ℝ$ and $L_a$ to prove that $L_a$ is uncountable.
I chose the following two functions:
$f:L_a \rightarrow ℝ:x \rightarrow x$ is injective
$g:ℝ \rightarrow L_a:x \rightarrow a+e^x$ is injective
It follows that a bijection exists between both sets, so $L_a$ is uncountable.
EDIT: corrected use of SBC, it should now work.
Thanks for your feedback.
Comment: You are using Schröder-Bernstein-Cantor Theorem wrongly.
Comment: Doesn't Schroder-Bernstein require injections in both directions.
Comment: @Cpc you're right. Thanks for pointing that out, I noted it wrong in my notes.
Comment: Yeah,  your two functions give the same inequality.  You don't need a bijection.  Just the other direction.
Comment: Do you know that an interval is uncountable?
Comment: As I am mostly working though the materials through self-study, this is why this platform is so useful. Thanks again for pointing out where I was mistaken.
Answer: The function $g$ doesn't make sense. For instance, $g(-1)\notin L_a$.
You can simply say that the function$$\begin{array}{ccc}\Bbb R&\longrightarrow&L_a\\x&\mapsto&a+e^x\end{array}$$is a bijection. Therefore, $L_a$ is uncountable.
Comment: Thanks! I wanted to solve this using Schröder-Bernstein-Cantor, but I think I have it corrected now.
Answer: Let $R_a:= \{x \in \mathbb R: x<a\}$ and define $f: L_a \to R_a$ by $f(x)=2a-x.$
Then $f$ is a bijection. Suppose that $L_a$ is countable, then $R_a$ is countable, hence
$$\mathbb R= L_a \cup R_a \cup \{a\}$$
is countable, a contradiction.
Answer: An interval is uncountable:
$$\tan:(-\pi/2,\pi/2)\to\Bbb R$$ is a bijection.
But any two (finite) open intervals are isomorphic (there's a bijection between them): $(c,d)\leftrightarrow(a,b)$ by $$x\to \dfrac{(d-x)}{(d-c)}a+\dfrac{(c-x)}{(c-d)}b$$.
Thus $L_a$ is uncountable, because it contains an interval.
Comment: Your bijection doesn't work when $b=\infty$
Comment: The only flaw in the reasoning here (and yes, I checked the previous edits) was the minor error at one point (since corrected) of saying the offered bijection between open intervals applied to all open intervals instead of just finite open intervals. But since the demonstration that one finite open interval was in bijection with $\Bbb R$ and thus uncountable, and the other bijection shows even small open intervals are likewise uncountable, it does follow that any set, including infinite invervals, that contains a finite open interval is also uncountable. I don't see a cause for downvoting.
Comment: @PaulSinclair thanks for weighing in


Considering getting in-ear monitors

Question: I am going to perform in a concert in a nearby club and I want to use in-ear monitors. But I don't have any idea which ones to buy or what other devices are required for using them.
Will I get all the components like a transmitter, amplifier, in-ears, etc., in one purchase or do I have to buy them separately?
Comment: Telling exactly what you want the monitors used for may get you better answers. However, recommendations for gear don't usually get allowed to stay on site for long.  If the question was more about how to use iem., it may be more acceptable.
Comment: You might want to add information on what kind of band you are in, what your role is in the band, what kind of music and such. In my experience, a band goes from beeing very loud on stage in several steps. The band gets most effect form in-ears when all band members use in-ear monitors, especially that guitar player that used to have a large amplifier cranked up to max volume.
Answer: As ghellquist commented, this depends so much on the musical setting that it's impossible to answer confidently without further information.
However I'm going to disagree with Todd Wilcox. Using in-ears is, more often than not, a good idea, and they don't need to be overly expensive – provided you're ok with being cable-bound. Cheap wireless systems will only give you lots of noise problems, incontrollable dynamic-range issues, drop-outs at the Sod spots... Cable-bound headphone amps are cheap and reliable though.
The in-ears themselves should be decent quality (positively don't use consumer in-ear headphones!), but that doesn't mean you need crazy top-notch 4-way systems that cost thousands. The lower-range models e.g. by Shure, albethey not super comfortable and not exactly nice-sounding, can still allow you to hear much better that with the typical floor monitoring system.
The mix is is important, but this is doable. Requirement is of course that you actually have an aux channel at your disposal; fortunately, these days digital consoles with plenty of them start to become the universal norm. The general guideline with monitoring in general and also with in-ear is: as little as possible. When I set up a new mix for my in-ears, I start out with only my own signal and the most important signals I need for orientation (playing bass/cello, this is generally keyboards, rhythm guitar and a bit of kick drum). I set up the volume of these so I can still hear everything else about ok through the direct sound from the other musicians' instruments / floor monitors. Only when the crucial elements are fine, I consider whether I need a bit extra of some of the other instruments.
The most important thing you actually need to get used to is how in-ears change the way your own voice sounds. That's a main factor why more expensive models, and custom molds, are desirable. If you only sing harmonies then this isn't so much of an issue (in fact, the strong amplification of the inner voice can be useful), but for lead vocals this can be quite weird at least at first.
Answer: You do not want to buy in-ears just for a show soon before the show. In-ears take time to learn to use and require a high-quality monitor mix, which is usually not available at smaller venues. Also, in-ears are very expensive.
A better solution is to use the club's existing monitor system. If you are concerned about it being too loud (which is also a common problem with in-ears!), a good solution is a pair (or two pairs - just in case) of high quality, musician's earplugs, like Etymotic's ER-20XS. They are a lot cheaper than in-ears, you can work with any existing monitor system or practice situation, and they make playing loud gigs much more comfortable.
Comment: There's a big difference between using iems as monitors and using them as defenders. Whilst I certainly agree that they make loud gigs bearable, they certainly won't help monitoring anything.
Comment: @Tim I don't know what a defender is and I don't understand how your comment is related to my answer. My answer is saying to **not** use IEMs at all. Not as monitors, and not as anything else.
Comment: Only just picked up your reply. Defenders, as the name alludes, are worn to eliminate some of the volume that otherwise would be received via ears unprotected on stage. Iems to an extent do this job by blocking some of the on-stage noise due to being in the ears.
Comment: @Tim Oh. In the colonies we call them "earplugs". I wasn't suggesting using IEMs as defenders/earplugs. I was suggesting using defenders/earplugs **instead** of IEMs.

Considering getting in-ear monitors


Spring MVC - JS file interns needs to load backgroundImage using CSS

Question: I am using Spring-MVC structure for my project.Where in I have set up the static resource handling and I am able to access the css, js & images in my JSP pages very well.
Now, I am adding 1 js file(linked as external to the JSP) which interns setting one background image for the dynamically created items. The problem is - as it's trying to set backgroundImage as below(It is working fine in the local browser), but it's not allowed on the server(being a static resource).
( function( $ ){

$.fn.speedometer = function( options ){

    var $this = $( this );

    if ( $this.length > 1 ) {
        $this.each( function(){
            $( this ).speedometer( options );

        });
        return $this;
    }

    var def = {
        /* If not specified, look in selector's innerHTML before defaulting to zero. */
        percentage : $.trim( $this.html() ) || 0,
        scale: 100,
        limit: true,
        minimum: 0,
        maximum: 100,
        suffix: ' %',
        animate:true,
        thisCss: {
            position: 'relative', /* Very important to align needle with gague. */
            width: '210px',
            height: '180px',
            padding: '0px',
            border: '0px',
            fontFamily: 'Arial',
            fontWeight: '900',
            backgroundImage : "url('./background.jpg')"

    ---------------
    ---------------

So, similar to JSP (using taglib)- I am trying to set backgroundImage as below :
    backgroundImage : "url(<spring:url value='/images/background.jpg'/>)"

That is not working for me. I am stuck here, tried multiple ways but nothing worked for me. 1 of them is : Setting the BackgroundImage using css class. which also I tried by creating a class as:
    .myClass{
     background-image: url(<spring:url value='/images/background.jpg'/>);
     }

But making a function call to apply this is getting a big challange for me. Here is the complete js code :
( function( $ ){

    $.fn.speedometer = function( options ){

        /* A tad bit speedier, plus avoids possible confusion with other $(this) references. */
        var $this = $( this );

        /* handle multiple selectors */
        if ( $this.length > 1 ) {
            $this.each( function(){
                $( this ).speedometer( options );

            });
            return $this;
        }

        var def = {
            /* If not specified, look in selector's innerHTML before defaulting to zero. */
            percentage : $.trim( $this.html() ) || 0,
            scale: 100,
            limit: true,
            minimum: 0,
            maximum: 100,
            suffix: ' %',
            animate:true,
            thisCss: {
                position: 'relative', /* Very important to align needle with gague. */
                width: '210px',
                height: '180px',
                padding: '0px',
                border: '0px',
                fontFamily: 'Arial',
                fontWeight: '900',
                backgroundImage : "url('./background.jpg')"

            },
            digitalCss: {
                backgroundColor:'black',
                borderColor:'#555555 #999999 #999999 #555555',
                borderStyle:'solid',
                borderWidth:'2px',
                color:'white',
                fontSize:'14px',
                height:'20px',
                left:'72px',
                padding:'0px',
                position:'absolute',
                textAlign:'center',
                top:'65px',
                width:'60px',
                zIndex:'10',
                lineHeight:'20px',
                overflow:'hidden'
            }
        }

        $this.html( '' );

        $this.css( def.thisCss );

        $.extend( def, options );

        /* out of range */
        if ( def.limit && ( def.percentage > def.maximum || def.percentage < def.minimum ) ) {
            /* the glass cracks */
            $this.css( 'backgroundImage' , 'url("./background-broken.jpg")' );
        } else {

            /* call modified jqcanvas file to generate needle line */
            $this.jqcanvas ( function ( canvas, width, height ) {

                var ctx = canvas.getContext ( "2d" ),
                lingrad, thisWidth;

                ctx.lineWidth = 2;
                ctx.strokeStyle = "rgb(255,0,0)";

                /* point of origin for drawing AND canvas rotation (lines up with middle of the black circle on the image) */
                ctx.translate( 105,105 );

                ctx.save(); //remember linewidth, strokestyle, and translate

                function animate(){

                    ctx.restore(); //reset ctx.rotate to properly draw clearRect
                    ctx.save(); //remember this default state again

                    ctx.clearRect( -105, -105, 300, 300 ); //erase the canvas

                    /* rotate based on percentage. */
                    ctx.rotate( i * Math.PI / def.scale );

                    /* draw the needle */
                    ctx.beginPath();
                    ctx.moveTo( -80,0 );
                    ctx.lineTo( 10,0 );
                    ctx.stroke();

                    /* internally remember current needle value */
                    $this.data('currentPercentage',i);

                    if ( i != def.percentage ) {

                        //properly handle fractions
                        i += Math.abs( def.percentage - i ) < 1 ? def.percentage - i : def.increment;

                        setTimeout(function(){
                            animate()
                        },20);
                    }
                }

                /* Are we animating or just displaying the percentage? */
                if (def.animate) {
                    var i = parseInt( $this.data('currentPercentage') ) || 0;
                    def.increment = ( i < def.percentage ) ? 1 : -1;
                } else {
                    var i = ( def.percentage );
                }

                animate();

            }, { verifySize: false, customClassName: '' } );

        }

        /* digital percentage displayed in middle of image */

        var digitalGauge = $( '

' );
        $this.append( digitalGauge );
        digitalGauge.css( def.digitalCss );
        digitalGauge.text( def.percentage + def.suffix );

        return $this;

    }

})( jQuery )

Any suggestions for better way of doing it, would be highly appreciated.
Answer: I got to fix this!
The JS code, which interns setting the background Images was breaking somewhere. So, I have made it loading the Background image using the CSS class.


Set up a Postfix server on Ubuntu for use with Apple Mail (or any mail client)

Question: I set up a Postfix server on my Ubuntu VPS and it works for sending email from the mail utility in the command line. I set up SPF records, DKIM, pretty much everything I could read about. However, I'd like to be able to send and receive email without SSHing into my box each time.
When I try to set up my server (borogov.es) with my mail client, and I use "mail.borogov.es" as my outgoing mail server, I get "Server not responding." I feel like this is an access issue of some sort, but I'm not sure.
I'm not running a firewall. What could be going on?
Answer: See what netstat -tlnp returns; if Postfix is listening to 127.0.0.1:25, then it's bound to loopback interface instead of a network card interface.
In that case your Postfix /etc/postfix/main.cf does not have inet_interfaces = all line.
The other option is that your ISP does not allow private SMTP servers.
Comment: It is listening on `all`, and DigitalOcean does allow SMTP servers.
Answer: You should not be attempting to send mail from your email client on port 25; rather using 587 (the standard submission port). Port 25 is meant for transfer between mail servers, and many home ISPs block it to reduce spam from compromised home computers.
Your Postfix server isn't listening on port 587:
$ telnet mail.borogov.es 587
Trying 188.8.131.52...
telnet: connect to address 188.8.131.52: Connection refused

This means you probably forgot to set up a submission section in Postfix's master.cf configuration file. It should look something like:
submission inet n       -       n       -       -       smtpd
  -o smtpd_tls_security_level=encrypt
  -o smtpd_sasl_auth_enable=yes
  -o smtpd_client_restrictions=permit_sasl_authenticated,reject

Comment: I just paste that into my master.cf?
Comment: So I get this: http://i.imgur.com/suBgWrt.png
Comment: After restarting Postfix, that is.


$ \int_{-\infty}^\infty f(x)e^{-2\pi i\xi x}dx=0$ for all $\xi\in\mathbb R$ with $|\xi|>M $

Question:
Suppose that $f(z)$ is an entire function on $\mathbb C $, and that there exist constants $M>0$ and $A>0$ such that
  $$ |f(x+iy)|\le\frac{A}{1+x^2}e^{2\pi M|y|}\quad \text{for all}\ x,y\in\mathbb R. $$ Prove that
  $$ \int_{-\infty}^\infty f(x)e^{-2\pi i\xi x}dx=0\quad\text{for all}\ \xi\in\mathbb R\ \text{with}\ |\xi|>M .$$

My attempt:
I have tried to apply the residue theorem. Let $\Gamma$ denote the semi-circle centered at $0$ with radius $R$ lying in the upper half plane. Then
\begin{align}
\int_{\Gamma+[-R,R]}f(z)e^{-2\pi i\xi z}dz&=\int_{-R}^R f(x)e^{-2\pi i\xi x} dx + \int_{\Gamma}f(z)e^{-2\pi i\xi z}dz\\
&=0
\end{align}
since $f(z)e^{-2\pi i\xi z}$ is analytic in $\mathbb C$. We have
$$ \int_{-\infty}^\infty f(x)e^{-2\pi i\xi x}dx=-\lim_{R\to\infty}\int_{\Gamma}f(z)e^{-2\pi i\xi z}dz .$$
However, I failed to show that the right-hand side is zero.
Answer: I suggest using the upper rectangular contour $C(R)$ with vertices at $\pm R$ and $\pm R + Ri$ for $\xi < -M$, and a lower rectangular contour for $\xi > M$. Assume $\xi < -M$. The contour integral $\oint_{C(R)} f(z)e^{-2\pi i \xi z}\, dz$ is zero by Cauchy's theorem, since $f$ is entire. The integrals of $f(z)e^{-2\pi i\xi z}$ along the vertical edges of $C(R)$ are $O(1/R)$ and the integral along the top edge is $O(e^{2\pi(M+\xi)R})$ as $R\to \infty$. Indeed, along the vertical edges, the integral is dominated by $\phi(R) := \frac{A}{1 + R^2} \int_0^R e^{2\pi(M+\xi)y}\, dy$; since $e^{2\pi(M+\xi)y} \le 1$ for $y \ge 0$, $\phi(R) = O(1/R)$. The integral along the upper edge is dominated by $$\int_{-R}^R \frac{A}{1 + x^2} e^{2\pi(M+\xi)R}\, dx = O(e^{2\pi(M + \xi)R})$$ Thus, the integrals along the verticals and top edge are $O(1/R)$ and $O(e^{2\pi(M + \xi)R})$, respectively, as claimed.
Now, in the limit as $R \to \infty$, the result is obtained for $\xi < -M$. A similar argument for the case $\xi > M$ holds using the corresponding lower rectangular contour.
Comment: If you have a bound condition on the integrand that depends on the real or imaginary parts of $z$, typically a rectangular contour works better. On the other hand, if the bound condition depends on $\lvert z\rvert$, a circular contour typically works better.
Comment: Nice! Do you know why sometimes rectangular contour works better than the circle?
Answer: Using a rectangular contour gives you better control.  So with a rectangular contour, vertices $\pm R,\pm R+ib$.  We have
\begin{align*}
I&=\int_{-R}^R f(x)\exp(-2\pi i\xi x)\,\mathrm{d}x\\
I_1&=\int_0^b f(R+iy)\exp(-2\pi i\xi (R+iy))i\,\mathrm{d}y\\
I_2&=\int_R^{-R} f(x+ib)\exp(-2\pi i\xi (x+ib))\,\mathrm{d}x\\
I_3&=\int_b^0 f(-R+iy)\exp(-2\pi i\xi (-R+iy))i\,\mathrm{d}y
\end{align*}
and $I=-I_1-I_2-I_3$, so it suffices to show each $I_1,I_2,I_3$ vanish in the limit.
We can easily estimate $I_1, I_3$:
\begin{align*}
\lvert I_1\rvert&\leq\int_0^{\lvert b\rvert} \lvert f(R+i\operatorname{sgn}(b)y)\exp(2\pi\xi (\operatorname{sgn}(b)y-iR))\rvert\,\mathrm{d}y\\
&\leq\int_0^{\lvert b\rvert} \frac{A}{1+R^2}\exp(2\pi M y)\exp(2\pi\xi \operatorname{sgn}(b) y)\,\mathrm{d}y\to 0\\
\lvert I_3\rvert&\leq\int_0^{\lvert b\rvert} \lvert f(-R+i\operatorname{sgn}(b)y)\exp(2\pi\xi (\operatorname{sgn}(b)y+iR))\rvert\,\mathrm{d}y\\
&\leq\int_0^{\lvert b\rvert} \frac{A}{1+R^2}\exp(2\pi M y)\exp(2\pi\xi \operatorname{sgn}(b)y)\,\mathrm{d}y\to 0
\end{align*}
as $R\to\infty$, for every $b$.
Finally, for $I_2$, we have
\begin{align*}
\lvert I_2\rvert&\leq\int_{-R}^R \lvert f(x+ib)\exp(-2\pi i\xi (x+ib))\rvert\,\mathrm{d}x\\
&\leq\int_{-R}^R \frac{A}{1+x^2}\exp(2\pi (\operatorname{sgn}(b)M+\xi)b)\,\mathrm{d}x\\
&\leq\pi A\exp(2\pi (\operatorname{sgn}(b)M+\xi)b)
\end{align*}
Thus $\lvert I\rvert\leq \pi A\exp(2\pi (\operatorname{sgn}(b)M+\xi)b)$, and so taking limit $b\to\pm\infty$ (opposite sign to $\xi$), we have $I=0$ for $\lvert\xi\rvert>M$.


Giving angular material $mdDialog a url in angular ui-router state

Question: I want to show an Angular Material Dialog on a particular url while keeping the previous visited route as a background state.
Hence the workflow will be:

User visits a page with url business/6/contacts. (state: business.contacts)
User visits a url business/6/checkout. (state: business.checkout)

It should keep the contacts page in the background and load the checkout modal on top of it with the given url.
However for another workflow where user visits url business/6/settings, it should keep the settings page as background and load the checkout modal if user visits business/6/checkout.
Also clicking outside anywhere should dismiss the modal and load back previous page.
Answer: You should make these modal states as the child states of contacts and settings pages. In this sceneario your url will be business/6/contacts/checkout and business/6/settings/checkout respectively. You have to have some identifier in your url to seperate these two cases. Otherwise when you enter the page directly from url you can not distinguish these two cases if you use the same url.
Here is an example:
var checkoutStateObject = {
        url: '/checkout'..,
        controller:"CheckoutModalCtrl" // same controller for below state
      };

yourApp.state("business", {
        url: "/business/:businessId"...}) //parent state
.state('business.contacts', {
        url: '/contacts'..
      })
.state('business.settings', {
        url: '/settings'..
      })
.state('business.contacts.checkout', checkoutStateObject)
.state('business.settings.checkout', checkoutStateObject)

Comment: or you can use onEnter instead of controller. ('statename', { url: '..', templateUrl: '...', onEnter: [ '$mdDialog', function($mdDialog){ $mdDialog.alert({  your code here  }) } ]  }
Comment: @PiyushChauhan you can set state object into a variable and for each state you can use the same object. I edited the answer using a similar approach. If you insist on using `business.checkout` way, you can check url params in business state and open your modal according to it. But then in this case you have to add this url params to each different state you can show this dialog.
Comment: I thikn using a controller would help reduce the duplication of the code, you can reuse the same controller in different states etc.
Comment: I like this but is there any way we can achieve this on `business.checkout` state otherwise if there are other states like `business.inventory` , `business.canvas` or many other I have to keep track for every single one of them. @cubbuk
Comment: for `onEnter` we have to duplicate too, otherwise it doesn't persist the previous state in background. @neftedollar


Existence of a binary symmetric matrix from row sums

Question: Give a sequence of column/row sums, is it possible to determine (other than by brute force) whether there exists a binary, symmetric matrix with the same column/row sums?
I did find the following article,

Ben Johnsen, Eldar Straume, Counting binary matrices with given row and column sums, Mathematics of Computation, Volume 48, Number 178, April 1987.

but my math skills aren't good enough to extract what I'm looking for or really determine 100% that this is what I'm talking about.
Comment: I take it that by "binary" you mean the entries are all zeros and ones. If you drop the word, "symmetric", there is a thorough discussion in Chapter 6 of Ryser, Combinatorial Mathematics, which is Number 14 in the Carus Mathematical Monographs series published by the Mathematical Association of America. The books in that series are expository in nature. Maybe you can adapt the methods in that chapter to the special case of symmetric matrices.
Comment: Thanks for the references, I did mean 1/0s.  I guess an equivalent problem would be finding whether a undirected graph exists given vertex degrees
Comment: It's equivalent if you allow your graphs to have loops, that is, edges joining a vertex to itself.
Comment: I think it has certain relations with LONESUM matrices.
Comment: LONESUM MATRICES are the matrices avoiding the $2 \times 2$ submatrix of the types [[1,0],[0,1]] or [[0,1],[1,0]].
Comment: See also http://arxiv.org/abs/1107.1299 authored by Ju & Seo.
Answer: From https://en.wikipedia.org/wiki/Degree_%28graph_theory%29

Hakimi (1962) proved that $(d_1, d_2, ..., d_n)$ is a degree sequence of a
  simple graph if and only if $(d_2 − 1, d_3 − 1, ..., d_{d_1+1} − 1, d_{d_1+2},
> d_{d_1+3}, ..., d_n)$ is. This fact leads to a simple algorithm for finding
  a simple graph that has a given realizable degree sequence:
1) Begin with a graph with no edges.
    2) Maintain a list of vertices whose degree requirement has not yet been met in non-increasing order of residual degree requirement.
    3) Connect the first vertex to the next d1 vertices in this list, and then remove it from the list. Re-sort the list and repeat until all
  degree requirements are met.
Comment: What is dd1+1-1? Is that $d_{d_1+1}-1$?


Como recuperar apenas 1 valor da URL com CodeIgniter?

Question: Estou passando dois parâmetros
http://localhost/topsamp-ci/votar/4-slug-de-algo
 public function votar($id) {
    echo $id;
    die;
 }

E ele me retorna 4-slug-de-algo. Eu queria apenas recuperar o ID mas exibindo na url os dois parametros, como eu faço isso?
Minha rota está assim:
$route['votar/(:any)'] = 'Home/votar/$1';

Botão de votar
<a href="<?= base_url("votar/{$row->id}-{$row->slug}"); ?>" class="btn btn-vote">VOTAR

Answer: A delimitação do parâmetro é a barra /
Precisa montar o link assim:
<a href="<?= base_url("votar/{$row->id}/{$row->slug}"); ?>" class="btn btn-vote">VOTAR

Troque o traço - pela barra /
Fica assim:  http://localhost/topsamp-ci/votar/4/slug-de-algo
Se quiser manter do outro jeito, irá receber tudo junto mesmo, ai tem fatiar a string.
Comment: Funcionou cara, vou deixar assim mesmo por segurança obrigado!
Comment: Eu já ia fazer isso, porém estava dando erro tinha que esperar 7 minutos haha, vlw!


How do I get the username of the logged-in user?

Question: I am working on a site where on a page I am querying some data related to my project.
Here I have many clients and I have given all of them access to project search page. On search page I run a query according to the fields selected by the user and display the result as a table on the page itself. But my query is as such that it is not user dependent.
I just want to ensure that each user has a specific set of output for itself (i.e not all the table would be displayed to all users).
How do I get the username or user ID of the logged-in user?
Comment: You have access to the current user with the global variable `global $user`. So you can have `$userlogin = $user->login;`, `$userID = $user->uid;`, etc ...
Answer: You can use the global $user object:

An object representing the user currently visiting the site.
Contains preferences and other account information for logged-in users. When a user is not logged-in, the $user->uid property is set to 0.

e.g.
global $user;
$name = $user->name;
$id = $user->uid;

// or
$name = $GLOBALS['user']->name;
$id = $GLOBALS['user']->uid;

Comment: Where should I write this piece of code in my website.
Comment: Wherever you need to use it....
Answer: You can use:
   global $user;
   if (!empty($user->uid))
   {$id = $user->uid;} //$id will only have a value if user is logged in

Comment: _When a user is not logged-in, the $user->uid property is set to 0._ ...if you're looking to test whether or not the user is actually logged in `user_is_logged_in()` and `user_is_anonymous()` would probably be more appropriate
Comment: 0 will return empty() to be TRUE so $id will not be set!
Comment: Yeah sorry, hadn't finished writing that comment when I submitted it :)


finiteness of k-th moment implies finiteness of lower moments

Question: Random variables $X$ and $Y$ have joint distribution $F(x,y)$, with $E[X]=\mu_X$.
(*) Prove that if $E[X^4] < \infty$ then $E[(X-\mu_X)^4]<\infty$

It seems obvious but I'm not convinced. Expanding the polynomial we get
$E[(X-\mu_X)^4] = E[(X^4-\mu_X X^3 +\mu_X^2 X^2 - \mu_X^3X +  \mu_X^4]$
Now we just need to prove that $E[X^3] < \infty$ and $E[X^2] < \infty$

In a measure-theoretic probability book i found the following theorem:
if k>0 and $E[X^k]<\infty $ then $E[X^j]<\infty $ for all $0<j<k$
Proof of the theorem is:
(**) $\rVert X \lVert_j \leq\rVert X \lVert_k$  for $0<j<k$

I have two questions:

Is there an easier way to prove (*)? (without doing the expansion perhaps?)
In the proof for (**) is $\rVert X \lVert_j = \rvert \int_{x \in A} \lvert x \lvert^j dx \vert^{1/j} $ where A is all the possible values that random variable X can take? If it's not, then what is it? And if it is, then how does that prove the finiteness of lower order moments?
Comment: To prove $(\ast)$, use $$(X-\mu)^4\leqslant2^3\cdot(X^4+\mu^4)$$To prove $(\ast\ast)$, use, for every $j<k$,  $$|x|^j\leqslant1+|x|^k$$
Answer: 1) I would use the inequality
$$|a-b|^4\leq (|a|+|b|)^4\leq 2^3(|a|^4+|b|^4)$$
which follows from the triangle inequality and from applying twice $(x+y)^2\leq 2(x^2+y^2)$. Now the claim follows applying 2).
2) Set
$$\|X\|_j=\left(\int |x|^j d\mathbb{P}_X(x)\right)^{\frac1j}.$$
where $\mathbb{P}_X$ is the law of the random variable. Then the inequality $\|X\|_j\le\|X\|_k$ for $j\leq k$ follows from Hölder's inequality $$\|fg\|_{1}\leq\|f\|_p\|g\|_q$$
for $\frac1p+\frac1q=1$, applied with $f=|x|^j$, $g=1$, $p=\frac kj$ (and the value of $q$ follows).