Do the different levels of treatment in a completely randomized design come from different population?

Question: Suppose in a completely randomized design , a treatment A have four levels. When we check whether the means of four levels are statistically significant ,i.e.,
$$H_0:\mu_1=\mu_2=\mu_3=\mu_4$$
$$\text{Vs}$$
$$H_1:\mu_i\ne \mu_j;\forall i\ne j; i=1,\ldots,4;j=1,\ldots,4;$$
are those levels from four different populations as their means are different ? Or they have come from same population ?
I suppose they are from different population as we write,$$y_i\sim NID(\mu_i,\sigma^2)$$
So does it imply :

$2$ different sample coming from $2$ different population can be either statistically significant or not; and
$2$ different population  coming from same  population should be statistically insignificant.
Answer: If you assign people randomly to treatments, then the people come from the same population and there is no test needed or possible of whether they came from the same population: They did.
If you then compare these groups on 100 measures, approximately 5 of those will show significant differences.
That's what a p value means - if you fling poop at a wall, what percentage do you want to stick?
This is one reason that you might still want to include covariates in a randomized experiment: Groups can vary, even if they are randomized.
Comment: In Randomization (one of the three principles of design), don't we assume treatment should be randomly allocated to experimental units ,ie , we assign treatments randomly to people.
Comment: How should i know , when i need to assign people randomly ? And when to assign treatments randomly ? If i assign people randomly, it implies the people come from the same population.Why?and when should be it from different population ?
Comment: Because that's what random assignment means. It's pretty much always better to have a randomized design, but it is often impossible to do so.
Comment: If we take homogeneous experimental units,then why do we need to concern about whether we randomly allocate experimental unit or randomly allocate treatment?
Comment: Would you please give me reference so that i can clear about random assignment . I am not understanding the first line of your answer.
Comment: If i am able to assign people randomly to treatments, then i don't need any test. Then what would be the result of my experiment? And if it is not always possible to do a randomized design, then what is the benefit of it and what is the alternative ?
Comment: You need to read a book on experimental design; any book on the subject will cover all this. I don't have any particular one that I like best.
Comment: I agree with the OP that the first line of this answer is puzzling.  Whether or not the groups come from the same population, what bearing does that have on whether one can apply a statistical test?  The second line is difficult to fathom, too: what is a "measure"? Apparently these 100 "measures" are assumed to be independent in order for you to draw the conclusion about only five showing significant differences: how is that possible when you are using the same set of "these groups" in all 100 tests?  And I will try to forget I ever read the third line... .
Comment: Oh, I see the confusion; I meant a test of whether they come from the same population.  I will edit my answer.


How to test express api on Travis

Question: As mention in a previous post, the following lines only works on local machine for testing.
node app.js
karma start karma.conf.js --single-run

If I put it into the .travis.yml, it make Travis hanging on the "node app.js" line and fail the test after timeout. I think this is because node is supposed to start the app.js and keep listening. On the local machine, I can open 2 terminal windows and run them separately but I am not sure how to do it on Travis. Can anyone help?
Answer: node app.js & will make Travis run app.js in the background (this should also work locally). The "&" bit is a standard piece of shell syntax to make a process run in the background.
Comment: Thanks for helping out!

How to test express api on Travis


Why is this counter-example valid?

Question: I don't understand why the counter example of the following argument is valid:

$\forall x\exists y(Ax\iff By)$
$\exists xBx \land \exists x\sim Bx  $
$\forall x(Ax \to \sim Cx) $
Therefore: $\sim \forall x Cx$
Let there be two objects in the universe, 0, and 1.
A: $\{ \}$
B: $\{0\}$
C: $\{0,1\}$
The first premise is true because everything is such that something is such that 'A' is true of the first if and only if 'B' is true of the second. In fact, 'A' is true of nothing at all. And no matter what there is, there is something that 'B' is not true of, namely 1. So there is always something that makes the biconditional true. The second premise is clearly true since 'B' is true of something, namely 0, and 'B' is also false of something, namely 1. The third premise is true because 'A' is true of nothing, so that every instance is a conditional with a false antecedent. The conclusion is false because 'C' is indeed true of everything.

What I don't understand is how premise 1 is true. Left to right of the IFF is true because A is true of nothing: vacuous truth. But right to left doesn't look true to me: $\forall x\exists y(By\to Ax)$ Clearly there is something B is true of (i.e. 0), so the antecedent is true. But the consequent is false - so how is this IFF true?
Also, the explanation mentioned that 'no matter what there is, there is something that 'B' is not true of, namely 1'; I don't get the relevance of this either. The concerned proposition is about something which is true of B, not something which is not true of B. Also $\exists x By$ and $\exists x \sim By$ can both be true!
Thank you so much!
Comment: You know that in a given finite universe, the quantifiers can be converted into $\land$ and $\lor$ expressions, and everything is just a propositional logic expression?
Comment: Yes but I am not sure how that fits in here...?
Answer: $P\Leftrightarrow Q$ if $P$ and $Q$ are both false.
$\forall x \sim \!\!Ax $. So to make the "iff" in the first premiss true, it is enough to find $y$ where $By$ is false. And $y=1$ will serve, because $y\notin B$.
To prove $\exists y\;By\rightarrow Ax$, it is enough to find a $y$ where either $By$ is false or $Ax$ is true. It doesn't matter if there is also a different $y$ where $By$ is true.
Comment: Indeed I wasn't thinking of what you say, but what you say is true. $By\rightarrow Ax$, $\sim Ax\rightarrow \sim By$ and $Ax \vee \sim By$ are equivalent.
Comment: You beat me to it.
Comment: I don't think this is quite you were talking about; but the way you put it reminds me of contraposition. Since $\forall x\exists y(By \to Ax) \iff \forall x\exists y(\sim Ax \to \sim By)$, so when By is false and Ax is true, that would prove the conditional, which I suppose is kinda the same as you mean...?
Answer: I will assume that $Ax$ means $x \in A$ just to make it easier to interpret. Similarly for $B$ and $C$. Now what you want to prove is: For all $x$ there is a $y$ such that $x \in A$ iff. $y \in B$.
First case: Let $x=0$ and $y=1$ then $0 \in A$ is false and $1\in B$ is false and therefore $0\in A \Leftrightarrow 1 \in B$ is true.
Second case: Let $x=1$ and $y=1$ then $1 \in A$ is false and $1\in B$ is false and therefore $1\in A \Leftrightarrow 1 \in B$ is true.
Overall $\forall x \exists y Ax\Leftrightarrow By $ is true.

Why is this counter-example valid?


What is the difference in playing a mode in key vs in sequence?

Question: So I got more serious about guitar recently and I learned the major scale and all of the modes.
My question is, what is the difference, assuming you're in the key of G major, in playing A Dorian, and playing G Dorian?
As best I can remember both sounded good but a bit different.  What's happening here?
Comment: "G Dorian" ... did you mean G Ionian perhaps?
Comment: I assume you mean G Ionian. No difference as this is the same set of notes. If you literally play A Dorian scale in the key of G then you are still effectively use Ionian mode but play the sequence starting from the second degree of the scale
Answer: The factors which determine keys and modes are not only the notes involved, but targeting the root, or tonic. In your example, G major (parent) and A Dorian both contain G A B C D E and F♯. Playing in G means G notes will feel like 'home', often heralded by the appearance of the dominant D chord. Whereas playing in A Dorian has the tendency to use A and A minor as the 'home' places.
G Dorian, though? Its parent key is F major, with F G A B♭ C and D. So it's slightly different, in that F/F♯ and B/B♭ are changed over.
Don't get confused with labelling: G Dorian is not the same as the Dorian of G, a simple mistake we can make.
I used to sometimes play an accompaniment in A major, often using 7ths, while a student used the notes from G major - a similar sort of thing that you're finding. Although at the end of the day, as I very often say, any note, in any key, can be made to fit anywhere.
Comment: @rcd To be clear: I could say "this song contains this set of notes; what key or mode is it in," and you can't know the answer with only that information.


Ajax call module function

Question: I need to make asynchronous page requests on every page load using AJAX, the idea being that a function in my module is called even when pages are cached.
The only documentation I've been able to find (Drupal 7) is for form handling using AJAX and handling links.
How do I call a module function from a custom AJAX request? Would I just implement hook_menu() and write a custom ajax request or is there a better way of doing this in Drupal 7?
Answer: I guess the answer depends on what that ajax call does, and if it is for a 'one site use' or for a contribution module.
If it s for a contribution module hook_menu might be the only way to go.
Though if it s just for a 'one site use' i would just add a JS snippet in your page.tpl.php or even html.tpl.php that launches the Ajax query. This would work on every page even when if cached.
EDIT
Actually you could also use the page preprocess function and add a js file to all your pages.
Comment: Yes that is the plan, although I'll still be doing it in the module... what I'm wondering is if I should write the request manually (i.e. $.get()) or can use Drupal API for this
Comment: Well if you know how to write the Jquery yourself i would definitely do that, you ll gain a little performance and avoid a couple of headaches.
Comment: I am trying to do something similar, but couldnt get hook_menu get working with ajax. as explained here http://drupal.stackexchange.com/questions/11330/ajax-reload-of-block-on-an-event. any idea on this?

Ajax call module function


Page template suggestion per language?

Question: How can I add page templates for different Languages in my Drupal 6?
For example, if I want to make different page template for Bulgarian language, page-bg.tpl.php doesn't work.
Answer: A drupal.org groups comment shows examples how to allow use of multiple tpl.php file versions.
Using
<?php $vars['template_file'] ?>

it is possible to create your own template file suggestions.
Example:
function phptemplate_preprocess_page(&$vars, $hook) {

  if($vars['language']->language == 'bg') {
    $vars['template_file'] = 'page-bg';
  }
}

Page template suggestion per language?


SSL cert not verifying, AWS interfering?

Question: Previous Setup: AWS load balancer and AWS cert.
current setup: GeoTrust QuickSSL cert from host provider, on apache
My host provider has given me the C NAME details and I added them in route53, but the https doesn't seem to want to resolve. http://www.example.com works great, but  https://www.example.com shows nothing. I have deleted the amazon cert, but is AWS still having an effect? There are 2 other cname records in AWS that I haven't changed or removed.
I have posted screenshots of the dns records. I changed the A records already so the site points to the correct IP. the nameservers are unchanged - still AWS.
It was previously setup with a weird certificate (previous person) that just referred to (literally) example.com - this cert went out of date. So I setup a new one in amazon. The AWS cert didn't work at first until I linked it to route53, which iirc linked to a load balancer. I have also deleted the lb.
I just realised something. The cert I setup (since deleted) in AWS was in region Ireland (where the business is based), but if I change the region to n. Carolina, there is an AWS cert active there:
Domain name:
*.example.com
Record Name:
_09ede9a0bba2bcf36e9f0c4f843f1397.example.com.
Record Type:
CNAME
Record Value:
_specificaws.number.acm-validations.aws.
Should I just delete this too? Is it enough to remove the cname record, or do I delete the cert?
Edit: more details and screenshots removed
Edit2: removed reference to actual domain
Comment: You just need to set SSL / TLS up correctly on your web server. You really need to give us much more information about your environment and configuration - is this EC2, what web server you're using, web server configuration, firewall configuration, etc. Please edit your question to give that information.
Comment: If you're going to post screenshots, please make them right way up, so people can see them. The main thing we need to help is a description of your environment and your web server configuration. For example, you may be using a load balancer and AWS certificate manager, you may be using Apache and Let's Encrypt.
Answer:
Your www.example.com doesn't listen on port 443 (HTTPS) hence we're unable to check your certificates.
<code>$ telnet www.example.com 443
Trying 192.0.0123...
telnet: Unable to connect to remote host: Connection refused
</code>
That <code>_09ed...1397.example.com.</code> DNS record is just for AWS Certificate Manager (ACM) domain validation purposes, it's not the actual certificate.
Guessing from the IP you are no longer hosting the site on AWS so you can't use ACM certificates. You'll have to obtain one e.g. through Let's Encrypt.
Comment: Hi MLu, many thanks for your answer.  would you mind removing references to the website and the IP numbers etc? The solution for me was that the A records needed to be updated with the new IP address, which I hadn't received from the host. Also the .htaccess file needed code to allow https.
Comment: @PaulMurphy Ok, done. If it helped please upvote and accept the answer. Thanks.


Correct way of writing a filter query on a geodjango model (finding out if a multipolygon field contains a point)

Question: I am new to geodjango and trying to build an application after going through the tutorial. So, I have this model:
from django.contrib.gis.db import models

class CountryBorder(models.Model):
    f_code = models.CharField(max_length=5)
    name = models.CharField(max_length=254)
    ....
    ....
    #the multipolygonfield on which I want to perform lookup
    geom = models.MultiPolygonField(srid=4326)

    def __str__(self):
        return self.name

and I am trying to find the model instance which contains (the model.geom field contains) a point. I tried doing that as described in the documentation:
from app_name.models import CountryBorder
from django.contrib.gis.geos import Point
pnt = Point(23.1827, 75.7682)
CountryBorder.objects.get(geom_contains=pnt)

But I get the following error message:

django.core.exceptions.FieldError: Cannot resolve keyword 'geom_contains' into field. Choices are: f_code, geom,name.....

Am I missing something?
Answer: You separate the field name (here geom) and lookup (here __contains [Django-doc], with two consecutive underscores (__), not a single underscore, so:
from app_name.models import CountryBorder
from django.contrib.gis.geos import Point

pnt = Point(23.1827, 75.7682)

CountryBorder.objects.get(geom__contains=pnt)
Comment: @musical_ant: what error do you get?
Comment: I figured it out, the data set I have contains points in (longitude, latitude) format instead of (latitude, longitude). Thank you for your help :)
Comment: yes I am not getting the same error now, but I think there's something wrong with the coordinates. Is there a way to print the list of coordinates contained within different polygons of a multipolygon field?


What's pgrp in this context?

Question: Quoted from here.

gdb puts the debugged process in its
  own pgrp and sets the terminal to that
  pgrp.  (Try e.g. ps j on the PIDs of
  gdb and your program being debugged.)

And what does it mean by

ps j on the PIDs of gdb and your program being debugged

does that mean ps j PID?
I don't get anything special from this though...
Basically I don't understand what that article is talking about,can anyone explain it in more great details?
Answer: A "pgrp" is a process group. ps j lists the process group ID (the column is called PGID). The PGID of a process is typically itself or its parent's process group, but can be arbitrarily set with setpgid(). Process groups control what processes receive job control signals. I think gdb moves the process to its own group so as to avoid having the process receive job control signals that would mess up gdb's control over the process.
The bug report is about using gdb with a program that uses sigwait. sigwait allows a process to receive a signal in an underhand way: instead of being delivered to the process in the usual manner, the signal is removed from the pending queue and sigwait returns. This is mainly useful to arrange for a signal to be always delivered to a particular thread: block the signal, but have a thread consume it by running sigwait.
Since the signal is not actually delivered to the process, ptrace sees nothing, and so gdb isn't notified that the process has underhandedly consumed the signal.
The debate in the bug report is about whether the kernel should be modified so that ptrace sees something when the signal is consumed through sigwait, or whether gdb should handle this situation differently. I don't know enough about this to take sides.
Comment: Do you understand the explanation in that bug that says it's not a bug?
Comment: @locale: I've expanded my answer, but deciding whether it's a bug or not is beyond my level of expertise. P.S. This is getting really into developper territory; I've recommended that your question be migrated to [so], and I recommend that you create an account there and associate it with your [sf] account.

What's pgrp in this context?


PHP doesn't follow if..else conditions

Question: I have this working website yet I got a problem with the following lines of code:
<?php

//CREATION OF CONNECTION

$con=mysqli_connect("localhost","root","","dbJobsheets");

//CHECKING OF CONNECTION

if (mysqli_connect_errno($con)) {
    echo "Failed to connect to MySQL " . mysqli_connect_error();
}

$checker = mysqli_query($con, "SELECT colActualStart FROM tblChecklist WHERE colEntryID='1' AND colDate='Aug 19,2014'");

if ($checker != NULL) {
    $result=mysqli_query($con,"SELECT * from tblChecklist WHERE colEntryID='1'");

    while ($row=mysqli_fetch_array($result)) {
        echo "
";

        echo "";
        echo $row['colActualStart'];
        echo "	";
        echo "
";

        echo "
";
    }
} else {
    echo "
<input type=button value=\"Enabled\" id=clickY onClick=action2(); style=\"left:10;\">
";
    echo "
<input type=text id=as1 value=\'\' style=\"visibility:\'hidden\'; width:120px;\">";
}

?>

Everything is working up until the $checker mark; what I want with is for the system to check if the corresponding colActualStart entry for the corresponding colEntryID and colDate is null or not. If its null, it should run the commands inside the if tag, else if not.
The problems seems to be in the $checker, since the entire line of code is inside the $checker variable, it is not null; that is why the code is running the if commands. It doesn't fetch the data inside the colActualStart column and convert to string to be really able to check if its null or not.
Comment: -1 for a really really misleading and false title.
Comment: `It doesn't fetch the data inside the colActualStart column and convert to string to be really able to check if its null or not` You already know the problem.
Comment: Why'd you escape single quotes inside of double quotes under the else block…?
Answer: You cannot check value of colActualStart by checking the result of the mysqli_query.
After your mysqli_query, your must call a fetch function to retrieve data, like you did 2 lines below.
A something like that and it will work :
$checker=mysqli_fetch_array(mysqli_query($con, "SELECT colActualStart FROM tblChecklist WHERE colEntryID='1' AND colDate='Aug 19,2014'"));
    if($checker[0] != NULL){

Comment: Tried this and it worked, thank you for answering my question rather than hitting the -1 for certain technicalities.

PHP doesn't follow if..else conditions


Execommand problem with Delphi,relative link of image

Question: I have a problem with the command Execommand javascript that uses a component in Delphi.
Order inserthtml used to insert a code in a html editor html.Quand throws this command with the following code ** ****
I see html code has changed the image link relative
that the .
you have a solution to keep the real link of the image?
Comment: This doesn't make much sense to me but the fact that your question includes `heigth` and the spurious spaces in the filename suggest you have failed to include the real code.
Comment: What Delphi component are you talking about? Is `Execommand` something you do from Delphi code, or from JavaScript? What was the expected `src=` for your image? You really need to add a lot more details, and should probably **copy-paste** the relevant parts of your Delphi code.
Comment: I Played the component is geckobrowser (a component based on the Gecko SDK).
yes I use the command with delphi Execommand geckobrowser because the component has an interface to this command.
In fact I generate the HTML code to insert an image.
Answer: Working as designed. When the domain of the page your working on matches that of an inserted image an absolute URL is changed to be a relative URL. To keep full URLs put the images on another domain (or drive letter in this case). The SUBST command can be used on a Windows command prompt to make another drive letter point to C: if you don't want to move stuff around. To let C: be accessible as I: so your image links can start with I: use the following:
SUBST I: C:\


Zoom on UITextField

Question: I am working on an iOS application which contains of many UIView's. UINavigation is used to navigate between those views.
One of my UIView contains UITextField. My problem is that, when I zoom it display the content of another view. I had not added any code for zooming.
Below is screen shot of my actual design.
On zoom, It display's the root view of navigation

Also, it work properly on simulator. This problem is detected when I had tested application on device.
Thanks in advance
Answer: I had solved this problem. The real problem was with PPRevealSideViewController. I had implemented PPRevealSideViewController and the flow was not properly set. So the root view in PPRevealSideViewController was having the highest window level and thus on zooming it was displaying content of that view.

Zoom on UITextField


How do I find the spectral radius of the Jacobi and Gauss-Seidel iteration matrices?

Question: Matrix
a)I need to find the spectral radius of the Jacobi and Gauss-Seidel iteration matrices from the given matrix.
I know that the spectral radius is the maximum eigenvalue however I am still confused by the question.
Any help would be very appreciated
Comment: Check wikipedia.
Comment: @Moo Yes thank you. I was able to find the spectral radius of the Gauss-Seidel Method however, i was not able to do it for the relaxation (SOR) method. Is there any chance you can help me with this?
Comment: Wouldn't you have to find the parameter $\omega$. Then using this result, find the spectral radius using the preconditioning matrix (where $D$ is the diagonal and $E$ is the lower triangular like you used in the GS-Method) $$\dfrac{1}{\omega}\left(D - \omega E\right)$$
Comment: @Moo I tried doing that however i did not get the correct answer. I worked out w to be 1.1716 however then when working out p I get 0.3719 which is incorrect. I know it is incorrect because the answer does not satisfy this equation: p = w - 1
Comment: $\omega$ looks correct, but the spectral radius does not. Let me take a quick look.
Comment: @Moo Yeah the spectral radius is also where I think i went wrong, thank you
Comment: $$msor = 1/w(D - w E), tsor =  ID[9] - inverse(msor) A$$ Then find the largest eigenvalue. I got the result $$\rho_{sor} = 0.17157$$
Comment: @Moo Thank you very much, you've helped me a huge amount!
Answer: We are given
$$A = \begin{pmatrix}
 4 & -1 & 0 & -1 & 0 & 0 & 0 & 0 & 0 \\
 -1 & 4 & -1 & 0 & -1 & 0 & 0 & 0 & 0 \\
 0 & -1 & 4 & 0 & 0 & -1 & 0 & 0 & 0 \\
 -1 & 0 & 0 & 4 & -1 & 0 & -1 & 0 & 0 \\
 0 & -1 & 0 & -1 & 4 & -1 & 0 & -1 & 0 \\
 0 & 0 & -1 & 0 & -1 & 4 & 0 & 0 & -1 \\
 0 & 0 & 0 & -1 & 0 & 0 & 4 & -1 & 0 \\
 0 & 0 & 0 & 0 & -1 & 0 & -1 & 4 & -1 \\
 0 & 0 & 0 & 0 & 0 & -1 & 0 & -1 & 4 \\
\end{pmatrix}$$
For the Jacobi Method, we have
$$mjac = \begin{pmatrix}
 4 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 \\
 0 & 4 & 0 & 0 & 0 & 0 & 0 & 0 & 0 \\
 0 & 0 & 4 & 0 & 0 & 0 & 0 & 0 & 0 \\
 0 & 0 & 0 & 4 & 0 & 0 & 0 & 0 & 0 \\
 0 & 0 & 0 & 0 & 4 & 0 & 0 & 0 & 0 \\
 0 & 0 & 0 & 0 & 0 & 4 & 0 & 0 & 0 \\
 0 & 0 & 0 & 0 & 0 & 0 & 4 & 0 & 0 \\
 0 & 0 & 0 & 0 & 0 & 0 & 0 & 4 & 0 \\
 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 4 \\
\end{pmatrix}$$
$$tjac = I - mjac^{-1} A =
\begin{pmatrix}
 0 & \frac{1}{4} & 0 & \frac{1}{4} & 0 & 0 & 0 & 0 & 0 \\
 \frac{1}{4} & 0 & \frac{1}{4} & 0 & \frac{1}{4} & 0 & 0 & 0 & 0 \\
 0 & \frac{1}{4} & 0 & 0 & 0 & \frac{1}{4} & 0 & 0 & 0 \\
 \frac{1}{4} & 0 & 0 & 0 & \frac{1}{4} & 0 & \frac{1}{4} & 0 & 0 \\
 0 & \frac{1}{4} & 0 & \frac{1}{4} & 0 & \frac{1}{4} & 0 & \frac{1}{4} & 0 \\
 0 & 0 & \frac{1}{4} & 0 & \frac{1}{4} & 0 & 0 & 0 & \frac{1}{4} \\
 0 & 0 & 0 & \frac{1}{4} & 0 & 0 & 0 & \frac{1}{4} & 0 \\
 0 & 0 & 0 & 0 & \frac{1}{4} & 0 & \frac{1}{4} & 0 & \frac{1}{4} \\
 0 & 0 & 0 & 0 & 0 & \frac{1}{4} & 0 & \frac{1}{4} & 0 \\
\end{pmatrix}$$
The eigenvalues of $tjac$ are
$$-\frac{1}{\sqrt{2}},\frac{1}{\sqrt{2}},-\frac{1}{2 \sqrt{2}},-\frac{1}{2 \sqrt{2}},\frac{1}{2 \sqrt{2}},\frac{1}{2 \sqrt{2}},0,0,0$$
The largest in absolute value makes the spectral radius of the Jacobi Method
$$\rho_j = \frac{1}{\sqrt{2}}$$
Can you do this for the Gauss-Seidel Method?


Reference request: Introduction to Finite Group Cohomology

Question: I don't know anything about group cohomology and I'd like to.

What is the best text to learn this subject?

I'd prefer as soft an introduction as possible - that is, lots of motivation, lots of examples, slow moving development of intuition.  (Something like Simmons' Intro to Category Theory, if you've read that.)  I have a background in finite group theory and some character theory.  The text should actually show how to compute group cohomologies, preferably not too far in, something I have not found in the group cohomology books in my University library.
A textbook would be great, but good lecture notes or papers would be fine too.
Answer: For many reasons, I would suggest Weibel's "Intro to Homological Algebra", because it puts things like "group cohomology" into a somewhat larger context, enabling comparisons to other things... Perhaps no reason to be a complete slave to the ordering of topics therein... but to see that "group cohomology" consists of the right-derived functors of the "fixed-vector" functor (and "group homology" of left-derived functors of "co-fixed-vector" functor), as an example comparable to Lie-algebra (co-) homology, and many others, makes it easier to understand each particular example.
Comment: I would like to recommend Serre's "Local Fields" for finite groups, and "Galois Cohomology" for profinite groups.
Comment: Brown's "Cohomology of groups" is another standard reference.


Refresh a uma datatable

Question: É assim eu estou a fazer um pequeno site em java só que quando adiciono um produto e clico para listar a datatable não actualiza, não sei como e que tenho que fazer para que cada vez que a pagina for exibida actualizar o Array.
Outra coisa que me acontece e que quando adiciono um produto o campos nao ficam limpos.
Imagens (1 adicionei depois foi listar e como vêem não aparece a cenoura)
Inserir

Listar
Comment: O que está usando? Só JSP? Spring?
Comment: estou a usar Spring com primefaces
Answer: Já resolvi eu metia todas a class no spring ou seja assim
<code><bean id="Verificarsessao" class="service.Verificarsessao"></bean>
</code>
O que fazia com que pré carrega-se tudo nao sei se tou certo ou não mas resolveu o problema

Refresh a uma datatable


supabase.auth.getUser() returns error on vue-router route guard

Question: I am attempting to build a Vue application that uses Supabase authentication. Inside one of the route guards in the router file, I implemented supabase.auth.getUser() in order to retrieve the user login status for a conditional that prevents next() from executing before the user is authenticated:
// Route guard for auth routes
router.beforeEach((to, from, next) => {
  // const user = supabase.auth.user();
  const { data: { user } } = await supabase.auth.getUser();

  if (to.matched.some((res) => res.meta.auth)) {
    if (user) {
      next();
      return;
    }
    next({ name: "Login" });
    return;
  }
  next();
});

However, when I implement supabase.auth.getUser() inside the router guard, I get the following error in the console before logging in: "invalid claim: missing sub claim". After logging in, the error goes away. If I remove the supabase.auth.getUser conditional from the route guard, the error also goes away. After some additional digging online and running my Supabase anon key in jwt.io, it appears that my key is missing sub claim in the payload. If this is preventing the key from being authenticated properly, how can I resolve it?
Comment: Please check this link. It might help. https://github.com/supabase-community/supabase-custom-claims
Answer: You should be checking against the session rather than the user. The user will try to check against a JWT first which wouldn't exist at the time of checking since you're not logged in. Use getSession instead:
// Route guard for auth routes
router.beforeEach((to, from, next) => {
  // const user = supabase.auth.user();
  const { data: { session } } = await supabase.auth.getSession();

  if (to.matched.some((res) => res.meta.auth)) {
    if (session?.user) {
      next();
      return;
    }
    next({ name: "Login" });
    return;
  }
  next();
});

Comment: Thanks. Yeah I actually figured that out after consulting with the Supabase admins. Now I see it in the docs: https://supabase.com/docs/reference/javascript/auth-getsession. I didn't see this before as I was looking under user management in the regular API docs, not the docs for the JavaScript client. Thanks nonetheless! I'll still up-vote this answer.


How to generate mean curve of non-function?

Question: I am currently working on curves generated in tensile tests of polymer specimens. Here, I try to generate a mean curve of five data sets generated at the same composition of the samples. Unfortunately, the resulting curve is not a function but has a vertical section which is why a simple smooth is not sufficient. Is there a way to fix the smoothed curve to a defined end point in R? Or an even better way that I did not see yet?
I already tried a geometric_smooth() from ggplot2 on all data points but it did not work as wished.
My current approach:
<code>data <- read.csv("data.csv", header = TRUE, sep = ";")
ggplot(data, aes(y=stress, x=strain))+geom_point()+geom_smooth()
</code>
In the figure, you can see that the blue average curve does not fit the actual curves near their end points, probably due to the vertical sections. That's why I want to fix it to the mean end point. Additionally, I would like to fix it to (0|0) as the blue mean curve starts somewhere above it which does not fit the actual behaviour.
Comment: To the state the obvious: `geometric_smooth` is for a *quick* visualisation. If we actually need a proper curve fitting, it is not the proper tool for the job. It is not a *bad tool* just it is not designed to be curve fitting tool but rather a way to show a smoothly varying trend conveniently.
Comment: You may find it considerably easier to approximate $\exp(\text{stress}|\text{strain})$ (possibly a weighted fit, to account for the effect of the transformation on variance); you can then do a first order bias correction when transforming back. It won't be certain to work perfectly but is likely to do better if you're sticking to quick and simple function approximation tools like this one.
Answer: I believe you are looking for a spline with boundary conditions. A quick Google search for "spline with boundary conditions R" produces quite a few results and functions that you may be able to use.
https://stat.ethz.ch/R-manual/R-devel/library/splines/html/bs.html
https://stat.ethz.ch/R-manual/R-devel/library/splines/html/ns.html
You could also consider piecewise polynomials wherein you try to fit polynomials of different degrees to different sections of your data.
Non-parametric methods are known to have weaknesses at boundaries. You may want to look into that before you start.
I'd suggest Chapter 7 of An Introduction to Statistical Learning with Applications in R titled Moving Beyond Linearity to get started with splines. There should be a free copy of this book available for download online.
Comment: I think that while you are correct to suspect boundary conditions play a part at this, it is not the main things. The obvious issue is that certain curves "taper off" (?) before other and this not adequately captured. The OP do not want an "arithmetic" mean here but rather a "warped" mean.


What is meant with "$df_x(h)$ is a linear function of $h$"?

Question: In Milnor's Topology From the Differentiable Viewpoint, the derivative of a smooth map $f: U\to V$  is defined as
$$
\mathrm{d}f_x: \mathbb{R}^k \to \mathbb{R}^l
$$
$$
h\mapsto \lim_{t\to0} \frac{f(x+th)-f(x)}{t}
$$
On the fifth page he remarks

Clearly $\mathrm{d}f_x (h)$  is a linear function of $h$.

What does he mean here? This would require that $\mathrm{d} f_x (h_1+h_2)= \mathrm{d} f_x(h_1)+\mathrm{d} f_x(h_2)$, but this is does not seem to the case in general.
Comment: For differentiable functions, $\mathrm{d} f_x (h_1+h_2)= \mathrm{d} f_x(h_1)+\mathrm{d} f_x(h_2)$ is true in general. For differentiable $f$, $\mathrm{d}f_x(h)=J_x(h)$ where $J_x$ is the Jacobian at $x$.
Comment: $df_x(h)$ is just $D_h f (x)$, i.e. the directional derivative of $f$ at $x$ and in the direction of $h$.
Answer: I think Milnor means what he says: $df_x(h)$ is a linear function of $h$ (not of $f$, as @Jp McCarthy suggested). I think "clearly" is overstating the case, however.  In fact, the usual definition of what it means to say that $f$ is differentiable at $\boldsymbol x$ is equivalent to the statement that the limit
$$
\lim_{t\to0} \frac{f(x+th)-f(x)}{t}
$$
exists and depends linearly on $h$. Milnor's claim that this is the case relies on a theorem that a function of class $C^1$ (meaning that all first partial derivatives exist and are continuous) is differentiable at every point. This can be proved, for example, by using Taylor's theorem, or more directly by applying the fundamental theorem of calculus to the function $t\mapsto f(x+th)$.
Comment: Thank you I deleted my incorrect answer. I thought things were straightforward but then, as I said, I got confused. I appreciate your tone by the way.
Comment: @Jp McCarthy: You're welcome!


RightClick CellTable Header

Question: I need to make the column headers of my celltable to do something on right click.
I implemented a header which uses by now a clickabletextcell, but can be anything.
here is how I declare my celltable so far:
<code>Header header = new Header(new ClickableTextCell()) {

    @Override
    public String getValue() {
        return actual.getCaption();
    }
};

TextColumn<ObjetoDato> columna = new TextColumn<ObjetoDato>() {

    @Override
    public String getValue(ObjetoDato origen) {
        return origen.getValor(actual.getNombreCampo());
    }
};
columna.setSortable(true);
sortHandler.setComparator(columna, new Comparator<ObjetoDato>() {
    @Override
    public int compare(ObjetoDato o1, ObjetoDato o2) {
      return o1.getValor(actual.getNombreCampo()).compareTo(o2.getValor(actual.getNombreCampo()));
    }
});
table.addColumn(columna,header );
</code>
Answer: Check out the click sample here https://developers.google.com/web-toolkit/doc/latest/DevGuideUiCustomCells#cell-onBrowserEvent
In your case after you confirm its a "click" event, you can figure out the left/right by using the NativeEvent#getButton()
Comment: i use the example of the page, but on right click i cant manage to do anithyg. onBrowserEvent is nt trigger. But yes keydown. Why is this?
Comment: Impossible to say unless you want to show us what you have tried

RightClick CellTable Header


Approach to classify text using machine learning

Question: I am trying to find the best approach to this problem.
Consider that there is a type of text document, for instance a letter.  I will refer to this as the Document Type.
I will refer to an individual instance of a Document Type as a Document.
A Document is a list of words, and includes word, x_position and y_position for each word, but there will be slight variations.  For example words may be slightly differently positioned, or maybe not present, or maybe extra words. This is the core of the problem.
I will use supervised learning to classify each document, resulting in data of this shape -
Training Data
document, word, x_position, y_position, classification
1, {anonymized}, 167, 198, FirstName
1, some, 454, 17, 0
1, other, 124, 279, 0
1, words, 687, 826, 0
1, {anonymized}, 946, 342, PhoneNumber
2, {anonymized}, 169, 195, FirstName
2, some, 453, 16, 0
2, different, 123, 276, 0
2, words, 689, 822, 0
2, {anonymized}, 948, 346, PhoneNumber

Of course there will be many more documents and many more words in each document.
Note that an unclassified word has changed between documents, and the x_positions and y_positions have also changed slightly, as described above.
What is the best approach to use machine learning to build a model that will classify the following document, again with slightly different x_positions and y_positions and words.
Test Data
James, 165, 196  -> expect classification of FirstName
similar, 452, 18
different, 121, 279
words, 689, 822
0121789456, 941, 348 -> expect classification of PhoneNumber

This is a follow on question from this question.  Your thoughts and advice would be greatly appreciated.
Comment: There is no "best" way, but look into word embeddings and the vector space model to construct your input layer and then apply a any number of classification algorithms (e.g., random forests, boosted trees, SVM, neural nets) etc to actually determine how to best classify to categories based on the input layer.
Answer: Let me first restate the problem in a way more suitable for ML.
When you apply your model, you don't know which words are "named entities" - names, phones, etc. So in fact your data looks like
James, 165, 196      -> expect classification of FirstName
similar, 452, 18     -> expect classification of NoEntity
different, 121, 279  -> expect classification of NoEntity
words, 689, 822      -> expect classification of NoEntity
0121789456, 941, 348 -> expect classification of PhoneNumber

Given train data in this format, you can assign a class to each word in the letter, if you create good features and feed them to a good classifier.
I would start with a tree-based model (random forest or gradient boosting) and simple manually engineered features, like:

type of the document
x position of the word
x distance from the rightmost word
y position
y distance from the lowest word
position of the word in the document (from the beginning)
position of the word in the document (from the end)
position of the word in the current sentence (from the beginning)
position of the word in the current sentence (from the end)
number of occurences of this word in the document
number of letters in the word
number of capital letters in the word
number of digits
occurence of special symbols
part-of-speech of the word (predicted by nltk.tag, for example)
The word itself (word2vec embedding, or one-hot encoding) - if you have enough training data (which is, I would guess, not the case)
similar statistics for the $k$ previous and next words
distance from the closest occurence of the word 'number'
distance from the closest adjective
...

Maybe you would like to concentrate on the nearest words (both sequentially and geometrically). To accomplish this, you could take the $k$ closest words (I would start with $k\approx 10$) in the document, and use them as features in a Naive Bayes classifier. Probabilities predicted by this classifier could be used directly or as additional features for the tree-based model.
You could include in your model all the possible words, but there would be tens of thousands of features, and your model would most likely overfit. You can decrease number of possible words by first taking embeddings of your words from a pretrained model (e.g. word2vec or fastText), clustering them, and using cluster labels instead of words. As a result, synonims or semantically close words will go into the same feature.
A more elaborate approach would be to train a RNN on your data, but probably this simple design will already suffice.
Comment: I do not know a good way to include distances from all the words. Of course you can just loop across all the possible words, but there would be thousands of features, and your model would most likely overfit. You can decrease number of possible words by first taking embeddings of your words from a pretrained model (e.g. word2vec or fastText), clustering them, and use cluster labels instead of words.
Comment: Thank you for this very helpful answer and suggested approach.  Would it be possible using tree-based model to take into consideration the position of the words in relation to other words, almost "triangulating" them?  Or is this a crazy idea?
Comment: @gamesmad yes, you can add features like  or .
Comment: For instance, in my training data from the question, if take the word "some" in document 1 and add -287 to x, and 181 to y, we will find the position of FirstName.  In document 2 this is add -284 to x and 179 to y.  These values are similar.  I feel like the subtle similarities of the documents such as just described would be lost using the tree-based model?  Or am I misunderstanding?
Comment: For example if we then find the word "some" in the test data, and try to find elements in range of -287 to -284 of x, and +181 to +179 of y, we are likely to find the FirstName value.  Taking into account all of those relationships on the document would find the correct value.  Again this may be a crazy idea...!?
Comment: If you included feature like  and  or ,  your tree model will easily discover them.  But to include such features, you need first to recognize that the word 'some' is useful in the first place. You can do it with a word-count-based model - see modification to my answer.
Comment: Thank you again Dale.  Is it possible to take into account horizontal and vertical distance from all other words in the document?  As opposed to specifically training for the word "some"?


Why gossip_payload_buffer_size increases?

Question: I am doing performance testing on a Hyperledger Fabric-based application. In order to increase the throughput, I changed the value of BatchTimeout of the channels. Could someone please explain why the gossip_payload_buffer_size metric is increasing up to 41 when the load is high? when the load is very low it is 0. This only happened when I changed the default value of BatchTimeout of the channel.
https://hyperledger-fabric.readthedocs.io/en/release-2.2/metrics_reference.html#:~:text=gossip_payload_buffer_size
Answer: That value represents an internal queue of blocks from the gossip layer to the ledger layer, in the peer.
When the peer's ledger is slower in processing blocks than the rate at which blocks arrive, the queue (payload buffer) is starting to fill.
Comment: Thanks @yacovm Can you please suggest a way to improve the processing speed of peer's ledger? I am using couch DB as the state database.
Comment: don't use couchDB :D


HP ALM Python rest api - How to properly pass cookie for API calls

Question: How to pass the HP ALM authentication session object for rest api calls. I am following some examples to connect to HP ALM via REST API to run basic CRUD operations.
One of the example - https://github.com/vkosuri/py-hpalm/blob/master/hpalm/hpalm.py
Below is the code snippet to establish the connection which is working perfectly fine. I am getting 200 OK response for login.
headers = {'Cookie' : lwssocookie}
headers["Accept"] = 'application/xml'
login_url = self.base_url + '/qcbin/authentication-point/authenticate'

resp = requests.get(login_url, headers=headers, auth=HTTPBasicAuth(self.username, self.password), verify=self.verify)
alm_session = resp.headers['Set-Cookie']
logger.debug("Is QC session launched: %s" %alm_session)
cookie = ";".join((lwssocookie, alm_session))

But all the subsequent operations are failing with unauthorized error even though I added the cookies to header
self.headers['cookie'] = cookie
url = self.base_url + '/qcbin/rest/domains/' + self.domain + '/projects/' + self.project + '/test-instances'
response = requests.get(url, params=params, headers=self.getheaders())

Can anyone please suggest how to hold the session to run operations and what am I missing here.
I also tried to pass cookies in get call as below and even that didn't work.
response = requests.get(url, params=params, headers=self.getheaders(), cookies=cookie)

Thank you in advance
Answer: Thanks to requests.Session(), there is no need to manipulate HTTP headers for cookies.
Here is a code snippet I run for old ALM version 12.01 which took me a couple of hours to design thanks to this post:
session = requests.Session()
session.verify = False

auth = session.post(hpqc_server + "authentication-point/authenticate?login-form-required=y",
                    auth=HTTPBasicAuth(username, password))
print("Authentication ", auth, auth.text, session.cookies)

site_session = session.post(hpqc_server + "rest/site-session")
print("Session ", site_session, site_session.text, session.cookies)

check = session.get(hpqc_server + "rest/is-authenticated")
print("Check ", check, check.text)

# Enforce JSON output
session.headers.update({ 'Accept': 'application/json' })
projects = session.get(hpqc_server + "rest/domains/DOMAIN/projects")


Clear DataGridView datasource linked to Entity Framework

Question: I'm new to Entity Framework, I have a DataGridView connected to Entity Framework as it shown below
dgvDebit.DataSource = (from daily in accountingEntities.DailyAccounts
                       join voucherdetails in accountingEntities.VoucherDetails on daily.DailyId equals voucherdetails.DailyId
                       where voucherdetails.VoucherId == keyvalue
                       group voucherdetails by daily.DailyName into dgroup
                       select new
                              {
                                  DailyName = dgroup.Key,
                                  SumOfDebit = dgroup.Sum(s => s.Debit)
                              }).ToList();

My question is: I want to clear DataGridView datasource but every thing I did has failed - please any help here?
Comment: `dgvDebit.DataSource = null;` should clear the data source - do you get an error with this? (and if so: ***what*** error do you get??)
Comment: dgvDebit.DataSource = null; its work but its clear columns too, so when i load datagridview again i loose grid format
Answer: OK, so you want to bind to an empty list of the type that you have.
Step 1: define a .NET type for your query result return type:
public class ResultDTO
{
    public string DailyName { get; set; }
    public decimal SumOfDebit { get; set; }
}

Step 2: change your "normal" query to:
dgvDebit.DataSource = (from daily in accountingEntities.DailyAccounts
                       join voucherdetails in accountingEntities.VoucherDetails on daily.DailyId equals voucherdetails.DailyId
                       where voucherdetails.VoucherId == keyvalue
                       group voucherdetails by daily.DailyName into dgroup
                       select new ResultDTO
                              {
                                  DailyName = dgroup.Key,
                                  SumOfDebit = dgroup.Sum(s => s.Debit)
                              }).ToList();

Step 3: if you want to "clear" the DataGridView, but retain the columns, you can now use:
dgvDebit.DataSource = new List<ResultDTO>();

Comment: Thank you for dedicating your time to my answer
Comment: @HusseinAl-Obaidy: you're welcome - glad I was able to help! Have a great day


Accordion with Bootstrap 3

Question: I am trying to make accordion with Bootstrap Collapse. I have this HTML:

             <button>

             </button>
             Name

                item 1

                item 2

When I click on #ul > li, it must show ul.collapse.
I am using this JS:
$('#ul > li').on('click', function (e) {
    $('.collapse.in').collapse('hide');
    $(this).find('.collapse').collapse();
});

, but it works only first 2 clicks for open and close and after that, it doesn't work. I need to do this with JS.
Comment: You don't seem to be using [Bootstrap's collapse api](https://getbootstrap.com/docs/3.3/javascript/#collapse).
Comment: Also, you have a syntax error in your list: ``
Comment: You are not using the collapse API. That being the case - if you don't care if it uses the BS API, then you can use this simple accordion I recently built.
https://jsfiddle.net/gemlarin/5y3x672h/
Answer: Try that
 $('#ul > li').on('click', function (e) {
  if($('.collapse').hasClass('in')) {
    $('.collapse.in').collapse('hide');
  } else {
      $(this).find('.collapse').collapse('show');
  }
});

it can be written in better form but that will fix your issue.
Answer: Option 1: You can use slideToggle() from jQuery.

$('#ul > li').on('click', function(e) {
  $(this).find('.collapse').slideToggle();
});
.collapse {
  display: none;
}

      <button>

      </button>
      Ресторант Топ Мания

        Обедно меню

        Вечерно меню

Option 2: use collapse('hide') and collapse('show');

$('#ul > li').on('click', function(e) {
  $('.collapse.in').collapse('hide');
  $(this).find('.collapse').collapse('show');
});
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>

      <button>

      </button>
      Ресторант Топ Мания

        Обедно меню

        Вечерно меню

Accordion with Bootstrap 3


Why order topology is defined with open intervals, not closed ones?

Question: In Wikipedia order topology is defined by the subbase consisting of $(a,\infty)$ and $(-\infty,b)$.
Why is not it defined by intervals $[a,\infty)$ and $(-\infty,b]$ instead? Is this Wikipedia definition (with open intervals) accepted by all or absolute most of mathematicians?
Consider an one-point ordered set (call this point $0$). With the Wikipedia definition we have an empty subbase. Isn't it better to have the subbase consisting of the set $\{0\}$?
Answer: If you define the intervals $[a,\infty)$ and $(-\infty,b]$ to be open, then you just get the discrete topology.  Indeed, for any $a$ in your set, $\{a\}=[a,\infty)\cap(-\infty,a]$ would be open.  On the other hand, defining it with open intervals gives the standard topology in the case of $\mathbb{R}$, which is pretty strong evidence that this definition is useful at least in some contexts.
There is nothing wrong with having an empty subbase.  When generating a topology from a subbase, you can take finite intersections of your subbase sets.  This includes the intersection of no subbase sets (the intersection of all the elements of the empty subset of the subbase), which gives you the entire space.
Comment: Oh sorry, really stupid question by me


Multiplos objetos em seletor jquery

Question: Por questão de organização e por desempenho costumo usar varios seletores juntos para realizar um método jquery. Por exemplo:
$("#bola, #casa, #arvore").css("background-color", "blue");

Neste exemplo funciona pois o seletor é uma string.
Porém ao utilizar objetos eu não sei como fazer essa junção.
Novo cenário:
var bola = $("#bola");
var casa = $("#casa");
var arvore = $("#arvore");

$(bola, casa, arvore).css("background-color", "blue");

Neste caso apenas o fundo de "bola" é pintado.
Ou concatenando com vírgula:
$(bola+ ","+ casa + "," + arvore).css("background-color", "blue");

Neste caso nenhum dos dois é pintado, como já era esperado.
Então gostaria de saber se há alguma forma de juntar esses objetos por virgula ou de alguma forma que fiquem no mesmo seletor.
Fiddle de teste: http://jsfiddle.net/nsMw3/
OBS: Não vale colocar que var itens = $("#bola, #casa"), pois utilizo objetos que são trazidos de forma bem mais complexa, e defino eles um a um.
Answer: Você pode usar o método add() para combinar objetos em um conjunto
var bola = $("#bola");
var casa = $("#casa");

$(bola).add(casa).css("background-color", "blue");

JSFiddle
Opção
jQuery não permite adicionar vários elementos de uma só vez para um objeto jQuery, uma opção seria adicionar vários elementos DOM puro à uma array:
var bola = $('#bola'),
    casa = $('#casa'),
    arvore = $('#arvore');

// array de elementos DOM
$( [bola[0], casa[0], arvore[0]] ).css("background-color", "blue");

Ao fazer bola[0] você esta acessando o elemento DOM div#bola
JSFiddle 2
Comment: +1 O bom do método `add` é que ele preserva o stack: http://jsfiddle.net/nsMw3/2/
Comment: @abfurlan essa solução do array com o [0] acho que é o máximo que dá pra chegar em termos de legibilidade, organização e desempenho. Obrigado!
Comment: @JoaoPaulo legal, tb descobri agora esta forma de fazer e achei interessante postar, sempre que precisei usei com add
Comment: Solução matadora! +1
Comment: No caso de id não precisa passar como var, apenas o ID do elemento nó e não há necessidade de passar posição do INDEX, logo que você não pode repetir ID's e é dispensável passar o index.
Answer: Para isso utilize o método .merge()1
var bola = $("#bola");
var casa = $("#casa");

$.merge(bola, casa).css("background-color", "blue");

Estou adicionando o código dos comentários que coloquei:
Para usar com dois ou mais ID's:
HTML:

bola

casa

rodape

rodape

JS:
$([bola, casa, rodape, aa]).css("background-color", "blue");

Dessa forma você não precisa declarar os ids em vars e seu código fica mais limpo.
Comment: Ronny, tinha marcado como correta, porém eu testei com 3 elementos e não funcionou. Editei minha pergunta para que fique claro minha necessidade de multiplos elementos e não apenas dois.
Comment: @JoaoPaulo Talvez `$.merge(bola, casa, arvore)` não funcione, mas que tal `$.merge($.merge(bola, casa), arvore)`? (Nota: segundo a documentação linkada, o método `merge` modifica o primeiro elemento - de modo que se você precisa usá-lo em outra operação qualquer, não use esse método)
Comment: A intenção principal é fazer isso de forma que fique bem legível e de fácil compreensão para manutenção. A principio varios merges iria bagunçar muito. Vou continuar pesquisando, mas se não encontrar nada melhor marcarei essa resposta pois ela já ajuda e agrega conhecimento.
Comment: Amigo, perca um pouco do seu tempo para ver a documentação, ajuda muito. Agora olhe este meu exemplo, olha que mágica, nem preciso declarar váriaveis, é só ler a documentação...: http://jsfiddle.net/nsMw3/4/
Comment: Estou pesquisando na documentação desde que fiz a pergunta. Muito legal o seu exemplo, porém ele se utiliza das ids. Como mencionei, no meu caso real de uso os objetos são obtidos de forma mais complexa. Na real acho que não terei como fazer de forma organizada como espero, separando em virgulas num unico seletor, mas obrigado pelas dicas e resposta.
Comment: E de qualquer forma, referir-se ao elementos diretamente pelo `id` - sem usar `document.getElementById` - não é considerado uma boa prática. [Essa resposta no SOen](http://stackoverflow.com/a/7827037/520779) dá algumas razões para tal.
Comment: @mgibsonbr você está se baseando em uma resposta de 2011, poderia me apontar 1 problema resultante do mesmo? :)
Comment: @RonnyAmarante A resposta é de 2011, mas a funcionalidade em questão é bem mais antiga. Achei os argumentos da resposta convincentes, em particular a questão da poluição do namespace global. Mas isso é questão de opinião, não tenho como te dar uma razão objetiva. Na [discussão linkada na resposta](https://www.w3.org/Bugs/Public/show_bug.cgi?id=11960) também há várias opiniões conflitantes (pra mim não ficou claro se essa funcionalidade foi incorporada no HTML5, se ficou só no 'quirks mode", ou se foi eliminada).
Comment: @mgibsonbr está incorporado sim, e eu não achei nenhuma razão, se você achar me avise. ;)
Comment: @mgibsonbr tente fazer esse teste: `var casa = "a";
alert($([casa]))` logo se eu fizer `var casa = document.getElementById("casa")` ele vai ler a váriavel casa ou pegar o elemento diretamente?
Comment: @RonnyAmarante Abri [uma pergunta separada](http://pt.stackoverflow.com/q/22583/215) para tratar disso. Não adianta eu discutir com você, pois não tenho experiência prática suficiente para embasar minhas opiniões. Se quiser dar uma resposta lá e/ou ver o que os outros escrevem a respeito, fique à vontade. P.S. Não entendi a pergunta - se você define algo com `var`, a definição é o que conta; somente se *não existir* nada com o nome `casa` é que o elemento com mesmo `id` será considerado.

Multiplos objetos em seletor jquery


2nd order distribution differential equation

Question: Denote by $f(x)$ a quadratic polynomial with coeffitients $a, b, c$:
$$ f(x) = ax^2 + bx+ c$$
And let's look at distribution differential equation
$$f \left(\dfrac{d}{dx}\right) y =\text{p.v.} \dfrac{1}{x}$$
Or in another form
$$a\dfrac{d^2y}{dx^2} + b\dfrac{dy}{dx} + cy = \text{p.v.} \dfrac{1}{x}$$
Where the distribution $\text{p.v.} \dfrac{1}{x}$ act's in the following way
$$(\text{p.v.} \dfrac{1}{x} , \psi ) = \int_{\mathbb{R}} \dfrac{\psi(x) - \psi(0)}{x} dx$$
Is there any way to solve this equations? I have tryid it in simple case, where $f(x)$ hase 2 real roots, but i failed, any help and links will be appriciated.
Answer: Let $u$ be some distribution, e.g. $\operatorname{pv}\frac{1}{x}$ and consider the differential equation ("d.e.")
$$
ay'' + by' + cy = u.
$$
Let $r=r_1,r_2$ be the two (possible equal) roots of $ar^2+br+c.$ Then we have
$$
ay'' + by' + cy = (D-r_1)(D-r_2)y,
$$
where $D$ is the differentiation operator, $Df=f'.$
Thus the d.e. can be written
$$
(D-r_1)(D-r_2)y = u.
$$
Now multiply the equation with $e^{-r_1 x}$:
$$
e^{-r_1 x} (D-r_1)(D-r_2)y = e^{-r_1 x} u.
$$
The left hand side can then be rewritten:
$$
D(e^{-r_1 x}(D-r_2)y) = e^{-r_1 x} u.
$$
Taking antiderivative gives
$$
e^{-r_1 x}(D-r_2)y = \int e^{-r_1 x} u \, dx
$$
so
$$
(D-r_2)y = e^{r_1 x} \int e^{-r_1 x} u \, dx.
$$
There is always a distribution $U$ such that $U'=e^{-r_1 x} u$ but it can be impossible to write in an explicit form. I think that is the case when $u=\operatorname{pv}\frac{1}{x}.$
Anyway, to solve for $y,$ just repeat what we did: multiply with $e^{-r_2 x}$ and rewrite $e^{-r_2 x}(D-r_2)$ as $D(e^{-r_2 x}\cdots),$ take antiderivative and multiply with $e^{-r_2 x}.$
Comment: I suppose it's not always true that there is always a distribution $U$ such that $U′=e^{−r1x}u$, it seems that it depends on the space where the distribution acts. By the way, it's very interesting fact, is there any links how to prove this?
Comment: I'm referring to $u \in \mathcal{D}'(\mathbb{R})$ for which the space of test functions is $C^\infty_c(\mathbb{R}).$
Comment: [Proof](https://math.stackexchange.com/questions/1592344/prove-that-a-distribution-has-its-primitive-distribution)


How to use custom tables in any views?

Question: I have created a custom table in drupal database. I need to use this table data in views . For this I have used schema module but its displaying only new views. But I need to use these table data in all views in our site.
Any suggestions?
Answer: You can use hook_views_query_alter and alter the views query by merging your custom query with the views SQL query itself.
Also there is an option in "advanced" section - theme suggestions
There you can write your custom query to fetch results into tabular format.
Comment: You can create a custom module using hook_view_api() and hook_view_data().In hook_view_data() you can add the table and fields that you want to display in view.You can go through the link given below:     https://www.sitepoint.com/exposing-tables-views-drupal-7
Comment: After adding fields you can see the table name in view content type dropdown
Answer: While hook_views_data() definitely allows to expose the custom table to the Views module, I would recommend you to use one of the following modules, so that you don't have to write code every time you create a custom table.

Views Expose Tables
Data Module

How to use custom tables in any views?


Understanding the number of samples in a correlation test

Question: I am struggling to understand what "number of samples" for correlation tests refers to.
Let's say you run a correlation test between weight and age.
You take 12 measurements of weight, and 12 of age, and find a positive correlation.
You decide to report the results as "Weight and age showed a positive correlation (r coefficient, number of samples, significance level)...".
Is the number of samples 12 (the number of measurements taken for each variable), 2(the number of variables) or 24 (the total number of variables used in the correlation test)?
Answer: If you are looking at the correlation between two variables, it means they have been measured together. If I took 24 people and asked 12 their weight and 12 their age, could I say anything about the association between the two? Of course not. You ask the same 12 people for both and look at how the two quantities are associated. So you've sampled 12 'things' but taken two measurements for each.
Answer: Sample size is N. In your case it equals 12.
If one variable had one missing value, it would be 11.


Object.memberFunction(argument).MemberFunction(); - I just don't get this

Question: I am working on a bigger assignment - a fictional internet banking database. All's okayish, only it needs to be able to respond to a call like this:
bank.Account("123456").Balance();

bank is an instance of a class Bank which holds an array (yep, I am forbidden to use most of the STL) of objects of the class Account.
Thoughts: I need a function Account & Account ( const char * ) in the class Bank that would be a friend function for the class Account and then it is possible to call the Balance function that is declared in the Account class.
Am I doing this right? I am not really asking you to write the code for me, I only want to know if I am headed in the right direction. Thanks.
Answer:
I need a function Account & Account ( const char * ) in the class Bank that would be a friend function for the class Account and then it is possible to call the Balance function that is declared in the Account class. Am I doing this right?

You don't need any friend class or function, just make the getters public:
class Bank {
public:
    Account & Account ( const char * );
};

class Account {
public:
    Balance& Balance();
};

Comment: did this and it solved a lot, only now I am having a problem where the Account function is fighting with the Account constructor. Ah. A lot of work ahead of me.
Comment: @LeaPetrášová The usual way to handle a non existing account (no match is found for the string), is to throw an exception. You can also have a dummy `Account` class member in your `Bank` class, that indicates itself as invalid (e.g. has an id -1), and return a reference to that one in case no matching account is found.
Answer: The pseudo-code in your title should probably be object.MemberFunction1(arguments).MemberFunction2(). And it's all okay, it will work fine.
If MemberFunction1 returns an object, or a reference to an object, you can then chain on more calls to the returned object (or reference). And the classes don't have to be friends, if they are not trying to access and non-public members.
In fact, if the returned object contained a method which in turn returned an object, then you could have
object.MemberFunction1(arguments).MemberFunction2().MemberFunction3();

And so on and so on.
Comment: Yay that's cool! Had no idea about this. I actually need to access the private members - Account IDs, so that's why. Or I could use a getter - I am not really sure what's the difference, only I feel like -etters are lazy.
Comment: @LeaPetrášová If you *need* private members you should probably rethink your design. Worst case, you add getter/setter function (functions that only gets or sets these private variables), best case you redesign the classes to minimize this access.
Answer: Yes, it is the right direction. Your Bank class needs a public method
Account& Account (const char*);

And your Account class needs the public function
int Balance();

Actually you do not need "friend" in order to access the methods, they just have to be public.
Be careful about your Account method though. If you enter an account name that does not exist, what will you return? Perhaps you should return in this case an empty Account object (needs to be a member of your Bank class though). In this case, you should check your returned Account object if it is valid before calling Balance().


Find $\angle{FPC}$: impossible question?

Question: I was given this question by one of my friends:

Shape $ABCD$ is a parallelogram.
$AE = EB$
$BF = FC$
Find $\angle{FPC}$.

but when I tried to solve it, I found it impossible without at least a side value. I disagree with myself, as I am finding an angle, and size doesn't matter. I did this with trigonometry:
$$(EP) = \frac{(BC) \sin(180 - 110)}{\sin(90)}$$
This is using The Law of Sines. Then:
$$\angle{EFP} = \cos^{-1}(\frac{(EF)^2 + (FP)^2 - (EP)}{2(EF)(FP)})$$
This is using The Law of Cosines. Since $(EF) = (FP)$, I simplified that to:
$$\angle{EFP} = \cos^{-1}(\frac{2(EF)^2 - (EP)}{2(EF)^2}) = $$
$$\angle{EFP} = \cos^{-1}(1 - \frac{(EP)}{2(EF)^2})$$
From there, I went to:
$$\angle{FPC} = \frac{\angle{EFP}}2$$
Here I stopped. I thought something was wrong, so I went here to ask. Is there something I'm doing wrong? Did I make a mistake in my calculations? Is this question even possible? Note: please don't criticize me. I'm only grade 8.
Comment: The given data do not determine $\angle FPC$. You can translate the vertical line $C\vee D$ to the right, keeping the other sides of the parallelogram fixed,  and adjust the point $F$ accordingly. In this way the angle in question will become larger. – Maybe originally one more piece of information was given, e.g. $|EB|=|EF|$.
Comment: How do you know EF=FP?
Comment: @tatan because BF = FC, and shape ABCD is a parallelogram, so BC is straight.
Comment: So,what?How do you prove it?
Comment: EBF and FPC-these two triangles are not congruent..
Comment: @tatan since F is halfway from B to C, and BC is straight, (putting a new point between E and P and naming it G) then FG ⊥ EP. Triangle FGE would then be a reflection of triangle FPG, so then EF = FP.
Comment: @ChristianBlatter It seems you are right. I will ask my friend about this question and change it depending on what he says.
Answer: There are two points I want to make.
(1) Your suggestion (about EF = PF) is correct. Your approach is correct too.
However, the proof can be slightly simplified by quoting the "intercept theorem". It says:-
If BE // CP // FG, and F divides BC into two intercepts in the ratio BF : FC, then G will divide EP into two intercepts in the same ratio. That is, EG : GP = BF : FC.
Therefore, after constructing a line through F parallel to BE cutting EP at G, we have EG = GP because BF = FC.
Because $\angle FGP = \angle BEG = 90^0$, FG is actually the perpendicular bisector of EP. Thus, your argument about symmetry can continue.
(2) This problem has no solution.

The diagram above shows if we draw another parallelogram (AB'C'D) having the same characteristics as ABCD, $\angle FPC$ will not equal to $\angle F'P'C'$. This means that angle is NOT constant and is quite length (of $AB$, say) dependent.


Pairwise Mahalanobis distances

Question: I need to calculate the sample Mahalanobis distance in R between every pair of observations in a $n \times p$ matrix of covariates. I need a solution that is efficient, i.e. only $n(n-1)/2$ distances are calculated, and preferably implemented in C/RCpp/Fortran etc. I assume that $\Sigma$, the population covariance matrix, is unknown and use the sample covariance matrix in its place.
I am particularly interested in this question since there seems to be no "consensus" method for calculating pairwise Mahalanobis distances in R, i.e. it is not implemented in the dist function nor in the cluster::daisy function. The mahalanobis function does not calculate pairwise distances without additional work from the programmer.
This was already asked here Pairwise Mahalanobis distance in R, but the solutions there seem incorrect.
Here is a correct but terribly inefficient (since $n \times n$ distances are calculated) method:
set.seed(0)
x0 <- MASS::mvrnorm(33,1:10,diag(c(seq(1,1/2,l=10)),10))
dM = as.dist(apply(x0, 1, function(i) mahalanobis(x0, i, cov = cov(x0))))

This is easy enough to code myself in C, but I feel like something this basic should have a preexisting solution. Is there one?
There are other solutions that fall short: HDMD::pairwise.mahalanobis() calculates $n \times n$ distances, when only $n(n-1)/2$ unique distances are required. compositions::MahalanobisDist() seems promising, but I don't want my function to come from a package that depends on rgl, which severely limits others' ability to run my code. Unless this implementation is perfect, I'd rather write my own. Anybody have experience with this function?
Comment: Are you only using the sample covariance matrix?  If so, then this is equivalent to 1) centering X; 2) computing the SVD of the centered X, say UDV'; 3) computing pairwise distances between the rows of U.
Comment: Welcome. Can you print the two matrices of the distance in your question? And what is "inefficient" for you?
Comment: Thanks for posting this as a question. I think that your formula is not correct. See my answer below.
Comment: @vqv Yes, sample covariance matrix. Original post is edited to reflect this.
Comment: See also very similar question http://stats.stackexchange.com/q/33518/3277.
Answer: Starting from ahfoss's "succint" solution, I have used the Cholesky decomposition in place of the SVD.
cholMaha <- function(X) {
 dec <- chol( cov(X) )
 tmp <- forwardsolve(t(dec), t(X) )
 dist(t(tmp))
}

It should be faster, because forward-solving a triangular system is faster then dense matrix multiplication with the inverse covariance (see here). Here are the benchmarks with ahfoss's and whuber's solutions in several settings:
 require(microbenchmark)
 set.seed(26565)
 N <- 100
 d <- 10

 X <- matrix(rnorm(N*d), N, d)

 A <- cholMaha( X = X )
 A1 <- fastPwMahal(x1 = X, invCovMat = solve(cov(X)))
 sum(abs(A - A1))
 # [1] 5.973666e-12  Ressuring!

   microbenchmark(cholMaha(X),
                  fastPwMahal(x1 = X, invCovMat = solve(cov(X))),
                  mahal(x = X))
Unit: microseconds
expr          min       lq   median       uq      max neval
cholMaha    502.368 508.3750 512.3210 516.8960  542.806   100
fastPwMahal 634.439 640.7235 645.8575 651.3745 1469.112   100
mahal       839.772 850.4580 857.4405 871.0260 1856.032   100

 N <- 10
 d <- 5
 X <- matrix(rnorm(N*d), N, d)

   microbenchmark(cholMaha(X),
                  fastPwMahal(x1 = X, invCovMat = solve(cov(X))),
                  mahal(x = X)
                    )
Unit: microseconds
expr          min       lq    median       uq      max neval
cholMaha    112.235 116.9845 119.114 122.3970  169.924   100
fastPwMahal 195.415 201.5620 205.124 208.3365 1273.486   100
mahal       163.149 169.3650 172.927 175.9650  311.422   100

 N <- 500
 d <- 15
 X <- matrix(rnorm(N*d), N, d)

   microbenchmark(cholMaha(X),
                  fastPwMahal(x1 = X, invCovMat = solve(cov(X))),
                  mahal(x = X)
                    )
Unit: milliseconds
expr          min       lq     median       uq      max neval
cholMaha    14.58551 14.62484 14.74804 14.92414 41.70873   100
fastPwMahal 14.79692 14.91129 14.96545 15.19139 15.84825   100
mahal       12.65825 14.11171 39.43599 40.26598 41.77186   100

 N <- 500
 d <- 5
 X <- matrix(rnorm(N*d), N, d)

   microbenchmark(cholMaha(X),
                  fastPwMahal(x1 = X, invCovMat = solve(cov(X))),
                  mahal(x = X)
                    )
Unit: milliseconds
expr           min        lq      median        uq       max neval
cholMaha     5.007198  5.030110  5.115941  5.257862  6.031427   100
fastPwMahal  5.082696  5.143914  5.245919  5.457050  6.232565   100
mahal        10.312487 12.215657 37.094138 37.986501 40.153222   100

So Cholesky seems to be uniformly faster.
Comment: +1 Well done!  I appreciate the explanation why this solution is faster.
Comment: You are right, it doesn't, so my edit is not entirely relevant. I'll delete it, but maybe one day I'll add a pairwise version of maha() to the package. Thanks for pointing this out.
Comment: That would be lovely! Looking forward to it.
Comment: How does maha(), give you the pairwise distance-matrix, as opposed to just the distance to a point?
Answer: The standard formula for squared Mahalanobis distance between two data points is
$$ D_{12} =  (x_1-x_2)^T \Sigma^{-1} (x_1-x_2) $$
where $x_i$ is a $p \times 1$ vector corresponding to observation $i$. Typically, the covariance matrix is estimated from the observed data. Not counting matrix inversion, this operation requires $p^2+p$ multiplications and $p^2+2p$ additions, each repeated $n(n-1)/2$ times.
Consider the following derivation:
\begin{eqnarray*}
  D_{12} &=& (x_1-x_2)^T \Sigma^{-1} (x_1-x_2) \\
  &=& (x_1-x_2)^T \Sigma^{-\frac{1}{2}} \Sigma^{-\frac{1}{2}} (x_1-x_2) \\
  &=& (x_1^T \Sigma^{-\frac{1}{2}} - x_2^T \Sigma^{-\frac{1}{2}}) (\Sigma^{-\frac{1}{2}}x_1 - \Sigma^{-\frac{1}{2}}x_2) \\
  &=& (q_1^T - q_2^T)(q_1 - q_2)
\end{eqnarray*}
where $q_i = \Sigma^{-\frac{1}{2}}x_i$. Note that $x_i^T \Sigma^{-\frac{1}{2}} = (\Sigma^{-\frac{1}{2}} x_i)^T = q_i^T$. This relies on the fact that $\Sigma^{-\frac{1}{2}}$ is symmetric, which holds due to the fact that for any symmetric diagonalizable matrix $A = PEP^T$,
\begin{eqnarray*}
  A^{\frac{1}{2}^T} &=& (PE^{\frac{1}{2}}P^T)^T \\
  &=&  P^{T^T} E^{\frac{1}{2}^T} P^T \\
  &=& PE^{\frac{1}{2}}P^T  \\
  &=& A^{\frac{1}{2}}
\end{eqnarray*}
If we let $A=\Sigma^{-1}$, and note that $\Sigma^{-1}$ is symmetric, we see that that $\Sigma^{-\frac{1}{2}}$ must also be symmetric. If $X$ is the $n \times p$ matrix of observations and $Q$ is the $n \times p$ matrix such that the $i^{th}$ row of $Q$ is $q_i$, then $Q$ can be succinctly expressed as $X\Sigma^{-\frac{1}{2}}$. This and the previous results imply that
$$D_{k\ell} = \sum_{i=1}^p (Q_{ki}-Q_{\ell i})^2.$$
the only operations that are computed $n(n-1)/2$ times are $p$ multiplications and $2p$ additions (as opposed to the $p^2+p$ multiplications and $p^2+2p$ additions in the above method), resulting in an algorithm that is of computational complexity order $O(pn^2 + p^2n)$ instead of the original $O(p^2n^2)$.
require(ICSNP) # for pair.diff(), C implementation

fastPwMahal = function(data) {

    # Calculate inverse square root matrix
    invCov = solve(cov(data))
    svds = svd(invCov)
    invCovSqr = svds$u %*% diag(sqrt(svds$d)) %*% t(svds$u)

    Q = data %*% invCovSqr

    # Calculate distances
    # pair.diff() calculates the n(n-1)/2 element-by-element
    # pairwise differences between each row of the input matrix
    sqrDiffs = pair.diff(Q)^2
    distVec = rowSums(sqrDiffs)

    # Create dist object without creating a n x n matrix
    attr(distVec, "Size") = nrow(data)
    attr(distVec, "Diag") = F
    attr(distVec, "Upper") = F
    class(distVec) = "dist"
    return(distVec)
}

Comment: Interesting. Sorry, I don't know R. Can you expain what `pair.diff()` does and also give a numeric example with printouts of every step of your function? Thanks.
Comment: I edited the answer to include the derivation justifying these calculations, but I also posted a second answer containing code that is much more concise.
Answer: Let's try the obvious.  From
$$D_{ij} = (x_i-x_j)^\prime \Sigma^{-1} (x_i-x_j)=x_i^\prime \Sigma^{-1}x_i + x_j^\prime \Sigma^{-1}x_j -2 x_i^\prime \Sigma^{-1}x_j $$
it follows we can compute the vector
$$u_i = x_i^\prime \Sigma^{-1}x_i$$
in $O(p^2)$ time and the matrix
$$V = X \Sigma^{-1} X^\prime$$
in $O(p n^2 + p^2 n)$ time, most likely using built-in fast (parallelizable) array operations, and then form the solution as
$$D = u \oplus u - 2 V$$
where $\oplus$ is the outer product with respect to $+$: $(a \oplus b)_{ij} = a_i + b_j.$
An R implementation succinctly parallels the mathematical formulation (and assumes, with it, that $\Sigma=\text{Var}(X)$ actually is invertible with inverse written $h$ here):
mahal <- function(x, h=solve(var(x))) {
  u <- apply(x, 1, function(y) y %*% h %*% y)
  d <- outer(u, u, `+`) - 2 * x %*% h %*% t(x)
  d[lower.tri(d)]
}

Note, for compability with the other solutions, that only the unique off-diagonal elements are returned, rather than the entire (symmetric, zero-on-the-diagonal) squared distance matrix.  Scatterplots show its results agree with those of fastPwMahal.
In C or C++, RAM can be re-used and $u\oplus u$ computed on the fly, obviating any need for intermediate storage of $u\oplus u$.
Timing studies with $n$ ranging from $33$ through $5000$ and $p$ ranging from $10$ to $100$ indicate this implementation is $1.5$ to $5$ times faster than fastPwMahal within that range. The improvement gets better as $p$ and $n$ increase.  Consequently, we can expect fastPwMahal to be superior for smaller $p$.  The break-even occurs around $p=7$ for $n\ge 100$.  Whether the same computational advantages of this straightforward solution pertain in other implementations may be a matter of how well they take advantage of vectorized array operations.
Comment: Looks good. I assume it could be made even more rapid by only calculating the lower diagonals, although I can't off-hand think of a way to do this in R without losing the speedy performance of `apply` and `outer`... except for breaking out `Rcpp`.
Comment: apply/outer have *no* speed advantage over plain-vanilla loops.
Comment: @user603 I understand that in principle--but do the timing. Moreover, the main point of using these constructs is to provide semantic help for parallelizing the algorithm: the difference in how they *express* it is important. (It may be worth recalling the original question seeks C/Fortran/etc. implementations.)  Ahfoss, I thought about limiting the calculation to the lower triangle too and agree that in `R` there seems to be nothing to gain by that.
Answer: If you wish to compute the sample Mahalanobis distance, then there are some algebraic tricks that you can exploit.  They all lead to computing pairwise Euclidean distances, so let's assume we can use dist() for that. Let $X$ denote the $n\times p$ data matrix, which we assume to be centered so that its columns have mean 0 and to have rank $p$ so that the sample covariance matrix is nonsingular.  (Centering requires $O(np)$ operations.) Then the sample covariance matrix is $$S = X^T X / n.$$
The pairwise sample Mahalanobis distances of $X$ is the same as the pairwise Euclidean distances of $$X L$$ for any matrix $L$ satisfying $LL^T = S^{-1}$, e.g. the square root or Cholesky factor.  This follows from some linear algebra and it  leads to an algorithm requiring the computation of $S$, $S^{-1}$, and a Cholesky decomposition.  The worst case complexity is $O(np^2 + p^3)$.
More deeply, these distances relate to distances between the sample principal components of $X$.  Let $X=UDV^T$ denote the SVD of $X$.  Then $$S=VD^2V^T/n$$ and $$S^{-1/2}=VD^{-1}V^T n^{1/2}.$$ So $$X S^{-1/2} = UV^T n^{1/2}$$ and the sample Mahalanobis distances are just the pairwise Euclidean distances of $U$ scaled by a factor of $\sqrt{n}$, because Euclidean distance is rotation invariant. This leads to an algorithm requiring the computation of the SVD of $X$ which has worst case complexity $O(n p^2)$ when $n>p$.
Here is an R implementation of the second method which I cannot test on the iPad I am using to write this answer.
u = svd(scale(x, center = TRUE, scale = FALSE), nv = 0)$u
dist(u)
# these distances need to be scaled by a factor of n

Answer: This is a much more succinct solution. It is still based on the derivation involving the inverse square root covariance matrix (see my other answer to this question), but only uses base R and the stats package. It seems to be slightly faster (about 10% faster in some benchmarks I have run). Note that it returns Mahalanobis distance, as opposed to squared Maha distance.
fastPwMahal = function(x1,invCovMat) {
  SQRT = with(svd(invCovMat), u %*% diag(d^0.5) %*% t(v))
  dist(x1 %*% SQRT)
}

This function requires an inverse covariance matrix, and doesn't return a distance object -- but I suspect that this stripped-down version of the function will be more generally useful to stack exchange users.
Comment: This could be improved by replacing `SQRT` with the Cholesky decomposition `chol(invCovMat)`.
Answer: I had a similar problem solved by writing a Fortran95 subroutine. As you do, I didn't want to calculate the duplicates among the $n^2$ distances. Compiled Fortran95 is nearly as convenient with basic matrix calculations as R or Matlab, but much faster with loops. The routines for Cholesky decompositions and triangle substitutions can be used from LAPACK.
If you only use the Fortran77-features in the interface, your subroutine is still portable enough for others.
Answer: The formula you have posted is not computing what you think you are computing (a U-statistics).
In the code I posted, I use cov(x1) as scaling matrix (this is the variance of the pairwise differences of the data). You are using cov(x0) (this is the covariance matrix of your original data). I think this is a mistake in your part. The whole point of using the pairwise differences is that it relieves you from the assumption that the multivariate distribution of your data is symmetric around a centre of symmetry (or to have to estimate that centre of symmetry for that matter, since crossprod(x1) is proportional to cov(x1)). Obviously, by using cov(x0) you lose that.
This is well explained in the paper I linked to in my original answer.
Comment: I think we're talking about two different things here. My method calculates Mahalanobis distance, which I've verified against a few other formulas. My formula has also now been independently verified by `Matteo Fasiolo` and (I assume) `whuber` in this thread. Yours is different. I'd be interested in understanding what you are calculating, but it is clearly different from the Mahalanobis distance as typically defined.
Comment: @ahfoss: 1) mahalanobis is the distance of the X to a point of symmetry in their metric. In your case, the X are a n*(n-1)/2 matrix od pairwise differences, their center of symmetry is the vector 0_p and their metric is what I called cov(X1) in my code. 2) ask yourself why you use a U-statistic in the first place, and as the paper explains you will see that using cov(x0) defeats that purpose.
Comment: I think this is the disconnect. In my case the $X$ are the rows of the observed data matrix (not distances), and I am interested in calculating the distance of every row to each other row, *not* the distance to a center. There are at least three "scenarios" in which Mahalanobis distance is used: [1] distance between distributions, [2] distance of observed units from the center of a distribution, and [3] distance between pairs of observed units (what I am referring to). What you describe resembles [2], except that $X$ in your case are the pairwise distances with center $O_p$.
Comment: After looking at the [Croux et al. 1994](https://lirias.kuleuven.be/bitstream/123456789/205831/1/gs.pdf) paper you cite, it is clear they discuss Mahalanobis distance in the context of outlier diagnostics, which is scenario [2] in my post above, although I will note that `cov(x0)` is typically used in this context, and seems to be consistent with Croux et al.'s usage. The paper does not mention [U-statistics](http://en.wikipedia.org/wiki/U-statistic), at least not explicitly. They do mention $S$-, $GS$-, $\tau$-, and $LQD$-estimators, perhaps you are referring to one of these?
Answer: There a very easy way to do it using R Package "biotools". In this case you will get a Squared Distance Mahalanobis Matrix.
#Manly (2004, p.65-66)

x1 <- c(131.37, 132.37, 134.47, 135.50, 136.17)
x2 <- c(133.60, 132.70, 133.80, 132.30, 130.33)
x3 <- c(99.17, 99.07, 96.03, 94.53, 93.50)
x4 <- c(50.53, 50.23, 50.57, 51.97, 51.37)

#size (n x p) #Means
x <- cbind(x1, x2, x3, x4)

#size (p x p) #Variances and Covariances
Cov <- matrix(c(21.112,0.038,0.078,2.01, 0.038,23.486,5.2,2.844,
        0.078,5.2,24.18,1.134, 2.01,2.844,1.134,10.154), 4, 4)

library(biotools)
Mahalanobis_Distance<-D2.dist(x, Cov)
print(Mahalanobis_Distance)

Comment: Can you please explain me what a squared distance matrix means? Respectively: I'm interested in the distance between two points/vectors so what does a matrix tell?
Answer: This is the expanded with code my old answer moved here from another thread.
I've been doing for a long time computation of a square symmetric matrix of pairwise Mahalanobis distances in SPSS via a hat matrix approach using solving of a system of linear equations (for it is faster than inverting of covariance matrix).
I'm not R user so I've just tried to reproduce @ahfoss' this recipe here in SPSS along with "my" recipe, on a data of 1000 cases by 400 variables, and I've found my way considerably faster.

A faster way to calculate the full matrix of pairwise Mahalanobis distances is through hat matrix $\bf H$. I mean, if you are using a high-level language (such as R) with quite fast matrix multiplication and inversion functions built in you will need no loops at all, and it will be faster than doing casewise loops.
Definition. The double-centered matrix of squared pairwise Mahalanobis distances is equal to $\mathbf{H}(n-1)$, where the hat matrix is $\bf X(X'X)^{-1}X'$, computed from column-centered data $\bf X$.
So, center columns of the data matrix, compute the hat matrix, multiply by (n-1), and perform operation opposite to double-centering. You get the matrix of squared Mahalanobis distances.
"Double centering" is the geometrically correct conversion of squared distances (such as Euclidean and Mahalanobis) into scalar products defined from the geometric centroid of the data cloud. This operation is implicitly based on the cosine theorem. Imagine you have a matrix of squared euclidean distances between your multivariate data poits. You find the centroid (multivariate mean) of the cloud and replace each pairwise distance by the corresponding scalar product (dot product), it is based on the distances $h$s to centroid and the angle between those vectors, as shown in the link. The $h^2$s stand on the diagonal of that matrix of scalar products and $h_1h_2\cos$ are the off-diagonal entries. Then, using directly the cosine theorem formula you easily convert the "double-centrate" matrix back into the squared distance matrix.
In our settings, the "double-centrate" matrix is specifically the hat matrix (multiplied by n-1), not euclidean scalar products, and the resultant squared distance matrix is thus the squared Mahalanobis distance matrix, not squared euclidean distance matrix.
In matrix notation: Let $H$ be the diagonal of $\mathbf{H}(n-1)$, a column vector. Propagate the column into the square matrix: H= {H,H,...}; then $\mathbf {D_{mahal}^2} = H+H'-2 \mathbf{H}(n-1)$.
The code in SPSS and speed probe is below.

This first code corresponds to @ahfoss function fastPwMahal of the cited answer. It is equivalent to it mathematically. But I'm computing the complete symmetric matrix of distances (via matrix operations) while @ahfoss computed a triangle of the symmetric matrix (element by element).
matrix. /*Matrix session in SPSS;
        /*note: * operator means matrix multiplication, &* means usual, elementwise multiplication.
get data. /*Dataset 1000 cases x 400 variables
!cov(data%cov). /*compute usual covariances between variables [this is my own matrix function].
comp icov= inv(cov). /*invert it
call svd(icov,u,s,v). /*svd
comp isqrcov= u*sqrt(s)*t(v). /*COV^(-1/2)
comp Q= data*isqrcov. /*Matrix Q (see ahfoss answer)
!seuclid(Q%m). /*Compute 1000x1000 matrix of squared euclidean distances;
               /*computed here from Q "data" they are the squared Mahalanobis distances.
/*print m. /*Done, print
end matrix.

Time elapsed: 3.25 sec

The following is my modification of it to make it faster:
matrix.
get data.
!cov(data%cov).
/*comp icov= inv(cov). /*Don't invert.
call eigen(cov,v,s2). /*Do sdv or eigen decomposition (eigen is faster),
/*comp isqrcov= v * mdiag(1/sqrt(s2)) * t(v). /*compute 1/sqrt of the eigenvalues, and compose the matrix back, so we have COV^(-1/2).
comp isqrcov= v &* (make(nrow(cov),1,1) * t(1/sqrt(s2))) * t(v). /*Or this way not doing matrix multiplication on a diagonal matrix: a bit faster .
comp Q= data*isqrcov.
!seuclid(Q%m).
/*print m.
end matrix.

Time elapsed: 2.40 sec

Finally, the "hat matrix approach". For speed, I'm computing the hat matrix (the data must be centered first) $\bf X(X'X)^{-1}X'$ via generalized inverse $\bf (X'X)^{-1}X'$ obtained in linear system solver solve(X'X,X').
matrix.
get data.
!center(data%data). /*Center variables (columns).
comp hat= data*solve(sscp(data),t(data))*(nrow(data)-1). /*hat matrix, and multiply it by n-1 (i.e. by df of covariances).
comp ss= diag(hat)*make(1,ncol(hat),1). /*Now using its diagonal, the leverages (as column propagated into matrix).
comp m= ss+t(ss)-2*hat. /*compute matrix of squared Mahalanobis distances via "cosine rule".
/*print m.
end matrix.

[Notice that if in "comp ss" and "comp m" lines you use "sscp(t(data))",
 that is, DATA*t(DATA), in place of "hat", you get usual sq.
 euclidean distances]

Time elapsed: 0.95 sec

Pairwise Mahalanobis distances


Windows 7 caches FTP credentials?

Question: On my remote machine I have an IIS 7.5 (Windows Server 2008). I set up an ftp site with IIS Manager authentication. I then did Active Directory user isolation and isolated my users to physical folders according to their names. So far, so good. I can access with FTP clients from everywhere with different test accounts that I previously set up in the IIS Manager authentication. Every user connects to its own folder.
When I now tested with windows 7 as a client, I did the following:
Explorer -> computer -> right click -> add network address -> the ip of my remote machine -> user1 -> password1
Perfect - it works. I now want to connect with user2. So I deleted this network address and set up a new connection, but with user2 (or even anonymous) instead. Now the strange thing: Windows doesn't even ask me for a password again. It just connects me to the folder of the user1.
I already disabled FTP caching in the IIS and I disabled the user1 account in IIS manager authentication! Still, if I set up a network connection with this windows 7, it connects to the folder user1, no matter which username I use (anonymous, administrator, user2,...).
And if I connect with other ftp clients or other computers, it all works perfectly. So I assume that this one Windows somehow caches the credentials... but then, how can I keep IIS from still accepting these credentials even if I have disabled the user1 account?
Comment: sorry, but you didn't read my post :) every "normal" ftp client works except the windows explorer. And sadly enough my client wants to have the "ftp folder" right next to her hard drives.
Comment: Have you tried using an incognito Window?
Answer: Have you checked the Credential Manager in Windows to see if it is storing something in there?
Start -> Control Panel -> Credential Manager

or if it the Control Panel is in Category View
Start -> Control Panel -> User Accounts and Family Safety -> Credential Manager

I would start there to see if there are any credentials stored that seem to match the credentials it is using.
Comment: I did already. There is absolutely nothing stored.

Windows 7 caches FTP credentials?


How to get values from any row in the mutator module after editing table?

Question: I'm having problems getting the values from the first three rows of table after user edits table.
Table should award points to columns "pts1, pts2,… ptsn" (Points awarded) by matching columns "sp1, sp2,… spn" (selected pilot) and column "ro" (official results).
1.- If "spn" value match "ro" in same row, user gets points from column "po" (official points by pilot's place).
2.- Else if "spn" value is in podium (first 3 rows) then user gets only 2 points for any value that matches and did not met first condition.
3.- Else user gets 0 points.
Column "ro" can be edited by user to make predictions.
Problem:
If table is edited on page by user then mutator will process 1st and 3rd conditions ok, but won't process second condition, so it never awards the 2 points. Console log results in undefine on var podium. This does not happens if "ro" values are loaded so I guess the logic works.
Look everywhere and cant figure this one out, what could I be missing?.
Here is my sample Code:
<code>var tabledata = [
    {id:1, ro:'', op: 25, sp1:"HAM", pts1:''},
    {id:2, ro:'', op: 18, sp1:"VER", pts1:''},
    {id:3, ro:'', op: 15, sp1:"BOT", pts1:''},
    {id:4, ro:'', op: 12, sp1:"PER", pts1:''},
    {id:5, ro:'', op: 10, sp1:"RIC", pts1:''},
    {id:6, ro:'', op: 8, sp1:"ALO", pts1:''} // table is only 10 rows first 10 pilots

];

var table = new Tabulator("#pronosticos", {
    height:"310px",
    dataTree: true,
    reactiveData:true,
    data:tabledata,
    dataChanged:function(data){
        document.getElementById("bt-puntaje").style.display="inline-block";
    },
    cellHozAlign:"center",
    layout:"fitColumns",
    columns:[
            {title:"POS", field: "pos", formatter:"rownum", width:40, frozen:true},
            {title:"RES PRE", field:"ro", width:70, frozen:true, editable:true, editor:'autocomplete',
                editorParams: {
                    allowEmpty:true,
                    showListOnEmpty:true,
                    values:["ALO", "BOT", "GAS", "GIO", "HAM","LAT","LEC","MAZ","NOR", "OCO", "PER", "RAI", "RIC", "RUS", "SAI", "MCH", "STR", "TSU", "VET", "VER"] // list of pilots to select
                },

            {title:"PTS", field:"op", width:40, frozen:true, visible:false},

//          *****************************************    sp1   *****************************************
            {title:"PN", headerTooltip: "Players Name",
                columns:[
                {title:"SEL", field:"sp1", width:50},
                {title:"PTS", field:"pts1", bottomCalc:"sum", width:10,
                    mutator:function(value, data){
                        var selected = data.sp1;
                        var winner = data.ro;
                        var podium = [tabledata[0].ro, tabledata[1].ro, tabledata[2].ro]; // Error Undefine if table edited
                        if(selected === ""){
                            return
                        } else {
                            if(podium.length > 0){
                                    if(selected == winner){
                                        return data.op; // This part works ok
                                    } else {
                                        if(podium.includes(selected) && data.id < 4){
                                            return 2; // this part does not work
                                        } else {
                                            return 0;}}}}}

                ]
            },
        ],
    });

    $("#bt-puntaje").click(function () {
        table.updateData(tabledata);
    });

</code>
Answer: Ok, just resolved my issue, was loading a second table in the same page with both the same generic structure. Changed this table's var name from tabledata to tabledata2 and table to table2 and works ok. Tabulator is very nice, excited to learn more about its functionality. Best regards to the creator and to all the community.


How to redirect to l() function link after login?

Question: I'm having a Simplenews newsletter template with a link guiding newsletter readers to a intranet site with more news.
<?php print l('hier.', 'node/' . $build['#node']->nid, array('absolute' => TRUE)); ?>

My problem now is, that if the user is not logged in, that link only brings him to the login site, where he is then stucked.
What would I have to do or what function would help me to somehow provide a link that redirects the not logged in user to the proper aim after logging in, and which would not affect the already logged in user?
Comment: nit3ch's correct answer putted on the questioned snippet: ` array( 'destination' => 'node/' . $build['#node']->nid))); ?>`
Answer: You can add a additional destination parameter to the function.
<?php
print l(t('Title'), 'url', array('query' => array('destination' => 'destination_url')))
?>

This will create :
Title

Hope it helps.
Comment: or just to previous page: `print l(t('Title'), 'url', array('query' => drupal_get_destination()));`
Comment: @nit3ech - Is `destination` also making the link automatically `absolute`? Seems to...