Validation of logistic regression - goodness of fit (pearson)

Question: I have developed a scoring system using logistic regression. The score ranges between 0 and 6 (using integers) and predicts death. It does not use a conventional regression formula and thus I am not able to calculate a precise value of the predicted risk of dying. An example of the score could look like this:
Score      Dead    Alive
0            0      101
1            1      911
2            3      672
3            2      291
4            8      78
5            10     60
6            5      4
I know that I have to use Pearson's goodness of fit to test the goodness-of-fit and have three cohorts, a development cohort and two independent validation cohorts.
My question is: How do I calculate the Pearson Goodness-of-fit test in each cohort? In the development cohort, what would be my expected mortality? In the validation cohorts, I guess that I could use the observed mortality in the development cohort as expected mortality.
Comment: You seem to have a great predictor.  When plotted, there is a strong curvilinear relationship between percent dead and your predictor score.  Perhaps the Pearson Goodness-of-fit test is not the best way to index this fit.
Comment: That test has been shown to be arbitrary and not have competitive power in some situations.  I prefer directed tests (e.g., nonlinearity) but if you want an omnibus test see the following, as implemented in the `R` `rms` package's `residuals.lrm` function: Hosmer, D. W.; Hosmer, T.; le Cessie, S. & Lemeshow, S. A comparison of goodness-of-fit tests for the logistic regression model Statistics in Medicine, 1997, 16, 965-980
Comment: The chi square test is not the only option for test goodness of fit.
Comment: Often the Hosmer-Lemeshow test is used for testing goodness-of-fit for logistic regression; see [link](http://en.wikipedia.org/wiki/Hosmer%E2%80%93Lemeshow_test).
Answer: I don't see where this is a goodness of fit problem.  It appears to be more of a risk estimation problem, for which you might consider fitting a binary logistic model that is quadratic in the score.  @RioRaider - note that the older Hosmer-Lemeshow test is now obsolete.


Escrever dentro de uma div com uma função

Question: Tenho uma função que pega valores de um documento via parser:
    var soma = 0;

    $(document).ready(function () {

    $.get(file, function (data) {
        ivps = parseDataToIvp(data);
        let fIvps = ivps.filter(i => i.idleTime < -60)
        fIvps.map(i => console.log(i.idleTime))
        soma = fIvps.map(i => i.idleTime).reduce((a,b) => a + b);

        console.log(soma);
    });

});

Gostaria de escrever esse resultado "soma" dentro da minha div no HTML, porém não estou conseguindo, alguém tem alguma idéia?

Comment: Felipe Deolindo, faz um teste usando o código que adicionei como resposta e me diga se era o que você queria.
Answer: Para se adequar ao seu código, você pode usar o comando .innerHTML para inserir o valor da sua variável soma dando um document.getElementsByClassName para capturar o elemento desejado.
Adapte o seu código com o seguinte código:
var soma = 0;

$(document).ready(function () {

    $.get(file, function (data) {
        ivps = parseDataToIvp(data);
        let fIvps = ivps.filter(i => i.idleTime < -60)
        fIvps.map(i => console.log(i.idleTime))
        soma = fIvps.map(i => i.idleTime).reduce((a,b) => a + b);

        console.log(soma); //Caso você queira apenas inserir o valor na sua
, remover essa linha.
        document.getElementsByClassName("count")[0].innerHTML = soma;

    });

});

Comment: André fiz isso, porém esse valor que estou pegando de uma planilha do excel é dinamico, ele todo dia soma todos os valores e me gerá um resultado, com esse seu código o valor que me mostra é sempre 0, porque é o valor que está declarado lá em cima
Comment: A variável está declarada lá em cima por **0**, mas o `innerHTML` está adicionando o valor retornado dessa sua função:`fIvps.map(i => i.idleTime).reduce((a,b) => a + b);` que provavelmente está retornando 0.
Comment: @FelipeDeolindo, qual valor o seu `console.log` exibe?
Comment: o valor que meu console está mostrando, o valor total somando todos eles é `-1674` , ele me mostra todos os valores que estão sendo pegos e no final mostra o total deles, mas amanhã esse valor será outro, assim por diante, todo dia esse valor final muda
Comment: Deu certo cara, faltava um ; no final, não me atentei, muito obrigado
Comment: não querendo abusar, mas eu li que se usar aquele `math.abs` eu consigo fazer esse número negativo virar positivo, sabe onde posso usar o `math.abs` dentro dessa função?
Comment: Caso a variável `soma` retorne um valor negativo, por exemplo: **-15**. você deseja retornar **15** ? Se for isso que deseja, basta subtituir o código: `= soma;` por `= abs(soma);`. Vale lembrar que a *função* `abs` só aceita como prâmetro valores numéricos.
Answer: Para inserir queira inserir dentro da div algum conteúdo, você pode fazer das seguintes formas:
Conteúdo em HTML:

$('div.count').html('Seu código HTML aqui');
document.querySelector('div.count').innerHTML = 'Seu código HTML aqui';

Conteúdo em texto simples:

$('div.count').text('Seu texto aqui');
document.querySelector('div.count').innerText = 'Seu texto aqui';

Acima mostro como você pode fazer essa inserção, tanto com JQuery, como apenas com Javascript.
Answer: var soma = 0;

$(document).ready(function () {

$.get(file, function (data) {
    ivps = parseDataToIvp(data);
    let fIvps = ivps.filter(i => i.idleTime < -60)
    fIvps.map(i => console.log(i.idleTime))
    soma = fIvps.map(i => i.idleTime).reduce((a,b) => a + b);

    console.log(soma);
});

document.getElementById("result").innerHTML = soma;

});

ou

Calculando valores....

Answer: Tentou isso?
$("#div_id").html("seu texto aqui");

Obs.: código usando jQuery
Comment: @AndréFilipe nesse caso você substituiria esse ID pelo ID da sua div.
Recomendo usar o atributo "id" para seleção, pois se trata de um identificador único.
Use classe quando quiser selecionar um conjunto de elementos na tela.


How many labeled trees exist on 100 vertices, such that all vertices have degree 1,2 or 3, and there are exactly 32 leaves?

Question: I know Cayley's theorem, but no idea how should i solve this.
If i consider this graph without that 32 leaves, then i have a graph with 68 vertices, and each vertice's degree is 1 or 2?
Comment: There are two quite different questions. (1) we label the points and specify the degree of each one and require the graph to be a tree; (2) we simply put constraints on what the degrees can be. So in your previous question if you specified that each of points 1,2,3,4,5 has degree 1, and each of points 6,7,8 has degree 3, then the Prufer approach gives the answer 90. But if you simply require a tree with 5 points of degree 1 and three of degree 3, then the number is far larger (7!).
Comment: Why not make a little more effort on your earlier question about labeled trees with 8 vertices, before asking a much harder question.
Comment: Ive solved that one, with Prufer code stuff (answer is 90= 6!/(2!2!2!)). But i dont see how could i use prufer code with this one.
Answer: Cayley's formula says there are $n^{n-2}$ trees on $n$ vertices. This is great, but our problem has more constraints. Luckily for us, there is a stronger result of Cayley's formula, which states:
$$\begin{pmatrix}n-2\\ d_1 - 1, d_2 - 1,....,d_n - 1\end{pmatrix}=\frac{(n-2)!}{(d_1 - 1)!(d_2 - 1)!...(d_n - 1)!}$$
Which gives us the number of trees with $n$ vertices with degree $d_n$. You said there are exactly $32$ vertices with degree $1$ (the leaves), which makes this quite a bit easier since if $d_i = 1$ then $(1 - 1)! = 0!=1$. Thus we need to count
$$\begin{pmatrix}100-2\\ d_1 - 1, d_2 - 1,....,d_{68} - 1\end{pmatrix}=\frac{(100-2)!}{(d_1 - 1)!(d_2 - 1)!...(d_{68} - 1)!}$$
Furthermore, the same applies to if $d_i = 2$, since $(2-1)!=1!=1$. Thus, we arrive at a final counting function of
$$\begin{pmatrix}100-2\\ d_1 - 1, d_2 - 1,....,d_{68-a} - 1\end{pmatrix}=\frac{(100-2)!}{(d_1 - 1)!(d_2 - 1)!...(d_{68-a} - 1)!}$$
Where $a$ is the number of times $2$ appears and $d_{n-a}$ is either of degree $3$ and $a$ is the amount of times we must count the case $d_n = 2$. Also in any graph we have the formula
$$\sum_{v_i\in V}deg(v_i) = 2\left | E \right |$$
Or in other words the sum of the degrees of each vertex equals $2$ times the amount of edges. Luckily for us, trees have an even harder definition that
$$\left | E \right | = \left | v \right | - 1$$
Or the amount of edges is equal to the amount of vertices minus 1. Now recall that we do not have to count the leaves of the tree in our original counting function, so our tree is a graph with $100$ vertices, thus using our formulas we get
$$\sum_{v_i\in V}deg(v_i) = 2\left | v \right |-2=2i-2$$
Therefore,
$$\sum_{v_i\in V}deg(v_i) =2(100) - 2 = 198$$
So now we have to find how many distinct ways we can sum $2$ and $3$ together to get $198$ using exactly $68$ $2's$ and $3's$ and $32$ $1's$ to see how many distinct versions of Cayley's formula we need to sum to get our result. In other words we are trying to solve
$$2a + 3b + 32 = 198$$
$$a + b + 32= 100$$
So by substitution we get
$$2a + 3b= 166$$
$$a = 68 - b$$
Therefore
$$2(68-b)+3b=166$$
$$136+b=166$$
$$b=30$$
so
$$a+30=68$$
$$a=38$$
Which clearly has only 1 unique positive solution. Now we are ready for a final answer plugging in our $30$ $3's$ and $a=38$ to our counting formula
$$\begin{pmatrix}100-2\\ d_1 - 1, d_2 - 1,....,d_{68-a} - 1\end{pmatrix} \rightarrow \begin{pmatrix}(100-2)!\\ d_1 - 1, d_2 - 1,....,d_{30} - 1\end{pmatrix}$$
And, as discussed earlier, $d_n = 3$ for all $n$, so we have
$$\frac{(100-2)!}{(3 - 1)!(3 - 1)!(3-1)!...(3-1)!} = \frac{98!}{2!2!2!2!...2!}=\frac{98!}{2^{30}}$$


Inaccessible cardinals and well-founded models of ZFC

Question: This was a problem in an exam I took last semester, but I never got the chance to ask my professor how to solve it. Here goes:
Let $\kappa$ be an inaccessible cardinal. Then $V_\kappa$ is a transitive model of ZFC (with the usual $\in$). Let $U$ be a non-principal ultrafilter over $\kappa$ and let $\tilde{M} = (V_\kappa)^\kappa/U$ be the corresponding ultrapower of $V_\kappa$.
We say that an ultrafilter $U$ has the $\sigma$-property if given sets $A_i \subset \kappa, i \in \mathbb{N}$, we have that if $A_i \in U$ for every $i \in \mathbb{N}$ then $\bigcap_{i \in \mathbb{N}} A_i \in U$.
(a) Show that $\tilde{M}$ is well-founded iff $U$ has the $\sigma$-property.
(b) Suppose $\tilde{M}$ is well-founded, and let $M$ be obtained from $\tilde{M}$ through the Mostowski collapse (so that $M$ is a transitive model of ZFC). Show that $M$ is elementarily equivalent to $V_\kappa$ but $M \neq V_\kappa$.
IDEAS:
One of the definitions of well-founded (and I believe the best one for this problem) is:
A model of ZFC $(M, \varepsilon)$  is NOT well-founded iff there exists a sequence $x_1, x_2, \ldots$ in $M$ (note that we're talking about a ''true'' sequence and not a sequence of the model) with $x_{n+1}$ $\varepsilon$ $x_n$ for all $n \in \mathbb{N}$.
I managed to prove the easier direction in part (a):
Suppose $\tilde{M}$ is not well-founded. Then there exists a sequence such that $\ldots$ $\varepsilon$ $x_2$ $\varepsilon$ $x_1$. Let $f_i$ be an element in the equivalence class $x_i$. By definition, $x_{i+1}$ $\varepsilon$ $x_{i} \Leftrightarrow A_i := \{k \in V_\kappa | f_{i+1}(k) \in f_i(k) \} \in U$.
Since $V_\kappa$ is well-founded, $\bigcap_{i \in \mathbb{N}} A_i = \emptyset \notin U,$ thus $U$ does not have the $\sigma$-property.
Also, in part (b), $M$ is clearly elementary equivalent to $V_\kappa$ since it is isomorphic to $\tilde{M}$ (through the Mostowski collapse), which is elementary equivalent to $V_\kappa$.
Any thoughts on the other parts?
Answer: The $\sigma$-property is also commonly known as saying that the ultrafilter is countably complete, and the existence of an ultrafilter with this property is equivalent to the existence of a measurable cardinal, since any countably complete ultrafilter is actually $\delta$-complete for some measurable cardinal $\delta$.
Question (a) is treated in any of the standard accounts of large cardinals, such as Kanamori's book The Higher Infinite. There are two directions. You have shown that if the ultrafilter is countably complete, then the ultrapower is wellfounded. Conversely, suppose that the ultrafilter is not countably complete. Then there is a sequence $X_n\subset\kappa$ with each $X_n\in U$ but $\bigcap_n X_n\notin U$. We may assume that $\bigcap X_n=\emptyset$, by throwing out a measure zero set, and we may assume that $X_{n+1}\subset X_n$. For each $\alpha\lt\kappa$, let $n_\alpha$ be least such that $\alpha\notin X_{n_\alpha}$.  Let $f_k(\alpha)=n_\alpha-k$, if $\alpha\in X_k$. Note that as $k$ increases, these functions decrease on their domain, which have measure $1$, and so we have a violation of the well-foundedness of the ultapower. Indeed, the ultrapower has a nonstandard $\omega$, since our functions have values in $\omega$.
For part (b), you've observed that $V_\kappa$ is elementary equivalent to its ultrapower by the Los theorem. To see that $M\neq V_\kappa$, one could argue directly from the Kunen inconsistency, which implies it as an immediate consequence. Alternatively, we may argue as follows. First, if every set in $U$ has size $\kappa$, then the identity function $id:\kappa\to\kappa$ is larger than the constant functions on a measure one set, and hence represents an ordinal in the ultrapower at least as large as $\kappa$ itself, which ensures that the height of $M$ is strictly taller than $\kappa$, and so $M\neq V_\kappa$. So we may assume that $U$ concentrates on some $\gamma\lt\kappa$, and we may correspondingly restrict the functions to $\gamma$. Again it follows that $j(\gamma)\gt\gamma$, where $j$ is the map $V_\kappa\to M$, since the identity function exceeds the constant functions. Now let $\delta\lt\kappa$ be the $\gamma^{\rm th}$ cardinal with $\delta^\gamma=\delta$. It follows that $j(\delta)\gt\delta$, but observe that every element of $j(\delta)$ is represented by a function $f:\gamma\to\delta$, of which there are only $\delta$ many. This violates elementary if $V_\kappa=M$, since $j(\delta)$ is supposed to be a cardinal. QED
Comment: Part (a) is clear, although I'd like to add the following comment that made all the difference to me: note that $\{\alpha : f_{k+1}(\alpha) \in f_k(\alpha)\} \supset X_{k+2} \in U$.

As for part (b), the part with the cardinal $\delta$ got me confused. Could you provide more detail?
Comment: Ok, I almost understood it. One question though: why does $\delta$ have to be the $\gamma^{th}$ cardinal with such property?
Comment: We need that $j(\delta)\gt\delta$ to get the contradiction, and this follows if $\delta$ is the $\gamma$-th with a property, since we already know $j(\gamma)\gt\gamma$.
Comment: I confess I didn't understand all the details, but the proof seems correct. Besides, the Kunen inconsistency does kill the rabit, so I'll accept the answer. Thanks!


Change language programmatically after login

Question: I have a multilingual site and I want to change the language programmatically after user login to his own language to see all the content in his language.
How can I do this?
Answer: It should not be necessary to do it from code, as one of the settings present in admin/config/regional/language/configure allows to set the language to the one selected from the users in their user profile settings.
Comment: And you can also define your own language negotiation plugins if you have some custom logic, see http://drupal.stackexchange.com/questions/5164/use-another-language-than-default-as-standard


Closing or referencing the websocket from chrome dev console?

Question: I'm trying to break my own app that is using socket.io by opening up a socket and sending data to it through the dev console.
I see the web socket open under the network tab, and can see the data it's sending and receiving, however, I cannot right click and grab the reference to send more data, which is fine...
Next thing I tried, was to open up another socket, point it to the same IP/port and try using the same session ID, but that only automatically closes the socket since there is already a socket open for that session ID.
Is there a way to close the open socket, open up one with the same session ID, and send messages through the dev console? Or is there any other way someone can mess with the socket through the dev console?
Answer: You can set a breakpoint in some scope of the page Javascript that has access to the webSocket object.  It will take some understanding/study of the page's Javascript code to determine where this breakpoint should be set.  Then, run the code that hits the breakpoint.  While sitting at that breakpoint with access to the webSocket object, you can then execute methods on that object to send data over it.
Comment: for some reason though, I have issues saving the file (when saving, it still runs the original code) and actually doing what you said... but this is definitely the right step in the right direction...
Comment: I'm not sure what you mean by "saving".  You can't "save" a change to a web page and expect that change to still be in effect the next time you visit that web page.  The web page source is on the web server and only the web server can permanently "edit" it.
Comment: But in the dev console, you can go under sources, edit the source, save, and you should be running the new edited script... I've done that before, but for some reason this time it is not working... That's the way I was trying to grab the socket. Of course refreshing gets rid of the changes.

So I'm a little confused on how to execute the methods while it's at the breakpoint. So you set the breakpoint on the websocket line and then what? How do you execute the methods?
Comment: @Jaime - at the breakpoint, you can type code into the console and execute it at that specific point in time.  While at the breakpoint, you can access any variables that are within the Javascript scope of the breakpoint (such as the socket object).  This is a one-time hack, not something that works subsequent times you access the page.


How to improve search results filtering on taxonomy

Question: I would like to know the best way to filter drupal search results using taxonomy. I want users to be able to search for particular results from a particular taxonomy..this can be done to refine already searched results, or can be done from scratch.
Any module for Drupal 7 that does this well?
Comment: why dont u use views with expose filters
Answer: Use Custom Search module.

This module alters the default search box in many ways. If you need to
  have options available like in advanced search, but directly in the
  search box

Or, the other best solution is to use create a view with exposed filters. Here is article about it
Comment: Thanks for the article, I tried custom search but it didn't quite get there :'(
Answer: I  think you should give a try to Extending Drupal 7 search. The form ID on the search result page would be search_form. You can use hook_search_execute() to filter the result as you need.
Or you could also try the Extended search page module, but it is in beta and it requires Search API and Search API pages.
Personally I would write a custom module rather than installing many modules.
Answer: One of the best solution to this is using Faceted search. You need to switch search engine to Solr to get that. There are several different vendors that sell Solr hosting if you don't want to set that up yourself, including Acquia.
Drupal integration is provided either by Apache Solr search integration or Search API.


Let $\lim_{n \to \infty} (x_n)_{n\in\mathbb{N}} = x$ and $\theta: \mathbb{N} \rightarrow \mathbb{N}$. Show $\lim_{n \to \infty} x_{\theta(n)} = x$

Question:
Let $(x_n)_{n\in\mathbb{N}}$ be a convergent series and $x \in \mathbb{R}$ with $\lim_{n \to \infty} x_n = x$. Furthermore let $\theta : \mathbb{N} \rightarrow \mathbb{N}$ a mapping with the property that for $\forall n \in \mathbb{N}$ the fiber $\theta^{-1}(\{n\})$ is finite.
Show that: $\lim_{n \to \infty} x_{\theta(n)} = x$.

Solutions and hints are just as appreciated.
Comment: If you show $\lim_{n\rightarrow \infty} \theta(n)=\infty$, you are done (Can you see why?). The finite fiber condition will be useful to show this. The key is that $\theta^{-1}(\{n|n\leq N\})$ is finite for all $N$.
Comment: Problems like this make the notion "almost all" so convenient
Answer: We have that $|x_{n}-x|<\epsilon$ for $n\ge N$ for some large $N$. Since $\theta^{-1}({n})$ is finite for all $n$ then for sufficiently large $m_{0}$ we can guarantee that $\theta(m)\ge N$ for all $m\ge m_{0}$. So $|x_{\theta(m)}-x|<\epsilon$ for all $m\ge m_{0}$.
More explicitly, let $S = \{n \in \mathbb{N} \mid n \lt N \}$. Then $\theta^{-1}(S)$ is finite (since it can be expressed as a finite union of finite fibers) and has a maximum element $n_0$. Then if $n \geq n_0 + 1$, $\theta(n) \not\in S$ and hence $\theta(n) \geq N$. If we put $m_0 = n_0 + 1$, the result follows as above.


bind zone choking on IN TXT record added to subdomain

Question: When I add this line to my zone record: subdomain.example.org. IN TXT "some text here", my syslog reports the zone can't reload due to errors. subodmain IN TXT "some text here" also fails.
The zone reloads fine without this line.
Comment: Sounds like the name where you try to add the `TXT` record is an alias (has a `CNAME` record). A name cannot both be an alias and have data of its own, so this is expected.
Comment: Can you show the actual error (and actual record if the above is not it)?
Comment: Use `named-checkzone` to test the zone.
Comment: in syslog, the error is ` dns_master_load: /etc/bind/zones/example.org.hosts:30: subdomain.example.org: CNAME and other data`
Comment: I don't know what you mean by actual record. You mean the non-anonymized one?
Answer: Based on the error message posted in the comments:
dns_master_load: /etc/bind/zones/example.org.hosts:30: subdomain.example.org: CNAME and other data

It appears that the name where you are trying to add the TXT record is an alias (has a CNAME record).
A name cannot both be an alias and have data of its own, so this error is the expected outcome if you try to add any other records.
(The TXT record listed in the question would otherwise be fine.)


Using pytest to test max_length of django model field

Question: I'm doing some scraping of several webpages and storing the information into a django model.
I recently discovered the max_length that I had considered for some fields was not long enough so I had to increase it.
In order to make sure nobody in our team nobody is using a old version of the model, nor in production, we wanted to prepare a few simple tests with pytest.
Lets consider the following excerpt of the model
class JobOffer(models.Model):
    title = models.CharField(max_length=100) # this should be 120

Now, I try to make a test that fails when we store a string longer than 100 chars.
@pytest.mark.django_db
def test_joboffer_title_length(self):
    lots = 'x'*120
    JobOffer.objects.create(title=lots)

When I run, this test passes. However, when I execute the same command in the shell it rises a DatabaseError
What could be the reason of that behavior? Does pytest consider the max_length of the fields?
Comment: How are you executing those tests? You mention "When I run, this test passes", and "when I execute the same command in the shell", what those commands are exactly?
Comment: What I meant is that when I execute the test as shown it fails. However when I run the command inside it ( ```JobOffer.objects.create(title=x'*120)``` ) in the shell, it rises an error
Comment: @kiril Did you resolve this?
Answer: A late answer but I hope to be useful for further reader.
Django documentation refer to this:

Note that full_clean() will not be called automatically when you call your model's save() method. You'll need to call it manually when you want to run one-step model validation for your own manually created model

Try next solution
@pytest.mark.django_db
def test_joboffer_title_length(self):
    lots = 'x'*120
    job_offer = JobOffer(title=lots)
    job_offer.full_clean()

This will fail with ValidationError. Next code could be useful for checking if exception is raised when exceed max length:
@pytest.mark.django_db
def test_joboffer_title_length(self):
    lots = 'x'*120
    job_offer = JobOffer(title=lots)
    with self.assertRaises(ValidationError):
        job_offer.full_clean()

Answer: I think you need to save() the object you're creating, as that's when the constraints are evaluated:
@pytest.mark.django_db
def test_joboffer_title_length(self):
    lots = 'x'*120
    JobOffer.objects.create(title=lots).save()

Now that test should fail.
Comment: The create method is a shortcut to using the constructor then calling `save`. This makes no difference.


Proguard retrace output confusion

Question: I have here a stack trace from one of my games from android market. I have de-proguarded it but I can't really understand it!
I'm not asking for help in the error itself, but just how to interpret this.
I started with this from Market:
java.lang.IllegalArgumentException
at java.nio.Buffer.position(Buffer.java:299)
at com.a.a.k.o.a(Unknown Source)
at com.a.a.k.w.a(Unknown Source)
at com.a.a.k.w.onDrawFrame(Unknown Source)
at android.opengl.GLSurfaceView$GLThread.guardedRun(GLSurfaceView.java:1363)
at android.opengl.GLSurfaceView$GLThread.run(GLSurfaceView.java:1118)

But retrace.bat has output this, which is longer, so I can't tell what com.a.a.k.o.a is (for exmaple).
java.lang.IllegalArgumentException
at java.nio.Buffer.position(Buffer.java:299)
at com.eaw.graphics.WorldViewShader.void glSetMVPMatrix(float[])(Unknown Source)
                                    void glSetNormalMatrix(com.eaw.graphics.AMatrix)
                                    void SetVertices(java.nio.FloatBuffer)
                                    void ApplyArgs(com.eaw.graphics.WorldViewShaderArgs)
at com.eaw.graphics.TriangleRenderer.void onDrawFrame(com.eaw.airrace.ILayer,com.eaw.airrace.StepOutput,boolean)(Unknown Source)
                                     void loadTexture$332cd44f(int[],int,int)
                                     void delayedLoadTexture(int[],int[],int,int)
at com.eaw.graphics.TriangleRenderer.void onDrawFrame(javax.microedition.khronos.opengles.GL10)(Unknown Source)
at android.opengl.GLSurfaceView$GLThread.guardedRun(GLSurfaceView.java:1363)
at android.opengl.GLSurfaceView$GLThread.run(GLSurfaceView.java:1118)

Has it rolled 4 functions into 1 during obscuration? or what?
Answer: You should add -keepattributes SourceFile,LineNumberTable to your proguard configuration file!
Answer: Your processed code and stack trace doesn't contain line numbers, so ProGuard can't tell to which original method name the obfuscated method name 'a' corresponds. It then prints out all possible alternatives. Cfr. ProGuard's Retrace manual.
The manual also documents how you can preserve line numbers in the obfuscation step.
Comment: The retrace manual doesn't seem to be accessible as of today. I have enabled `LineNumberTable` etc, and I can see line numbers in my mapping file, but retrace still can't disambiguate between the methods.

Proguard retrace output confusion


What do you call the mimicking of music and sounds through whistling?

Question: I recently realised that I can repeat sounds I hear by whistling. Not all sounds, some fall out my whistling range, but I can whistle any music I know. What is this phenomenon called? I don't think it is perfect pitch because I don't know the names of notes.
I think I'm going to practice my whistling by trying to expand my range and get my whistling to become more musical, maybe I should consider becoming a concert whistler. I don't know, mimicking sounds and music I hear by whistling is just something I have done my whole life.
Comment: Echolalia is an automatic tic where one repeats the last words of everything that someone else has just said, which happens regardless of whether it was interesting. It has nothing to do with deliberate mimicking of sounds you like.
Comment: It's just called 'whistling'. Most people can do it, just as they can sing anything they know.
Comment: Ummm... I think that's just called "whistling". [Obligatory reference.](https://www.youtube.com/watch?v=8W3puhJiGGE)
Comment: It's literally just called "whistling".
Comment: You can whistle the *pitches* you hear, but I doubt you can whistle the *sounds*. Oboe, sax, violin, guitar, piano, harp...? The list goes on... Vtc rather than dv. Phenomenon, also., not phenomena (plural).
Comment: Ok, the term I was searching for was echolalia. I often repeat accents and sounds I find interesting some trough whistling..
Answer: It's called 'being able to whistle'.   A posh name for someone who has this skill is 'siffleur'.
Not to be confused with this gentleman:
https://en.wikipedia.org/wiki/Le_P%C3%A9tomane
Comment: 'It's an ill wind...'


load balancing multiple horizontal drupal instances

Question: I've developed a REST WebAPI using the Services module. It works fine. I have a client of that API with projected usage requiring I horizontally scale my Drupal instance. Note that due to the nature of my API, requiring significant CPU and GPU resources, I can not use cloud servers. Also, due to the nature of my API, the Drupal instances have to run on Windows OS. (My application requires software only available on Win64.) I have a fairly beefy server in a co-location now, and for this ambitious client I am planning to horizontally scale my hardware in the following manner:

One CentOS server running HaProxy as the front end load balancer,
Two to start, with more added as needed, Windows Server 2008 R2
servers hosting Drupal,
One CentOS database server providing a single database for the
multiple Drupal instances,
One CentOS database server running in replication mode in case DB
server 1 dies.

My questions have to do with how the HaProxy load balancer works. I'm assuming that the sessionIds created by the Drupal instances will be unique from one another. Does the load balancer look at the sessionId and route all requests to the same server that produced that sessionId? How would a REST WebAPI communication work if load balancing caused each API request to go to a different server? Does any and all data referenced by the WebAPI have to be stored in the database because I can't insure that multiple API requests for the same resource will be routed to the same Drupal instance?
Comment: Very interesting question. I can't help feeling that it's more of a general question than one strictly about Drupal though (it could apply to any PHP-based REST API that uses session authentication if I'm reading it right); if that's the case you might benefit from flagging for it to be migrated to the main SO site. Just a thought :)
Comment: +1 for finding more info elsewhere. You can use most of the advice for scaling any PHP application with Drupal. As my comment was just a tad too long, I posted an answer that may help you find what you need.
Comment: Thanks rocketeerbkw and Berdir for your insights. In my ongoing research into this, I've learned that HaProxy does not handle SSL with sticky sessions, and I need to use something like stunnel for SSL, since all my API communications are over SSL. Looks like more research is needed to fully understand my next move here.
Comment: And more research seems to indicate my configuration needs to look like tier1: firewall server & stunnel, tier2: load balancer, tier3: multiple drupal web servers, tier4: shared database server, tier5: replicating database server. And possibly along with tier4 a SAN for shared file storage for the multiple Drupal instances. Any insight, bread crumbs, or web articles describing people setting up something like this are welcome.
Answer: Having multiple webservers behind a load balancer/reverse proxy is quite common for Drupal and well supported. Varnish is typically used in the Linux world because that thing is just insanely fast when being able to actually use it, meaning anonymous visitors. Which is obviously not the case for your site.
Sessions are stored in the database by default, so that's not a problem. The only other thing that needs to be shared across all servers is the public files directory and any other like the private files if you're using something like that). In most cases, a shared/distributed file system like NFS is used for this although there are some more advanced approaches. On one site where I'm involved is the file system provided by yet another server that is an NFS-mount on the Drupal servers (so access there is slow) and is being distributed under a different domain by Lighthttpd. But again, that is probably not so relevant for you as you're not going to server lots of images and css files, I guess.
As mentioned by rocketeerbkw, there are cache backends for Memcache, Redis and others. So far, Ive only used Memcache but I recently started to look into Redis and it looks very promising but I'm not sure if it is available for Windows. However, it would be possible to set up a separate Linux server to be used for the cache. Drupal 7 relies heavily on caches, being able to get them off the database is very important for two reasons:

Tools like Redis and Memcache are designed for fast key based lookups and they keep their data always in memory to make the lookup as fast as possible. They have also built in support for automatically cleaning up old cache data if the configured limit gets closer.
Maybe even more important, it helps to get database load down. Once you have the basic setup in place, adding additional webservers is easy. Once you start reaching the limits of a single database server, things get much more complicated and you need to look into things like master/master replication (Drupal 7 doesn't really gain much from master/slave environments).

So, it's basically just your own API that you need to take care of. If possibly, you need to make sure that everything is always available from all servers. You can use either the databse, the file system or something else (Drupal can also use MongoDB to store certain data, e.g. fields). If that is not an option, then you will need to use sticky sessions so that users always end up on the same instance. You should however really try to avoid that because if one of the server fails then all users which were on that server need to re-connect to another server, possibly losing data.
Answer: By default PHP stores sessions on disk. If a user logs into Server 1, then hits Server 2 they will be logged out. There are a few options for fixing this:

Don't store sessions on disk
Ensure users always hit the same server
Mount a shared filesystem on all servers

To implement #2 and answer your questions about HAProxy; In the most basic setup you can run it in TCP Mode and use the "source" balancing algorithm (http://cbonte.github.com/haproxy-dconv/configuration-1.4.html#4-balance) to make sure users hit the same server. You should read the docs to determine if there are any downsides for you using that approach.
For #1 you can use a key/value store like Redis or Memecached that all your servers would connect to and retrieve sessions. This makes sessions load/save very quickly and you could use either as a shared Drupal cache as well.
Comment: Drupal by defaults stores the sessions in the database and not in the file system.


Why did Euclid treat magnitudes and numbers twice?

Question: In the Elements, Euclid states and proves twice that (in modern notation)
$$\boxed{\text{from } \frac{a}{b} = \frac{c}{d} \text{ it follows that } \frac{a}{b} = \frac{a-c}{b-d}}$$
– first for magnitudes (lengths), then for numbers.
(1) Book V, Proposition 19

(2) Book VII, Proposition 11

Note that the proper propositions are almost identical in the Greek original:

So what does it mean that Euclid decidedly treats magnitudes (lengths) separately from numbers, even though he was obviously aware that they are (or behave) very much the same?
Furthermore, in the two proofs he makes use of different definitions, i.e. axioms, i.e. theories - but arrives at the very same result. What does this tell us about the two theories?
Comment: This would seem to be a good question for the [History of Science and Mathematics Stack Exchange](http://hsm.stackexchange.com).
Comment: Remark that - as I [show here](https://math.stackexchange.com/a/117659/242) - this is the descent step in an inductive proof showing that a fraction writable with denominators $a$ and $b$ is writable with denominator $\,\gcd(a,b).\,$ This immediately implies Euclid's Lemma, hence uniqueness of prime factorizations.
Comment: You are right: the first is about magnitudes, the second is about numbers.  These are not the same thing at all in Euclid.  Perhaps see https://hsm.stackexchange.com/a/5958/229
Comment: But Euclid talks about them with the very same words, at least sometimes. So what does "at all" mean?
Answer: To Euclid, number meant whole number, or ratio of whole numbers (fraction). On the other hand, length was just that: the length of a line segment. It had been shown that some lengths were not "numbers" in Euclid's sense, in particular $\sqrt{2}$, the length of a diagonal of a unit square. So, not all lengths were numbers.
On the other hand, multiplication of lengths was very limited: it only made sense to multiply two or three lengths together, since objects were only $2$- or $3$-dimensional! On the other hand, one could multiply as many numbers as desired, since they were separate entities, not bound by geometry.
Therefore, to the ancient Greeks, numbers and lengths were completely separate things: they had different uses and behaved differently. So, Euclid had to treat them separately when proving properties about them.
Comment: BTW: Did Euclid ever treat **lengths of arcs of circles** (as another "completely separate thing"? (At least he treated the circumference of a circle.)
Comment: Note, that angles (in radians) "are" (nothing but) the lengths of arcs of the unit circle. But for Euclid angles were of course a "completely separate thing" from numbers and lengths (of any kind).
Comment: I'm afraid I don't know at all :/ As suggested above, I'm sure you'd be more likely to get complete answers at the History of Science and Mathematics Stack Exchange!
Comment: I guess Euclid couldn't have told which number relates to an arc, did he?
Comment: I followed your advice: https://hsm.stackexchange.com/questions/7862/did-euclid-consider-the-length-of-circle-segments-as-another-magnitude
Answer: Euclid defines proportionality differently for magnitudes than for numbers.

Definition V.5: Magnitudes are said to be in the same ratio, the first to the second and the third to the fourth, when, if any equimultiples whatever are taken of the first and third, and any equimultiples whatever of the second and fourth, the former equimultiples alike exceed, are alike equal to, or alike fall short of, the latter equimultiples respectively taken in corresponding order.
Definition V.6: Let magnitudes which have the same ratio be called proportional.

But

Definition VII.20: Numbers are proportional when the first is the same multiple, or the same part, or the same parts, of the second that the third is of the fourth.

Note that the second definition is a lot simpler than the first! So, when proving things from it, there's a lot less to check, which is why your second proof is shorter than your first proof.
Intuitively, numbers are all multiples of the same common unit, so can be dealt with via (what we in modern times would call) integer arithmetic. But magnitudes have no such restriction, so you need to do something resembling real analysis to work with them. (When Dedekind constructs the real numbers, he mentions being inspired by Euclid's Definition V.5...)
Comment: Sorry, in the meanwhile I changed my question slightly.


confusion about individual notation

Question: Let's say I am trying to estimate the regression of $y$ on $x$:
$$y= x \beta + \epsilon.$$
So, when moving to regression frameworks, I often see people use the individual notation:
$$y_i = x_i \beta + \epsilon_i,$$
and derivations of expectations as we are estimating:
$$\mathbb{E}[y_i|x_i].$$
The individual notation is confusing me.  Ultimately, we are interested in the general relationship between $x$ and $y$, correct?  The individual notation seems to me to look like it is the relationship between $x_i$ and $y_i$, so for individual $i$, the relationship between changing $i$s $x$ on $i$s $y$.
Is it not just two random variables, $y$ and $x$, which vary/have realizations experienced by different individuals indexed by $i$?  Or is it that we are estimating the conditional expectation function for each of say $N$ (number of data points) $y$s given $x$, and imposing that the effect ($\beta$) is the same for all $N$?
Answer: This matrix equation
$$\begin{bmatrix} y_1 \\ y_2 \\ \vdots  \\ y_{n-1}\\ y_{n}\end{bmatrix} = \beta \cdot \begin{bmatrix} x_1 \\ x_2 \\ \vdots  \\ x_{n-1}\\ x_{n}\end{bmatrix} + \begin{bmatrix} \epsilon_1 \\ \epsilon_2 \\ \vdots  \\ \epsilon_{n-1}\\ \epsilon_{n}\end{bmatrix}$$
can be written as
$$\forall i : y_i = \beta x_i + \epsilon_i$$
Which is called index notation.

The individual notation is confusing me. Ultimately, we are interested in the general relationship between x and y, correct? The individual notation seems to me to look like it is the relationship between $x_i$ and $y_i$, so for individual i, the relationship between changing i's x on i's y.

You are supposed to think of the relation as being true for all $i$. In the equation above I have expressed this as '$\forall i$:' which means 'for all $i$:'
Comment: Just to follow up - so if thinking about this being true for all i, then it is just simply the relationship between x and y, and is the index more just notational to signal the unit of observation/that we are talking about a scalar?
Comment: @Steve Yes it is just notational. It is to signify that there are multiple measurements $x$ and $y$ (that each follow the same relationship). It is especially useful for more complex relationships (e.g. mixed effects models or other measurements with multiple units/subjects/groups) when you may get multiple indicators $i$, $j$, $k$, etc.
Answer: If both $y$ and $y_i$ are univariate, it doesn't matter if you use index $i$ or not. It's the expected value of the dependent variable given the independent variable, i.e. $E[y|x=a]=E[y_i|x_i=a]$. Sometimes $y$ is the vertical concatenation of each sample response, in which $y=x\beta+\epsilon$ is the matrix notation for the relationship.
The notation $y_i=x_i\beta+\epsilon_i$ doesn't mean that we get to estimate $\beta$ only from sample $i$. So, it's the relationship between $y_i$ and $x_i$ but we estimate $\beta$ from all the samples (training samples).
Comment: usually I see i referring to the individual in the sample, but does this mean then that i's actual y is determined by the 'structural' effect of x and also i's error, and hence the indexing with i? so basically, does $E[y_i|x_i]$ refer to the expectation of all possible realizations of i's particular y, or is it still the expectation of y across all i's?
Answer: As far as I know, there are three possible notations:

Individual notation: $y_i = \beta_0 + \beta_1x_{1i} + ... + \beta_Kx_{Ki} + \varepsilon_i$ where $i=1,...,N$.

Without expression $i=1,...,N$, this notation is mostly pointless, however it is common to assume this addition and omit this part. Omitting does not mean, that it does not exist.

Such notation means, that this is a system of N equations. One equation for every observed unit.

Sometimes individual notation is written shorter using vectors: $y_i = \pmb{ x}_i\pmb{\beta} + \varepsilon_i$ where $i=1,...,N$.

In this case: $\pmb{x}_i = [1, x_{1i}, ... , x_{Ki}]$ and $\pmb{\beta}^T = [\beta_0, \beta_1, ... , \beta_K]$.

It is equevalent individual notation to (1), because $\pmb{ x}_i\pmb{\beta} = \beta_0 + \beta_1x_{1i} + ... + \beta_Kx_{Ki}$.

The same problem of omission of $i=1,...,N$ is in place here. We also have N equations here.

Matrix notation: $\pmb{y} = \pmb{X\beta} + \pmb{\varepsilon}$.

Here: $\pmb{y}^T =  [y_1,...,y_N], \pmb{X}^T = [\pmb{x}_1, ..., \pmb{x}_N]$, $\pmb{\beta}^T = [\beta_0, \beta_1, ... , \beta_K]$, $\pmb{\varepsilon} = [\varepsilon_1, ..., \varepsilon_N]$ .

This notation also describes exactly the same. The N equation system.

Now, to the confusion in question:

Ultimately, we are interested in K+1 parameters $[\beta_0, \beta_1, ... , \beta_K]$, which are the same for every equation in the whole system of N equations.

We have one random variable for the righthand side of every equation, $\varepsilon_i$. $\pmb{x}_i$ is often assumed non-random. Therefore for every $i = 1,...,N$, $y_i$ is a sum of a constant $\pmb{ x}_i\pmb{\beta}$ and a random variable $\varepsilon_i$.

Therefore we are having different random variables in every equation, which have common properties, like for example for every $i=1,...,N$: $\varepsilon_i \sim N(0,\sigma^2)$.

Generally, this approach is slightly different, than regression of two random variables known from probability calculus. This is statistics.
Comment: There are unsurprisingly all sorts of small variations on this, e.g. some people as in various other answers (FWIW me too) prefer $n$ for sample size. Pedantically I will note that $\beta_0, \beta_1, \dots, \beta_K$ is $1 + K$ parameters.
Comment: Definitively you are right! K + 1! And you are absolutely true, that notations may vary.
Answer: The notation using subscript $i$ is the standard way to express the regression model, although you would also implicitly assume (or explicitly state) that this equation holds over a range of values ---e.g., $i=1,...,n$.  When we have different observations/"realisations" of a generic form, we use the subscript notation to specify which of those observations/"realisations".  If we do not use the subscript, then it is unclear what we are actually referring to.
In a regression context, the equation $y= \mathbf{x} \boldsymbol{\beta} + \epsilon$ does not really make sense without these subscripts for the observations, because there is no such thing as an "error term" $\epsilon$ that applies in general to all observations.  The whole idea of the regression model is that the error terms are the deviations of the observed response values from their conditional expectation, and these deviations are different for different observations.  The regression model consists of a stipulated form for the conditional expectation of the response variable and a distribution for the error terms (note the plural --- error terms, not error term).

How the linear regression equation is derived
In order to obtain the model form for the linear regression model, suppose that we are willing to stipulate that the conditional expectation of the response variable is a linear function of the unknown parameters $\boldsymbol{\beta}$ for all the observable values over some sample range.  Let's denote this conditional expectation function (called the true regression function) by $u$.  This gives us the starting equation:
$$u(\mathbf{x}) \equiv \mathbb{E}(Y_i | \mathbf{X}_i = \mathbf{x}) = \mathbf{x} \boldsymbol{\beta}
\quad \quad \quad \text{for all } i = 1,...,n.$$
Now, the error term for each observation is defined as the deviation of the response value from its conditional expectation ---i.e., for each $i=1,...,n$ we have:
$$\epsilon_i \equiv Y_i - u(\mathbf{x}_i) =  Y_i - \mathbf{x}_i \boldsymbol{\beta}.$$
Note that this is a definition of what the error term is measuring.  By rearranging this definition we get the standard form of the linear regression model:
$$Y_i = \mathbf{x}_i \boldsymbol{\beta} + \epsilon_i
\quad \quad \quad \text{for all } i = 1,...,n.$$
In order to obtain a regression model, we also need to make some assumption about the distribution of the error terms.  The standard assumption is that the error terms are IID random variables with zero mean and a fixed finite variance (often also assumed to be normally distributed).  This distributional assumption then gives us the full regression model, but as you can see, the defining equation for the model form follows directly from our definition of what the error terms (again, note the plural) are measuring.
A crucial thing to note here is that the true regression function $u$ is (assumed to be) the same for all the observations.  (Consequently, when introducing this function I did not need to put a subscript on the value for the explanatory vector.)  This means that we have a single generic true regression function that applies to all the observations.  We still need to write our full model form as a set of equations over $i=1,...,n$ because we need to stipulate that this form holds for all the observations.  Consequently, while it is not valid to state the model equation generically (since the error terms are different for different observations), there is still a single underlying function that we are trying to estimate.

Okay, so what about estimating the "general form"
In your question, you correctly note that we are interested in the general relationship between the response variable and the explanatory variables.  This is encapsulated in the true regression function $u$.  By assumption, this function is the same for all the observations, so we are only estimating this one regression function.
When we use the data to estimate the parameter $\boldsymbol{\beta}$ this gives us a corresponding estimator for the true regression function $\hat{u}(\mathbf{x}) = \mathbf{x} \hat{\boldsymbol{\beta}}$, leading to the predicted and residual values defined by:
$$\hat{Y}_i = \hat{u}(\mathbf{x}_i) = \mathbf{x}_i \hat{\boldsymbol{\beta}}
\quad \quad \quad
R_i = Y_i - \hat{u}(\mathbf{x}_i) = Y_i - \mathbf{x}_i \hat{\boldsymbol{\beta}}.$$
Again, you can see that even though we are estimating a single function $u$, this leads to different predicted values and residual values for each of the observations.  Consequently, we again see that we need to use subscript $i$ on each of these equations even though they are all based on estimation of the same underlying true regression function.
Answer: I believe the confusion arises when distinguishing between population and sample levels. There is some inconsistencies with notation (when to use capital/cursive/bold letters), but once you determine on which level the notation is, everything should be clear. Usually, it is clear when we are on the sample levels since the equations would have to iterate through all observations $\{1 \dots n\}$ or $\{1 \dots T\}$, whereas on population levels only a single $i$ or $t$ as index is shown for models.
On population level, the distinction between indexed and non-indexed is very important when describing properties of the model. It is best to understand this when dealing with indexing by time $t$. Consider $y_t=\beta^Tx_t+\varepsilon_t$. On population level every observation is a random variable/vector, so the model holds for every $t$. Then:

Indexed values show a relation that holds only between variables for the same time point. For example: $E[\varepsilon_t|x_t]=0$ is the innovation property of the noise $\varepsilon_t$ (or predetermined property of the regressors $x_t$) and it states that $\varepsilon_t$ has no influence (in the mean) on any of the current response $y_{t}$. It does not rule out no influence on past/future values.

Non-indexed values show a relation that holds between variables for all time points. For example: $E[\varepsilon|x]=0$ is the exogeneity assumption of the regressors $x$, meaning that $\varepsilon$ has no influence (in the mean) on any of the responses $y$, both past, present and future. Here, $\varepsilon$ and $x$ are vectors that include all $\varepsilon_t$ respectively $x_t$.

Obviously, 2 is stronger than 1. Note that both $x_t$,$\varepsilon_t$ and $x$,$\varepsilon$ can be vectors.

confusion about individual notation


Shrink FreeBSD root partition

Question: I currently have a pfSense 2.3.2-RELEASE which was installed with too little RAM and, now I realized that the swap partition is too small (8GB) and I want to expand it. The problem is there's no free space to do that, so I need to shrink the UFS root partition so I can create a bigger swap.
Is there a safe way to do that, besides reinstalling the pfSense?
For FreeBSD servers, i usually use gpart + growfs, but obviously it's not entirely the case.
Answer: You can easily add the swap using plain file on the FS without resizing of existing FS. The whole procedure is explained in the chapter 11.12 of the FreeBSD handbook https://www.freebsd.org/doc/handbook/adding-swap-space.html
Comment: FreeBSD updates are very cautious and you'll be asked for changes to the each config file involved. Additional items in the fstab can't crash your system until they are reasonable.
Comment: It's a good alternative, but i'm a bit concerned since my server is an appliance, and i'm afraid any "non default" fstab may break the system on an update or so, but thank your for that tip, very useful. I may use that.

Shrink FreeBSD root partition


Proving the identity of $\sum_{k = 0}^n{4n \choose 4k} = 2^{4n - 2} + (-1)^n2^{2n - 1}$ combinatorially

Question: I want to prove the following identity combinatorially:
$$\sum_{k = 0}^n{4n \choose 4k} = 2^{4n - 2} + (-1)^n2^{2n - 1}$$
Here's my attempt so far: The left hand side is counting the number of teams among $4n$ people where the size of the team is a multiple of 4. Now let $A$ and $B$ be the last two people among these $4n$ people. Now let $T$ be a team such that $|T| = 4k$. Then we have 4 cases:

$A, B \in T$
$A, B \notin T$
Only $A \in T$
Only $B \in T$

Now I will construct all teams among the $4n - 2$ people after removing $A$ and $B$ (I don't care about their size) and convert them to a team of size $4k$ by adding a subset of $\{A, B\}$ to them. Clearly there are $2^{4n - 2}$ teams that don't contain $A$ or $B$. Let $T$ be one of these teams. Then we have the following cases:

$|T| = 4k$. Teams of this kind correspond to teams of size $4k$ that don't contain $A$ and $B$.
$|T| = 4k + 1$. Teams of this kind will just be discarded.
$|T| = 4k + 2$. Teams of this kind correspond to teams of size $4k'$ that contain both $A$ and $B$. We will just add $A$ and $B$ to $T$.
$|T| = 4k + 3$. Teams of this kind will be converted to teams of size $k'$ that contain either $A$ or $B$. Then for each team of this kind, we should add $1$ to $2^{4n - 2}$ because we have 2 cases here. Either add $A$ or add $B$.

Based on these cases, we will have $2^{4n - 2} - \sum_{i = 0}^{n - 1}{4n - 2 \choose 4i + 1} + \sum_{i = 0}^{n - 2}{4n - 2 \choose 4i + 3}$. If I've made no mistakes, then I should show that $- \sum_{i = 0}^{n - 1}{4n - 2 \choose 4i + 1} + \sum_{i = 0}^{n - 2}{4n - 2 \choose 4i + 3} = (-1)^n2^{2n - 1}$ but I don't know how to do this.
Answer: Here's an indirect approach that works.
First prove combinatorially that
$$(x-1)(1+x+x^2+\dots+x^{n-1}) = x^n - 1 \quad \text{for $n \ge 1$},$$
which is Identity 216 in Proofs That Really Count: The Art of Combinatorial Proof.
Then take $n=4$ and $x=i^k$ to yield
$$\frac{(i^k)^0+(i^k)^1+(i^k)^2+(i^k)^3}{4} = \begin{cases}1 & \text{if $4 \mid k$} \\ 0 & \text{otherwise}\end{cases}$$
and so
$$\sum_{k \ge 0}^n a_{4k} = \sum_{k \ge 0} \frac{1+i^k+(-1)^k+(-i)^k}{4} a_k.$$
Now take $a_k = \binom{4n}{k}$ and apply the binomial theorem, which has a clear combinatorial proof, to obtain
\begin{align}
\sum_{k \ge 0}^n \binom{4n}{4k}
&= \sum_{k \ge 0} \frac{1+i^k+(-1)^k+(-i)^k}{4} \binom{4n}{k} \\
&= \frac{1}{4} \sum_{k \ge 0} \binom{4n}{k}
 + \frac{1}{4} \sum_{k \ge 0} i^k \binom{4n}{k}
 + \frac{1}{4} \sum_{k \ge 0} (-1)^k \binom{4n}{k}
 + \frac{1}{4} \sum_{k \ge 0} (-i)^k \binom{4n}{k} \\
&= \frac{(1+1)^{4n} + (1+i)^{4n} + (1-1)^{4n} + (1-i)^{4n}}{4} \\
&= \frac{2^{4n} + (-4)^n + 0 + (-4)^n}{4} \quad \text{for $n>0$} \\
&= 2^{4n-2} + (-1)^n 2^{2n-1}.
\end{align}
Answer: I don't know the combinatorial answer to this question, at least not fully. But here is how I would solve this:
Define $n_{i}$ as the number of subsets of $\{1,...,4n\}$ such that the number of elements in the subset is $i$ in modulo $4$.

The number of subsets with even number of elements is $2^{4n-1}$, so $n_{0}+n_{2}=2^{4n-1}$.
The difference $n_{0}-n_{2}$ is given by the real part of $(1+i)^{4n}$, which is $(-1)^{n}\phantom{.}2^{2n}$

Therefore we get $n_{0}=\frac{2^{4n-1}+(-1)^{n}\phantom{.}2^{2n}}{2}=2^{4n-2}+(-1)^{n}\phantom{.}2^{2n-1}$

Regarding the combinatorial proof, I cannot get my mind off the fact that if $m=2^{2n-1}$ then the term on the right hand side of your equation is $2\binom{m}{2}$ if $n$ is even or $2\binom{m+1}{2}$ if $n$ is odd. $m$ can be interpreted as the number subsets with even (or odd) number of elements from $\{1,...,2n\}$


How to use ng-repeat inside a directive template Angular JS

Question: I have a problem displaying the JSON object data that my controller passes to the directive template. Here's my code.
Directive
app.directive('heroes', function(){
    return{
        scope:{
            heroes: '='
        },
        template: '
{{ x.Name }}
', // DOESNT WORK
        link:function(scope,element,attributes){

            });
        }
    }
});

Controller
app.controller('MainController',function($scope, $http){
    $scope.getData = function(){
          $http({
              url: 'js/directives/herolist.php',
              method: "GET"
        }).success(function (data) { $scope.heroes = data.records; })

    }

Comment: maybe you shoul try $scope.$apply() in $http callback
Comment: what does $apply do? you mean $http.$apply ??
Comment: @scokmen $http will triggers the $digest
Comment: Guess `ng-repeat="x in hereos">` is a typo btw? (Hereos instead of heroes)
Answer: Working Plunkr
You should include the directive in your HTML and rename your values a bit
html can be
 <heroes data="heroes"></heroes>

then in your directive you would do
 scope:{
        heroes: '=data'
    }

If you would do heroes: "=" and you are not restricting the directive to let's say an element, then you are basically including the directive twice (you don't want that). If you do want to use heroes as an attribute, like this
<heroes heroes="heroes"></heroes>
then add

restrict: "E"

to your directive.
Comment: yep. still the same can't display
Comment: Thanks! this worked.. just a question..  do I always need to post a "="heroes" inside the scope of a directive? what does it mean by the way?
Comment: In this case yes. You are passing the data from your controller to the directive. In your controller you have $scope.heroes = data.records; if that would be $scope.myData then you would do  . The directive has its own scope and in the directive you can define attributes to easily pass data (see : scope:{
        heroes: '=data'
    }). That is where you link the value of the data attribute of your directive to the scope of your directive. Hope that makes it a bit more clear for you. I recommend you to read a bit more on directives to get a clear understanding.
Comment: Thanks muller! yes I am watching videos on directives right now. And it so happen I just stumble upon '=' in your answer. I thought it was just imited to '=', '@' . But anyways thanks again!
Comment: Thank you for this plunkr, saved my life


Is it reflexive: everyone who has visited Web page a has also visited Web page b, for all webpages

Question: This is a question from "Discrete Mathematics and Its Applications":
Determine whether the relation R on the set of all Web
pages is reflexive, symmetric, antisymmetric, and/or tran-sitive,
where(a, b) ∈ R if and only if

a) everyone who has visited Web page a has also visited Web page b .

The answer is:
a) Reflexive, transitive

I don't understand well why it's "Reflexive". If there is a web page which has never been visited by anybody, (a,a) won't be belonged to R, that R should not be reflexive, right?
Do I misunderstand something wrong?

Thanks for @Brian M. Scott's answer, I understand it now. Let me add something important here:
The description of $R$ is:
$R$={$(x,y) | \forall p (F(p,x) \to F(p,y))$}, where $F(p,x)$ means "p has visited x", and $ p \in P $ where P is "all people".
When page $x$ has never been visited, that $F(p,x), p \in P$ is always false, that $\forall p (F(p,x) \to F(p,y))$ is always true, that F(x, any y) is always true.
That's why the relation is "Reflexive".
Comment: It will be helpful for you to review the definition of a relation first. What does $aRb$ mean? What does $aba$ mean?
Comment: "Everyone who has visited the Sun has (also) visited the Sun" is true.
Answer: If $a$ is a web page, let $V(a)$ be the set of people who have visited $a$. Then $\langle a,b\rangle\in R$ if and only if $V(a)\subseteq V(b)$. Now it's always true that $V(a)\subseteq V(a)$, even if $V(a)=\varnothing$, so it's always true that $\langle a,a\rangle\in R$. Thus, $R$ really is reflexive.
Here's a slightly different way to look at it. If $a$ and $b$ are particular web pages, how could you prove that $\langle a,b\rangle\notin R$? You would have to find someone who has visited $a$ but has not visited $b$. If no one has visited $a$, you can't do this: you can't find anyone who has visited $a$, let alone someone who has visited $a$ but not $b$! This shows that if $a$ has never been visited, then $\langle a,b\rangle\in R$ for all $b$ (and hence certainly for the particular case $b=a$).
Comment: @Freewind: Yes, that's one correct way to describe it, though it would be better if you wrote $\forall p\in P$ and defined $P$ to be the set of all people.
Comment: $R$={$(x,y) | \forall p (F(p,x)  \to F(p,y))$}, where $F(p,x)$ means "p has visited x". Is it right?
Comment: If page $x$ has never been visited, that $F(p,x)$ will always be `false`, that $\forall p (F(p,x) \to F(p,y))$ will be `true`, so $(x, any y)$ belong to $R$.
Comment: @Freewind: Yes, that's right.


Uniformly most powerful test does not exists

Question: I am having tough time understanding this concept
The book says:
"We caution the reader that UMP tests for testing H0 : θ1 ≤ θ ≤ θ2 and
H0′ : θ = θ0 for the one-parameter exponential family do not exist. An example will suffice.
Example 5. Let X1,X2,...,Xn be a sample from N(0,σ2). Since the family of joint PDFs of X = (X1,...,Xn) has an MLR in T(X) = $\sum_X_i^2, it follows that UMP tests exist for
one-sided hypotheses σ ≥ σ0 and σ ≤ σ0."
Does this means that if we have only one sample actually our z-test and t-test For inequality hypothesis does not exist?
Answer: The $z$-test and $t$-test still exist and they have all the nice power properties that are available.  It's just that UMP tests don't make sense with a two-sided alternative.
If you have a two-sided test of equality of means, you can increase the power in one direction (eg, against an increase in mean) at the expense of lower power in the other direction (a decrease in mean). You can think of it in terms of partitioning the size $\alpha$ of the test: the rejection region has to have probability $\alpha$ in total, and it comes in two parts with the non-rejection region separating them.  If you make the upper rejection region larger, by moving the threshold down towards equality, you need to make the lower rejection region smaller by moving its threshold down, away from equality.
None of these tests are uniformly more powerful than each other; they are all more powerful against some alternatives and less powerful against others.  This sort of thing is why UMP tests so rarely exist: there are usually lots of alternatives and different tests have higher power against different ones.
(This is addition to the interesting technical reasons why UMP tests sometimes fail to exist even in one-sided, one-dimensional problems)


listing options in the selected tag through a SQL query in PHP

Question: I want to retrieve a value from <select> tag into PHP... the options in this selected tag is a function from PHP which lists those options from a separate php files called functions.php
see the function below from functions.php
function list_brand (){
  $sql = "SELECT brand FROM laptop
         ";
  $query = mysql_query($sql) or die (mysql_error());

  if ($query) {
     //echo 'success'; <-- testing the function functinality

     while ($query_row = mysql_fetch_assoc($query)) {
           $brand = $query_row['brand'];

           echo '<option value="brand">'.$brand.'</option>';
     }
  } else {echo 'fiald if';}
}

and below is the selected tag:
<select id="test" onchange="document.getElementById('text_content').value=this.options[this.selectedIndex].text">
    <option value="select">SELECT BRAND</option>
    <?php list_brand(); ?>
</select>
<input type="hidden" name="brand_text" id="text_content" value="" />

now my question is that i have two other selected tags that should list the options depending on that selected option in the first selected tag and that it should list thorough a SQL query
below is my full html code:
<form action="comparison.php" method="GET">

    Lap 1
    Lap 2

    Brand
    <select><option value="brand1">==SELECT BRAND==</option>
                    <?php
                      list_brand();
                    ?>
                    </select>
    Brand
    <select name="brand2"><option value="brand2">==SELECT BRAND==</option>
                    <?php
                      list_brand();
                    ?>
                    </select>

    Model
    <select><option value="model1">==SELECT MODEL==</option></select>

    Model
    <select><option value="model2">==SELECT MODEL==</option></select>

    Partnumber
    <select><option value="pn1">==SELECT PARTNUMBER==</option></select>

    Partnumber
    <select><option value="pn2">==SELECT PARTNUMBER==</option></select>

</form>

Comment: Its not clear to me what a "tag" is in this context
Comment: First, you don't need to manage a "onCHange" to set the value in an input field, select are, like other input element, able to be submit on the form (if it has a name, you will get it on your $_GET, on the server side). Secondly, it appear that you want to update your second select depend on the value of the first select. Then, you should add a onChange listener on the first select, and when the value is changes, run an ajax request to refresh the second select.
Comment: hi. i did slipt ur comment dude. i just had to run two function on the "onchange" value and it did work
Answer: this is it. I had to put two functions on OnChange one for assigning the selected value and the other is to submit the page so it can refresh...
 <form name="index" action="" method="GET">
  <select id="brand" onchange="document.getElementById('brand_content').value=this.options[this.selectedIndex].text; document.index.submit();">
          <option value="">==SELECT BRAND==</option>
                      <?php
                        list_brand();
                      ?>
  </select>
  <input type="hidden" name="brand_text" id="brand_content" value="" />

<?php
      $brand = $_GET['brand_text'];
      if (isset($brand)){

      }  else {echo 'no brand selected';}
?>

  <select id="model" onchange="document.getElementById('model_content').value=this.options[this.selectedIndex].text; document.index.submit(); ">>
  <option value="model1">==SELECT MODEL==</option>
  <?php
       list_model($brand);
  ?>
  </select>
  <input type="hidden" name="model_text" id="model_content" value=""
</form>

Answer: You would need to handle this with a JavaScript solution, so you essentially want to use JavaScript to firstly check what option was selected in the first select tag, and then you would want to use JavaScript to then generate the contents for the second and third. The only way I can think of doing this is using an ajax request, as PHP is client side and parses once so it can't be changed once it has parsed.
Also, the mysql_* functions are now deprecated, you should consider using PDO or MySQLi in your future and current projects. You can read further on this here
Comment: Hi again... GOT IT SOLVED :) will post my solution tomorrow after God's well.


Mapping 2d point (x,y) into grid index (row,col)

Question: I have a particular **Grid ** for robot navigation showing as so:

I have scaled this by a factor of 10 to create my Environment. This is given in Cartesian coordinates

I would like to map a point in the Environment (x,y) into Grid index (row, col)
The obstacle format is given in the form:
[[(60.0, 0.0), (70.0, 0.0), (70.0, 10.0), (60.0, 10.0)],
[(70.0, 0.0), (80.0, 0.0), (80.0, 10.0), (70.0, 10.0)],
[(60.0, 10.0), (70.0, 10.0), (70.0, 20.0), (60.0, 20.0)],
[(70.0, 10.0), (80.0, 10.0), (80.0, 20.0), (70.0, 20.0)],
However when i try to plot these using the following code:
fig, ax = plt.subplots()
        for obs_corner in self.obstacle_vertices:
            ox=obs_corner[0][0]
            oy=obs_corner[0][1]
            w=self.planner.scaling_factor
            h=self.planner.scaling_factor
            ax.add_patch(patches.Rectangle((ox,oy),w,h,edgecolor='black',facecolor='black',fill=True))

The graph generated is :

I think i am making a basic mistake in mapping matrix into a 2d environemnt
Comment: Please provide the data as code/text, not images.
Answer: Your drawing has the origin in the top left but your code produces a plot with the origin in the bottom left. If you want it in the top left then you should flip (invert) the y-axis.
ax.invert_yaxis()


Create an app from responsive site that uses ajax calls that return both html and javascript - easiest way?

Question: I'm looking for the easiest and most efficient way to create a mobile app from my website that is already fully responsive.
I have a page that contains 5 different ajax calls. Each ajax call returns both html and javascript which is created by a PHP script. All JavaScript that is is not user dependent is in a separate file. There is also a separate file for all css.
I think converting the code (using phonegap) will be very difficult because of the ajax calls. Preferably I would like to have an app that installs an icon on someone's phone and that just opens my website in a browser (without showing anything of that browser).
My question: What is the easiest way to create an app for android and ios?
Comment: That app will not pass review in Apples Appstore. (See submission guidelines)
Answer: Webview? If you are looking to build an app that just opens your webpage and does not show that its opened AOSP browser or any other browser for that matter then just use webview. It would open like any other activity in your app but the content (depending on how big you want the webview) will just be your site. I did a very similar thing in my android app and here is the code.
Java Class:

public class website extends Activity {
<code>@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_website);

    String url = "http://www.YourWebsiteHere.co.uk";
    WebView view = (WebView) this.findViewById(R.id.webViewSite);
    view.getSettings().setJavaScriptEnabled(true);
    view.loadUrl(url);
}
</code>

XML File:

<code><WebView
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/webViewSite"
    android:layout_alignParentTop="true"
    android:layout_alignParentBottom="true"
    android:layout_alignParentRight="true"
    android:layout_alignParentEnd="true"
    android:layout_alignParentLeft="true"
    android:layout_alignParentStart="true" /> </RelativeLayout>
</code>

http://developer.android.com/reference/android/webkit/WebView.html


Mvc delete object with ajax

Question: I have a view with table of objects list. When I press "Delete" I want a confirmation popup (the borwser's default popup is fine) to show a message "Are you sure?" and confirmation will just delete the object from db and from the table int the view (without refreshing the page again).
In the table I have this code:
<code>@Ajax.ActionLink("Delete", "Delete", new { id = item.LicenseID },
        new AjaxOptions { HttpMethod = "POST", OnSuccess = "onDeleteSuccess" },
        new { @class = "href", id = "delete",
        onclick = "return confirm('Are you sure you want to delete this?');" })
</code>
My Delete action in the controller is this. along with a totally empty Delete view:
<code>public ActionResult Delete(int id = 0)
{
    License license = unit.LicenseRepository.GetObjectById(id);
    if (license == null)
    {
        return HttpNotFound();
    }

    unit.LicenseRepository.DeleteObject(license);

    unit.Save();

    return View(license);
}
</code>
I have few problems. Sometimes when I press "Delete" the object deleted succesfully.
Sometimes the page is redirecting to the empty Delete view page (if I'll delete the view page I'll get the error "The view 'Delete' or its master was not found or no view engine supports the searched locations").
Sometimes I'm getting the page HTTP Error 404.0 - Not Found.
In both cases, when I'm returning to the table again I see that the object WAS deleted succuessfully.
So, why I'm getting those two pages? What's wrong?
Comment: What does `onDeleteSuccess` do?
Answer: AjaxOptions already have a Property for confirmation, try
<code>@Ajax.ActionLink("Delete", "Delete", new { id = item.LicenseID },
    new AjaxOptions {
        HttpMethod = "POST",
        OnSuccess = "onDeleteSuccess",
        Confirm = "Are you sure you want to delete this?"
    },
    new { @class = "href", id = "delete"})
</code>
http://msdn.microsoft.com/en-us/library/system.web.mvc.ajax.ajaxoptions.confirm(v=vs.118).aspx
Comment: Find row  by concrete selector, and then use remove() function. Before that you should set selector class to rows(during generating table)
Comment: now it's just deleting the object, no popup message is shown before to confirm.
Comment: have a look here http://stackoverflow.com/questions/10253487/ajaxoptions-confirm-does-not-pop-up-in-actionlink-or-beginform-submit
Comment: alright, so I added the reference to unobtrusive-ajax and now it's good, but after deleting the object I need to manually refresh the page in order to see the changes, how can it delete from the table without refreshing the page again?
Comment: @user2254436 you could delete the tr in the success event or you could put your whole table in a PartialView and return an updated version in your delete method... you should find plenty examples for this

Mvc delete object with ajax


Parsing external torrent informations

Question: I'm build a a BitTorrent tracker with CodeIgniter, and i'm use Torrent RW class for parsing .torrent files (info hash, read/write tracker url, etc.).
I would like to run external torrents, and i need help: how to parse external torrent stats -> seeders-, leechers number.
Please, help me, and sorry for my bad english.
Thanks!
Answer: Save yourself the time and use an existing open php torrent tracker (or better yet, convert it over to CodeIgniter and open source it to contribute back!).

RivetTracker
PHPBTTracker+
TBDEV.net

Most are based on the original PHPBTTracker by DeHackEd.
Answer: My recommendation would be to look up the PHP required to do this and then think about implementing it in Codeigniter.
The Torrent RW class will read the torrent but you will need to somehow connect to the torrent and its seeds and leechers in order to get this information.
Check out:
http://sourceforge.net/projects/tbdevnet/

Parsing external torrent informations


Count the number of #defines in a .c file using VBS

Question: I need to count the number of #define lines in C files (3 of them) using VBS. Please suggest the best way to accomplish this.
Comment: Did one of the answers below solve your problem?  If so you should mark this question as answered.  I noticed that you have many questions out there with answers, but none have been flagged as answered.
Comment: A text file consists of a sequence of characters. If you don't define where one "string" ends and where the next one starts, the answer is just "1". You could create a function that just returns 1.
Comment: hi daniel,
          To make the question more clear and better.i want to write a vbs script file which counts the number of #define strings present in a.c,b.c and d.c.
Comment: I've rewritten the question based on this. Please let me know if it's accurate.
Comment: I didnt get u jon??Where had u rewritten my question.
Comment: @Maddy - In the area where the question appears on screen.
Comment: Thanks a lot.Still searchinga a lot but not yet found any answer to this.Can anyone plz help me out
Answer: The script below uses a regular expression to count the #define statements that appear at the beginning of the lines. Whitespace is allowed before the statement as well as between # and define. The list of files to search in should be passed in as arguments, e.g.:
cscript.exe script_name.vbs c:\myfile1.c c:\myfile2.c

Here's the script code:
Const ForReading = 1

Set oFSO = CreateObject("Scripting.FileSystemObject")

Set re = New RegExp
re.Pattern    = "^\s*#\s*define\b"
re.IgnoreCase = False
re.Global     = True
re.Multiline  = True

strReport = ""
For Each strFileName in WScript.Arguments.Unnamed
  Set oFile = oFSO.OpenTextFile(strFileName, ForReading)
  strText = oFile.ReadAll
  oFile.Close

  intCount  = re.Execute(strText).Count
  strReport = strReport & "There are " & intCount & " #define statement(s) in " & strFileName & vbNewLine
Next

WScript.Echo strReport

The script output is like:
There are 7 #define statement(s) in c:\myfile1.c
There are 0 #define statement(s) in c:\myfile2.c

Answer: This code should count all #define statements in any number of input files.  Provisions have been made for whitespace in the statements, such as "# define" or "#      define" both of which are valid statements.
NOTE: I do not count for the # on one line and the "define" on the next, I'm assuming the # and "define" are at least on the same line, though you could do so by reading the entire file and removing all whitespace, then save to a variable or temp file or something like that and use that as your input.
You can shorten the code a bunch by ditching the file access constants and what not, otherwise it will give you output like this:
There are: 9 define statements in the source: c:\define.txt
There are: 11 define statements in the source: c:\define2.txt
There are: 10 define statements in the source: c:\define3.txt

The command line would be:  cscript scriptname.vbs c:\define.txt c:\define3.txt etc...
' Define constants for file access
Const TristateFalse = 0
Const ForReading = 1
Const ForWriting = 2
Const ForAppending = 8

Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objArgs = WScript.Arguments

If objArgs.Count > 0 then

    For i = 0 To objArgs.Count - 1

        Set objFileInputStream = objFSO.OpenTextFile(objArgs(i), ForReading, False, TristateFalse)

        intTempCount = 0
        tokenCount = 0
        Do while not objFileInputStream.AtEndOfStream

            strLine = replace(ucase(objFileInputStream.ReadLine), " ", "")
            intLineLength = len(strLine)

            Do

                If instr(strLine, "#DEFINE")  <> 0 then
                    tokenCount = tokenCount + 1
                    strLine = replace(strLine, "#DEFINE","", 1, 1)
                    intTempCount = intTempCount + 1
                else
                    exit do
                End If

            Loop until intTempCount = intLineLength

        Loop

        objFileInputStream.Close
        wscript.echo "There are: " & tokenCount & " define statements in the source: " & objArgs(i)

    Next

Else
    wscript.echo "You must enter at least one filename."
End If

Answer: How about something like this?  just pass the files in as arguments

Const token = "#define"
Set objArgs = WScript.Arguments

tokenCount = 0

Set fso = CreateObject("Scripting.FileSystemObject")

For i = 0 To objArgs.Count - 1
    Set objFile = fso.OpenTextFile(objArgs(i), 1)
    Do Until objFile.AtEndofStream
         lineCount = lineCount + 1
         If InStr(1, objFile.ReadLine, token, 1)  0 Then
              tokenCount = tokenCount + 1
        End If
    Loop
Next

WScript.echo tokenCount

This will ignore blank spaces between # and define

Const token = "#define"
Set objArgs = WScript.Arguments

tokenCount = 0

Set fso = CreateObject("Scripting.FileSystemObject")

For i = 0 To objArgs.Count - 1
    Set objFile = fso.OpenTextFile(objArgs(i), 1)
    Do Until objFile.AtEndofStream
         lineCount = lineCount + 1
         If InStr(1, Replace(objFile.ReadLine, " ", "", 1, -1, 1), token, 1)  0 Then
            tokenCount = tokenCount + 1
        End If
    Loop
Next

WScript.echo tokenCount

Comment: Notice that the `#` and `define` tokens may be separated by an arbitrary number of whitespaces! `#     define` is still a valid define-macro and isn't found by your code.
Answer: I'm not that good at VB script, but something like ...
Dim re as New RegExp
re.IgnoreCase = True
re.Global = True
re.Pattern = "#define"
Set mc = re.Execute(yourFileText)
ans = mc.Count


Why don't previous events affect the probability of (say) a coin showing tails?

Question: Why doesn't a previous event affect the probability of (say) a coin showing tails?
Let's say I have a fair and unbiased coin with two sides, heads and tails.
For the first time I toss it up the probabilities of both events are equal to $\frac{1}{2}$.
This much is intuitive and clear to me.
Now suppose that I toss it up $1000000000$ times and the scores are,
$501000000$ Heads
$499000000$ Tails
Now, for the $1001000000^{th}$ toss, shouldn't the probability of a tail coming up be greater than that of heads showing up?
I have seen many books which say that even for the $1001000000^{th}$ toss, the probabilities of both events are equal to $\frac{1}{2}$.
This seems wrong to me since the same books affirm that if a coin is tossed a large number of times, the quantity $\frac{heads}{tails}$ will approach $1$.
I know this is very elementary and naive, yet I had only superficially studied probability and I hope you all will bear with me.
My Objections with some of the top-voted answers

It isn't that future flips compensate for the imbalance, it is that there are so many of them it doesn't matter.

I don't get this statement. What exactly does the second sentence mean? Moreover, if what you said is true then, the following comment by a user should be wrong,

Law of large numbers

So these are contradicting each other I feel. Please bear with my lack of knowledge.
Comment: Four words: law of large numbers.
Comment: You seem to think that the probability of a event should change so that the counting ratio tends to whatever it should in long run, right? I don't see any reason why this should be true, especially for $\textbf{independent}$ events but i've seen many proofs of the law of large numbers...
Comment: And of course, no matter how many times you toss, those ratios will never be equal to exactly what they're limiting to—that's part of the definition of a limit—but they approach them arbitrarily close.
Comment: To the edit:  no they are not contradictory.  If you look at my example, even if heads are ahead by $100$ after the first $100$ flips you expect the ratio $\frac {heads}{tails}$ to be close to $1$ after a million flips.  The standard deviation of the number of heads in a million flips is $500$, so the error of $100$ is quite small.  If that isn't small enough to ignore, think about a trillion flips.
Answer: The assumption for a coin is that is has no memory.  That means that the chance of heads is the same on every toss.  For a fair coin, that chance is $\frac 12$ regardless of the history.  If you toss $100$ times and get heads every time (very unlikely, but it could happen)  the most probable event after a million tosses (including the $100$ you already did) is $500050$ heads and $499950$ tails.  It isn't that future flips compensate for the imbalance, it is that there are so many of them it doesn't matter.  Look how close the head/tail ratio would be to $1$ at that point.
Comment: Pls see edits in qn,thanks
Answer: Even in the 1000th time with a 999 tails, 0 heads, the probability of head is 1/2. But the probability that you get 1000th times tails in a row is 0.5^1000,  9.332636e-302.
Comment: Exactly so how is that possible? How can a _same event_ have _different_ probabilities?
Comment: also see the edit
Comment: Pls see edits in qn,thanks
Answer: Imagine one tosses $1,000,000$ fair coins at once. Hence the outcomes of the coins are independent and then the numbers of heads and tails will be approximately (if not exactly) equal.
Comment: pls see edits in qn, thanks
Comment: I've seen your 3rd edits. You are wondering why $n$th toss still has $1/2$ probability of head or tail rather than to have more or less depending on the previous result. The thing is $n$th toss does not depend on the previous tosses. In order to get rid of this dependence, I suggested thinking of tossing the fair coins (as many as you want) at once. So there is no previous, there is only present. I hope it helps.
Answer: Your question mentions a 'fair and unbiased coin.' That very concept means a coin that on any given flip has a $0.5$ probability of heads and a $0.5$ of tails on any given flip, $\underline{\rm{independently}}$ of what has happened on any other flip.
To understand the statement 'It isn't that future flips compensate for the imbalance, it is that there are so many of them it doesn't matter,' let's think about an example:  You want to make a $50-50$ mixture of oil and vinegar.  But accidentally you start with $1$ cup of oil and $2$ cups of vinegar.  Fortunately you want a large amount of the mixture, so you add $1000$ cups of oil and $1000$ cups of vinegar.  You haven't fixed the imbalance of $1$ extra cup of vinegar; but you have added so much of the proper mixture, that you hardly notice the imbalance.  (Your mixture went from about $66.67\%$ vinegar to about $50.02\%$ vinegar, even though there is still one full extra cup of vinegar.)
Things aren't quite as clear with the coin-flipping situation because there is no certainty that you will get exactly $1000$ heads and $1000$ tails in the next $2000$ flips; but it is spectacularly likely that the ratio of $2000$ flips will be a lot closer to $50-50$ than the first $3$ flips (that's where the law of large numbers comes in).
Answer: The ratio of heads to tails will approach $1$ as the number of times it's tossed tends towards infinity.  If you've tossed the coin $1000$ times, you have hardly tossed it at all.
Another way to think about it: we agree that the first time you toss the coin, the probability of heads is $1/2$.   Suppose you toss the coin $1000$ times, and you have $501$ heads and $499$ tails.  You ask your friend to toss the coin for you.  He does not know that you have already been tossing the coin.  What is the probability that he will get heads?
Comment: see edits @D_S  changes to 1000000000
Comment: You have still hardly tossed it at all.  See my edit.
Comment: I think the probability is justifiably less than 1.
Comment: Pls see edits in qn,thanks
Comment: You have said "For the first time I toss it up the probabilities of both events are equal to $1/2$. This much is intuitive and clear to me."  Now, based on the second paragraph I wrote, you should also agree that this is true on the $1000$th time you toss the coin.
Answer: The probability will always be 1/2 for each coin toss because the event physically has no tie to the previous throws.  It will approach 1 because, as you approach infinity, the difference between the number of heads and tails will become smaller.  The difference between heads and tails will become smaller because the probably for each are equal to each other.  So, when you have 10000000000003 heads vs 10000000000017 tails, you get 0.99999999999860000000000238 or very close to 1.  Just keep going infinitely and you will get closer and closer to 1.
Comment: Pls see edits in qn,thanks


Impossible to enable modules in SimpleTest

Question: I am building SimpleTests for my modules:
It seems like the standard procedure for enabling modules it doesn't work for me:
function setUp() {
    parent::setUp('mymodule');
 }

I constantly get a stupid error code: Duplicate entry 'bartik-system-main' for key 'tmd': INSERT INTO {block}
As I am using profiles I used the $profile variable:
protected $profile = 'myprofilename';

I have forced this by using a Drupal function:
module_enable(array('mymodule'), $enable_dependencies = TRUE);

In this final case the error that persists is
Undefined property: stdClass::$name

Here below is a sample of my code:
class mymoduleWebTestCase extends DrupalWebTestCase {

  protected $privileged_user;

  protected $profile = 'myprofile';

  public static function getInfo() {
    return array(
        'name' => 'mymodule',
        'description' => 'mydescription.',
        'group' => 'mygroup',
    );
  }

  function setUp() {
    $this->privileged_user = new stdClass();
    parent::setUp();
   // Login a user that has access to the content sync server admin settings
    $this->privileged_user = $this->drupalCreate();
    $this->drupalLogin($this->privileged_user);
  }

  function testMyModule() {

    //Create content of community type
    $settings = array(
      'type' => 'mycontenttype',
      'title' => 'Sample Content',
      'link' => 'http://www.google.com',
      'body' => array(LANGUAGE_NONE => array(array('body'))),
      'moderate' => 1,
      'status' => 1,
      'revisions' => NULL,
      'taxonomy' => NULL,
    );
    $node = $this->drupalCreateNode($settings);
    $this->drupalGet('mymodule/sample-content');
    $this->assertRaw('Sample Content', t('Content created.'));

    $node = $this->drupalCreateNode($settings);

   //This if we have a valid link inside
    $this->clickLink(t('http://www.google.com'));

  }

Answer: You should make triple-sure that your module declares all of its dependencies properly. Even if it does, Simpletest struggles with dependencies and you may have luck if you enable them explicitly in setUp() before your module.
Also, not sure if it's the contributing your error, but instead of $this->privileged_user = new stdClass(); I would use DrupalWebTestCase::drupalCreateUser like so: $this->privileged_user = $this->drupalCreateUser(). I might also declare it after setup() but I'm not sure that's significant.
Answer: The Duplicate entry 'bartik-system-main' for key 'tmd' seems to be the same as an error caused by using fe_block module, reported here
Simpletest: database exception during setUp
The solution proposed for that question was to enable modules after the main setup was complete. It worked for me when I had the same exception. Using an installation profile makes it more difficult, but assuming it is the same case, perhaps there is a way to make a simplified test profile with the features module disabled, and re-enable it manually?


How to solve $\frac{\mathrm dy}{\mathrm dx}=\frac{x+y}{x}$

Question: I am looking for a help with the below equation
$$\frac{\mathrm dy}{\mathrm dx}=\frac{x+y}{x}$$
I don't get the suggested answer $$y = x\ln(x) + c x$$
My attempt
$$\mathrm dx(1+\frac{y}{x})=\mathrm dy$$
$$c+x+y\ln(x)=y$$
$$y=\frac{c+x}{1-\ln x}$$
Comment: **Hint:** Integrating Factor
Comment: The mistake in your derivation: Note that $y = y(x)$ is a function of $x$ so you cannot just integrate $dx\left(1+\frac{y}{x}\right)$ by holding $y$ constant (as you have done).
Answer: The problem with your approach is that:
$$ \int \left(1 + \frac{y}{x}\right) dx \neq C + x + y \ln x $$
Note that $y$ is a function of $x$, so you cannot treat it as a constant when you integrate.
One appropriate way to do this problem using an integrating factor:
Doing some algebra:
$$ y'(x) - y(x)/x = 1 $$
Let $\mu(x) = \exp(\int -\frac1x dx) = 1/x$. Multiplying both sides by $\mu$:
$$ y'(x)/x - y(x)/x^2 = 1/x $$
Note that $-1/x^2$ is the derivative of $1/x$:
$$ \frac{dy}{dx} \frac{1}{x} + \frac{d}{dx} \left( \frac{1}{x} \right) y(x) = \frac{1}{x} $$
Using the product rule:
$$ \frac{d}{dx} (y/x) = \frac{1}{x}$$
You can finish the rest yourself.
Answer: We have:
$$\frac{dy}{dx}=\frac{x+y}{x}=1+\frac{y}{x}$$
Suppose $y=xv(x)$ with $v(x):\mathbb{R}\rightarrow\mathbb{R}$
Then $$\frac{dy}{dx}=v+x\frac{dv}{dx}=1+v$$
Now notice we have:
$$x\frac{dv}{dx}=1$$ which is separable.
$$v(x)=\ln(x)+C,$$ where $C\in \mathbb{R}$
Thus $$y=x\ln(x)+Cx$$
Answer: Hint:
$$\frac{dy}{dx}=\frac{x+y}{x}\implies xdy=(x+y)dx\implies xdy-ydx=xdx\implies\frac{xdy-ydx}{x^2}=\frac{dx}{x}$$
Answer: With $\mu(x)=e^{\int\frac{M_y-N_x}{N}dx}$, where $M=x$ and $N=-x-y$ then $\mu(x)=\frac{1}{x^2}$, Now we have:
$\frac{1}{x^2}(xdy+(-x-ydx))=\frac{1}{x^2}*0\Rightarrow \frac{1}{x}dy+(-\frac{1}{x}-\frac{y}{x^2})dx=0 $, we take $f_y=\frac{1}{x}\Rightarrow f=\frac{y}{x}+h(x)$, after $f_x=-\frac{y}{x^2}+h'(x)=-\frac{1}{x}-\frac{y}{x^2}\Rightarrow h'(x)=-\frac{1}{x}$ then $h(x)=-\ln x$.
The solution is $\frac{y}{x}-\ln x=c$ where $c$ is constant
Answer: Just another way to do it.
Considering $$\frac{dy}{dx}=\frac{x+y}{x}$$ define $y=z-x$ which leads to $$\frac{dz}{dx}-1=\frac{z}{x}$$ that is to say $$\frac{dz}{dx}-\frac{z}{x}=1$$ Solving the homogeneous equation leads to $z=C x$. Now, using the method of variation of parameters, this leads to $$C+x C'-C=1$$ that is to say $xC'=1$ then $C=\log(x)+K$ then $z=x(\log(x)+K)$ and finally $y=x(\log(x)+K)-x=x \log(x)+(K-1)x=x \log(x)+ Lx$.
Answer: Hint
$$xy'=x+y$$
$$xy'-y=x$$
This is Euler-Cauchy Equation,see


Bloco de txt com Regex

Question: Galera como faço para pegar bloco por bloco de um txt com esse formato ?
Eu tenho que pegar até a ultima data.
As vezes vem duas datas em cada bloco
AAAAAAAAAA AAAAAAAAAAA - AAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAA
AAAAAAAA em: 20/04/2017

AAAAAAAAAA AAAAAAAAAAA - AAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAA
AAAAAAA em: 20/04/2017
AAAAAAAAAAAAAAAAAAAAAAAA
AAAAAA em: 21/06/2016

AAAAAAAAAA AAAAAAAAAAA - AAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAA
AAAAAA em: 20/04/2017

AAAAAAAAAA AAAAAAAAAAA - AAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAA
AAAAAA em: 20/04/2017

Comment: Quais são exatamente os valores que você pretende pegar do texto? Todas as datas? Se sim, elas estão sempre neste formado `dd/mm/YYYY`?
Comment: Cada data é formada por linhas consecutivas? Separando blocos com linha em branco?
Comment: Um bloco pode ter mais de uma data.
Comment: E na verdadeo não tem espaço entre os blocos. Coloquei aqui com epaço para ficar mais visivel.
Answer: Como o flavor não foi especificado, o Excel VBA foi usado, que usa javascript.
Regex
Habilitar o Regex no Excel

RegEx precisa ser habilitado, Habilite o modo Desenvolvedor
Na aba 'Desenvolvedor', clique em 'Visual Basic' e a janela do VBA irá abrir.
Vá em 'Ferramentas' -> 'Referências...' e uma janela abrirá.
Procure por 'Microsoft VBScript Regular Expressions 5.5', como na imagem abaixo. E habilite esta opção.

Padrão
Um Regex simples que identifica se possui números:
Demo no Regex101 e o padrão: \d{2}\/\d{2}\/\d{4}
Código em Excel VBA
Validar Dados
Este padrão somente pega uma string no formato 2números/2números/4números e a validação da Data, para verificar se a mesma é válida, é realizada pelo Excel com o IsDate().
O IsDate pode causar alguns erros (Pois tenta verificar se é data em formatos universais, de vários países...), refira a esta resposta para outra forma de verificar se é data.
Sub ValidarDados()

    Dim objStream As Object
    Dim strData As String
    Dim fileName As String, textData As String, fileNo As Integer
    sFilename = "temp.txt"
    sFilepath = ThisWorkbook.Path & "\" & sFilename
    fileNo = FreeFile                            'Get first free file number

Inicio:
    If Dir(sFilepath) <> "" Then
        Open sFilepath For Input As #fileNo
        strData = Input$(LOF(fileNo), fileNo)

        Dim objMatches As Object, objRegExp As Object
        Set objRegExp = CreateObject("VBScript.RegExp")
        'Regex
        objRegExp.Pattern = "\d{2}\/\d{2}\/\d{4}"
        objRegExp.Global = True

        Set objMatches = objRegExp.Execute(strData)
        If objMatches.Count <> 0 Then
            For Each m In objMatches
                If IsDate(m) Then MsgBox m 'Debug.Print m
            Next m
        End If
    Else
        MsgBox "O arquivo não pôde ser carregado - Escolha o arquivo."
        strPath = EscolherCaminho
        GoTo Inicio
    End If
    'Close
    Close #fileNo

End Sub

Escolher Caminho
Caso não encontre o caminho referido no código, uma janela será aberta para escolher o arquivo no sistema.
Public Function EscolherCaminho() As String
    'Créditos: http://software-solutions-online.com/excel-vba-open-file-dialog/
    Dim intChoice As Long
    Dim strPath As String

    'only allow the user to select one file
    Application.FileDialog(msoFileDialogOpen).AllowMultiSelect = False
    'make the file dialog visible to the user
    intChoice = Application.FileDialog(msoFileDialogOpen).Show
    'determine what choice the user made
    If intChoice <> 0 Then
        'get the file path selected by the user
        strPath = Application.FileDialog( _
                  msoFileDialogOpen).SelectedItems(1)
        'print the file path to sheet 1
        EscolherCaminho = strPath
    End If
End Function

Resultados
Com estes dados encontrados num teste no txt:

20/04/2017
20/04/2017
21/06/2016
20/04/2017
20/04/2017
32/04/2017
30/02/2017
20/13/2017

Após a validação com IsDate(), são estes resultados:

20/04/2017
20/04/2017
21/06/2016
20/04/2017
20/04/2017
Answer: regex: (((0[1-9]|[12][0-9]|3[01])[- /.](0[13578]|1[02])|(0[1-9]|[12][0-9]|30)[- /.](0[469]|11)|(0[1-9]|1\d|2[0-8])[- /.]02)[- /.]\d{4}|29[- /.]02[- /.](\d{2}(0[48]|[2468][048]|[13579][26])|([02468][048]|[1359][26])00))
para testar: https://regexr.com/

Bloco de txt com Regex