Probability and Venn Diagram

Question: There are 35 children in a class. Among them, 18 like red, 16 like blue and 20 like green. These counts include 10 children who like blue and at least one of the other colours. Two children don't like any of the colours and five children like all 3 colours. How many children like red and also like green?
My method
I tried using a Venn diagram to help visualise this question but I still can't see a way to continue from there.

And the numbers don't seem to add up too. Does anyone know how to solve this? Thanks in advance.
Answer: If you take out $2$ children who do not like any of the colors and $5$ children who like all three colors, using your venn diagram,
$(15 - x - z) + (13 - x - y) + (11- y - z) + (x + y + z) = 35 - 5 - 2$
$x + y + z = 11$
Also we have been given,
$y + z + 5 = 10$
So, $x = 6$. Then including $5$ children who like all three colors, we have in total $11$ children who like red and also like green.
Answer: Call $y$ the number of children who like red and green.
Firstly, if $16$ people like blue and $10$ children like blue as well as at least one other color, then $16-10=6$ children like only the color blue.
Now, on the one hand, the number of children who like red or green is given by
$18+20-y$ ("red" + "blue" - "red and blue"), which equals $38-y$.
On the other hand, among the $33$ children who like some color, there are $33-6=27$ who like at least one of red or green (since $6$ children like only blue).
In total, we get
$$38-y=27,$$
so that $$y=11.$$

Probability and Venn Diagram


Intermediate question on calculus

Question: Let $f$ be twice continuously differentiable on $[-1,1]$. Assume that $f(-1)=f'(0)=0$. Show that there exists some $\xi\in (-1,1)$ such that $$f(1)=\frac{1}{3}f''(\xi).$$
I have no idea after two days' thinking...
I should say sorry that I have corrected the problem as $f'(0)=0$, no $f(0)=0$...It is not difficult for the case $f(-1)=f(0)=0$ for some intermediate value, but possibly not $1/3$.
Comment: Do you mean $f$ when you write $F$?
Comment: I'd try a power series expansion at zero, getting a coefficient, shift it to -1, getting another coefficient.  The remainder of the problem should be straightforward.
Comment: How does the right hand endpoint of the interval relate to the question ? There must be some assumption about it.
Answer: This is not true. Consider $f(x)=x(x+1)$. This has $f''(x)=2$ and $f(1)=2$, and $2 \neq 2/3$.
Comment: there might be other zeros. If not, then you're correct +1.
Comment: @Ian I have changed the problem...I am sorry.
Comment: @VarunIyer It only takes one for a counterexample :)
Answer: $$ (1) \ \exists c \in (-1,1): f'(c) = \frac{f(1)-f(-1)}{1-(-1)}=\frac{f(1)-0}{2} \ \ \ , (\text{Mean Value})$$
$$ (2) \ \exists d \in (-1,c): f''(d) = \frac{f'(c)-f'(-1)}{c+2} = \frac{f'(c)}{c+2} = \frac{f(1)}{2(c+2)} \Rightarrow 2(c+2)f''(d) = f(1)$$
Your prompt is not true, but if you would like to see what is true and how to use mean value, here you go. I did the second WLOG for differentiability on $(-1,c)$ or $(c,1)$. I did this so you could see the fallacy in the argument. Solve $2(c+2)= \frac{1}{3}$ and we see that our choice of "$c$" couldn't possibly lie in our domain.
Comment: I have changed the problem...I am sorry.
Comment: It's fine. Just correct the problem in the question and i can edit if necessary.
Answer: The modified prompt is also false. Consider $f(x)=x^2-1$, then $f''(x)=2$ and $f(1)=0$, and $0 \neq 2/3$.

Intermediate question on calculus


Intellij Idea - how to maintain multiple versions of the package in one project?

Question: I have case as follows and don't know if there is any conveninet solution:
I wrote some set of sources and put them in into a package.
Next, I refactored it deeply for performance reasons.
Now, I have new version which contains at least one bug, that I have to find.
I would like to have both version of my package in one project and easily switch between them
when I compile and run test application.
Of course I can compile both of them and choose in runtime because of names conflicts.
Is it any smart way to solve this?
Comment: Sounds like version control would help you here.
Answer: You are looking for a version control system (which is supported through intellij IDEA).
Try git, they have good support in IDEA.
http://www.jetbrains.com/idea/webhelp/using-git-integration.html
http://www.jetbrains.com/idea/features/version_control.html
Here is a good link for git / vcs tutorials.
http://sixrevisions.com/resources/git-tutorials-beginners/
Comment: Currently I use bzr from outside IJ. I wonder if VCS used from IJ can serve me without need to copy/paste branches addresses or revision numbers each time. I would like to have some one-click-switch
Comment: With IntelliJ you have a dropdown in lower right corner, just pick whichever branch you want to use and IntelliJ will switch to that branch right away.


How to change the text of navigationItem.leftBarButtonItem for iPhone

Question: How do I change the text value navigationItem.leftBarButtonItem?
In view A I did self.title=@"hi"
So when I go to B my back button has the text @"hi". now I want to change it to back
How do I do that?
Answer: UIBarButtonItem *backButton = [[UIBarButtonItem alloc] initWithTitle:@"blah blah blah" style:UIBarButtonItemStylePlain target:nil action:nil];
self.navigationItem.backBarButtonItem = backButton;
[backButton release];

you can use this in view A and enter any text you want
Comment: awesome thanks a lot i was trying same thing but in View B . never thought of A  :(  you saved me :-)


Replace em angularJs

Question:

Essa criação poderosa - forjada à imagem de uma gárgula - o
   manteve

 seguro em suas jornadas, permitindo que ele
   desempenhasse seu importante trabalho sem medo de retaliações daqueles
   hostis à sua terra natal.

 Isso é, até despertar a ira do
   Alto Comando Noxiano com suas sentinelas.

Usando {{content.lore}} no meu html exibo o texto acima. Quando tento usar content.lore.replace("
", "") as palavras
 não são substituidas. Como posso fazer para substituí-las?
Comment: Poste um trecho do código javascript que você possui, se possível.
Comment: Achei a solução no SO, coloco aqui ou apago a pergunta?
Comment: Responda sua própria pergunta, ela pode ser a dúvida de outros usuários (:
Answer: Uma das maneiras é usando um filtro que converte o HTML para texto:
app.filter('htmlToText', function(){
  return function(html){
     return angular.element('
').append(html || '').text();
  };
});

Na view:
{{content.lore | htmlToText}}

Replace em angularJs


Tem como referenciar um enum dentro dele mesmo em Python?

Question: Gostaria de usar uma constante que criei em um enum como um atributo de outra, por exemplo:
from enum import Enum

class Jokenpo(Enum):
    PEDRA = ('Rock', [Jokenpo.PAPEL], [Jokenpo.TESOURA])
    PAPEL = ('Paper', [Jokenpo.TESOURA], [Jokenpo.PEDRA])
    TESOURA = ('Scissors', [Jokenpo.PEDRA], [Jokenpo.PAPEL])

    def __init__(self, nome, fraco, forte):
        self.nome = nome
        self.fraco = fraco
        self.forte = forte

Em um jogo de pedra-papel-tesoura, para especificar que pedra perde para papel mas vence tesoura posso fazer algo parecido com isso. Provavelmente meu enum possui alguns erros, sou iniciante, mas tem como usar uma constante dentro de outra?
Comment: Soa como [o problema XY](https://pt.meta.stackoverflow.com/questions/499/o-que-%c3%a9-o-problema-xy). Eu analiso que você quer implementar a lógica do jogo, em vez de realmente ter essa dúvida sobre enums.
Answer: Tem, mas não da maneira que você está fazendo, embora não seja realmente um problema criar um enumerável a partir de tuplas, mas a lógica, em si, ficou bastante estranha.
Tendo em mente que cada valor do Enum será uma instância do próprio Enum, você pode definir uma propriedade que retorna a fraqueza e força de cada item. Por exemplo:
from enum import Enum

class Jokenpo(Enum):
    PEDRA = 1
    PAPEL = 2
    TESOURA = 3

    @property
    def weakness(self):
        if self == self.PEDRA:
            return self.PAPEL
        elif self == self.PAPEL:
            return self.TESOURA
        else:
            return self.PEDRA

print(Jokenpo.PEDRA.weakness)  # Jokenpo.PAPEL
print(Jokenpo.PAPEL.weakness)  # Jokenpo.TESOURA
print(Jokenpo.TESOURA.weakness)  # Jokenpo.PEDRA

Veja funcionando no Repl.it | Ideone | GitHub GIST


Guitar beginner - What does this card show?

Question: I am a  beginner (just had 4 hours with a teacher) and I bought something where I can read the notes for the fretboard to better learn them. Also there was a card included with the following prints:

The upper one is clear to me, it shows the notes on the fingerboard at which place etc.
But I have no clue how I should read the lower one. Can someone explain that to me? How can I read it? What does it show?
Comment: See https://en.wikipedia.org/wiki/Nashville_Number_System
Comment: Thanks, @dom.  What is the difference between what's shown and the Nashville number system, besides using roman numerals vs arabic numerals?
Comment: A couple of things seem off to me on that (second) card.  The row labelled "F/F#" should actually be "F/E#" (or just plain "F").  As for the row labelled "Cb/C#", I'm not quite sure what they were going for (maybe "B/Cb", but they already have a "B" row).  If there's any row that warrants a slash, I would think that it should be the "Gb" row (which should be listed as "F#/Gb").  That way the card better matches the Circle of Fifths.  (Maybe they did it to save space, but the 13 rows they used is one more than the usual 12 needed for the Circle of Fifths.  Looks more like a typo to me.)
Comment: @default that's not the Nashville number system, that system never uses Roman Numerals.
Comment: @default I suggest asking that as a question on this site as I could not find it on the site and it's a question we should answer.
Comment: @dom - https://music.stackexchange.com/q/88566/23859
Comment: @J-L The row labelled F/F♯ is correct. It shows two keys F major and F♯ major and the corresponding chords. Similar with C♭/C♯. See my answer where I elaborate on this.
Answer: The lower card shows the chords that go with the tones in each key. The chords built on tones of a scale are often referred to by roman numerals, for example, the root tone is the I, the next tone in the scale is II (or ii, if the chord is minor), the fifth is V etc. Often, chord progressions are referred to by these numerals, like the Blues progression: I-IV-I-V-IV-I. In that way, you can discuss the functions of chords in a piece, independent of the key that it is transposed to.
The card shows you how to translate that back to concrete notes and chords in a given key. So when you're in the key of A major, you find the row that has "A" in the first column, and then look up the columns that have the right numbers. In this example, the Blues progression translates to A-D-A-E-D-E. If you want to play a blues in F, it would be F-Bb-F-C-Bb-F.
For each note in a key, you can build a triad consisting of the notes in the scale - the so-called diatonic chords. The card also shows you what kind of chord you get in major scales: without extra symbols next to the chord, you get a major chord. The "m" next to the note refers to minor triad. The "o" refers to diminished triads.
Comment: Ok, I think I understand. A rather more advanced topic for me. Still training to get a smoother transition between two chords :) Thank you for the explanation!
Answer: Just to complement Richard's fine answer, the name for this kind of chart is Harmonization of the Major Scale (in all 12 keys).
Answer: Here is an elaboration to @Richard Metzler's answer regarding the keys on the lower card:
The card actually shows 15 keys.
C major is one key.
1-7 sharps make 7 keys.
1-7 flats also make 7 keys.
Total 15 keys.
But there are only 13 rows because two rows each have two keys. I guess that is because the size of the card doesn't allow space for 15 rows, otherwise I don't know why there aren't 15 rows.
Anyway, the row that says C♭/C♯ shows two keys. On the left side of the dash is C♭ major and all the chords belonging to C♭ major are on the left side of the dashes. On the right side of the dash you have C♯ major and the coresponding chords are on the right side of the dashes.
Similar with the last row F/F♯. Two keys F major and F♯ major.


When finding residues, is there a way/approach that simplifies the computations below?

Question: I have $f(z)=\frac{z^{2}}{1+z^{4}}$, which has poles the fourth roots of $-1$: $$
 a_{n} = \exp \biggl(i\biggl[ \frac{\pi}{4}+(n-1)\frac{\pi}{2} \biggr]   \biggr), \quad n=1,2,3,4,
$$   and I want to compute $\mathrm{Res}(f; a_1)=\lim_{z\to a_1} \frac{a_1^{2}}{(a_1-a_2)(a_1-a_3)(a_1-a_4)}$.
How can I find the residue without doing a lot of tedious computations?
My approach has been to use Euler's formula but the computations that I do end up being very tedious and time consuming. I want to be able to do these computations in an exam setting (without calculators). How do the experts approach this? Can someone show me their detailed computations, please?
I skipped doing alot of these before but now that I have to do a lot of them to find resides, I wish I could learn some technique that would simplify my life a little.
The answer, by the way, is  $\mathrm{Res}(f, a_1)=\frac{1}{4}\exp\biggl( -\frac{i\pi}{4} \biggr)$.
Answer: What I do is this.
Let $\zeta=z-a_1$.
We want the coefficient of $\zeta^{-1}$ in $\dfrac{(\zeta+a_1)^2}{1+(\zeta+a_1)^4}$,
which is the coefficient of $1$ in
$$
\frac{\zeta(\zeta+a_1)^2}{1+(\zeta+a_1)^4} = \frac{a_1^2\zeta+O(\zeta^2)}{(1+a_1^4)+4a_1^3\zeta+O(\zeta^2)}=\frac{a_1^2+O(\zeta)}{4a_1^3+O(\zeta)},
$$
that is $\dfrac{1}{4a_1}$.
Comment: Thank you so much. Very helpful.
Answer: The quick shortcut is that if $f(z)= \frac{g(z)}{h(z)}$  then at each  simple pole of $f$,  $Res[ f,z_0] =\frac{ g(z)}{h'(z)}$.
In your example this becomes $Res[f]= \frac{ z^2}{ 4 z^3} =\frac{1}{4} z^{-1}$.
PS. This formula works except in unusual cases when $z_0$ is a pole of order two or more.
In such cases you can tell that more work is needed, because the shortcut formula will degenerate to an undefined expression involving  division by zero.  If you ever encounter a double pole you can search online to find the more complicated formula  that covers that case.


Query does not change

Question: I've got a problem with hook_views_query_alter().
I want to override the view's query with a rather complex one. In the first step, I placed the hook in my views.inc and tested it. The hook is called. But none of my tests to alter the query worked.
function glass_lagermanagement_views_query_alter(&$view, &$query) {
  if ($view->name == 'lagerbestand') {
    $query = db_select('materials');
    $query->condition('materials.ID', 1, '==');
  }
}

To test the function, I want to show only one entry which has got the ID "1", but nothing happens at all in the view. What am I doing wrong?
I'm using Drupal 7 here. It is an old project I need to update.
Answer: I got it.
I used this code to alter the query and it worked.
$query->where[1]['conditions'][0] = array('field'=>"materials.ID","value"=>'1',"operator"=>"LIKE");

Answer: Based on the documentation of hook_views_query_alter you can change the condition by using the following code :
foreach ($query->where as &$condition_group) {
  foreach ($condition_group['conditions'] as &$condition) {
    // If this is the part of the query filtering on title, change the
    // condition to filter on node ID.
    if ($condition['field'] == 'node.title') {
      $condition = array(
        'field' => 'node.nid',
        'value' => $view->exposed_raw_input['title'],
        'operator' => '=',
      );
    }
  }

Which means that in your case :
//foreach
if ($condition['field'] == 'materials.ID') {
  $condition = array(
    'field' => 'materials.ID',
    'value' => 1,
    'operator' => '=',
  );
}

You can also check this post for another way.
Comment: Thank you for your answer.
Sadly it still does not work. I tried other fields and values, I deactivated and activated my module, cleared the cache several times but still the view does not change at all. The changes of the query are not called, the query still looks the same. I tried $query->orderby[0]['direction'] = "DESC"; and that worked. But the condition-changes wont. May there be a problem because the fields are from the data tables module? My code now looks like this: if($view->name == 'lagerbestand'){ $query->orderby[0]['direction'] = "DESC"; //works foreach ($query->where as &$conditi

Query does not change


phpPgAdmin: "Identificação desabilitada por motivos de segurança"

Question: Ao instalar o phpPgAdmin no Linux, aparece a seguinte mensagem: "Identificação desabilitada por motivos de segurança". O que pode ser?
Answer: Consegui resolver e estou compartilhando aqui a solução.
No diretório de instalação do phpPgAdmin (geralmente o caminho é: /usr/share/phppgadmin/conf/config.inc.php), abra o arquivo chamado config.inc.php e altere a seguinte linha:
De:
<code>$conf['extra_login_security'] = true;
</code>
Para:
<code>$conf['extra_login_security'] = false;
</code>
Após feitas as alterações reinicie o servidor web.


jQuery: Is there any reason not to store DOM elements in a variable instead of attaching them to the DOM?

Question: I've got a plug-in I'm working on which fetches a portion of a remote page, and saves that portion to be used in a jQuery UI dialog widget; originally I was attaching the HTML to the DOM and hiding it with display:none until it was called with $.dialog but I realized I could just leave the DOM node in a variable.
Is there any reason not to do this? Here's an example:
function makeDialogLink() {

    var HTML = $("
").load('file.html #container', function() {

        $('a#test').bind('click', function(e) {
            e.preventDefault();
            showDialog();
        });
    });

    function showDialog() {
        $(HTML).dialog({
            autoOpen : true,
            width  : opts.width,
            modal  : opts.modal,
            resizable : opts.resizeable,
            title  : opts.title
        });

        // some other stuff happens in here, and a setTimout
        closeDialog();
    }
    function closeDialog() {
        $(HTML).dialog('close');
    }
}

I've simplified this quite a bit from what I'm actually doing, but this encapsulates what my question is about pretty well.
As you can see I've loaded a portion of a remote document, I pop it up in a dialog, and close that dialog later, but I never directly attach the fetched HTML to the DOM ($.dialog does it at some point, of course).
Is there any reason to NOT do it this way? Seems a lot nicer then having to shove the HTML into a hidden DIV and then fetch it later. I'm just wondering if there's some pitfall I'm unaware of to using closures in javascript in this fashion.
Comment: You don't need to re-wrap your `HTML` variable with `$()` every time you use it. Once it's wrapped as a jQuery object, it will stay that way until you overwrite the variable in that scope.
Comment: A small note on code style. I notice you're using all caps for your HTML variable. Often all-caps indicates a constant. I'd use lower-case.
Answer: I can't think of any serious drawbacks to that. It may be a bit slower, since it's reattaching it to the DOM every time you need a dialog but it doesn't really matter since 1) the difference would not even be noticeable unless you're popping up hundreds of dialogs and 2) it may not be that much slower, if at all, than having a div that you toggle.
It seems like the best and cleanest solution. I would keep it if I were in your position.
Answer: Yes, you have to be careful about nodes which are not attached to the DOM.  IE is notoriously bad at leaking memory. (Scroll down to the section on cross-page leaks.)
Since you're creating an unattached DOM tree and then attaching it to the document (in showDialog()), I'd imagine your code leaks.  Of course, the only way to be sure is to get some profiling tools and find out.
A safer way to do this is to use a hidden div.
var HTML = $("#hiddenDiv").load('file.html #container');

Comment: I'm not sure if a memory leak problem is applicable. $.load is only getting called once for each element the plug-in operates on, but I'm going to read the article you linked :)
Comment: @Will: The DOM insertion order leak is a problem for any number of calls.  So, if the plugin operates on ten elements, you'll leak those ten elements.  Worse, you're actually leaking *across pages*: the leaked memory won't be freed until the browser is closed.
Answer: You can also just store the data from your ajax call as a string (use $.get or $.ajax instead). Only create the dom elements after the user clicks on the dialog button.


Taking node map from /map/node and using it on home page

Question: I need a google map block which would show all the nodes' location with markers. I noticed that Location module has this built in if I follow <code>/map/node</code> url. My question is, can I somehow take this map block and use it on my home page? Add it through blocks interface or by page components?
Answer: Just create an appropriate view, give that view some path that you like, and set that path as your homepage. To actually create such view with the kind of data your question is about,  have a look at the IP Geolocation Views & Maps module. Partial quote from its project page:

Despite what the name may suggest, IP Geolocation Views & Maps (IPGV&M) is first and foremost a mapping engine.
The module makes it very easy to create Views-based mapping solutions using the map renderer of your choice (Google, OpenLayers or Leaflet) with any location storage module of your choice, e.g.:

Get Locations,
Geofield,
Geolocation Field
Location.

This allows you to bring together modules and feature sets that without IPGV&M you would not be able to combine.
Like beautiful animated marker clustering on Google or Bing or Mapbox ... any of various map providers.
But more importantly IPGV&M adds some features you won't find as conveniently packaged elsewhere.
These include marker differentiation based on field values or ranges (2nd screenshot) with or without font icons, various centering options, super-imposing the current visitor's location, allowing multiple content types to be displayed on the same map, full screen button and mini-map inset (bottom screenshot), polygon support (Geofield), marker tags and tool tips and cross-highlighting of associated content on the page when markers are hovered (and vice versa).

Head over to its (impressive) project page for even more information about it. That project page also includes various screenshots.


Split-sample design

Question: I am currently working on a large data set containing about 9,000 observations belonging to different groups. Now, I would like to use a method called split-sample design to analyze this data. Let me explain in detail what I would like to do. My data has the following structure:
GroupID  Performance   Commitment   Affect   Size
1234     5             4            2        2
1234     6             8            9        2
2235     4             3            2        5
2235     4             3            2        5
2235     2             1            7        5
2235     2             1            7        5
2235     2             6            10       5
3678     3             5            5        4
3678     7             3            5        4
3678     5             2            6        4
3678     1             4            6        4

Now, I would like to aggregate this data in the following way: For each group, I would like to use the average performance score of the first half of the group and the average commitment and affect scores of the second half of the group to create one new observation (for uneven group sizes I would like to drop one random observation within the group - e.g. the last observation in a group - to create an even group size). However, I would like to do this in two steps. First, the data should look like this:
GroupID  Performance   Commitment   Affect   Size
1234     5             8            9        2
2235     4             1            7        5
2235     4             1            7        5
3678     3             2            6        4
3678     7             4            6        4

In the next step, I would like to aggregate the data. The new data set would have one observation per group and look like this:
GroupID  Performance   Commitment   Affect   Size
1234     5             8            9        2
2235     4             1            7        5
3678     5             3            6        4

Again, please note that the last observation of group 2235 was dropped, since the group size was an uneven number.
Is there any package out there that would split and aggregate my data in this way? If not, how would you go ahead and code this? I would be very grateful for any advice, since I have currently no idea how to elegantly approach this, other than writing a bunch of for loops.
Here is the code for the above example:
groupid <- c(1234, 1234, 2235, 2235, 2235, 2235, 2235, 3678, 3678, 3678, 3678)
performance <- c(5, 6, 4, 4, 2, 2, 2, 3, 7, 5, 1)
commitment <- c(4, 8, 3, 3, 1, 1, 6, 5, 3, 2, 4)
affect <- c(2, 9, 2, 2, 7, 7, 10, 5, 5, 6, 6)
size <- c(2, 2, 5, 5, 5, 5, 5, 4, 4, 4, 4)
mydata <- data.frame(groupid, performance, commitment, affect, size)

Many thanks!!
Comment: Have you tried anything on your own? `?aggregate`
Comment: I would start writing code in Matlab using a lot of 'for' loops, however, I thought there must surely be an easier way to do it in R. I have not used the aggregate function yet, but will look into it. Thanks!
Comment: I would split the data first, then use `aggregate` on both subsets, then put it back together.
Comment: [This post](http://stackoverflow.com/questions/3505701/r-grouping-functions-sapply-vs-lapply-vs-apply-vs-tapply-vs-by-vs-aggrega) may be useful to get started with the various aggregating functions in R.
Comment: Why do you need two steps? Also, you should be careful about your variable naming. `data` is an r function.
Comment: Could you please tell what will you do if you have only one observation for one of the groupID?
Comment: If I only have one observation in one group, I will just initially drop it from my sample, i.e. there will not be any groups with one observation. I would need to do it in two steps because I will have to run a couple of tests after the first step and before the aggregation.
Answer: Here is the solution:
library(plyr)
mydata1<-ddply(mydata,.(GroupID),summarize,aveper=mean(head((Performance),length(GroupID)/2)),
avecom=mean(tail((Commitment),length(GroupID)/2)),
aveaff=mean(tail((Affect),length(GroupID)/2)),avesiz=mean(Size))

> mydata1
  GroupID aveper avecom aveaff avesiz
1    1234      5  8.000      9      2
2    2235      4  2.667      8      5
3    3678      5  3.000      6      4

Update:
    mydata2<-ddply(mydata,.(GroupID),transform,aveper=mean(head((Performance),length(GroupID)/2)),
avecom=mean(tail((Commitment),length(GroupID)/2)),
aveaff=mean(tail((Affect),length(GroupID)/2)),avesiz=mean(Size),lengr=length(GroupID))

    > mydata2
   GroupID Performance Commitment Affect Size aveper avecom aveaff avesiz lengr
1     1234           5          4      2    2      5  8.000      9      2     2
2     1234           6          8      9    2      5  8.000      9      2     2
3     2235           4          3      2    5      4  2.667      8      5     5
4     2235           4          3      2    5      4  2.667      8      5     5
5     2235           2          1      7    5      4  2.667      8      5     5
6     2235           2          1      7    5      4  2.667      8      5     5
8     3678           3          5      5    4      5  3.000      6      4     4
9     3678           7          3      5    4      5  3.000      6      4     4
10    3678           5          2      6    4      5  3.000      6      4     4
11    3678           1          4      6    4      5  3.000      6      4     4

mydata2<-mydata2[-7,] # this assumes that you have already taken care of uneven groups
mydata3<-Map(function(x)head(mydata2[mydata2$GroupID==x,],head(mydata2$lengr[which(mydata2$GroupID==x)],1)/2),unique(mydata2$GroupID))

library(plyr)
mydata4<-ldply(mydata3)

mydata5<-mydata4[,c(1,6:9)]
> mydata5
  GroupID aveper avecom aveaff avesiz
1    1234      5  8.000      9      2
2    2235      4  2.667      8      5
3    2235      4  2.667      8      5
4    3678      5  3.000      6      4
5    3678      5  3.000      6      4

Comment: Perfect, thanks a lot! This is pretty much exactly what I needed (I can always figure out a way to drop the last observation of a group with an uneven number). However, is there a way to really do it in two steps as outlined above? I would need to run some tests on the data sample after step one and before the aggregation. Thanks again!
Comment: Yes, I think its possible. Instead of summarize, use `transform` and it will get back to your original dataframe with these additional cols. You can then work on.
Comment: Is there any way to get the data set into the exact format outlined above after step one - i.e. for group `2235` two observations with `4` in the performance column and `1`, `7` and `5` in the commitment, affect and size columns, respectively?
Comment: There should be.You can do subset. I will update if I have a solution.
Comment: Thanks! I have now coded it not very elegantly using for loops (see update in my original post), but it does the trick.
Comment: Great. You should post that as an answer and accept your answer.
Comment: See my updates which assumes that you have already taken into account uneven groupid for step 1. You can test which one is efficient and use accordingly.
Answer: I have now coded it the following way (rather brute force). Please let me know if you know a better way of getting the trick done. In the end, I have used the code provided by Metrics in one of the answers to aggregate my data (thanks for that again!):
ids <- unique(groupid)
pos <- 1
for (i in 1:length(ids)) {
    total <- mydata[pos,5]
    num <- floor(total/2)

    for (m in pos:(pos+num-1)) {
        mydata[m,-c(1,2)] <- mydata[m+num,-c(1,2)]
    }

    for (l in (pos+num):(pos+total-1)) {
        mydata[l,] <- NA
        print(l)
    }

    pos <- pos+total

}

mydata <- mydata[!is.na(mydata$groupid),]

mydata2<-ddply(mydata,.(groupid),summarize,aveper=mean(performance),avecomm=mean(commitment), aveaff=mean(affect), avesiz=mean(size))

Split-sample design


Amazon Route 53 domain mapping

Question: We have some EC2 instances running NGINX that will be accessed via a loadbalancer that can be reached via www.example.com. The loadbalancer redirects the traffic to the appropriate EC2 servers. This works fine, but sometimes we want to bypass the loadbalancer (to save money and increase data throughput). We connect on ip12-23-34-45.ec2.aws.amazon.com (example) and retrieve the information directly.
This works fine, but now we started to migrate to SSL for all our services. We have a domain certificate for the example.com domain and it works fine if we connect throught the load-balancer. When we connect to the EC2 servers directly, then it doesn't work because we present a certificate for our domain instead of the Amazon domain.
We can control the hostname where we want to redirect to, so I could choose to redirect to ec2.example.com instead of ec2.aws.amazon.com. So instead of redirecting to ip12-23-34-45.ec2.aws.amazon.com we would redirect to ip12-23-34-45.ec2.example.com. This presents the example.com certificate which should be fine.
The problem is that these hostnames cannot be resolved. Our servers are created dynamically and changing the Route53 DNS to modify the aliases over and over again seems a bit cumbersome. I would rather create a DNS rule in Route53 to map everything to .ec2.example.com to .ec2.aws.amazon.com.
Is it possible to create a rule that maps an entire subdomain to another subdomain in Route53? Or is there an other solution that we could use to bypass the load-balancer and still use SSL?
Comment: Please [avoid using other people's domain names and IP addresses](http://meta.serverfault.com/q/963/126632) for obfuscation.
Comment: What if I just bought it?
Comment: I will congratulate you with your purchase ;)  But I have updated my post, so it uses the example.com domain instead. Hopefully, now someone could answer my question instead of being annoyed of using the wrong domain.
Comment: Is your cert for example.com, example.com and www.example.com, *.example.com, or what?  ie. you might need an additional cert depending on the SANs included in your current cert.
Comment: You say your servers are created dynamically. When you create a server, you could also create a Route53 DNS entry under your domain e.g. server1.example.com => ip12-23-34-45.ec2.aws.amazon.com - then, your wildcard certificate will match.
Comment: We have a *.example.com domain certificate, so that shouldn't be an issue. Of course, we cannot include *.amazon.com in our certificate.
Comment: The myamazingservice.com domain is not in use...
Answer: There is no 'wildcard' DNS that can map a whole domain.
I would suggest that you use whatever software automatically creates your servers to also create DNS entries. You can have a single domain name map to multiple servers - each time you lookup the domain name, it will give you the next server in the list (round robin DNS).
So, you could have server.example.com => ip12-23-34-45.ec2.aws.amazon.com. Then, when you create another server, add its hostname into the list, so that server.example.com resolves to ip12-23-34-45.ec2.aws.amazon.com AND ip45-67-89-10.ec2.aws.amazon.com.
Then, when you connect to server.example.com, you will connect to one of the two servers.
Alternatively, if you need to know specifically which server you're connecting to, then maintain a count, and assign server1... server2... etc.
Comment: This is a solution that I proposed in my question, but it requires a bit more work. I am also worried about replication delays. Suppose we start a new server instance, then this instance would register itself in Route53, but when somebody asks for it, then it might not have been replicated yet. Removing instances might also be an issue, but I guess we get a signal before the instance is terminated.

Amazon Route 53 domain mapping


addressing multicollinearity and low levels in PCA

Question: I am trying to build a multiple regression model to predict properties prices and I would like to cunduct PCA to choose the most relevant variables.

I know that the the variables should be uncorrelated. What would be the best way to check and deal with multicollinearity? I have 80 variables. I have tried correlation plot and VIF function in r and deleted those ones with VIF around 10 (>=9.9 should I be more/less conservative??).
After I created dummy variables out of my categorical variables I applied
prin_comp <- prcomp(pca.train, scale. = T) and then it returned an error: Error in prcomp.default(pca.train, scale. = T) :
cannot rescale a constant/zero column to unit variance.
I do realize that some of the levels whithin the factors(there are about 17 of them with such a condition) don´t appear very often in the dataset and as a dummy variable contain mostly zeros. What can I do about such an unfair level distribution?

I am new to stats so any help would be appreciated.
Answer:
If you genuinely care about prediction and not at all about explanation (cause and effect), then with a large enough sample size you needn't exclude any of your predictors, even the very collinear ones.  If your sample size is on the small side, e.g., < 1600, then you have a considerable number of choices to make in reducing from 80 predictors.  You could continue to judge based on VIF or you could look up variable selection or regularization methods.
You probably have variables that have no variation when the data set is reduced to just those cases missing no data (the complete cases).  Eliminating these variables should help; or you could embark on imputation of missing values.

EDIT:  Since from your comments you are reluctant to exclude predictors, and since apparently missing data are not much of an issue, you could, for predictive purposes, conduct PCA on the majority of variables, while keeping others intact outside of the PCA, e.g., preserving all categories.  Levels (dummy variables) with nearly all zeroes will prove relatively uninformative; I wouldn't expect much predictive power to come from a category with 3 "1"s out of 2500 cases.  But at least you wouldn't be ruling anything out as a possible predictor.
As to a subjective rating of quality, there's nothing wrong with adding that if you feel it will be valid and reliable.  If it's collinear with other predictors,  you won't have lost anything by trying it.
More problematic is your statement that you want to "explain what influences the property price."  For this you would have the unenviable task of reducing your 80 predictors to a subset that covers the different domains you and other experts might have identified (location, style, various aspects of quality, etc.) while also avoiding the inflation of coefficient standard errors that comes with correlated predictors.  Ideally this would be a collaborative task for which you would allow plenty of time and multiple iterations of analysis.
Comment: I tried PCA and Boruta. Apparently my big poblem is low level categorical variables(there are 32 of them out of 82). For now I am recoding those levels < 5% to "Others".  Using my data without modifications in PCA after creating dummy variables  returns 150 significant varibles. I want to find the way to reduce 80 variables of my dataset to aprox. 20 the most important ones to later on create  a regression model to predict the price.
Comment: Hi Ronaldo! I am now at the stage of numerical variables transformation. I have read about standardization and various transformations like log, etc., which made me feel very confused. My numerical variables are square meters, age (in years), and number of attributes like bathrooms, rooms (they are approx. between 1-5). My questions are:

1.The area and price variables distributions are kind of right-skewed. Would it be ok if I log transform all of them?
Comment: 2. The age variables distributions are multimodal. Are there any transformations that I can apply in this case? Should I leave them as they are or just discard them from the modeling?

3. How should I treat the variables such the number of room, kitchens, bathrooms (they are usually low numbers 1 to 5)? wouldn't it cause any problems if the area variables are log transformed?
In some articles they say that the mean and std. dev. standardization is a must for all of the numerical variables. Should I just do it instead of all of the above?
Comment: You are grappling with many important questions, and many of them will no doubt apply to future analyses you conduct.  They seem to require more in-depth and sustained communication than this site provides, though.
Comment: Thank you ronaldo! 1.The idea is to explain what influences the property price in the first place and then create a model that predicts the price. There are about 2500 rows in my dataset. That´s why I thought PCA or Boruta would help to select the most important variables to include in my model.
Comment: 2. I have already used nearZeroVar() function to eliminate no variation variables. But the thing is that I have many categorical variables and 17 of them have many levels (10-20) and some of them rarely occur. For example in the neighbourhood variable there 20 levels and let´s say there are a couple of neghbourhoods that only appear 2-3 times. Any idea what I can do with them? Is there any threashold of the number of cases whithin a level? I really don´t want to just drop the data.
Comment: 3. It might be a silly question, but I was wondering if it is at all possible to set a categorical variable of quality, like overall quality (and I have kitchen, basement, etc quality) as numeric variable? Let´s say very poor -1 , excellent -10. And then later check them colliniarity? I feel like they might be correlated.


Diferença no tempo de execução entre stdio.h e iostream

Question: Fiz dois códigos para que um online judge corrigisse. São essencialmente iguais. Mas o com stdio.h é aceito e o com a iostream não, pois excede o tempo limite. Por que isso ocorre?
#include <stdio.h>
int tipo[1000000];
int main(){
    int qtdrot, qtdtipos, i, x, min;
    scanf("%d%d", &qtdrot, &qtdtipos);
    for(i=0; i<qtdrot; ++i){
        scanf("%d", &x);
        tipo[x]++;
    }
    min=1000000;
    for(i=1; i<=qtdtipos; i++){
        if(tipo[i]<min)min=tipo[i];
    }
    printf("%d\n", min);
    return 0;
}

O com a iostream:
#include <iostream>
using namespace std;
int tipo[1000000];
int main(){
    int qtdrot, qtdtipos, i, min, t;
    cin>>qtdrot>>qtdtipos;
    for(i=0; i<qtdrot; ++i){
        cin>>t;
        tipo[t]++;
    }
    min=1000000;
    for(i=1; i<=qtdtipos; i++){
        if(tipo[i]<min)min=tipo[i];
    }
    cout<<min<<endl;
    return 0;
}

Answer: cin e cout "gastam" uma boa quantidade de tempo sincronizando com os buffers do stdio. Não é difícil ver programas com operações 3 a 4 vezes mais lentas em comparação ao scanf e printf (veja esse exemplo no SOEn).
Você pode reduzir o tempo de execução desabilitando essa feature com o comando:
std::ios_base::sync_with_stdio(false);

Adicionalmente o endl força um flush (veja essa resposta no Quora). Em loops \n pode vir a ser mais eficiente (no seu caso, como você só usa cout uma vez a diferença não é significativa):
cout << min << '\n';

Feitas as substituições o exemplo com iostream ficou em média 13% mais rápido do que o exemplo com stdio na minha máquina / compilador / SO (sempre tenha cuidado generalizando microbenchmarks, mas nesse caso a diferença foi notável).


why will laravel say all of a sudden Cannot end a section without first starting one in laravel 5.1

Question: @section("page_title", "Home Page")@stop
@section("body_class", "page-homepage navigation-fixed-top page-slider")@stop
The above code works just fine for as long as I can remember then yesterday, I ran composer install then aborted in the middle of it.
Afterwards, I started getting the error Cannot end a section without first starting one. I realized the @stop must be removed. I removed it, and everything is fine now, however, I will like to know why @stop suddenly started giving problems.
The version of laravel I was using when @stop started giving problems is Laravel Framework version 5.1.23 (LTS) and the current version which is giving problems with @stop is Laravel Framework version 5.1.46 (LTS)
Answer: You need to use like thsi
@section('page_title')

....here page title

@endsection

OR

    @include('includes.title')

Comment: Thanks for your response. What I wanted to know is why `@stop` started giving errors all of a sudden. I have fixed the issue already
Comment: check documendation


Is DNS included in the "Active Directory Domain Services"?

Question: If someone tells me that the "Active Directory Domain Services" role is installed on a Windows server, does that mean that the DNS role is also installed? What software is part of the Active Directory Domain Services?
In other words, is DNS part of Active Directory Domain Services.
Answer: Nope. Active Directory Domain Services and DNS are two different server roles. They work tightly together but does not mean they are on the same machine. I had a Domain Controller which wasn't a DNS server at one site as well as the other way around, a server had DNS but not AD.
From Microsoft:

Microsoft Active Directory Domain Services are the foundation for
  distributed networks built on Windows 2000 Server, Windows Server 2003
  and Microsoft Windows Server 2008 operating systems that use domain
  controllers. Active Directory Domain Services provide secure,
  structured, hierarchical data storage for objects in a network such as
  users, computers, printers, and services. Active Directory Domain
  Services provide support for locating and working with these objects.

And even better:

What is the AD DS server role?
AD DS provides a distributed database that stores and manages
  information about network resources and application-specific data from
  directory-enabled applications. Administrators can use AD DS to
  organize elements of a network, such as users, computers, and other
  devices, into a hierarchical containment structure. The hierarchical
  containment structure includes the Active Directory forest, domains in
  the forest, and organizational units (OUs) in each domain. A server
  that is running AD DS is called a domain controller.

From: Active Directory Domain Services Overview
Comment: @MaxMix ...that said, AD DS relies heavily on DNS, and the usual setup is that domain controllers also run DNS, for that reason.
Comment: How exactly do you install a domain controller that is not a DNS given that the domain controller install will automatically install the DNS and the DNS is a requirement for the domain controller?
Answer:
If I say, for example, that on this server Active Directory Domain Services is installed,
  does that mean that DNS is also installed?

No, and yes.
No, it is not installed WITH AD, but yes, it will be automatically installed if not already installed. It is a separate service, but the AD installer needs it to run a domain controller.

Are there other things that is installed with Active Directory Domain Services.

That is now the moment you should possibly consider reading the documentation - of AD and this site, which says no beginner questions.
Comment: That's as maybe, and it makes sense to do this as a 'sensible' default option that will always result in a workable directory service, but AD does not require a DNS server to be running on the DC. It doesn't even require a Microsoft DNS server at all. http://serverfault.com/questions/176653/active-directory-with-public-unix-dns-no-ms-dns or http://msdn.microsoft.com/en-us/library/ms954396.aspx or http://www.educause.edu/discuss/networking-and-emerging-technologies/network-management-constituent-group/evaluating-microsoft-dns-vs-bind-active-dir might be relevant here.
Comment: AD requires DNS and installs the DNS role to make it easy to facilitate this, but it doesn't require DNS *on the AD server* (Though yes, that's probably the most sensible choice in most cases).
Comment: I am sorry, but the dcpromo equivalent does install DNS if it is not installed on any ad server.


simples pergunta: "porque eval() não funciona?"!

Question: Tenho um código simples a ser executado, eu nunca usei o eval, mas sei sua sintaxe:
var package = "edos.desktop";
eval(package + ".main()");

Porém não está funcionando no meu navegador...
Eu tentei usar algumas alternativas como Function(package + ".main()"), setTimeout(package + ".main()");,setInterval(package + ".main()");, mas por incrível que pareça, só o setInterval() funcionou, porém, ele ficou repetindo o código sempre que pode...
meu script com o código do main:
var edos = {};
edos.desktop = {
    main: function() {
        document.writeln("este é um app!");
    },
}

e eu preciso de uma solução, porque eval() não funciona, ou alguma alternativa para contornar o eval...
DETALHES DO DISPOSITIVO TESTADO:
Disposiivo: Moto G6 Play
Android: 8.0
Chrome Canary: 74

Comment: Pelo que entendi, o que vc está fazendo aí é chamar a função `c()` dentro de um objeto `a.b`. Melhor colocar o código completo na pergunta e explicar melhor o que pretende fazer.
Comment: Ok, mas era exatamente isso que eu queria mostrar...
Answer: Já considerou que o erro pode ser alguma outra coisa que não seja o eval?
"Eval não funciona" é improvável, não tem como um bug desse acontecer num navegador como o Chrome, mesmo no Canary. Faça o teste
const body = "document.body";
const firstChild = eval(body + '.firstElementChild');
console.log(firstChild);

Funciona, não funciona? Então o problema não é no eval.

setInterval() funcionou, porém, ele ficou repetindo o código sempre
  que pode

Quando você passa uma string para setInterval, ele roda o comando eval por trás das cortinas, outra prova de que não há nada de errado com o eval. A única diferença nesse caso, é que o setInterval vai esperar um pouco antes de executar o eval, ao invés de executa-lo imediatamente.
Seu problema não é o eval, revise seu código. Se por outro lado você insiste em usar algo setInterval para solucionar o problema, use setTimeout, que tem a mesma funcionalidade que o setInterval, mas só é executado uma vez.
Comment: EduApps, por favor, JavaScript é a implementação das regras definidas no ES6. Eu não tenho como te dizer qual o erro de um código que você não postou, mas não é problema no comando eval.
Comment: Esse codigo que você disse acima retornou ```{ }```, isso é normal?
Comment: Ele retorna o primeiro elemento do `body`, se você rodar o código numa página vazia, o retorno será vazio.
Comment: o primeiro elemento é um ```code is```, e mesmo assim retornou ```{ }```
Comment: deve ser porque eu não uso ES6, mas sim o JavaScript...
Comment: Cara, obrigado, o problema era que eu tinha pego o arquivo com a string "edos.desktop" por meio de um HttpRequest, e o eval foi chamado antes do HttpRequest ser terminado...


Android: Implementing SlidingMenu and ABS

Question: I am trying to implement the SlidingMenu from https://github.com/jfeinstein10/SlidingMenu together with http://actionbarsherlock.com/ and I came across a problem that I could not fix myself that's why I turned to the issues page on SlidingMenu's GitHub. But 2 days and I got no reply so I am gonna ask it here.
Basically on the example project provided by jfeinstein10, I copied the SampleListFragment.java file and I've named it MenuListFragment.java on my project. I've made a couple of changes but those should not be an issue.
I also copied the menu.xml from the layout directory but changed its name attribute to the previous file including the package.
Project builds properly and no errors are encountered. Time to run the project.
Now on my project's main activity, when I call the setMenu(R.layout.menu); statement during runtime, it gives me an error which tells me something about ClassCastException (cannot cast com.dokgu.dota2stats.MenuListFragment to android.app.Fragment).
I've tried a couple of things like change the MenuListFragment.java to extend the android.app.Fragment instead of ListFragment but it didn't solve the problem and more issues came up because of that.
So please, can anyone help me with this please? I really want to make this work.
You can find the issue here as well: https://github.com/jfeinstein10/SlidingMenu/issues/546
Comment: Show us your code for the activity.
Comment: @Pork'n'Bunny - https://github.com/dokgu/Dota-2-Stats/blob/master/src/com/dokgu/dota2stats/MainActivity.java
Comment: @dokgu the response is in the same issue link:
cited: **I guess the problem is that you extend the class android.support.v4.app.ListFragment which itself extends the class android.support.v4.app.Fragment and this class is not android.app.Fragment. I'm not sure if this helps you but this is the reason for the ClassCastException.**
Answer: Actionbarsherlork  supports the lower lever version since android 2.x while the slidingmenu needs android 3.0+.Maybe you can add the android-support-v4.jar ,with some fragment and activity in slidingmenu project extending to.
Comment: thats not true, i am using the sliding menu for versions 2.3 onwards. It is not completely true in saying that the sliding menu needs 3.0+
Comment: infact the sliding menu lib has this in its manifest:


Recommendations for a short, yet theoretically rigorous, seminar or course on principal components analysis

Question: I am looking for a short course (1 week or less) that teaches the theoretical and applied aspects of principal components analysis in a mathematically rigorous way. I've seen university courses on multivariate statistics in general or the linear model, but not just PCA. Travel is not an issue, so good international courses are welcome, as long as they are in English. Also, I do not want to just learn how to run a PCA using some software package and interpret the results; I want to learn the detailed underlying theory as well.
I cannot attend a semester-long course, nor do I want to do a web-only class.
Comment: Would you be interested in literature with information on PCA, mostly theory and some practice?
Comment: @AdamO I have looked at some of these, but it seems that social and biological science versions of PCA do not go into depth on the math, just how to run and interpret the results.
Comment: @AleksandrBlekh yes, that would be good as well
Comment: Have you tried looking at departmental websites for clinical psychology programs to see if they offer any summer short courses on psychometrics / scale development / factor analysis?
Answer: I would recommend the book "The Elements of Statistical Learning: Data Mining, Inference, and Prediction" (2nd ed.) by Trevor Hastie, Robert Tibshirani and Jerome Friedman. Along with the printed edition, this IMHO beautiful (both content-wise and visually) book is available as free download in PDF format at the link on this page: http://statweb.stanford.edu/~tibs/ElemStatLearn.
Section 14.5 of the book is focused on PCA and is, in my humble opinion, theoretically relatively rigorous. The subsequent sections (14.6 and later) are focused on presenting some alternatives to PCA. Also, section 3.5.1 is focused on the related topic of principal components regression. Hope this helps (and I helped you to save some pocket change for a trip to a seminar/course :-).
Comment: Superb...and FREE. What more could one want!
Comment: @Eupraxis1981: Glad I could help!


How to adjust retrospective-observational survival times to account for immortal time bias?

Question: I would be very grateful for a gentle sanity check on adjusting survival times in my comparison groups. The scenario: I am using Cox regression to calculate HR risks over some covariates of interest.
My population is observed for six months, starting from the index event when a patient makes a medical complaint. There are a few competing events: death, leaving the study, lost-to-following-up, and remission. The population is split into two groups:

exposed (cases) when a patient has a record of drug exposure within 60 days from the Index date.
not exposed (controls) those patients without a record of drug exposure during the observation period.

All the patients in my exposed (cases) group have an immortal time bias because we know they can't have any competing risk (death, remission, etc.) until they've first had exposure within the initial 60 days after Index.
As far as I understand, there are several approaches to adjusting the survival times of the exposed group. However, my question is, do I need to do anything to the survival-times of the not-exposed (control) group? Thanks.
Update 1.
To answer my question, I will use a "Landmark" approach to treat the immortal time bias. This involves adjusting survival times in both groups by the same about of time.
Answer: The problem is that your "exposed" cases were in the "non-exposed" group until the time of exposure. This suggests that you would be better off with a multi-state model that includes the transition from the "non-exposed" to the "exposed" state. That would also help evaluate systematic differences between those who enter those two states, which would tend to confound any simple comparisons between those who happened to end up in those two groups by 60 days. Then you can evaluate the transitions from each of the "non-exposed" and "exposed" states to the other states of interest.
The R vignette on competing risks shows how to set up such models and use them to estimate the probability of state occupancy as a function of time and covariates.
Comment: Thank you for that information and the link. I haven't really gone into too much detail about competing risks, which I have factored into my analysis as per Terry Therneau's box on extending Cox regression. However, this vignette is 2022, I haven't seen it before. Thanks.


Piano oscillation on a single string

Question: Why is that when the hammer hits only one string on the piano, there is an oscillation and not a solid note throughout. I hear it like a wave of sound, not an absolute pitch. It doesn't happen on other keys but very noticeable on the D# and E one octave about middle C. Piano tuner calls this phenomenon having "beats" on a single note? He can't figure out the reason. It happens on some of the keys, even though all strings and parts are new after being entirely rebuilt last year.
Comment: This is how the piano is supposed to sound and I'm very concerned about your piano tuner.
Comment: @AndyBonner - don't think *all* strings are permanently damped. Top octave or so aren't. Never seen use of felt for those notes.
Comment: It sounds like sympathetic vibrations with another string of the same pitch but different octave. But normally piano tuners dampen all other strings using felt. Does this one seem like they know what they're doing? maybe it's even acoustics
Comment: Pianos have single string per note only in the lowest register and three for most part. When these are out of tune with each other, this produces the beats, or the wobbly saloon piano tone. But any tuner should know this so something is odd here.
Comment: When the piano tuner used the felt to dampen the other 2 strings, the lone string still created beats. That's why I'm scratching my head.
Comment: Thanks for the explanation. Without hearing the sound or seeing the piano it's difficult to say anything expect that something's resonating at a frequency that's close enough to resonate but far enough to create the beat. On guitars the parts of string between tuner and nut or between fret and nut sometimes do this, but pianos don't have anything like that.
Comment: Welcome to Music: Practice & Theory! Please use the [Contact Us](/contact) form to have your accounts merged, to regain full control over your posts.
Comment: There's always the possibility of resonant behavior of the housing, or even the room it's in.   Impossible to say without being there and doing careful acoustic tests.
Answer: Beats are a phenomenon that occurs when two sounds of frequencies that are a little different(out of tune) but not too different are played at the same time. This occurs due to the interference of the waves. Pianos usually have three strings per note and one of these strings being out of tune could cause this effect.
Comment: The question and comments make it clear that only one string is being struck.

Piano oscillation on a single string


Solving sextic polynomials with modular forms.

Question: A very long time ago, I made a since removed post about solving higher order polynomials. This post demonstrated the radical solutions for degrees $1$ to $4$ and also some solutions for higher degree polynomials with less familiar functions. It was intended to be far reaching while still being comprehensible by a beginner. However, there was $1$ formula I knew that didn't quite fit this bill. I tried to include it anyway, which led to the post being controversial and somewhat hated for involving higher functions at the end while still supposedly being beginner oriented. Therefore, I think it makes sense to make a separate post discussing this formula and how it might be generalized. $$x^{6}+10x^{3}+cx+5=0,\ x=\frac{5η\left(5j^{-1}\left(-c^{3}\right)\right)^{2}}{η\left(j^{-1}\left(-c^{3}\right)\right)^{2}}$$ This formula solves a special sextic using modular forms, and I started wondering. Could there be a general sextic formula in modular forms using a similar approach? If so, how so? I'm not entirely sure if I tagged this properly, kinda hard to tell since I haven't really seen anything like this before. I honestly don't even understand how I knew this back then. It's like it dropped out of the sky.
Comment: This is equivalent to a Dedekind $\eta$ product identity. Let $u_1:=\eta(\tau), u_2:=\eta(2\tau), u_5:=\eta(5\tau).$ Then $u_5^2(u_1^{24} + 256u_2^{24}) = u_1^6u_2^8(u_1^{12} + 250u_1^6u_5^6 + 3125u_5^{12}).$
Comment: By "**full** sextic formula" do you mean the **general** sextic $ax^6+bx^5+cx^4+\cdots$ ? Maybe with $a=1$ ?
Comment: Take a look [here](https://cpb-us-e1.wpmucdn.com/sites.psu.edu/dist/d/34699/files/2015/09/PolynomialsDraft3.pdf).
Comment: @JeanMarie Yeah that's what I meant. I'm not good with jargon but I have the concepts down. At least, I usually do. This formula still makes no sense to me. Would be nice to include a by the way, since it's trivial to reduce $ax^{6}+bx^{5}+cx^{4}+dx^{3}+ex^{2}+fx+g=0$ to $x^{6}+Bx^{5}+Cx^{4}+Dx^{3}+Ex^{2}+Fx+G=0$
Comment: @NoChance That is the Dedekind eta function. I'm not entirely sure what the numerical algorithm for this function is, but I prefer to just leave the answer in exact form regardless. I assume you're talking about the numerical algorithm anyway, it's not very clear.
Comment: Thanks for the quick reply. Maybe I get to understand this stuff one day...
Comment: @BabyHeartyBear Which part? I can perhaps elaborate more.
Regarding your other question, I don't think your formula works for a general sextic, because the closed solution requires the root $x$ to be related to $j$ (which in turn is related to your constant $c$) in a particularly nice way. One way to see how you get this particular eta quotient is to realise that the second equation in the answer is a defining equation for $x(\tau)^3$ as the Hauptmodul for the congruence subgroup $\Gamma_0(5)$, whose expression as an eta-quotient is known.
Comment: If on the other hand $j=R(x)$ with $R$ a "generic" rational function then $x$ is not a modular function for any subgroup of $SL(2,Z)$ in general.
Comment: This topic is way over my knowledge but it is indeed interesting. How can we go about finding the roots uisng the formula for $x$? What is $η$?
Comment: @NoChance Tbh I don't have the best comprehension of this formula either. I know what it is, but the process of deriving it as described by El Rafu genuinely doesn't make the slightest sense to me.
Answer: Consider the polynomial
$$P(x)=^6+10^3+(-j)^{\frac13}+5$$
Then $P(x)=0$ can be solved for $j$ as
$$j=\frac{\left(x^6+10 x^3+5\right)^3}{x^3}.$$
We can now lift both $j$ and $x$ to be functions of $\tau\in\mathbb H$, with $j$ the modular $j$-function. We can expand $j$ around $x=0$ and invert the series order by order. Inserting the $q=e^{2\pi i\tau}$-expansion of $j$, one finds
$$x(\tau)=5q^{\frac13}(1+2 q+5 q^2+10 q^3+20 q^4+...),$$
which agrees with the Fourier expansion of the inverse of the McKay-Thompson series of class 15D for the Monster group. Thus
$$x(\tau)=5\left(\frac{\eta(5\tau)}{\eta(\tau)}\right)^2.$$
By defining $c=(-j(\tau_c))^{\frac13}$, $P(x(\tau_c))=0$ has then one root  $x(\tau_c)=5\left(\frac{\eta(5\tau_c)}{\eta(\tau_c)}\right)^2$.
Comment: Indeed, you consider $j$ as a meromorphic function in $x$ and Laurent expand it around $x=0$. This allows to locally invert this relation.
Comment: It is hard to see how you assumed $j$ was the $j$ invariant for this very specific polynomial. Also, how did you "expand $j$ around $x=0$ and invert the series order by order"; maybe it is a Taylor or Fourier series for the inverse of the polynomial?
Comment: If $f$ is a modular function for a finite index subgroup $\Gamma$ of $SL(2,\mathbb Z)$, then it is the zero of a polynomial over the field of modular functions on $\Gamma$, whose degree is the index of $\Gamma$ in $SL(2,\mathbb Z)$. The above solution is just anticipating this fact. So for $j$ you could choose any other $SL(2,\mathbb Z)$ invariant function also.


If two matrices are similar, the geometric multiplicities of their eigenvalues are the same

Question: Problem

Let $A$ and $B$ be similar matrices. Prove that the geometric multiplicities of the eigenvalues of $A$ and $B$ are the same. [Hint: show that, if $B=P^{-1}AP$, then every eigenvector of $B$ is of the form $P^{-1}\vec{v}$ for some eigenvector $\vec{v}$ of A].

Attempted Proof
Write $A \vec{v} = \lambda \vec{v}$.   Since $B=P^{-1}AP$, this is equivalent to saying
$$B (P^{-1}\vec{v})=P^{-1}APP^{-1}\vec{v} = P^{-1}A\vec{v} = \lambda (P^{-1} \vec{v})$$
Since $P^{-1} \vec{v}$ is an eigenvector of $B$ only for eigenvalues of $A$, the dimensions of the eigenspaces must be the same.
Is this proof complete?
Comment: also show that every eigenvector of $B$ is of this form (just for completeness)
Comment: @Blah How would I do so?
Comment: If $Bv=\lambda v$ then $B(P^{-1}Pv)=\lambda P^{-1}Pv$,set $w=Pv$
Answer: You should also show that every eigenvector of $B$ is of this form (just for completeness):
If $Bv=\lambda v$ then $B(P^{-1}Pv)=\lambda P^{-1}Pv$. Set $w=Pv$ here. Observe that  $w$ is an eigenvector of $A$. Indeed,  $BP^{-1} = P^{-1}A$, so
$$P^{-1}Aw = \lambda P^{-1}w$$
(Based on a comment by Blah)


can some one convert the code below to a function?

Question: Can someone please help me write this into a function using MATLAB?
for i=1:50
  E(i+1)=E(i)+((W(i)[Sin[α(i)]-Tan[ϕ]Cos[α(i)]/F]-c*l/F))/(Cos[α(i)]+(Tan[ϕ]Sin[α(i)]/F))
end

Comment: Yes, someone can. But What kind of function you are looking for?
Comment: I do not understand fully what you are saying. but I meant to say make the above run as a script in matlab. thank you
Comment: Function and Script are two very different structures in matlabyet both stored in `.m` file format. Functions may return values and they **do not** share variables with the parent workspace and may contain nested functions. Scripts **do not** return values, **cannot** contain nested functions and **fully** share variables with the parent workspace. I'm asking what are the inputs, what shall be returned etc.
Comment: Say you want a `FooBar.m`, then provide us what shall be done when one call `FooBar` or `FooBar(inputs)`. Without this information one can only wish you good luck.
Comment: I should have known script and function are different. It just escaped me. The input variable here is 'F'. thank you.
Comment: And what about `alpha(i)`, `phi` and the others?
Comment: these will be determined from another script.
Answer: I think you want to get the following formula:
E = cumsum(((W.*(sin(a)-tan(phi).*cos(a)./F)-c.*l./F))./(cos(a)+(tan(phi).*sin(a)./F)));

This way, you don't need a for loop.
You can input W, a, phi, F, c and l as arrays or scalars. All the arrays you put must be the same size.
In your case, I believe that W and a will be [50x1] arrays while phi, F, c and l will be scalars.
Answer: If you want to run it as a script:
for ii=1:50
  E(ii+1)=E(ii)+((W(ii)[sin(alpha(ii))-tan(phi)*cos(alpha(ii)]/F)-c*l/F))/(cos{alpha(ii))+(Tan[phi]Sin[alpha(ii)]/F))
end

All variables (E(1), W,... must be defined in parent workspace.
If you want to run it as a function:
function[E]=FooBar(F,alpha)
%% define variables thet are not inputs
E=zeros(50,1);
W=rand(50,1);
phi=rand;
c=rand;
l=rand;

for ii=1:50
  E(ii+1)=E(ii)+((W(ii)*(sin(alpha(ii))-tan(phi)*cos(alpha(ii))/F)-c*l/F))/(cos{alpha(ii))+(tan(phi)*sin(alpha(ii))/F))
end

EDIT
I suggest creating fucntion like that:
function[E]=MainFoo()
%% Code for necessary variables...

W=FooW(Winput1,Winput2);
alpha=FooAlpha(AlphaInput1,AlphaInput2);
%% other parameters calculated by Foo*** functions

E=FooE(E1,W,alpha,phi,F,c,l);

%% Nested function
  function[WW]=FooW(Win1,Win2)
    %% code to calculate W
  end
  function[Alpha]=FooAlpha(AlIn1,AlIn2)
  %% code to calculate alpha
  end
%%Other Foo*** functions

  function[OutE]FooE(E0,Ws,Alphs,Phi,FF,cc,ll)
    OutE=zeros(50,1);
    OutE(1)=E0;
    for ii=1:50
      OutE(ii+1)=OutE(ii)+((Ws(ii)*(sin(Alphs(ii))-tan(Phi)*cos(Alphs(ii)]/FF)-cc*ll/FF))/(cos(Alphs(ii))+(tan(Phi)Sin[Alphs(ii)]/FF));
end
  end
end


Using purrr to recode across multiple columns with multiple mappings

Question: I have a dataframe with questionnaire response labels. I always like to make a tibble with item-answer definitions and then use dplyr::recode() to replace all item labels with their corresponding definitions. For ease of use the definitions tibble recode_df stores these correspondences as strings and within dplyr::recode() they can be unpacked with bangbangbang !!! and evaluated. In the following toy example there are 4 items, two for qa and two for qb that share the same answer definitions.
library(tidyverse)
set.seed(42)

# columns starting with `qa` and `qb` share the same answer structure
data_df <- tibble(
  qa_1 = sample(c(0, 1), 5, replace = TRUE),
  qa_2 = sample(c(0, 1), 5, replace = TRUE),
  qb_1 = sample(1:5, 5, replace = TRUE),
  qb_3 = sample(1:5, 5, replace = TRUE)
)

# `answer` column stores string definitions for use with `dplyr::recode()`
recode_df <- tibble(
  question = c("qa", "qb"),
  answer = c(
    'c("0" = "foo0", "1" = "foo1")',
    'c("1" = "bar1", "2" = "bar2", "3" = "bar3", "4" = "bar5", "5" = "bar5")'
  )
)

# Desired result
data_df %>%
  mutate(
    across(
      .cols = starts_with("qa"),
      .fns = ~recode(., !!!eval(parse(text = recode_df$answer[str_detect(recode_df$question, "qa")])))
    ),
    across(
      .cols = starts_with("qb"),
      .fns = ~recode(., !!!eval(parse(text = recode_df$answer[str_detect(recode_df$question, "qb")])))
    )
  )
#> # A tibble: 5 x 4
#>   qa_1  qa_2  qb_1  qb_3
#>   <chr> <chr> <chr> <chr>
#> 1 foo0  foo1  bar5  bar2
#> 2 foo0  foo1  bar1  bar3
#> 3 foo0  foo1  bar5  bar1
#> 4 foo0  foo0  bar5  bar1
#> 5 foo1  foo1  bar2  bar3

Created on 2023-02-26 with reprex v2.0.2
I can reach my desired result by using one mutate() and  across for each row of recode_df, but I am sure there is an elegant purrr solution that iterates and recodes without repeating code. Thank you.
Answer: There are a number of alternatives to consider, especially if storing your answer key in a different form. However, given the present data.frames, you could try the following. Using map_dfc to column-bind your end result. You can apply your recoding function to each element of a vector of character values, such as "qa" and "qb". Let me know if this helps.
library(tidyverse)

map_dfc(
  recode_df$question,
  \(x) {
    map(
      select(data_df, contains(x)),
      \(y) recode(y, !!!eval(parse(text = recode_df$answer[str_detect(recode_df$question, x)])))
    )
  }
)

Output
  qa_1  qa_2  qb_1  qb_3
  <chr> <chr> <chr> <chr>
1 foo0  foo1  bar5  bar2
2 foo0  foo1  bar1  bar3
3 foo0  foo1  bar5  bar1
4 foo0  foo0  bar5  bar1
5 foo1  foo1  bar2  bar3

Comment: @ClaudiuPapasteri It's a good question - my personal preference is to have your question/data data.frame in long (not wide) form, with only a few columns such as "question_type" (e.g., qa or qb that share a common recode), "item_number" (counter, as in 1, 2, 3...), and "item_response"...then, in your answer key data.frame, you want "question_type", "item_response", and "recoded_response"...then, just do a join (by both question_type and item_response) to recode your responses...I also tend to keep "both" raw and recoded responses for quality checking...
Comment: Thank you for the answer, it seems to work very well, although any other columns in the dataframe is dropped and needs to be cbinded back to it after. I am very interested in your suggestion regarding storing answer key in a different form. What would you say would ease this workflow? I am aware the question is off topic, but If you could give me any pointers, maybe I could post another, better question. Thank you again.
Answer: You can have that cheaper.
data_df[] <- lapply(names(data_df), \(x) if (grepl('qa', x)) paste0('foo', data_df[[x]]) else paste0('bar', data_df[[x]]))

If there are much more columns, you can use a simple dictionary dc consisting of a named vector with data prefixes as elements and column prefixes as names.
dc <- c(qa='foo', qb='bar')
## alternatively using `grep` to identify columns
# dc <- setNames(c('foo', 'bar'), unique(gsub('_\\d+$', '', names(data_df))))

We can now feed startsWith with names column name and dc-name to identify the correct entry in dc.
data_df[] <- lapply(names(data_df), \(x) paste0(dc[startsWith(x, names(dc))], data_df[[x]]))

data_df
#   qa_1 qa_2 qb_1 qb_3
# 1 foo0 foo1 bar4 bar2
# 2 foo0 foo1 bar1 bar3
# 3 foo0 foo1 bar5 bar1
# 4 foo0 foo0 bar4 bar1
# 5 foo1 foo1 bar2 bar3

This should also work well with hundreds of columns. It might be hard to avoid to define the translation once.
Comment: Yea, thanks for this, of course you can have it cheaper. It also works easy with for loops but I'd like a `tidyverse` implementation. More so, your `if else` implementation works for this toy example but `qa` and `qb` are only two questionnaires here out of potentially hundreds in real data, so that would mean a lot of `else`'s, which is as bad as a lot of `across`'s in my view.
Comment: @ClaudiuPapasteri Yeah, really bad, you're right about that, I added an update that uses a small dictionary. In tidyvert dialects I am not very interested, sorry.


user_load() and EntityFieldQuery not found when running script via Drush

Question: I'm trying to run a php script from the command line via Drush. When I tried to use EntityFieldQuery...
$query = new EntityFieldQuery;

I got the error:
PHP Fatal error:  Class 'EntityFieldQuery' not found in /path/to/my/script.php on line 43

So, I tried to make it even simpler, and just used this script:
<?php

print "inside script\n\n";
$user = user_load(1);
print "name: ".$user->name;

?>

But I get the error:
PHP Fatal error:  Call to undefined function user_load() in /path/to/my/script.php on line 17

It doesn't appear that drush is bootstrapping properly. Am I missing something? What do I need to do for drush to be able to use the drupal apis?
I read through Drush php-script | Drupal functions such as node_load() are not being found, but I've got mysql client libraries already installed so that isn't a solution for me.
Answer: Ok, WOW, I found the error by running my script with the -d option:
drush -d scr /path/to/my/script.php

I noticed in the log it spewed out that it was getting an error connecting to the database. I apparently had messed up the privs when I set them up. I regranted the privs and my script ran just fine.
The error message about not being able to find a function was a total red herring.
Comment: 3 years later I just had this problem again and Google searched to find out what was going wrong, found this incredibly helpful suggestion, and tried to upvote it... and StackOverflow told me I wasn't allowed to upvote my own answer. And that's when I realized -I- had posted this question and answer. /facepalm heh.


Displaying multiple node add forms using panels and contexts

Question: I'm using panels to create a single page that will display multiple (different) node add forms. Within panels, I use contexts to activate the node add forms I'm using and then put the forms in as content. However, the resulting page shows only the first node add form and then displays "Form" and "Form goes here" in place of the Title and fields of the second node add form.
Is there a fix for this? Or another way to display multiple node add forms within a page?
Comment: looks like bounty material to me :)
Comment: I would recommend either putting these node add forms on different pages or creating a single form the the forms api and having the submit function save this data to multiple content types. I don't think what you're looking for is supported out of the box.
Comment: Ah damn! Stupid me. I added a bounty by mistake. How do I take this back?
Answer: I doubt that panels can handle it.
I would try creating a custom page with hook_menu and outputting all the forms on it via a page callback like
   $output = drupal_get_form('foo_node_form');
   $output .= drupal_get_form('bar_node_form');
   return $output;
Answer: $created = true in the ctools_context_create_node_edit_form function in the node_edit_form.inc context plugin seems to be the one thing keeping us from adding multiple content profile node forms to a user edit form.
we easily added the first node edit form by passing a context, but the second one wasn't available on the layout page. if we comment out $created= TRUE we can pass in multiple node edit form contexts.
it seems that this value is being set as part of a performance thing?
we are going to copy the whole file, rename it, create a custom module, and drop it in.
Answer: Disclaimer: I haven't tested the following solutions myself.
Assuming you don't mind adding blocks to panels you can try the following solutions. Just make sure you allow blocks and regions in your panel.
I personally had problems with nested form tags using mini-panels (which should have worked in theory) so this (i.e. blocks) is the only solution I have outside of creating custom Ctools plug-ins.
(1) Try the Advanced Form Block module to create a custom block. It does nifty things like AJAX submits, multiple blocks and field selection.
(2) Write a module to create a custom blocks using hook_block_info and hook_block_view. In this example, a $form_state is passed along to drupal_build_form so you'll make sure language etc is passed in and that your includes (node.pages) is refreshed each time with AJAX loads.
function custom_example_block_info() {

    $blocks['example_node_form'] = array(
       'info' => t('What an example'),
    );
    return $blocks;

}

function custom_example_block_view($delta = ''){

    $block = array();

    switch ($delta) {
        case 'example_node_form':
            global $user;
            //Note: 'type' is your node content type and 'language' must be included
            $node = (object) array('uid' => $user->uid, 'name' => (isset($user->name) ? $user->name : ''), 'type' => 'example', 'language' => LANGUAGE_NONE);

            $form_state['build_info']['args'] = array($node);

            form_load_include($form_state, 'inc', 'node', 'node.pages');
            $block['content'] = drupal_build_form('example_node_form', $form_state);

            break;
    }
return $block;

}


How to calculate the determinant $\det(A+xI)$?

Question: Let $A$ be an $n\times n$ symmetry matrix with the diagonal elements of $A$ are $0$ (the diagonal elements of $A$ are can also be any constant ). Let $I$ be an  $n\times n$ identity matrix, and Let $x$ be a constant. How to calculate $\det (A+xI)$? We wish $\det (A+xI)$ be express by the combinations of $\det(A)$.
Comment: @Surb It means $A$ is a real symmetry matrix  which its diagonal elements  are $0$  or its diagonal elements are the same real constant $a \neq 0$ . How to  calculate $det (A+xI)$, with  $x$ is a real number ? And we wish $det (A+xI)$ can be expressed by the combinations of $det A$.
Comment: I do not understand what you are looking for.
Comment: Do you mean: by combination of [*minors*](https://en.wikipedia.org/wiki/Minor_%28linear_algebra%29) of $A$?
Comment: "the diagonal elements of $A$ are $0$ (the diagonal elements of $A$ are can also be any constant )" what do you mean? Are the other elements of $A$ variables?
Comment: @ccorn No,it is  the combination of $det A$, and it also means $det (A+xI)$ is expressed by the polynomial of $det A$.
Comment: @ccorn  Can $det (A+xI)$  be written to  the  polynomial of   $det A$?
Answer: If $A$ is diagonalizable:
$$A=U^{-1}DU$$
And
$$\det(A)=\prod \lambda_i$$
Where $\lambda_i$ is the eigenvalues
Thus
$$\det(A+xI)=\det\big(U^{-1}(D+xI)U\big)=\det(D+xI)=\prod (\lambda_i+x)$$
Comment: Note that for $n=2$, $det(A+xI)=det(A)+x*tr(A)+x^2$
Answer: That's impossible (unless $n=1$), as the determinant of $A+xI$ depends on the eigenvalues of $A$ rather than the determinant of $A$. Consider, e.g. $A_1=\pmatrix{1\\ &4}$ and $A_2=2I_2$. They have the same determinants, but $\det(A_1+xI)=(x+1)(x+4)\ne(x+2)^2=\det(A_2+xI)$.
Answer: for $n=3$, $$\det(A+xI)=x^3-tr(A)x^2+(A_11+A_22+A_33)x+\det A$$


Backing up contacts on SDcard

Question: Is to possible to copy the contacts2.db SQLite file in a non-rooted phone to SD Card programatically. If so how?
Answer: Apps don't have access to other apps' databases, so the answer is no, you can't.
There is an API to read all the contacts (ContactsContract) that you can use to store the contact information in your own database and/or file in the external storage.
Comment: So if I want to backup my contacts2.db to SD Card, what's the best way to do it? Use ContactsContract to read each contact individually and then store it in a custom DB created in the SD Card?
Comment: That sounds like a reasonable solution.

Backing up contacts on SDcard


How do I intercept and change password field values on form submit?

Question: I am trying to apply a password hash to all password fields before the form is submitted. So far what I have is this...
<code>$("#loginform").submit(function(e) {
    e.preventDefault();
    $('input[type=password]').each(function(){
        console.log($.sha256($(this).val())) //Hash password
        //Set password back
    });
    return true;
});
</code>
... which will intercept the submission and hash the password, but I cannot replace the plaintext password in the input box using normal methods.
I know how to do this with hidden inputs and the like, but I am applying this to a site that already has a fairly solid login structure in place, so I want to make the HTML modifications to a minimum.
Thanks :)
Comment: Just make the login call AJAX-wise.
Comment: Why not do the hashing on the server? There's no security from sending the hashed password; if someone intercepts it, they can send the same hashed password themselves.
Comment: I could do that, I was hoping to do it in this manner because there are about 10 forms that need the client-side hashing, all making calls to different PHP files. I am trying to make something more universal.
Comment: The answer on this question may help http://stackoverflow.com/questions/6837714/jquery-how-to-submit-a-form-with-edited-user-inputed-values?rq=1
Comment: Well you just make each request to `$(form).attr('action')`, after giving each form a common `.pleaseHashMe` class for example ^^. btw, isn't it just better to use HTTPS than hash stuff client side? I think a dictionary attack with sniffed hash and algorithm isn't an unlikely scenario, am I wrong?
Answer: If the point of the client-side hashing is to secure the passwords going over an unsecure connection (HTTP), make sure you use a salt and a random 'challenge'.
Like so:
response = sha256(challenge + sha265(salt + password))
The server knows challenge, salt and the answer to sha265(salt + password), it can then validate the response.
You need salt + password to avoid rainbow attacks, and the response / challenge to prevent replay attacks.
A better approach would be to just use SSH ;)


Search api autocomplete - how to show search form?

Question: I use Search Api with Search api autocomplete module.
I made configuration of autocomplete module on Search Api page, but I do not see block for input.
Should I config anything else for it?
Answer: There should be a block named Search box in admin/structure/block, i think it is the search box by default of drupal.
Remember that this block uses a view that returns a JSON, you can specify which view to use entering admin/config/search/search_autocomplete
Comment: Standard search block does not have possibility to autocomplite. This feature appears if I use exposed filter in Views (by index). I also want to use Views to make autocomlite more attractive (put their picture and some information) - in Autocomplite settings there is Views selection - but only Master, Page or Block. How to specify Views name to use?
Comment: Edit the view `nodes_autocomplete` (I think it comes with the autocomplete module) if not, create a new one of Content, with Format: Autocomplete JSON, add some fields, in format json settings, configure the label, link, and output fields you want to show etc. And then configure the view to use in `/admin/config/search/search_autocomplete/3/config`


what are the residues at poles of $\frac{1}{1+\cosh{z}}$?

Question: Consider the function $f(z)=\frac{1}{1+\cosh{z}}$. It has poles of order 2 at odd multiples of $\pi i$, but what are the residues at the poles? I've tried using $\frac{d}{dz} \Big((z-a)^2 f(z)\Big)$ for the residue at $a$, but get the answer to be 0, which I don't think is correct.
Answer: Why do you think $0$ isn't correct? Since $\cosh (\pi\mathrm i+z)=-\cosh z$ is an even function of $z$, so is $f(\pi\mathrm i +z)$. Thus its Laurent series contains only even powers of $z$, and in particular doesn't contain a $z^{-1}$ term, so the residue is indeed $0$.
Comment: @Harry: What's $v$? Assuming that it's a non-zero constant, no, the residues of that function aren't zero; $\mathrm e^{\mathrm iv(\mathrm i\pi + z)}$ has a linear term, and that times the $z^{-2}$ term of $f(\pi\mathrm i+z)$ gives a $z^{-1}$ term.
Comment: Thanks! This gives a quicker way of seeing that the residue is 0. But the next part of the question is to take the rectangular contour with corners at $\pm n\pi$ and $\pm n\pi + 2n\pi i$ and integrate $\frac{e^{ivz}}{1+\cosh{z}}$ around this contour. What is the limit of this integral as $n\rightarrow\infty$? Since all the residues are 0, the integral seems to be 0 regardless of $n$, so the question is trivial. Or am I missing something?
Comment: Lesson not to doubt oneself without good reason, and not to scratch out your answer because of it.  (What kind of idiot fails an exam more than once because he did this and was too slow to write something else?  I don't know >_> )


Sending Push Notification From QuickBlox in Android

Question: I've used the quickblox chat sample and it worked fine, But I wanted to use push notifications in it.. So I followed some tutorials and read the sample and just done like it.. But when I push notification from QuickBlox Admin Panel: Messages no thing happens in my application.. No Logs, No Notifications.. No Thing..!
I'm sure that the project number and api key are correct..
Here's the manifest :
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.quickblox.sample.chat"
android:versionCode="1"
android:versionName="1.0" >

<uses-sdk
    android:minSdkVersion="10"
    android:targetSdkVersion="19" />

<permission
    android:name="com.quickblox.sample.chat.permission.C2D_MESSAGE"
    android:protectionLevel="signature" />

<uses-permission android:name="com.quickblox.sample.chat.permission.C2D_MESSAGE" />

<uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />

<uses-permission android:name="android.permission.INTERNET" />

<uses-permission android:name="android.permission.GET_ACCOUNTS" />

<uses-permission android:name="android.permission.WAKE_LOCK" />

<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.INTERNET" />

<application
    android:name=".ApplicationSingleton"
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >
    <activity
        android:name=".ui.activities.SplashActivity"
        android:configChanges="keyboardHidden|orientation|screenSize"
        android:label="@string/app_name"
        android:screenOrientation="portrait" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <activity
        android:name=".ui.activities.NewDialogActivity"
        android:configChanges="keyboardHidden|orientation|screenSize"
        android:screenOrientation="portrait" />
    <activity
        android:name="com.quickblox.sample.chat.DialogsActivity"
        android:configChanges="keyboardHidden|orientation|screenSize"
        android:screenOrientation="portrait" />
    <activity
        android:name=".ui.activities.ChatActivity"
        android:configChanges="keyboardHidden|orientation|screenSize"
        android:screenOrientation="portrait"
        android:windowSoftInputMode="adjustResize" />

    <receiver
        android:name=".GcmBroadcastReceiver"
        android:permission="com.google.android.c2dm.permission.SEND" >
        <intent-filter>
            <action android:name="com.google.android.c2dm.intent.RECEIVE" />
            <action android:name="com.google.android.c2dm.intent.REGISTRATION" />

            <category android:name="com.quickblox.sample.chat" />
        </intent-filter>
    </receiver>

    <service android:name=".GCMIntentService" />

    <meta-data
        android:name="com.google.android.gms.version"
        android:value="@integer/google_play_services_version" />
</application>
</manifest>

GcmBroadcastReceiver :
package com.quickblox.sample.chat;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.support.v4.content.WakefulBroadcastReceiver;
import android.util.Log;

public class GcmBroadcastReceiver extends WakefulBroadcastReceiver {

@Override
public void onReceive(Context context, Intent intent) {
    // Explicitly specify that GcmIntentService will handle the intent.
    ComponentName comp = new ComponentName(context.getPackageName(), GCMIntentService.class.getName());
    // Start the service, keeping the device awake while it is launching.
    Log.d("Login", "Receiver - Received Message!");
    startWakefulService(context, (intent.setComponent(comp)));
    setResultCode(Activity.RESULT_OK);
}
}

GCMIntentService :
package com.quickblox.sample.chat;

import android.app.IntentService;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.NotificationCompat;
import android.support.v4.content.WakefulBroadcastReceiver;
import android.util.Log;

import com.google.android.gms.gcm.GoogleCloudMessaging;
import com.quickblox.sample.chat.definitions.Consts;

public class GCMIntentService extends IntentService {

public static final int NOTIFICATION_ID = 1;

private static final String TAG = GCMIntentService.class.getSimpleName();

private NotificationManager notificationManager;

public GCMIntentService() {
    super(Consts.GCM_INTENT_SERVICE);
}

@Override
protected void onHandleIntent(Intent intent) {
    Log.i(TAG, "new push");

    Bundle extras = intent.getExtras();
    GoogleCloudMessaging googleCloudMessaging = GoogleCloudMessaging.getInstance(this);
    // The getMessageType() intent parameter must be the intent you received
    // in your BroadcastReceiver.
    String messageType = googleCloudMessaging.getMessageType(intent);

    if (!extras.isEmpty()) {  // has effect of unparcelling Bundle
        /*
         * Filter messages based on message type. Since it is likely that GCM
         * will be extended in the future with new message types, just ignore
         * any message types you're not interested in, or that you don't
         * recognize.
         */
       if (GoogleCloudMessaging.
                MESSAGE_TYPE_SEND_ERROR.equals(messageType)) {
            processNotification(Consts.GCM_SEND_ERROR, extras);
        } else if (GoogleCloudMessaging.
                MESSAGE_TYPE_DELETED.equals(messageType)) {
            processNotification(Consts.GCM_DELETED_MESSAGE, extras);
            // If it's a regular GCM message, do some work.
        } else if (GoogleCloudMessaging.
                MESSAGE_TYPE_MESSAGE.equals(messageType)) {
            // Post notification of received message.
            processNotification(Consts.GCM_RECEIVED, extras);
            Log.i(TAG, "Received: " + extras.toString());
        }
    }
    // Release the wake lock provided by the WakefulBroadcastReceiver.
    WakefulBroadcastReceiver.completeWakefulIntent(intent);
}

// Put the message into a notification and post it.
// This is just one simple example of what you might choose to do with
// a GCM message.
private void processNotification(String type, Bundle extras) {
    notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

    final String messageValue = extras.getString("message");

    Intent intent = new Intent(this, DialogsActivity.class);
    intent.putExtra(Consts.EXTRA_MESSAGE, messageValue);

    PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
            intent, 0);

    NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(
            this)
            .setSmallIcon(R.drawable.ic_launcher)
            .setContentTitle(Consts.GCM_NOTIFICATION)
            .setStyle(
                    new NotificationCompat.BigTextStyle()
                            .bigText(messageValue))
            .setContentText(messageValue);

    mBuilder.setContentIntent(contentIntent);
    notificationManager.notify(NOTIFICATION_ID, mBuilder.build());

}
}

I have the following code for registration in activity :
    gcm = GoogleCloudMessaging.getInstance(this);

    regId = getRegisterationId(this);
    Log.d("Login", "ID: " + regId);
    if (regId.isEmpty()) {
        new Thread(new Runnable() {
            @Override
            public void run() {

                try {
                    if (gcm == null) {
                        gcm = GoogleCloudMessaging.getInstance(DialogsActivity.this);
                    }

                    regId = gcm.register(Consts.PROJECT_NUMBER);
                    Log.d("Login", "Registered! ID: " + regId);

                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            subscribeToPushNotifications(regId);
                        }
                    });

                } catch (Exception e) {
                    Log.d("Login", "Reg e: " + e);
                }
            }
        }).start();
    } else {
        Log.d("Login", "Already Exist");
        subscribeToPushNotifications(regId);
    }       gcm = GoogleCloudMessaging.getInstance(this);

    regId = getRegisterationId(this);
    Log.d("Login", "ID: " + regId);
    if (regId.isEmpty()) {
        new Thread(new Runnable() {
            @Override
            public void run() {

                try {
                    if (gcm == null) {
                        gcm = GoogleCloudMessaging.getInstance(DialogsActivity.this);
                    }

                    regId = gcm.register(Consts.PROJECT_NUMBER);
                    Log.d("Login", "Registered! ID: " + regId);

                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            subscribeToPushNotifications(regId);
                        }
                    });

                } catch (Exception e) {
                    Log.d("Login", "Reg e: " + e);
                }
            }
        }).start();
    } else {
        Log.d("Login", "Already Exist");
        subscribeToPushNotifications(regId);
    }

public void subscribeToPushNotifications(String regId) {
    String deviceId = ((TelephonyManager) getBaseContext()
            .getSystemService(Context.TELEPHONY_SERVICE)).getDeviceId();

    QBMessages.subscribeToPushNotificationsTask(regId, deviceId,
            QBEnvironment.DEVELOPMENT,
            new QBEntityCallbackImpl<ArrayList<QBSubscription>>() {
                @Override
                public void onSuccess(ArrayList<QBSubscription> result,
                        Bundle params) {
                    Log.d("Login", "Successfully Registered");
                }

                @Override
                public void onError(List<String> errors) {
                    Log.d("Login", "e : " + errors);
                }
            });

}

private String getRegisterationId(Context context) {
    SharedPreferences prefs = getGCMPreferences(context);
    String registerationId = prefs.getString(PROPERTY_REG_ID, "");
    if (registerationId.isEmpty()) {
        Log.d("Login", "Not registered!");
        return "";
    }
    return registerationId;

}

private SharedPreferences getGCMPreferences(Context context) {
    return getSharedPreferences(DialogsActivity.class.getSimpleName(),
            Context.MODE_PRIVATE);
}

private void storeRegisterationId(Context context, String regId) {
    final SharedPreferences prefs = getGCMPreferences(context);
    SharedPreferences.Editor editor = prefs.edit();
    editor.putString(PROPERTY_REG_ID, regId);
    editor.commit();
}

And I get that registration done successfully.. :S
I've been searching for the solution for 2 days now :/ Any help will be appreciated.. Thanks.
Answer: I don't have enough reputation to comment, so I am putting this as a possible answer -
I have been working through the same for the last couple of days, and here are a couple of things to check:

When you set up the GCM API key, did you set any IPs?  You should leave this blank to accept all.
When you say the registration is done successfully, do you mean you get the onSuccess Log message from subscribeToPushNotificationsTask?  Check your device id; I was getting null for deviceId from:

String deviceId = ((TelephonyManager)getBaseContext().getSystemService(Context.TELEPHONY_SERVICE)).getDeviceId();
So instead I had to use
String deviceId = Secure.getString(this.getContentResolver(), Secure.ANDROID_ID);

What options were you selecting in the Quickblox Admin Panel > Messages?  Be sure you are selecting "GCM (Android Push)" under the channel option.
Lastly, make sure you are using all production or all development for your environments (QBEnvironment.DEVELOPMENT).  I somehow ended up with a mix, and switched them all to production now.

My push notifications are now working, so perhaps I can help out more if you have specific questions.