Accessing a Local Variable through Xajax and Classes in PHP

Question: I have a Class
<?php
class cms{
    private $dataset;
    private $columns;
    private $configs;

    public function __construct(){
        global $frw, $dbg;
        $this->configs =array();
    }

    public function __get($key){
        if(array_key_exists($key, $this->configs)==true){
            return $this->configs[$key];
        }else{
            throw new Exception('Unable to get value from configuration. '.$key);
        }
    }

    public function __set($key, $value){
        if(array_key_exists($key,$this->configs)){
            throw new Exception('Unable to set configuration. '.$key);
        }else{
            $this->configs[$key] = $value;
        }
    }

    public function exists($key){
        if(isset($this->configs[$key])){
            return true;
        }else{
            return false;
        }
    }

  public function load(){

  }

}
?>

$cms = new $cms;
I need to have a variable set on the page that instatiates the object and is available globally throughout each page (for duration of session).  I do not want a  session variable and I'd like not to use a global.  Is there a way of passing the $dataset between pages and calling $cms->dataset in an xajax load.  I keep thinking that I should be able to set a variable $dataset = $cms->__get('dataset');
Answer: Declare $dataset as public right now private $dataset is not accessible out side the class
public $dataset;

will be accessible outside the class
$cms->dataset


Abrir um PDF no Intel XDK

Question: Estou tentando criar um link para abrir um PDF no Intel XDK.

Porém ele abre o navegador e fica apenas na tela em branco.
Alguma sugestão?
Answer: Cara, eu tive muitos problemas com o XDK para abrir arquivos XLS, o que você precisa é usar um plugin de terceiros (na aba de projetos você tem como adicionar plugins do seu computador). Ele sozinho não consegue abrir os arquivos.
https://github.com/sitewaerts/cordova-plugin-document-viewer
Esse aqui aparentemente funciona, vou usar ele também então se der certo aqui eu posto o código!

Abrir um PDF no Intel XDK


Problems with left hand chords on the keyboard

Question: I'm a beginner keyboard player and I'm having a hard time hitting the correct keys on the left hand while trying to play chords with the left hand and melody with the right.
Do you have any tips that can help me train better? Do you learn how to hit the correct keys by training your fingers to make the shape it should to hit the chord or is there something more i could try?
Answer: Practice manipulating chords.
Start with a C major triad. Play up and down the scale with the same shape - playing white notes only.
As you do this, you will notice the types of chords you play: (C) major, (D) minor, minor, major, major, minor, diminished (sharpen the F to make it a Bm), (C octave) major.
On each degree of the scale, practice changing the chords from a major to a minor (flattening or sharpening the 3rd - the middle note in the triad) and vice versa.
Just practice loads of this, playing loads of different chord types on all the different degrees of the scale. Once you've nailed the different chords with just the white notes as the tonics (the bottom note in the triad) then move on and do the same with a chromatic scale.
Keep practicing the different types of chords on every note. Once you've done this you can try swapping the order of notes around within the triad or playing the same 3 notes more than once - these are inversions and in my experience get you so much more used to playing around on many different chords.
An example of playing around with the order: beginning with C triad (C E G). Perhaps play, G C E or C G C E - you get the idea.
Answer: If you are a beginner, the problem may not be "how to hit the correct keys". A more fundamental problem is "how to use your two hands independently" - which is not a skill that has a lot of use in real life, but it's essential for playing a keyboard.
I would suggest you back off from "playing chords and a melody" and get a piano tutor that starts you off playing single notes in each hand, with independent musical lines for each hand. It may seem boring to practice that type of exercise if you want to play "real music", but it will pay off in the long run.
Answer: Do you know about inversions?
This is when you have the same notes but play them in a different voicing with a different root note.
For example of you are playing C Major and moving to F Major and play all in root position, closed voicing (C-E-G to F-A-C) you have to more the entire left hand.
If you change the voice there will (most likely) be a common chord tone that you keep your finger on, and you may only need to move a few fingers.
For example play the same closed, root position C mentioned above then move to an F with C in the bass (2nd inversion). C-E-G to C-F-A. This allows that C note to stay the same, and you can just move the E up to F and G up to A, which are right next to the notes you were playing. You are still playing the same chords but just different voices that may be easier to move back and forth to and from.
There are a bunch of combinations that you can do, a good teacher may help you with this.
Another thing that may work is not playing full chords. This will vary depending on if you are playing solo or with a bass player.


What is the expression of the vector orthogonal to all linearly independent vectors but one?

Question: Given $n$ linearly independent vectors, $v_{1}, v_{2}, v_{3}, .......v_{n}$.
How to find construct a vector that is orthogonal to $v_{2}, v_{3}, ....., v_{n}$ (all $v$ but not $v_{1}$) and what's the general expression of it?
Is brute force of solving $n-1$ equations the only way to find it, (or $A^{T}x = 0$, where the columns of $A$ are $v_{2}....v_{n}$)? If so, can this give me a neat expression of such vector in terms of $v_{i}$?
In addition, can Gram Schmitt process be a way to do this? Will Gram Schmitt process give me a neat expression of such vector in terms of $v_{i}$?
Thank you very much.
Comment: Gram-Schmidt will indeed do it, as long as you order the vectors $\{v_2,\dots,v_n,v_1\}$ before beginning; the last vector output will be orthogonal to each of $\{v_2,\dots,v_n\}$. You can also take the determinant of the matrix whose top row consists of the symbols $\bf e_1,\dots,e_n$ and whose other rows are the vectors $v_2,\dots,v_n$.
Comment: @Greg Martin but isn't that last output orthogonal to the orthonormal bases {e2,....,en} created in previous steps only? Why is it also orthogonal to {v2,…,vn}?
Comment: Because the subspace spanned by $\{e_2,\dots,e_n\}$ is the same as the subspace spanned by $\{v_2,\dots,v_n\}$. That's the beauty of Gram-Schmidt!
Answer: Let $G$ be the Gram-matrix of $v_2,\dots,v_n$, that is $g_{ij}=\langle v_i,v_j\rangle$ and let $\tilde v$ the vector with $\tilde v_k=\langle v_1,v_k\rangle$. Then $G^{-1}\tilde v$ is the coordinate vector of the orthogonal projection of $v_1$ on the span of $v_2,\dots,v_n$. Hence $v_1-G^{-1}\tilde v$ is the desired vector.


Generic Sort for Number or Alphabet in Ascending or Descending Order

Question: How can I sort Generic array which can contain alphabet or numbers only?

Lets say I have a generic list of array that contains numbers only and
  can be easily sort using

 public void sortAsc(ref T[] obj)

   {
      do
            {
                didSwap = false;
                for (int i = 0; i < obj.Length - 1; i++)
                {
                    if (Convert.ToInt32(obj[i]) < Convert.ToInt32(obj[i + 1]))
                    {
                        T temp = obj[i + 1];
                        obj[i + 1] = obj[i];
                        obj[i] = temp;
                        didSwap = true;
                    }
                }
            } while (didSwap);

   }

but if array contains string of names and we wants to sort in same way will fail.
due to this

if (Convert.ToInt32(obj[i]) < Convert.ToInt32(obj[i + 1]))

Please let me know if there is a generic method for this or I will have to separate logic for each.
Answer: Take a look at the List<T>.Sort() method as this will do what you need.
It solves your problem of having to use Convert.ToInt32 because by default it will use the IComparer implementation of the actual class being used, which both int and string have already for you.
So for strings:
var list = new List<string> { "dd", "aa", "ss" };
list.Sort();

//Output: list = ["aa", "dd", "ss"]

Or for integers:
var list = new List<int> { 1, 13, 5 };

list.Sort();

//Output: list = [1, 5, 13]

If you want to work with custom classes, just make your class implement IComparable or by having the caller to Sort() to provide a function delegate to use. See the first link for more details in the docs.


RobotFramework + Selenium2library - Click on link for page that uses angularjs

Question: I am using Robot Framework and Selenium2Library for automating our application which uses angularjs.
I want to know if there is a way to click on an element based on ng-click="functionName()" that is if I can somehow use the functionName to click a link or button.
Answer: You can go with Xpath or CssSelector to select the element
<code>driver.findElement(By.cssSelector("[ng-click=\"functionName()\"]"));

driver.findElement(By.xpath("//*[@ng-click=\"functionName()\"]"));
</code>
Comment: You've shown selenium commands, but you can't directly run selenium commands in a robot framework test.


Suggestion for MATLAB statistical pattern recognition toolbox?

Question: I am looking for a pattern recognition toolbox in MATLAB capable of doing well and have enough number of possible routines. What can be good candidate?
Comment: Kevin Murphy's [probabilistic modeling toolkit is nice](http://code.google.com/p/pmtk3/)
Answer: I like SPIDER, but just because it has cool graphics.  It isn't a bad SVM and it can do some basics.
When it comes to pattern recognition, there are a lot of flavors of algorithms to choose from and each has its own trade-offs.  The kinds of patterns that you are trying to work with determine which methods are going to work better.  Without a clear specification there, it is somewhat difficult to make more headway into recommending a particular direction.


COUNTIFS, multiple criteria, including only specific values within date range

Question: Excel countif - I need to count a list of policies that are within a date range (expired policies) and include specific transaction types.
Originally, I needed to do the countif based on excluding values. Now as the transaction types have grown, it would be more efficient to just include the values I want. Below was the formula based on excluding certain values.
=COUNTIFS(A1:A4,"<"&DATE(2018,1,15),B1:B4,"<>"&"Can",B1:B4,"<>"&"END") allows me to exclude values I don't want recorded.
Policies are defined by transaction type: New, Ren, End, Can, REN-1, REN-2 etc...
I only want to count New and Ren within the date formula above however when I edit the above formula to =COUNTIFS(A1:A4,"<"&DATE(2018,1,15),B1:B4,"New",B1:B4,"REN") I just get a 0 value. Thanks for reading.
Answer: You are counting those that are both New and REN at the same time. Count each individually and add the separate results.


What are the metrics to evaluate a machine learning algorithm

Question: What are the various techniques and metrics used to evaluate how accurate / good an algorithm is? How would you use a given metric to derive a conclusion about a ML model?
Comment: There are no "metrics" to evaluate machine learning algorithms since machine learning algorithms do not constitute a metric space, I think you mean what "measures of performance are there".
Comment: I have summarized all the important metrics used in machine learning in this article https://medium.com/machine-learning-through-visuals/performance-metrics-machine-learning-through-visuals-84ebd7cdcc20
Answer: Some possible methods:

Focus on the predictive capability of a model: confusion matrix (computing the accuracy, F1-score, cost of classification). You can draw an ROC curve, and performance of every classifier is represented as a point on the curve. When you change the threshold in the algorithm, sample distribution, or the cost matrix of classification, the point locations will change as well.
Learning curve (bias-variance tradeoff). It helps determine the sample size and the feature size.
Calculate the ratio between the predictive accuracy of the model and the baseline accuracy (without using your model). It is also called lift chart.
Confidence interval of accuracy.


python zip contains whole structure not the file that is desired

Question: I want to zip a file in python and below is the code
output_file = 'D:/users/aaa.zip'
input_file = 'D:/users/aaa.txt'
zf = zipfile.ZipFile(output_file, "w", zipfile.ZIP_DEFLATED)
zf.write(output_file, arcname=input_file)
zf.close()
print('>> End zipFile...')

I am trying to zip the file but when I open to extract the created zip I have users folder and then aaa.txt. Is there a way that I have aaa.txt directly?
Answer: try following:
zf.write(outputFilename, filePath)


Weekly Gym schedule / irregular recurring Events / D7

Question: I've been searching and trying for weeks now, but could not find a way to properly display a gym's schedule. Here is the setup:

atm there are 3 gym branches with their own unique schedule (but using one pool of classes)
each gym got its own node showing a schedule table/calendar
classes recur irregular e.g. Gym-1: "Zumba" each Mo 8-9am and Fr 6-7pm (but Gym-2 with different times)
tables only need to be editable by admins; no user interaction
table granularity should be 15 or 30 minutes (but only showing rows with at least one item)
also, on the front page there will be a block, showing the next class for each gym (day and time)

So I created one node for each class (e.g. "Bodypump", "Zumba",..) and added all kind of fields but can not work out how to show them in 3 independent schedules. I think it has to be 3 views but unsuccesfully tried TableField, multi-value date Fields with FullCalendar, Taxonomy,...  Is it actually possible to do this with existing modules? Pushing me in the right direction would be highly appreciated!
Note: I am not capable of programming my own modules, but at least i would know how things stand when this is becoming necessary. Also I am not a Drupal pro and might have missed the obvious.. Thank you!
Answer: Try this:

Create content types gym1, gym2, gym3... > add suitable fields to them eg. Title and time(name the time field to field_gym1_calendar, reason for this -- see part five).
Create content: EXAMPLE: "content type: gym 3 --> Title: bodypump, Time: 10/10/2013 14:00-14:30".
You can also add a taxonomy "bodypump, zumba, etc..." and add a 'Term Reference'-field to your content type (This way admin doesn't have to type 'bodypump' or 'zumba' every time he's adding stuff to calendar, just select the right one from dropdown-box)
Install "Date Tools" and "Date"- modules
Go to Views > look for button "+ Add view from template" On top of the page.
Search for the NAME of the TIME field you added to CONTENT TYPE gym1.
Should look something like this: "A calendar view of the 'field_gym1_calendar' field in the 'node' base table."
Name this view to 'Gym 1 calendar'- for example.
If you have content in "gym1/......." It should be listed in "Preview" Below

Play around with "+ Add view from template" button, it creates a calendar view of any node type with -date / time- field in it (I think)
All this works in a commerce_kickstart install I'm currently f*cking with.. All the modules you need are listed in my comment... don't know. Have fun :)


Android Unity vuforia game resolution too short

Question: Can anyone please advise why the UI elements in the android application are too little comparing to the ones in the unity editor?
Have to mention that when I start the game in the editor on pc looks ok.
Please see the differences in the screens.
Maybe there are some settings IDK.
I am a beginner to Unity/Android games.

The android phone image.

The unity editor image.
Comment: use the canvas scaler component in the canvas, set it to scale with screen size with 0.5 value. That will fix it.
Answer:
Can anyone please advise why the UI elements in the android
  application are too little comparing to the ones in the unity editor?

That's because they have different Resolutions and aspect ratios.

Select different values to test how your game will look on display with different aspect ratios. This is set to Free Aspect by default.
To understand how ui scales in unity, read this manual.


Pegando valor de um campo SQL depois do retorno da função

Question: Como eu faço para pegar um determinado valor da tabela SQL após eu ter feito um select. Sempre irá retornar um único valor
$sql = "SELECT MAX(cod_periodo) from periodo_edital";
$query = $this->db->query($sql);
$result = $query->result();

Esse é meu código preciso acessar o campo cod_periodo.
Existe algum comando especifico para executar?
Comment: Experimenta dar um var_dump na variável `$result`, talvez já fique mais fácil de resolver
Comment: Ele retorna correto, porém na hora de eu usar o $cod_periodo na minha query ele insere como () e da erro no banco
Comment: Parece que não esta vindo o campo que você quer, coloca a query na pergunta, talvez o problema esteja lá.
Comment: Alterei, mas surgiu outro problema. Ele retorna um array como faço para pegar o valor string que ele retornou e mudar para inteiro
Comment: Você usa PDO ou mysqli?
Comment: To utilizando PDO
Answer: Você pode criar um nome (alias) para o MAX da consulta, facilita na hora do uso.
$sql = "SELECT MAX(cod_periodo) AS max_cod_pedido from periodo_edital";

e para recuperar o valor que vai retornar como um array você pode fazer assim:
echo $result[0]->max_cod_pedido;

dentro do $result[0] provavelmente vai existir um objeto
e que você acesso a atributo com ->max_cod_pedido
se for um array
echo $result[0][max_cod_pedido];

Como você comentou que o retorno é de linha unica, não a necessidade de iterar.
Porém talvez seja legal validar o existe o resultado esperado, afim de não gerar erros.
Algo assim, por exemplo:
if (isset($result[0])) {

Comment: Deu certo, muito Obrigado!


using functions inside constructors php

Question: In an effort to keep my code clean, I am attempting to replace a whole bunch of code in my constructor with a function.  I believe I am calling the function correctly but i'm not able to assign values to the variables as intended.
public function __construct($docID) {

    self::getDocumentInfo($docID);
    self::getTranscriptionInfo($docID);

}

private static function getTranscriptionInfo($docID) {
    $this->documentTranscription = 5;
}

Im getting an error "PHP Fatal error:  Using $this when not in object context in ...".  This is simplified for postings purpose, but would it be better just have a very large constructor and skip the functions all together?  Or is their a better way to assign values?
Comment: you should change your `$this` to `self::`
Answer: A static method is not a part of the class instance.  The static keyword means the method can be called within your class but it won't have any of the instance variables.
Remove the static keyword and change this:
self::getDocumentInfo($docID);
self::getTranscriptionInfo($docID);

to this:
$this->getDocumentInfo($docID);
$this->getTranscriptionInfo($docID);

Using $this means it will be calling it within the right instance context.
Some info the static keyword (added emphasis in italics):

Declaring class properties or methods as static makes them accessible without needing an instantiation of the class. A property declared as static cannot be accessed with an instantiated class object (though a static method can).
Because static methods are callable without an instance of the object created, the pseudo-variable $this is not available inside the method declared as static.
Source
http://php.net/manual/en/language.oop5.static.php
Comment: Ok, that is very understandable.  Thank you!

using functions inside constructors php


There's 8 black balls and 7 white balls. 3 of the balls are drawn at random. Probability of drawing 2 of one color and 1 of the other color?

Question: A bin has 8 black balls and 7 white balls. 3 of the balls are drawn at random. What is the probability of drawing 2 of one color and 1 of the other color?
Here's what I tried:
Case 1: 2 black balls and 1 white ball
8/15 * 7/14 * 7/13 = 392/2730 = 28/195
Case 2: 2 white balls, 1 black ball
7/15 * 6/14 * 8/13 = 336/2730 = 24/195
28/195 + 24/195 = 52/195 = 4/15
My teacher said it was wrong and I don't get why. She didn't give me the solutions either and just told me the answer was 4/5. Can someone tell me what I'm doing wrong? Thanks!
Comment: You need to multiply by $3$ as for example, in the first case, the white ball can be either the first, second or third.
Answer: What you have written corresponds to the case when first two balls of one color and then the ball of the other color are drawn. Therefore your calculations miss the factor 3 accounting for possible permutations of the balls.
Answer: As stated in the comments to your question, you have ascertained the probability of drawing two black balls and a white ball in that order and the possibility of drawing two white balls and a black ball in that order.  You have to multiply by $3$ to account for all possible orders of drawing the balls you want.
Here's another approach.  The only other possibility is to draw three balls of the same color.  The probability of drawing three black balls is $\frac{8}{15} \cdot \frac {7}{14} \cdot \frac{6}{13}=\frac{336}{15 \cdot 14 \cdot 13}$ and the probability of drawing three white balls is $\frac{7}{15} \cdot \frac{6}{14} \cdot \frac{5}{13}=\frac{210}{15 \cdot 14 \cdot 13}$, so the probability of one of these two occurrences is $\frac{446}{15 \cdot 14 \cdot 13}=\frac 15$, and the probability that doesn't happen (i.e., you end up with two balls of one color and one ball of another color) must therefore be $1-\frac 15=\frac 45$.
Answer: Case $1$: $2$ black balls and $1$ white ball. The correct probability will be
$P(2B,1W) = \displaystyle \frac{ 3 \cdot8 \cdot 7 \cdot 7}{15 \cdot 14 \cdot 13} = \frac{28}{65}$.
$\big[\text{It is basically } \frac{8}{15} \cdot \frac{7}{14} \cdot \frac{7}{13} + \frac{8}{15} \cdot \frac{7}{14} \cdot \frac{7}{13} + \frac{7}{15} \cdot \frac{8}{14} \cdot \frac{7}{13}\big]$
I would suggest think as selecting $2$ black balls out of $8$ and $1$ white ball out of $7$ vs. selecting any $3$ balls out of $15$ which can be written as -
$P(2B,1W) = \displaystyle {8 \choose 2}{7 \choose 1} / {15 \choose 3}$
Case $2$: $2$ white balls, $1$ black ball
$P(2W,1B) = \displaystyle {8 \choose 1}{7 \choose 2} / {15 \choose 3} = \frac{24}{65}$.
Adding them, we get probability as $\displaystyle \frac{4}{5}$.
Answer: The answer follows from the story of the Hypergeometric distribution! A random variable that counts the number of successes (in this case, let's call a success drawing a white ball) from a fixed number of draws (3, in our case) without replacement is said to have a Hypergeometric distribution. (If the scenario were instead with replacement, we'd have a Binomially distributed random variable on our hands.)
Let's let $X$ be this particular random variable. We know that at a minimum $X = 0$, and at a maximum, $X = 3$, but we're interested in the probability that $X = 2$ (2 white balls, 1 black ball) or $X = 1$ (1 white ball, 2 black balls). Since these cases are disjoint, we can simply add the probabilities of these two cases: $P(X=1) + P(X=2)$.
There are $\binom{15}{3}$ ways to pick 3 balls. To get exactly 2 white balls (and therefore, 1 black ball), we need to choose 2 white balls from the 7 possible white balls, and 1 black ball from the 8 possible black balls. The same logic can be used to evaluate the other case:
$$
\begin{align}
P(X=1) &= \frac{\binom{7}{1}\binom{8}{2}}{\binom{15}{3}}\\
P(X=2) &= \frac{\binom{7}{2}\binom{8}{1}}{\binom{15}{3}}
\end{align}
$$
Adding the probabilities together, we arrive at:
$$
P(X=1 \cup X=2) = \frac{4}{5}
$$


webform telephone field validation fails

Question: I am using webform-8.x-5.0 and created a telephone field with international phone numbers support. Before submitting the form if i enter some number like "+91fdfgdfg45646" it shows "Invalid phone number" (which i am not sure if it is a valid number or not). But when I submit the form it gets submitted. The issue is if it is invalid, the form should not have been submitted. Please suggest a solution. The form should not be submitted if it is invalid number.
Thanks in advance
Image for reference:
Answer: The international phone number element is only a client-side enhancement which is using the International Telephone Input library.
To validate the phone number via server-side validation you would need write custom code and to use a PHP library like https://github.com/giggsey/libphonenumber-for-php
Comment: The form shouldn't really submit if validation fails though (if it's using JS to validate the form it can also use JS to stop the submission) would that be a bug that needs to be raised or is this expected/inevitable behaviour?
Comment: I think this should be addressed the International Telephone Input library but I would be open to committing enhancements to the Webform module's 'Advance Telephone' element's server-side validation.
Comment: Admittedly I don't know the specifics of the implementation, but I wouldn't expect a JS filter library to stop a form submitting itself. I'd expect it to provide a boolean response, on demand, to the question "is this field valid", and then for my code to decide whether or not the form should be submitted based on that. Probably a discussion for the issue queue though. Might have some tie later, if I do I'll chuck a patch up


Conditional probability solved by bayes theorem

Question: I have this problem:
A car dealer sells 20% of cars from brand $B_1$, 30% of $B_2$ and 50% of $B_3$. It was reported that 20% of $B_1$ cars have airbags, as well as 5% and 2% for $B_2$ and $B_3$ respectively.
Given that a selected car has airbag, what is the probability of being $B_1$?
I tried to solve the problem using Bayes Theorem:

A: brand
C: has airbag

$$p(A=B_1 | C) = \frac{ p(C | A = B_1) \cdot p(A=B_1) } { p(C)}, $$
$$ p(C | A=B_1) = 0,2 \cdot 0,2 = 0,04 $$
$$ p(A=B_1) = 0,2$$
$$ p(C) = \sum_{i=1}^{n}p(A_i \cap C)\cdot p(A_i) = 0,058$$
$$ p(A = B_1 | C) = \frac{0,04 \cdot 0,2}{0,058} = 13,79\%$$
This is the way i solved, but i can't see an alternative in my test with this result. What i've done wrong?
Thanks!
Answer: $P(C|A=B_1)=0.2$ because you already know that the brand is $B_1$, and you don't need to multiply with $P(B_1)$ again. What you calculate is actually $P(C\cap \{A=B_1\})$.
You've made a similar mistake in the calculation of $P(C)$. It should be
$$P(C)=\sum_{i=1}^3 P(C\cap \{A=B_i\})=\sum_{i=1}^3 P(C|A=B_i)P(A=B_i)$$
Comment: Oh, thanks. I finally came up with the result of 0,6153.


What is the class of the singularity $5$ for $\exp(\frac{z}{z-5})$

Question: $$\exp(\frac{z}{z-5})$$
Has a singularity at $5$. The power series representation is
$$\sum_{k=0}^\infty z^k(z-5)^{-k}\frac{1}{k!}$$
How can we classify the singularity at $5$? I don't know how to deal with $z^k$. I don't see a way to pull it out or combine it with $(z-5)^{-k}$.
As the exponent has a pole of order $1$ at $5$, I think the result should be that the singularity is essential. But that is only a feeling, I don't know how to check/prove it.
What is the class of the singularity $5$ and how can it be shown?
Answer: Since\begin{align}\exp\left(\frac z{z-5}\right)&=\exp\left(1+\frac5{z-5}\right)\\&=e\exp\left(\frac5{z-5}\right)\\&=e\sum_{k=-\infty}^0\frac{5^{-k}}{(-k)!(z-5)^k}\end{align}and therefore $5$ is an essential singularity of $\exp\left(\frac z{z-5}\right)$.
Answer: I'm sure that there's a simpler way to do this, but note that you can find different sequences - $z_k \rightarrow 5$ and $z_n \rightarrow  5$, such that $f(z_k)\rightarrow 1$ and $f(z_n)\rightarrow 2$.
You can thus conclude that the singularity is essential.
Answer: You can write
$$\exp\left(\frac z{z-5}\right)=\exp\left(1+\frac 5{z-5}\right)\\
=e\exp\left(\frac 5{z-5}\right)$$
and expand the last.  You will not have the $z^k$ to contend with.
Answer: Testing an essential singularity is rather simple without power series. An isolated singularity of $f$ at $z_0$ is essential iff there are two sequences $(x_n),(y_n)$ with $\lim x_n =z_0=\lim y_n$ and $\lim f(x_n) \neq \lim f(y_n)$ - including $\infty$ as limit. In case of $\exp$-function follow the real line to $\pm \infty$.


Compare two independent variables

Question: I have two variables, one containing project delivery rates for a particular language, and the second containing team size that worked on these projects. I am particularly new to statistics and I want to test the two variables which may or may not be dependent. In other words I want to test the dependency of these two variables. I am using SPSS. Can someone guide me in this regard, which statistical tools can or should be employed for the above scenario?
Comment: It seems like a simple correlation would be what you're after I think?
Answer: So there are many possible methods to check for the dependency between two variables, but probably the easiest way (as @Martyn suggestion) is to check the correlation between the variables.  If you are a fan of statistical tests and p-values then you can even run a test to see whether or not the two variables have a statistically significant correlation, but I prefer to simply calculate the correlation and to plot the two variables (as a scatterplot) against each other to check for underlying dependencies.  Here are some plots illustrating some possibly patterns you could see and some pitfalls to avoid:
So as with figure 1, you could have a very high positive correlation between the two variables. So as one variable increases so does the other variable.

Figure 2, you could still have a high positive correlation but with more dispersion (or rather less association between the two variables).

Figure 3, you could have a negative correlation between the two variables. So as one variable increases the other variable will decrease (and vise versa).

Figure 4, there could be no apparent correlation between the two variables (correlation close to zero) and so we would not be able to distinguish a linear relationship between the two.

Figure 5, here is a pitfall you want to avoid and this is why it is wise to plot the data as well as check the correlation.  Remember that correlation measures linear association, and so a correlation of zero does not imply that there is no association between the variables it just implies there is no LINEAR association.  Clearly from the figure there is an association its just not linear.

I don't use SPSS so sorry I cannot help you out on that front.
Comment: Thanks. Pearson correlation shows a 0.085 meaning no correlation right? logically though delivery rates should be correlated with team size. Or am i wrong?
Comment: wonderful the way you explained it though
Comment: Well try plotting the data as well to see what that reveals.  A Pearson correlation of 0.085 would suggest that there is no linear relationship between delivery rates and team size.  I cannot however comment on whether they SHOULD or SHOULD NOT be correlated although intuitively you would think that they would. Its very unlikely but you could have potential outliers masking the relationship so a plot of the variables would be very helpful to check for this.

Compare two independent variables


Selected, Checked, NoWrap, Disabled attributes without corresponding values

Question: We had an interresting conversation today at work regarding the usage of special attributes in HTML namely:

Disabled
Checked
Selected
All other similar attributes that don't require a ="same_name" value

Some people at work use:

<input disabled>
<option selected>
<input checked>

And it actually works but some others (including me) use:

<input disabled="disabled">
<option selected="selected">
<input checked="checked">

Both versions work fine and one of the integrators (I'm one of the programmers) says that both validate fine.
What are the cases where one scenario would be better than the other? I was thinking about XML validity when you put the values and code readability when you don't. Are there any other scenarios or explanations you could add to that?
Thanks
Comment: thats pretty much the definition of community post here.
Comment: Note that this is mostly for accumulating all possible ideas and not one specific anwser. Anyone giving a more complete anwser than just posting 1 simple fact will get the anwser flag.
Answer: Some templating systems (such as PHP TAL) will not validate properly without the full attribute: disabled="disabled".
Answer: The key question is whether you actually need XML conformance, but then this would be just one of the many details to take care of.
Omitting the value is slightly more readable and looks slightly less foolish (these "Boolean" attributes look foolish when using the full syntax, don't they?).
There is a small chance of messing things up using the full syntax—when you mistype the value. But validators will catch that.
Some ancient browsers only accepted the minimized syntax. This was long ago, but some of us still have habits based on such things.
Answer: In the HTML5 standard, attributes can be specified in four different ways. This is the way for disabled, readonly, etc:

Empty attribute syntax   Just the attribute name. The value is implicitly the empty string.   In the following example, the disabled
  attribute is given with the empty attribute syntax:

<input disabled>


Migrate Grail's HSQLDB embedded database

Question: how to migrate Grail's HSQLDB embedded database(That contains my App's Data that I don't want to lose) into external one, such as MySQL or ApacheDerby?
Answer: If your data isn't important just let hibernate regenerate your schema, else try this: http://www.grails.org/plugin/liquibase
Comment: But I do want to save the data!
Comment: I checked out LiquiBase features http://www.liquibase.org/swf/overview_long/LiquiBase%20TechTalk.html,

 I am curious is Apache DdlUtils similar to Liquibase?
Comment: @GrailsNewbie there's some functionality overlap but Liquibase has more features. Also there's dbmigrate plugin that is based on apache ddlutils.
Answer: Because grails uses hibernate underneath, no migration is necessary.  All you need to do is repoint your conf\DataSources.groovy to the new database, and next time you startup, it will create tables in the new DB.
See section 3.3 in this doc for more information on MySQL config.
Answer: The MySQL Migration Toolkit may be exactly what you need.
A little searching turned up this article that shows examples of what the GUI Tool looks like.
I haven't had to migrate data from a HSQLDB to any other DB, but if I had data that I didn't want to use in a HSQLDB then I'd definitely try this method.

You are going to want to backup the
HSQLDB database that you want to save
(I'm assuming you used a file DB
rather than an in-memory one right?)
Change your DataSource to a MySQL
datasource with the dbCreate set to
update (or something non-destructive)
Run the Migration Toolkit and migrate
your data

Otherwise you ought to be able to view the data in your DB by using another tool (DBVisualizer, RazorDB, or others)  and they might be able to help you export the data.


How to translate from statement-based to row-based replication in MySQL

Question: I have a production system that uses MySQL statement based replication for hot failover should a master database die. Running version 5.5 Percona. I have to use statement based replication for reasons that are immutable for the purposes of this question.
Now, I'd like to see the row-based replication stream of the same data, with the goal of trying to adapt this into an HBase based data store.
Is it possible to set up a MySQL server to slave (read) using statement-based replication, but at the same time be replication master (write to other slaves) using row-based replication? If so, how do I set this up? I've looked in the docs but failed to find it.
Answer:
I have to use statement based replication for reasons that are immutable for the purposes of this question.

I assume, for the purpose of this question, that there may indeed be compelling reasons for using statement-based logging¹ but it is not generally recommended, because statement-based logging is relatively fragile.  On any system where you have the flexibility not to use statement-based logging, don't use it -- use MIXED or ROW.²
MySQL Server (and compatible systems, like Percona Server, MariaDB, and Aurora for MySQL) automatically "translate" from one format to the other, based on the configuration of each individual server.

"Each MySQL Server can set its own and only its own binary logging format (true whether binlog_format is set with global or session scope). This means that changing the logging format on a replication master does not cause a slave to change its logging format to match."
— https://dev.mysql.com/doc/refman/5.6/en/binary-log-setting.html

To restate this with some additional implications, what you want to do "just works," because the setting of binlog_format on the slave does not specify what the slave expects.  It only sets what the slave will generate.
Configure the slave with binlog_format=ROW and enable log_slave_updates in my.cnf on the slave (which causes incoming events to be rewritten to the slave's binlog).
...and you're done.
The slave will log all of its DML as row-based events in spite of the master's binlog format.  You don't really have to do anything else to make a slave also be a master, since every MySQL server with binary logging enable is, essentially, already a master -- it just may happen to be a master without any actual slaves.
Any combination of master and slave binlog_format is valid except for a master configured as ROW and a slave configured as STATEMENT (the opposite of what you're doing here), because while statements can be translated into row events (they affect rows on the slave, after all), the converse isn't true -- you can't necessarily determine the specific statement that changed rows, if your only knowledge is the actual changed data.  But for the application you're asking about, the above should do exactly what you intend.
I also discussed the interactions of the possible combinations of master and slave binlog format here, on dba.stackexchange.com in some additional detail.

¹logging is used here rather than "replication" because it's a more accurate description of what is actually being configured, though arguably the meaning is unchanged.
² STATEMENT logs the actual queries that made the change; ROW logs "row images" of the rows inserted/updated/deleted by the query.  For updates, boththe old and new values are logged.  MIXED mode allows the server to choose the format for each query, always using ROW when there is anything about the query that makes its impact on the database potentially unsafe for statement-based replication, because the replica could potentially interpret it in a way that would cause the replica's data to diverge from the master, because the query isn't deterministic.  Examples might include an unordered UPDATE ... LIMIT where the replica might update a different set of rows depending on its index selection, and statements using non-deterministic functions like UUID().  Other seemingly-non-deterministic functions like NOW() and RAND() are compatible with statement-based replication, because there are hints written to the statement log to indicate the master's system time, and the master's random seed, at the time the query was executed.
Comment: Thank you for this answer. Triple-AAAA+, 10/10, would ask again!


'Server Application Unavailable' in IIS7 after switching to .net 4.0

Question: We recently upgraded to .Net 4.0 and wrote a custom deployment script for our application that uses the Microsoft.Web.Administration library to do things like create websites and setup app pools. We started testing the code on developer boxes and it seemed to work. Then we noticed that if the dev re-built the application it would stop running and IIS7 would give us this (practically useless) error message:

Server Application Unavailable
The web application you are attempting to access on this web
  server is currently unavailable.
  Please hit the "Refresh" button in
  your web browser to retry your
  request.
Administrator Note: An error message detailing the cause of this
  specific request failure can be found
  in the application event log of the
  web server. Please review this log
  entry to discover what caused this
  error to occur.

If we manually recycle the application pool the app will start right back up. We don't see any events or errors in the Application Log. The pool is set to automatically start and recycle on configuration changes.
We have tried every combination of setting in the app pool, application and ASP.net settings. We have tried running the app pool as different user accounts. We have tried deleting the app pool and the application and re-creating both by hand through the UI and the problem still persists.
It's as if using the Microsoft.Web.Administration library poisons the machine so it will never automatically restart app pools again??!!
We would appreciate any insight or debugging advice. We cant run this on any production systems until we understand what caused this to happen.
Answer: Are you calling Site.Stop() by any chance? That does change the autoStart property of the site to false, calling Start() would set it back to true.
To make sure there is no other tricks, you I would recommend copying the file %windir%\System32\Inetsrv\Config\ApplicationHost.config to some backup directory, then run your deployment app, and then Diff both files after that and see the differences, my guess is that you will see some autoStart properties set to false. If that is the case, that is caused because of calling Stop and never calling Start again (before CommitChanges)
Check to see if your code has a pattern of:
Site.Stop() ... do changes in memory .... ServerManager.CommitChanges() .... Site.Start()
You will never commmit the last Start that modified it to autoStart
Comment: That's a good angle of attack, at one point we has something like that. We have a cluster so we don't want any of the machines starting up until everything else is in place. So we stop all the sites in one pass. Then make configuration changes. Then start all machines in a final pass.

We have re-created the site by hand and the auto start property is set to true.

Diffing ApplicationHost.config against another working machine may reveal something...
Comment: Ok, I merged my ApplicationHost.config with a known working copy from another machine. They are nearly identical now (some of the crypto has to be different). All auto start type settings are as they are on the other machine. I still get the error when I re-build.

I'm starting to think it's not IIS or it's in there so deep that it might require a re-install.
Answer: I found this thread while searching for the exact same error description. And I found what was causing it in my case.
I was converting an application from .net 3.5 to 4.0 and after I changed the app-pool from 2.0 to 4.0 this started. It only happened in classic mode not integrated.
In my case I had wildcard http handlers in web.config:
<add name="Wildcard .net 64 bit" path="*" verb="*" modules="IsapiModule" scriptProcessor="C:\Windows\Microsoft.NET\Framework64\v2.0.50727\aspnet_isapi.dll" resourceType="Unspecified" requireAccess="None" preCondition="bitness64"/>
<add name="Wildcard .net 32 bit" path="*" verb="*" modules="IsapiModule" scriptProcessor="C:\Windows\Microsoft.NET\Framework\v2.0.50727\aspnet_isapi.dll" resourceType="Unspecified" requireAccess="None" preCondition="bitness32"/>

But I had forgotten to change the path to the .net 4.0 directory
so after changing \v2.0.50727\aspnet_isapi.dll to \v4.0.30319\aspnet_isapi.dll the website started behaving normally.
Hope this helps someone.
Comment: It does seem to be limited to the "classic" mode app pools. We have since switched over to integrated mode. I think your answer is as good as we will get on this.
Answer: Not sure if you've already been through this, but you can't mix .NET 4 and .NET 2 apps in the same application pool.  This problem bit us recently.  We had to create a new app pool, and assign the new .NET 4 web app to that pool.  All the .NET 2 apps reside in the other one.
At that point, everything was happy, and the message you mentioned went away.
Comment: In our case its a single 4.0 app in a pool by itself.
Comment: @Gareth - gotcha - sorry, it was worth a try.


DataTables JQuery não renderiza botão em coluna no Codeigniter

Question: Estou tentando colocar botões de ação na minha tabela através do plugin datatTable.
Meu código Javascript
$(document).ready(function(){

    var table = $('#dataTable').DataTable( {
        "processing": true,
        "serverSide": true,
        "ajax": {
            "contentType": "application/json",
                "url": "http://localhost:8000/usuario/listar"
        },
        "columnDefs": [{
            "targets": -1,
            "data": null
            }
        }]
    });

});

e meu Controller no Codeigniter
<?php

class Usuario extends CI_Controller {

    public function __construct(){
        parent::__construct();
        $this->load->model('UsuarioModel');
    }

    public function listar(){
        $data = $this->UsuarioModel->all()->result();
        $row = [];
        foreach($data as $dados){
            $row[] = array($dados->nome, $dados->endereco);

        }
        $d['data'] = $row;
        echo json_encode($d);
    }

}

A ideia é que pelo DataTable ele criar botões de ação com "editar", "remover", "visualizar" com o id no botão da minha resposta json.
Comment: Pelo código apresentado vc não está criando os botoes, para o Datatables.
Você pode fazer essa criação pelo PHP mesmo.
Answer: Substitua essa parte do seu código:
            $row[] = array($dados->nome, $dados->endereco);

por essa:
           $row[] = $dados->nome;
           $row[] =  $dados->endereco;
           $row[] = "id . "'class='btn btn-primary' >Editar";

Comment: Explique o seu código, as vezes a pessoa não entendeu, não sabe onde deve colocar, não conhece alguma função, etc.
Comment: já fiz a alteração


C Basic ring buffer issue

Question: I'm having an issue with a basic ring buffer that I am trying to make.
I can not seem to get it to wrap around correctly.
When I hit the number of elements = buffer_length, the behavior becomes unpredictable and in the debugger it will only show the first * elements.
Can anyone see a glaring error that I am missing.
Thanks In advance.
#include "stdafx.h"
#include <stdio.h>
#include <string.h>

#define BUFFER_LENGTH 8

typedef struct circular_buffer
{
    float buffer[BUFFER_LENGTH];
    float *buffer_end;
    float *head;
    float *tail;
    size_t count;
} circular_buffer;

circular_buffer buffer;

void cb_init(circular_buffer *cb)
{
    memset(cb->buffer, 0, BUFFER_LENGTH * sizeof(float));

    cb->buffer_end = (float *)cb->buffer + BUFFER_LENGTH * sizeof(float);
    cb->count = 0;
    cb->head = cb->buffer;
    cb->tail = cb->buffer;
}

void cb_push_back(circular_buffer *cb, float item)
{
    *cb->head = item;
    cb->head = (float *)cb->head++;
    if (cb->head == cb->buffer_end)
        cb->head = &cb->buffer[0];
    cb->count++;
}

float cb_pop_front(circular_buffer *cb)
{
    float item = 0;
    item = *cb->tail;
    cb->tail = (float*)cb->tail++;
    if (cb->tail == cb->buffer_end)
        cb->tail = &cb->buffer[0];
    cb->count--;
    return item;
}

float cb_peek_front(circular_buffer *cb, size_t pos)
{
    float *arrPos;
    size_t i = 0;
    do
    {
        arrPos = (float*)cb->tail + i;
        if (arrPos == cb->buffer_end)
            arrPos = cb->buffer;
        i++;
    } while (i <= pos);

    return *arrPos;

}

int _tmain(int argc, _TCHAR* argv[])
{
    cb_init(&buffer);

    cb_push_back(&buffer, 5);
    printf("%f\n",cb_pop_front(&buffer));
    cb_push_back(&buffer, 6);
    printf("%f\n", cb_pop_front(&buffer));
    cb_push_back(&buffer, 7);
    printf("%f\n", cb_pop_front(&buffer));
    cb_push_back(&buffer, 8);
    printf("%f\n", cb_pop_front(&buffer));
    cb_push_back(&buffer, 9);
    printf("%f\n", cb_pop_front(&buffer));
    cb_push_back(&buffer, 10);
    printf("%f\n", cb_pop_front(&buffer));
    cb_push_back(&buffer, 11);
    printf("%f\n", cb_pop_front(&buffer));
    cb_push_back(&buffer, 12);
    printf("%f\n", cb_pop_front(&buffer));

    // stops working here
    cb_push_back(&buffer, 13);
    printf("%f\n", cb_pop_front(&buffer));

    cb_push_back(&buffer, 14);
    printf("%f\n", cb_pop_front(&buffer));

    return 0;
}

Comment: Why don't you just treat the buffer as an array and work with an index instead of a pointer? Then the index wraps with say `index = (index + 1) % BUFFER_LENGTH` when advancing forward, or `index = (index + BUFFER_LENGTH - 1) % BUFFER_LENGTH` when moving backwards.
Comment: You don't test for "buffer full" on input or "buffer underrun" on output. The only test you do there is for "buffer run-around". Also, having "head", "tail" *and* "count" is somewhat redundant.
Comment: `cb->head = (float *)cb->head++;` Undefined behavior here. And why convert from float to float?
Answer: This
cb->buffer_end = (float *)cb->buffer + BUFFER_LENGTH * sizeof(float);

will not do what you expect.
Change it to be
cb->buffer_end = cb->buffer + BUFFER_LENGTH;

to have it point just beyond to the buffer's last element.

Also just remove all those useless casts to (float *).

Moreover you want to replace
cb->head = (float *)cb->head++;

by just a simple
cb->head++;

and
cb->tail = (float*)cb->tail++;

by
cb->tail++;

Comment: seems adequate to fix the problem in OP's code. It will be great if the downvoter left a comment.
Comment: @ManosNikolaidis, not me, but the downvote was on the first draft of the answer, which was then temporarily deleted.
Answer: You are incorrctly considering the size of the element when using pointer arithmetic. For example
bufpointer += 1;

advances to the next element, exactly like you do with array indexing, where you also do not need to consider the size of each element. So
cb->buffer_end = (float *)cb->buffer + BUFFER_LENGTH * sizeof(float);

becomes
cb->buffer_end = cb->buffer + BUFFER_LENGTH;

C Basic ring buffer issue


string.find() not finding the first character in Python

Question: I'm trying to make a hangman-style game, and it works, for the most part...I just can't get the word to find the first character in it(for instance, if the word is like "hello" and I typed in "h" it wouldn't work, but if I typed in any other character, it would)
Here's my code:
import os

def clear():
    os.system("clear")

def chooseWord():
    return input("Player 1, please choose a word: ")

def guessWord():
   return input("Player 2, please guess a character: ")

word = chooseWord().lower()
characters = len(word)
clear()
print(f"The word has {characters} characters!")
chances = 3
print(word)

guessedCorrectly = guessWord().lower()

if word.find(guessedCorrectly):
    print("Hi")
else:
    print("hi")

Comment: What is the output? Does it return -1 or any other integer?
Comment: Mureinik is correct.  But could use `if guessedCorrectly in word:` which will return true or false
Answer: Why don't you try this:
if guessedCorrectly in word:
    print("Hi")
else:
    print("hi")

Answer: find returns the first index in the string where the search string occurs, or -1 if it doesn't. Since string indexes are zero-based in Python, find returns 0 if the search string occurs in the first character, and 0 is a false-y. Instead of using the index as a condition directly, you could explicitly compare it to 0:
if word.find(guessedCorrectly) >= 0:
    print("Found this character")
else:
    print("Didn't find this character")

Answer: find() returns the index of the matched string, not a boolean. The index 0 is falsey, so treating it as a boolean will fail when the match is at the beginning of the string.
Since you don't care about the index, use the in operator:
if guessedCorrectly in word:

Answer: word.find doesn't return a true or false it returns an index. The index of H in Hello is 0 which happens to map to False in if/else statements. Try using
if guessedCorrectly in word:

Answer: str.find() returns the first index occurrence of a substring in a string. If it cannot find the substring, then it returns one. Just replace the condition part. Therefore, your code should be like this:
import os

# def clear():
#     os.system("clear")

def chooseWord():
    return input("Player 1, please choose a word: ")

def guessWord():
   return input("Player 2, please guess a character: ")

if __name__=="__main__":
    word = chooseWord().lower()
    characters = len(word)
    # os.system("clear")
    print(f"The word has {characters} characters!")
    chances = 3
    # print(word)

    guessedCorrectly = guessWord().lower()
    print(guessedCorrectly)

    if not (word.find(guessedCorrectly)==-1): #that means there is a substring match!!!
        print("Yes")
    else:
        print("no")

Comment: I think you mean "returns negative one"
Comment: `not(xxx == -1)` can be simplified to `xxx != -1`
Comment: Yes, but there's no difference in them, this is just a readable way:
https://stackoverflow.com/a/5782597/4781513
Comment: I guess it's just personal style, but I always from `!=` more readable than `not`


Second pair of matching birthdays

Question: The "birthday problem" is well-known and well-studied.  There are many versions of it and many questions one might ask.  For example, "how many people do we need in a room to obtain at least a 50% chance that some pair shares a birthday?"  (Answer: 23)
Another is this: "Given $M$ bins, what is the expected number of balls I must toss uniformly at random into bins before some bin will contain 2 balls?"  (Answer: $\sqrt{M \pi/2} +2/3$)
Here is my question: what is the expected number of balls I must toss into $M$ bins to get two  collisions?  More precisely, how many expected balls must I toss to obtain the event "ball lands in occupied bin" twice?
I need an answer for very large $M$, so solutions including summations are not helpful.

Silly Observation:
The birthday problem predicts we need about 25 US Presidents for them to share a birthday.  It actually took 28 presidents to happen (Harding and Polk were both born on Nov 2).  We see from the answers below that after about 37 US Presidents we should have a 2nd collision.  However Obama is the 43rd and it still hasn't happened (nor would it have happened if McCain had won or Romney had won; nor will it happen if H. Clinton wins in 2016).
Comment: Interesting. So a second collision occurs when a ball lands in a bin with either one or two other balls in it. That might be an extra challenge.
Comment: When you go to multiple collisions, there are more ways in which the event can happen. To be precise, is it correct that you're looking for the balls to toss until "either two bins have two balls each, or one bin has three balls"? Or only the former?
Comment: My statement is "ball lands in an occupied bin" twice; that would encompass both or your scenarios.  (Restricting to either of your two sub-cases would be interesting problems as well... I would be happy to see a solution to any of them.)
Answer: I'll first write down the exact answer (summation included), and then various approximations.
Let $X$ be the random variable denoting the number of balls after which the second collision occurs. We want $E[X]$. As $X$ takes only non-negative integer values, its expectation is
$$E[X] = \sum_{n=1}^{\infty}\Pr(X \ge n) = \sum_{n=0}^{\infty}\Pr(X > n)$$
The probability $\Pr(X > n)$ is the probability that after $n$ balls are thrown into the $m$ bins, the number of collisions is either $0$ or $1$. The probability of $0$ collisions is, as in the classical birthday problem, $\dfrac{m(m-1)\dots(m-n+1)}{m^n}$. The probability of exactly one collision can be calculated as follows: for this to happen, some pair of balls must go to the same bin, after which the other $n-2$ balls must go to the other $m-1$ bins without collision, so the probability of this is $\displaystyle \binom{n}{2} m \frac{1}{m^2} \frac{(m-1)(m-2)\dots(m-n+2)}{m^{n-2}} = \binom{n}{2} \frac{m(m-1)(m-2)\dots(m-n+2)}{m^n}$. Note that this is precisely $\binom{n}{2} \frac{1}{m-n+1}$ times the probability of $0$ collisions.
For the classical birthday problem, the same analysis as above gave that the expected number of balls until collision (call this random variable $Y$) is
$$
\begin{align}
E[Y]
&= \sum_{n=0}^{\infty} \frac{m(m-1)\dots(m-n+1)}{m^n} \\
&= 1 + 1 + \frac{m-1}{m} + \frac{(m-1)(m-2)}{m^2} + \frac{(m-1)(m-2)}{m^3} + \dots
\end{align}$$
The asymptotic expansion of this sum, related to Ramanujan's Q-function, is known to be
$$\sqrt{\frac{\pi m}{2}} + \frac{2}{3} + \frac{1}{12}\sqrt{\frac{\pi}{2m}} - \frac{4}{135m} + \dots$$
In our case, the expected number of balls until two collisions is the old sum, plus additionally the sum of the terms coming from the probabilities of having exactly one collision: it is
$$
\begin{align}
E[X] &= \sum_{n=0}^{\infty} \left( \frac{m(m-1)\dots(m-n+1)}{m^n} +  \binom{n}{2} \frac{m(m-1)(m-2)\dots(m-n+2)}{m^n} \right) \\
&= 1 + 1 + \frac{m-1}{m} + \frac{(m-1)(m-2)}{m^2} + \frac{(m-1)(m-2)(m-3)}{m^3} + \dots\\
&\phantom{=1+1} + \frac{1}{m} + 3\frac{(m-1)}{m^2} + 6\frac{(m-1)(m-2)}{m^3} + \dots
\end{align}
$$
That's the exact expression; now for the approximations.

One trivial fact we can prove rigorously is that $E[Y] < E[X] < 2E[Y]$. The former inequality is from the fact that the second collision can only happen after the first one, so $X \ge Y$. The second inequality is from the fact that after the first collision if we clear all the bins and wait for a collision to happen again from scratch, the second collision can only take longer than in the normal case. So
$$\sqrt{\frac{\pi m}{2}} < E[X] < \sqrt{2\pi m}$$

One avenue of approximation is to instead calculate the "median" $X$, as Ross Millikan's answer does: find the number of balls $n$ for which the probability of $0$ or $1$ collisions is $\frac{1}{2}$. The expected value of $X$ will be around this. (And also strictly more than half of this $n$, because we have $E[X] \ge n \Pr(X \ge n) = \frac{n}{2}$.)
His answer already gives one way, here is another. From the expression we calculated above for the probability, we want $n$ such that
$$
\begin{align}
\frac12
&= \frac{m(m-1)\dots(m-n+1)}{m^n} +  \binom{n}{2} \frac{m(m-1)(m-2)\dots(m-n+2)}{m^n} \\
&= \left(\frac{m-n+1}{m} + \binom{n}{2}\frac{1}{m} \right) \frac{m(m-1)(m-2)\dots(m-n+2)}{m^{n-1}} \\
&= \left(\frac{m-n+1}{m} + \binom{n}{2}\frac{1}{m} \right)
\left(1 - \frac1m \right) \left(1 - \frac2m \right) \cdot \dots \cdot \left(1 - \frac{n-2}m \right) \\
&\approx \left(1 + \frac{n^2}{2m} \right)
e^{-1/m} e^{-2/m} e^{-3/m} \dots e^{-(n-2)/m} \\
&\approx \left(1 + \frac{n^2}{2m} \right) e^{-n^2/2m} \\
\end{align}$$
which gives exactly the same approximation $\frac{n^2}{2m} \approx 1.678$ as in Ross Millikan's answer! Specifically, it gives $E[X] \approx 1.83\sqrt{m}$.

Another approximation is to use $E[X] = E[E[X|Y]]$ and assume that $Y$ (the time of the first collision) is concentrated about its mean. After the first collision happens (after $Y$ balls), there are $Y-1$ nonempty bins, so about a fraction $\frac{Y}{m}$ of the bins are nonempty and a fraction $1 - \frac{Y}{m}$ of the bins are empty. The second collision happens when either a ball lands into one of the currently occupied bins, or a ball lands for the second time into one of the bins not yet occupied. The former is much more likely to happen first than the latter. The expected time that the former takes is $\dfrac1{Y/m}$, as it's a geometric distribution (like tossing a coin that has probability $\frac{Y}{m}$ of heads, until heads comes up). So
$$E[X] \approx E\left[Y + \frac{m}{Y}\right] $$
which if $Y$ is strongly concentrated around $\sqrt{\frac{\pi m}{2}}$, will be
$$E[X] \approx \sqrt{\frac{\pi m}{2}} + \sqrt{\frac{2m}{\pi}} = \sqrt{m}\left( \sqrt{\frac{\pi}2} + \sqrt{\frac2\pi} \right)$$
which ($E[X] \approx 2.05\sqrt{m}$) is slightly more than the answer given by the first approximation.

We know that $E[X]$ is between $\sqrt{\frac{\pi}{2}}\sqrt{m}$ and $\sqrt{2\pi}\sqrt{m}$, so we know for sure that asymptotically, $E[X] \sim c\sqrt{m}$ for some constant $c$. We just need to find the constant $c$, and it seems the best way is to write a program for it. Here's a Python program that uses the exact formula above to calculate the value of $E[X]$ for increasing $m$, and prints $\frac{E[X]}{\sqrt{m}}$:
<code>import math

def x(m):
    ans = 2
    term = 1
    other_term = 1.0 / m
    for n in range(2, m + 2):
        term *= (m - (n - 1.0))  / m
        other_term *= (m - (n - 2.0)) / m
        ans += term + (n * (n - 1) * other_term) / 2
    return ans

m = 1
while True:
    m *= 2
    n = x(m)
    print m, n, n / math.sqrt(m)
</code>
which prints (among other things):
<code>...
16777216 7701.36209791 1.88021535594
33554432 10890.956487 1.88014384413
67108864 15401.7241385 1.88009327862
134217728 21780.9129334 1.88005752389
...
</code>
so $c \approx 1.88$ or $E[X] \approx 1.88\sqrt{m}$ seems to be the true statement.

We can say more about birthdays specifically ($m = 365$). With a minor change to the above program, for each $n$, we can calculate exactly the probability that $X = n$ (i.e., that it takes $n$ people until the second collision happens). This turns out to give the following distribution.
<code> n       P(X > n)      P(X = n)
 25      0.810743      0.023477
 26      0.785794      0.024950
 27      0.759490      0.026304
 28      0.731969      0.027521
 29      0.703384      0.028585
 30      0.673899      0.029485
 31      0.643690      0.030209
 32      0.612939      0.030752
 33      0.581830      0.031109
 34      0.550548      0.031281
 35      0.519278      0.031270
 36      0.488198      0.031081
 37      0.457476      0.030721
 38      0.427275      0.030202
 39      0.397741      0.029533
 40      0.369011      0.028730
 41      0.341204      0.027807
 42      0.314426      0.026779
 43      0.288763      0.025662
 44      0.264290      0.024473
 45      0.241061      0.023229
 46      0.219117      0.021944
 47      0.198482      0.020635
 48      0.179168      0.019315
 49      0.161170      0.017997
 50      0.144476      0.016695
 51      0.129058      0.015418
 52      0.114881      0.014177
 53      0.101902      0.012979
 54      0.090072      0.011830
 55      0.079334      0.010738
</code>
So as $P(X > 43)$ is still a very healthy $0.288763$, it's nothing to be very surprised about that there is still only one collision among the 43 US presidents so far. :-)
Comment: @Fixee: I've asked it as a question [here](http://math.stackexchange.com/questions/420923/conjecture-the-folowing-sum-is-asymptotic-to-exactly-9m-8).
Comment: Very nice!  I have been working on this problem since I posted it and I followed virtually the exact same steps as you do above, but you are faster.  I just last night wrote the same program you did (in C instead of Python, but they're almost identical!).  I feel guilty seeing all the work you did on this... I'm doing this just for fun (it's summer after all!).  Cheers.
Comment: @Fixee: No problem; I also did it just for fun. :-) Cheers,
Comment: I have worked (unsuccessfully) at finding a closed form for the constant $c \approx 1.88$ that you approximate via your python program above.  Unfortunately the integral that so nicely turns into $\sqrt{\pi/2}$ ends up being much harder with the ${n \choose 2}$ multiplier.
Comment: @Fixee: Yes, I don't know of a closed form either. BTW, after running (a C version of) that Python program for many *days,* going up to $2^{38}$, gave the impression that the limiting constant $c$ should be slightly less than 1.879973, and this is suspiciously close to $\sqrt{\frac98 \pi} \approx 1.879971$, but this may be just a coincidence.
Answer: Suppose there are $n$ people, and we want to allow $0$ or $1$ collisions only.
$0$ collisions is the birthday problem: $$\frac{M^{\underline{n}}}{M^n}$$
For 1 collision, we first choose which two people collide, ${n\choose 2}$, then the 2nd person must agree with the first $\frac{1}{M}$, then avoid collisions for the remaining people, getting $${n \choose 2}\frac{M^{\underline{n-1}}}{M^{n}}$$
Hence the desired answer is $$1-\frac{M^{\underline{n}}}{M^n}-{n \choose 2}\frac{M^{\underline{n-1}}}{M^{n}}$$
or
$$ 1-\frac{M^{\underline{n-1}}(M-n+1+{n\choose 2})}{M^n}$$
When $M=365$, the minimum $n$ to get at least a 50% chance of more than 1 collision is $n=36$.
Comment: I agree with you that this is the probability of obtaining 2 (or more) collisions throwing $n$ balls into $M$ bins, but I was asking for an expectation.  Every technique I know of requires computing a sum.
Answer: We will change the problem slightly and make some approximations.  Instead of the expected value of $n$ to get two collisions, we will think about the value of $n$ to get a $50\%$ chance of two collisions.  They should be very close, as the probability of two collisions will rise quickly from near $0$ to near $1$.  In the single collision case, it is the difference between a factor of $\sqrt{2 \log 2}\approx 1.177$ and $\sqrt {\frac \pi 2}\approx 1.253$.  The approximation is that each pair of chosen elements has the same probability to match, $\frac 1M$.  This ignores the correlations between the pairs.
In this case, the distribution of number of collisions is Poisson, with $\lambda$ being the expected number of collisions.  The chance that we will not have two collisions is $(1+\lambda)\exp(-\lambda)$ with solution $\lambda \approx 1.67835$ so we want $\frac {n^2}{2M}=1.67835$ or $n=\sqrt{2M1.67835}$ or about $55\%$ more than the number to get the first collision.
Comment: Well, I mostly understand what you did, but you approximated the median (tosses needed to get a 50% probability) rather than the mean, and they are not asymptotically equal for this problem (as you point out).  Based on computer simulations I've run, your 55% estimate isn't quite right: for small $M$ we need about 60% more, and for larger $M$ (say 100,000) it's less than 50%.  I don't think this 2-collision mean is proportional to $\sqrt{M}$ like the 1-collision mean is.
Comment: @Fixee: The "2-collision mean" *is* asymptotically proportional to $\sqrt{M}$, just like the "1-collision mean". This is because we can easily prove that that the 2-collision mean lies between the 1-collision mean and twice it. So assuming that $n = \Theta(m^e)$ for some exponent $e$, we can prove that $e = \frac12$ just like in the 1-collision case. Then the constant of proportionality turns out to be roughly $1.88$, i.e., $n \sim 1.88\sqrt{m}$. (See my answer for some calculation.)
Comment: @ShreevatsaR: The reason my simulation made me believe the answer was not proportional to $\sqrt{M}$ was that--as your program shows--the multiplier starts above 2.1 and gradually settles to 1.88...  But your argument in your answer that it **must** be a multiple of $\sqrt{M}$ is quite convincing.

Second pair of matching birthdays


my c++ and c# interop crashes in 64 bit, why? pointer size?

Question: i got a native 32 bit dll (no source) which runs as a plugin in an application i use. I've done another native dll myself which will communicate with that plugin in order to create and update the plugin's controls.
From that dll i've exported the functions I need in order to control the plugin from my c# application (with p/invoke).
here's the code:
h file:
#pragma once

#include "include\SpoutControls.h"

extern "C" { __declspec(dllexport) void InitializeControls(char *sendername, int *numControls, char** names, int *types, float* floats, float* toggles, float* press, char** text); }
extern "C" { __declspec(dllexport) bool UpdateControls(const char** text, float *floats, float *toggles, float *press, int *numControls); }
extern "C" { __declspec(dllexport) void CloseControls(); }
//
extern "C" __declspec(dllexport) int ReleaseMemory(float *pArray)
{
    delete[] pArray;
    //delete[] Usize;
    return 0;
};

the cpp:
#include "SpoutControls4vvvv.h"

//SpoutControls and the functions
//CreateControl, OpenControls, CheckControls, CloseControls
//are declared in SpoutControls.h, which comes with the 32 bit plugin dll
SpoutControls spoutcontrols;

void InitializeControls(char *sendername, int *numControls, char** names, int *types, float* floats, float* toggles, float* press, char** text) {

    int Vcontrols = numControls[0];
    int Tcontrols = numControls[1];
    int Pcontrols = numControls[2];
    int Scontrols = numControls[3];

    int all = Vcontrols + Tcontrols + Pcontrols + Scontrols;
    int v=0, t=0, p=0, s = 0;

    for (int controlID = 0; controlID < all; controlID++) {

        if (types[controlID] == 0) {
            spoutcontrols.CreateControl(names[controlID], "float",0.0,1.0, floats[v]);
            v++;
        }
        if (types[controlID] == 1) {
            spoutcontrols.CreateControl(names[controlID], "bool", toggles[t]);
            t++;
        }
        if (types[controlID] == 2) {
            spoutcontrols.CreateControl(names[controlID], "event", press[p]);
            p++;
        }
        if (types[controlID] == 3) {
            spoutcontrols.CreateControl(names[controlID], "text", text[s]);
            s++;
        }

    }

    spoutcontrols.OpenControls(sendername);
}

bool UpdateControls(const char** text, float *floats, float *toggles, float *press, int *numControls) {
    int Vcontrols = numControls[0];
    int Tcontrols = numControls[1];
    int Pcontrols = numControls[2];
    int Scontrols = numControls[3];

    int all = Vcontrols + Tcontrols + Pcontrols + Scontrols;
    int v = 0, t = 0, p = 0, s = 0;

    if (spoutcontrols.CheckControls(myControls)) {

        for (int controlID = 0; controlID < all; controlID++) {

            if (myControls[controlID].type == 10) {
                floats[v] = myControls[controlID].value;
                v++;
            }
            if (myControls[controlID].type == 0) {
                toggles[t] = myControls[controlID].value;
                t++;
            }
            if (myControls[controlID].type == 1) {
                press[p] = myControls[controlID].value;
                p++;
            }
            if (myControls[controlID].type == 100) {
                text[s] = myControls[controlID].text.data();
                s++;
            }

        }
        return true;
    }
    return false;
}

void CloseControls() {
    spoutcontrols.CloseControls();
}

and here's the c# code:
public unsafe class SystemSpoutSenderNode: IDisposable
    {

        [System.Runtime.InteropServices.DllImport("SpoutControls4vvvv.dll")]
        private static extern void InitializeControls(IntPtr sendername, IntPtr numControls,String[] names, IntPtr types, IntPtr floats, IntPtr toggles, IntPtr press, String[] text);
        [System.Runtime.InteropServices.DllImport("SpoutControls4vvvv.dll")]
        private static extern int CloseControls();
        [System.Runtime.InteropServices.DllImport("SpoutControls4vvvv.dll", CallingConvention = CallingConvention.Cdecl)]
        private static extern bool UpdateControls([In, Out] String[] text, [In, Out] float[] floats,  [In, Out] float[] toggles, [In, Out] float[] press, IntPtr numControls);
        [System.Runtime.InteropServices.DllImport("SpoutControls4vvvv.dll")]
        private static extern int ReleaseMemory(IntPtr ptr);

    public void Evaluate(int SpreadMax)
            {
                        //countControls determines number of controls per type (string,float,toggle,click)
                        int[] controls = countControls(FType);
                        //sumControls will just add up all elements in controls
                        int all = sumControls(controls);

                        //in my code these arrays will get filled with values, deleted here for readability
                        String[] names = new String[all];
                        int[] types = new int[all];
                        float[] floats = new float[controls[0]];
                        float[] toggles = new float[controls[1]];
                        float[] press = new float[controls[2]];

                        String[] text = new String[controls[3]];

                        //initialze return arrays
                        String[] Rtext = new String[controls[3]];
                        float[] Rfloats = new float[controls[0]];
                        float[] Rtoggles = new float[controls[1]];
                        float[] Rpress = new float[controls[2]];

                        //allocate pointers
                        IntPtr SndrNamePtr = NativeUtf8FromString(FSenderName);
                        IntPtr BinPtr = Marshal.AllocHGlobal(4*sizeof(int));
                        IntPtr TypePtr = Marshal.AllocHGlobal(all*sizeof(int));
                        IntPtr FloatPtr = Marshal.AllocHGlobal(controls[0]*sizeof(float));
                        IntPtr TogglePtr = Marshal.AllocHGlobal(controls[1]*sizeof(float));
                        IntPtr PressPtr = Marshal.AllocHGlobal(controls[2]*sizeof(float));

                        try
                            {
                            //copy control info + defaults to pointer
                            Marshal.Copy(controls, 0, BinPtr, 4);
                            Marshal.Copy(types, 0, TypePtr, all);
                            Marshal.Copy(floats, 0, FloatPtr, controls[0]);
                            Marshal.Copy(toggles, 0, TogglePtr, controls[1]);
                            Marshal.Copy(press, 0, PressPtr, controls[2]);

                            //initialize controls
                            if (FWrite) InitializeControls(SndrNamePtr,BinPtr,names,TypePtr,FloatPtr,TogglePtr,PressPtr,text);

                            //update controls
                            bool changed = UpdateControls(Rtext,Rfloats,Rtoggles,Rpress,BinPtr);

                            //FF, FT, FS and FP are the outputs in my c# host
                            if (changed){

                                for(int j=0; j<controls[0];j++){
                                FF[j]=Rfloats[j];
                                }
                                for(int j=0; j<controls[1];j++){
                                FT[j]=FloatToBool(Rtoggles[j]);
                                }
                                for(int j=0; j<controls[3];j++){
                                FS[j]=Rtext[j];
                                }
                            }

                            for(int j=0; j<controls[2];j++){
                                FP[j]=FloatToBool(Rpress[j]);
                                }

                            }

                        finally
                        {
                            Marshal.FreeHGlobal(SndrNamePtr);
                            Marshal.FreeHGlobal(BinPtr);
                            Marshal.FreeHGlobal(FloatPtr);
                            Marshal.FreeHGlobal(TogglePtr);
                            Marshal.FreeHGlobal(PressPtr);
                        }
                    }
                }
            }

            public void Dispose()
            {
                CleanUp();
                CloseControls();
            }
}

NOTE: the c# code runs without precompiling in a frame-based, c# host environment for graphical programming (vvvv), therefore i've deleted host specific decalarations of inputs (FType,FSenderName) and outputs (FF,FS,FP,FT) to avoid confusion. These will be used to "connect" this code with other functionality. Evaluate will be called every frame by the host.
Now to the actual question(s):
it's working fine so far in 32 bit, but in 64 bit my c# host crashes without any message. after some reading i believe this is due to pointer sizes being different in 32/64bit systems, but i'm not exactly sure what to do/if this actually applies here. I would be very thankful if you could

explain me how (and why) to get this code to run in 64 bit
point out any other mistakes you might spot along the way- i'm completely new to c++ and still a beginner in c#, so i'm pretty confident there's a lot to improve here; especially: memory leaks and passing the values from c++ to c# and vice versa...uiuiui.

I've understood that I shouldn't cast a pointer to an int in 64 bit, so the last thing I've tried is to change from
int Vcontrols = numControls[0];
int Tcontrols = numControls[1];
int Pcontrols = numControls[2];
int Scontrols = numControls[3];

to
int Vcontrols = (INT_PTR)numControls[0];
int Tcontrols = (INT_PTR)numControls[1];
int Pcontrols = (INT_PTR)numControls[2];
int Scontrols = (INT_PTR)numControls[3];

but with no luck, therefore I'm posting my original problem, even if this is a correct improvement(?).
EDIT: thanks to @dkackman for pointing out one unclear point: my cpp code calls functions which come as source code (SpoutControls.h) with the native 32 bit dll. It's not the source for the 32 bit dll itself but declares the functions used to (as far as i can tell) access the same shared memory as the 32 bit dll.
I can also copy paste the code here if this might be the problem?
Also can be found here
thank you.
Comment: Why do you need to pass pointers at all? That just results in a lot of tedious, error-prone code.
Comment: Your mistake is probably elsewhere. Perhaps in the shared memory code. You didn't show that. Show a [mcve].
Comment: it's the only way i found (to work) to pass arrays of floats/doubles/strings between managed and unmanaged code. can you elaborate please/guide me in the right direction, what am I missing?
Comment: as dkackman indicated below, it's not possible to load a 32bit DLL into a 64bit process. You'll either have to create a separate 32 process on 64bit to load that 32bit DLL and do ipc between the two processes or (much easier) compile your C# code for 32bits ONLY so that it runs 32bit even on 64bit OS.
Comment: please see my edit following dkackmans post: the 32 bit dll does get loaded by a 32 bit application and values are passed via shared memory. also, a similar version of the c# code (which shares textures instead of values) is working fine in both x64 and x32
Comment: @CodyGray thanks to your comment i found this: https://msdn.microsoft.com/en-us/library/hk9wyw21(v=vs.110).aspx and changed all my pointer/marshalling code in c# to just use arrays accordingly. thanks for that hint, makes it all  a lot shorter. however, on the c++ side this still uses pointers + it doesn't change anything, still crashes.
Comment: @DavidHeffernan does this mean you can not see a problem with my code? I can not provide a minimal example easily, as I'm including code by somebody else (linked above)....I've contacted the original author to help...thanks
Answer: I am afraid you are out of luck. If your process is 64bit, you won't be able to load that 32bit dll, no matter how much you try.
Can I load a 32 bit DLL into a 64 bit process on Windows?
from https://msdn.microsoft.com/en-us/library/windows/desktop/aa384231(v=vs.85).aspx

On 64-bit Windows, a 64-bit process cannot load a 32-bit dynamic-link
  library (DLL).

Without access to its source, your only option would be to convert your host to 32bit or otherwise figure out how to host the 32bit plugin in a 32bit process and use some sort of IPC to communicate with it from a 64bit host process.
So my guess is that this has nothing to do with your wrapper, array passing or interop code.
Comment: Can you clarify: Is your host process 64 or 32 bit? If so, there will be no way to load that 32bit dll into it. If not, I am not clear as to where references to 64 bit are coming from. A 32bit process, even if running on a 64 bit OS, is still a 32bit process. You cannot mix the bitness of compiled binaries in the same process.
Comment: sorry if this was unclear: the native 32 bit dll does get loaded fine in it's host application as a plugin, I do not need to load it in my c# 64 bit application. I think the problem occurs when the c# 64 bit code passes values via pointers to the c++ 64bit dll, which itself (afaik) writes the values to sharedmemory for the 32bit dll to access. will update my question to make this clearer. thanks
Comment: i'm running the 32 bit dll in a 32 bit application. always. i want it to communicate with another (c#) application, which can either run in 32bit or 64 bit. this application runs the above c# code and calls the dll I did (c++ from above, compiled to either 32bit or 64bit). but the 64bit version crashes the c# host.
note that I know that in theory this should work. there is a similar plugin for my c# host which shares textures instead of values, works both in 32/64bit on the c# side and 32 bit on the receiving side.
Comment: So that other C# application (that can run either 32 or 64) will only ever be able to load the 32bit dll when running as a 32bit process. Does it work when the other C# application is running 32bit?
Comment: if the c# app, let's call it app B, is running in 64 bit i'm loading my native 64 bit dll (code above) to communicate with app A. If app B is running in 32 bit i'm loading my native 32 bit dll (code above).
App A always is 32 bit and can only load the native 32 bit dll which is not mine, no source.
If app B is running in 32 bit it works, if app B is running in 64 bit app B crashes with no effect in app A.
Comment: as mentioned before, another code part of my native dll loaded from the same c# app B successfully is sharing a texture from app B to the same 32 bit dll in app A, no matter if app B is running in 32 bit or 64 bit (loading 32/64 bit versions of my native dll accordingly).
Getting values back from app A to app B, which is what i'm trying here, crashes app B in 64 bit, but works in 32 bit.


Preferred way of loading a specific entity revision

Question: In drupal 7 you can do this to load an entity revision using
entity_load($entity_type, $ids = FALSE, $conditions = array(), $reset = FALSE)
like this:
<code>$old_revision = entity_load('node', array(), array('vid' => 123));
</code>
However now $conditions is being deprecated.
Pretty much wherever you go you see people saying that you should use EntityFieldQuery instead of conditions, however that doesn't help in this case.
You can use age() to query revisions using EntityFieldQuery however it doesn't give you fully loaded node results so you then still have to load the entity and how do you load that revision of that entity without the conditions.
Answer: Currently the preferred way is to get the storage instance (EntityStorageInterface) for the entity type from the EntityTypeManager and then use its loadRevision() function. For example, you could do this for a node:
<code>$node_revision = \Drupal::entityTypeManager()
  ->getStorage('node')
  ->loadRevision($node_revision_id);
</code>
Previously to this you would get the storage instance from the EntityManager like this:
<code>$node_revision = \Drupal::entityManager()
  ->getStorage('node')
  ->loadRevision($node_revision_id);
</code>
This still currently works however it has been deprecated in favour of the first method. The change record relating to this is at https://www.drupal.org/node/2549139
The old way, which still currently works in Drupal 8 but is also deprecated, is the function entity_revision_load(), which is also available in drupal 7 via entity_revision_load() in the Entity API module.
This function replaces the use of conditions to load old entity revisions.
You can see the history of this change in the Drupal core issue about Remove deprecated $conditions support from entity controller.
The way you would use this function as per the original question is:
<code>$old_revision = entity_revision_load('node', 123);
</code>
Comment: Yes, this is the way to do it. There's also loadRevision() on the entity storage interface (this is a wrapper for that).
Comment: Answered my own question: entityStorageInterface::getQuery will create the query that i need. ::allRevisions() will cause the query to query both the base table and entity tables. Conditions apply as expected, and return value is an array indexed by vid.
Comment: Thanks for the info. I have now updated the answer with the current preferred method using the EntityTypeManager.
Comment: But how do you get the revision id in the first place? e.g. Let's say i have only an entity id, and i want to fetch the 10 latest revisions for it. What's the prefered way to build the revision query?


Qual é o comportamento do ciclo de vida do JSF 2 ao validar campos obrigatórios?

Question: Tenho um formulário de cadastro de clientes com dois campos, o primeiro campo é o CPF com preenchimento obrigatório e o segundo Nome com preenchimento opcional. Ao editar um cliente com CPF e Nome preenchidos, apagar os dois campos e clicar em Salvar, o JSF retorna a mensagem "O campo CPF é obrigatório". Entretanto, ao apresentar a mensagem o campo CPF vem em branco como foi submetido. O campo Nome não vem em branco como foi submetido e sim com o valor anterior.
Seria este mesmo o comportamento padrão do JSF 2? Consigo embasar este comportamento na documentação do JCP do JSF? Quais argumentos apresentar ao cliente que o campo CPF vem em branco para mostrar a obrigatoriedade e o campo Nome é restaurado porque o ciclo de vida do JSF não completou para aceitar o novo valor?
Comment: Posta sua página .xhtml e o seu managedBean!
Answer: Esse é o ciclo de vida da validação no JSF:

Segue um exemplo de um painel de cadastro:
<h:form>
        <h:panelGrid id="painelCadastro">
            <h:outputLabel value="CPF:"/>
            <h:inputText value="#{bean.cpf}" required="true"/>

            <h:outputLabel value="Nome:"/>
            <h:inputText value="#{bean.nome}"/>

        </h:panelGrid>

</h:form>

Nesse formulário a unica validação é se o campo é required, oque eu recomendo você fazer é um método de validação para seu objeto, onde vai validar todos os seus campos verificando se é null ou empty. O seu problema pode ser a falta de processar os novos dados para as variáveis do Bean, com o meu exemplo ele vai sempre processar os valores e vai fazer a validação do JSF.
Comment: Rafael, obrigado pela sua resposta mas o problema está em restaurar o valor sobrescrevendo o novo valor do campo nome quando o campo CPF é validado.
Answer: Encontrei a resposta do BalusC muito esclarecedora sobre este problema aqui.
Ele diz:

Quando pelo menos um componente de entrada é inválido, após a fase de validações, então não irá JSF actualizar os valores do modelo para qualquer dos componentes de entrada. JSF seguirá diretamente para renderizar fase de resposta.


Almost maximal subgroup by cyclic supplement

Question: This question is related to my previous post. Let $ S_{4} $ is the symmetric group of degree $ 4 $ and $ A_{4} $ is the alternating. $ S_{3} $ is a maximal subgroup of $ S_{4} $ and $ C_{3} $ is a maximal subgroup of $ A_{4} $ that $ C_{3} $ is the cyclic group of order $ 3 $. are there $ y \in S_{4} $ and $ x \in A_{4} $ such that $ S_{4} = \langle y \rangle S_{3} $ and $ A_{4} = \langle x \rangle C_{3} $ ?
Comment: Just to clarify, by $\langle z\rangle K$, do you mean $K+z K+\dots$ or the subgroup generated by such?
Comment: @Chanler $ \langle z \rangle K$ do mean subgroup generated,
Answer: We have that $(1234)S_3=S_4$. This can be seen by a counting argument as follows. We have that $S_3\cap yS_3=\varnothing$, by considering such an elements effect on $4$. Thus $S_3+yS_3+y^2S_3+y^3S_3\subset S_4$ is of order $4|S_3|=4*3!=4!$, so that the inclusion is equality.
Such an equality cannot exist for $A_4$ though, since all elements of $A_4$ have order $3$ or less, so that $|\langle x\rangle C_3|\le 9<12$. That said, the subgroup generated by $\langle (12)(34)\rangle C_3=A_4$. This can be seen as follows. The order of the product of two elements is atleast the $lcm$ of there individual orders. Thus our $(\langle (12)(34)\rangle C_3)$ contains an element of order $6$. Such a subgroup would be normal, since it would be of index $2$. But $A_4$ is simple so it must be the whole group.
Comment: But it is true for $ \langle (1,2,3,4) \rangle S_{3} $?


multiple form actions doesn't work using JS?

Question: I have a form and then a JS function which processes it and does 3 actions. Here's my function:
<code>function submit(){
    document.optin.action = "link1.php"
    document.optin.target = "_self";
    document.optin.submit();
    window.open('http://link2.html','','scrollbars=yes,height=600,width=900,resizable=yes');
    document.optin.action = "link3.php"
    document.optin.target = "_self";
    document.optin.submit();
}
</code>
The 2nd and 3rd actions work but the first does not. Actions 1 and 3 open on the same window with the latter overrides the former. Any idea what's wrong with my code? pls...
Comment: the action you don't see is a get request on a new window :)
Answer: The first one doesn't work because you're overriding the action with the 3rd one.
I don't know what you want to do, but you can't submit into two targets that are suposed to appear on the same window.
If the first submit is just for data purposes, I would sugest that you do the submit via ajax. so that the 3rd one doesn't overwrite the action.
Comment: Changing the target of the 1st to _blank does not work either. :(
The idea is, the 1st action does the submission of the data to the server so nothing should be displayed about it. While the 3rd displays the page of the next phase of the process.

You know what? This code was working until recently. I don't know what went wrong.. :(
Comment: what's going wrong is that you're trying to submit twice and the second submition overwrites the first.

If that's really it, then just use ajax for the first submission, it will simplify your life :)


Change of basis- vector space of polynomials

Question: Given is the vector space of Polynomials of degree $\le3$ and the basis
 $$\mathcal{B}_2 = \left\lbrace1,x-1,x^2-3x+2,x^3-6x^2+11x-6\right\rbrace$$
Furthermore the linear mapping
$$L: p(x) \rightarrow p'(x) + p(x)$$
I am looking for the transformation-matrix of $L$ w.r.t $\mathcal{B}_2$

For the regular basis $\mathcal{B}_1=\left\lbrace1,x,x^2,x^3\right\rbrace$ this transformation matrix should be given by
$$L_{\mathcal{B}_1}=\begin{pmatrix} 1&1&0&0 \\ 0&1&2&0\\0&0&1&3\\0&0&0&1\end{pmatrix}$$
Is this correct?

However, I am actually looking for $L_{\mathcal{B}_2}$
If I would have a basis-change-matrix (I am sorry, I do not know the correct english word for it, but I think it is clear what I mean) donated $S$ then it should hould
$$L_{\mathcal{B}_2} = S^{-1}L_{\mathcal{B}_1}S$$
Is this correct either?

I tried with
$$S=\begin{pmatrix}1&0&0&0\\-1&1&0&0\\2&-3&1&0\\-6&11&-6&1\end{pmatrix}$$
But the result I get seems to be wrong.
Comment: $S$ should be the transpose of what you have written there.  For example the last column ought to be $[ -6, 11, -6, 1]^\top$, expressing the last basis vector of $\mathcal(B)_2$ in terms of the standard basis.
Answer: The easiest if you simply perform the given linear map $L$ to the new basis ($\mathcal B_2$) and write it as a linear combination of polynomials from this same $\mathcal B_2$.
E.g., for the third column of the matrix, apply $L$ to $b_2:=(x^2-3x+2)$, getting
$$L(b_2)=b_2+2x-3=b_2+2b_1-b_0\,.$$


Scales changes in Orchestration

Question: There is a common technic used in orchestration across all genres of music. Sometimes in the second verse or before the singer is about to repeat another part in the song there is a move usually up in scale that brings a sense of a fresh beginning. I've heard some orchestrators come back to it and in some instances, in the end, there is a constant move of scales while the song is fading out.
Does anyone know how is this referred to in orchestration, and if there is a rule or a guide to determine the next scale in movement?
Thanks.
Answer: I think you're talking about the 'truck driver' modulation.    PLay it, then play it again, up one step!
A composing/arranging technique more than an orchestration one.
https://www.musical-u.com/learn/the-truck-drivers-gear-shift/
Here's a fun take-off of the technique!
Comment: Many church organists do this for the last verse of a hymn. J.S. Bach was known to do this, and it may have originated with him, as he was one of the first to temper organs so that they sounded good in all keys.
Comment: @PLL: The source is an 18th century report in the Dresdener Gelehrte Anzeigen, referenced in Stauffer & May: J.S. Bach as Organist (Indiana Univ Press 1986) page ix. "Bach played the Creed in D minor, but for the second verse he lifted the congregation into E-flat minor, and for the third verse he took those present even higher, to E minor. This could be accomplished only by a Bach and an organ in Altenberg." [Because of well-tempered tuning.]
Comment: @MarkLutton: Interesting to hear Bach did this; can you give any pointer to more information about that?  I was wondering about the older history of this modulation recently, and couldn't find much, but probably because I wasn't sure what other names it's known under.
Comment: @MarkLutton Absolutely fascinating, and thanks for sharing. So often this kind of modulation is viewed as kitschy and cheap. I never would have dreamt that Bach did it!
Comment: I rather suspect that Bach did more than just "pause, move hands, start playing higher with no transition"!
Answer: This is called modulation, and it is a very common technique for changing the feel of a piece. Very loosely speaking, a modulation toward higher pitches adds excitement; a modulation toward lower pitches calms things down.
There aren't exactly rules for determining the "next" scale, but there are some common techniques. One of the most common is to move upward one step (at a time). This adds energy to the music more gradually.
Another possibility is to do a more abrupt modulation to show off the soloist's/lead singer's range. A song might start in the singer's mid range but suddenly modulate upward so that the singer is belting at the top of their range.
There is an excellent (but somewhat technical) discussion of the various ways to modulate in How many types of modulation are there?.

Scales changes in Orchestration


Safe cast of Scala collection containing primitives

Question: I'm working on mixed Java-Scala projects, and quite often I need to convert collections.
When I want to convert a collection of primitives, I should be writing something like this
val coll: Seq[Int] = Seq(1, 2, 3)

import scala.collection.JavaConverters._

val jColl = coll.map(v => Int.box(v)).asJava

However, I know that with both Java and Scala generic collections use boxed values, so I can safely avoid iterating with needless boxing and just write
val jColl = coll.asJava.asInstanceOf[java.util.List[java.lang.Integer]]

However, compiler won't complain if I'll make a mistake in either collection type or element type.
Is there a type-safe way of doing this avoiding extra iteration? Is there at least a way to keep checks for collection type?
Comment: similar question https://stackoverflow.com/questions/24620574/implicit-conversion-between-scala-long-and-java-lang-long-in-collections
Comment: Why not `.asScala` ?
Answer: Well, I can't think of a way to avoid the scala.Int -> java.lang.Integer conversion being a bit manual or unsafe, but if you only implement it once and reuse it, it can pretty much eliminate the risk.
One approach might be:
import scala.language.higherKinds
implicit class IntCollectionBoxer[C[_] <: java.lang.Iterable[_]](elems: C[Int]) {
  def asJavaBoxed: C[java.lang.Integer] = elems.asInstanceOf[C[java.lang.Integer]]
}

(repeat for Double and other types)
Then usage would be this, which is pretty hard to make a mistake with:
val jColl = coll.asJava.asJavaBoxed

You might wish to change the bound on C depending on your usage as well.
Comment: I think it's a good place for implicit def instead of implicit class. Anyway, accepting the answer for as long as better idea doesn't come out.


$\boxed{1} f(x)=\frac{2-x^2}{2}f(\frac{2-x^2}{2})$

Question: Let $f(x)$ be a continuous function from $[-1,1] \rightarrow \mathbb{R}$ having the following properties:
$\boxed{1} f(x)=\dfrac{2-x^2}{2}\cdot f\!\left(\dfrac{2-x^2}{2}\right)$
$\boxed{2} f(0)=1$
$\boxed{3} \lim\limits_{x\to1^{-}}\dfrac{f(x)}{\sqrt{1-x}}$ exists and is finite.
Find $f(x)$.
Answer: Let $g(x) = (2 - x^2)/2$, so equation (1) says $f(x) = g(x) f(g(x))$.
$g$ has a fixed point $p = \sqrt{3}-1$, and $0 < g(p)< 1$ so $f(p) = 0$.
Moreover, for any $x_0 \in (0,1)$, we can show that
the iterates $x_n = g(x_{n-1})$ converge to $p$ as $n \to \infty$, with
$f(x_n) = f(g(x_{n-1})) =f(x_{n-1})/g(x_{n-1})$.  Thus
$$f(x_n) = f(x_0)/ \prod_{j=0}^{n-1} g(x_j)$$ and since $\prod_{j=0}^{n-1}g(x_j) \to 0$ while $f(x_n) \to f(p)$ we must have $f(x_0) = 0$.  In particular $f(0)=1$ is impossible.