Display a View Block multiple times in a region with each view using a different filter

Question: Here's a visual representation of what I wanted to happen.
<code><my-region>

    <article-list-view filter=article-type-1 />

    <article-list-view filter=article-type-2 />

    <article-list-view filter=article-type-3 />

</my-region>
</code>
Now I can actually just go ahead and create a separate region and a separate view block for each type of filter but it doesn't look like good design since It's going to be repetitive.
Is my goal doable? If not, what's the common approach to accomplish this task?
Answer: Based on what you have described, yes.  It is not only doable, it is quite easy.
You can add different pages, blocks or even attachments.  When you creating/editing a view, click on "Add" then select what you would like.

With an attachment, you can select before, after or both for each attachment.
The key to making this work is to only set criteria for that display only.  In the example below, I am in the "Add Fields" dialog.  If you want a separate filter for this particular page/block/attachment, make sure to select "This Page (Override)"

When you do this, anything in this view will be restricted to this display only.


How to pass classes into Pool.map as arguments - Pickling Error

Question: I am trying to process a file by cutting it up into chunks and running them through a function which processes the chunks and returns a numpy array. After looking around it seems the best method would be to use the Pool.map method by passing through classes as the arguments. These classes are initiated with the chunk sections as a variable, and another variable to store the numpy array. The output list of classes can then be parsed to get out the information I need to continue with the problem. Here is a simplified version of the script I am trying to write:
from multiprocessing import Pool

class container():

    def __init__(self, k):
        self.input_section = k
        self.ouput_answer = 0

def compute(object_class):
    # Main operation would go on in here....

    object_class.output_answer = object_class.input_section
    return object_class

def Main():

    # Create list of classes to path as arguments
    sections = [container(k) for k in range(10)]

    # Create pool and compute modified classes
    with Pool(4) as p:
        results = p.map(compute, sections)

    # Decode here to get answers
    sections = [k.output_answer for k in results]

    # Print answers
    print(sections)

if __name__ == '__main__':
    Main()

This is the error that I get when I run the script:

Exception in thread Thread-9: Traceback (most recent call last):
File "C:\Users\rbernon\AppData\Local\Continuum\Anaconda3\lib\threading.py", line 916, in _bootstrap_inner
 self.run()
File "C:\Users\rbernon\AppData\Local\Continuum\Anaconda3\lib\threading.py",  line 864, in run
 self._target(*self._args, **self._kwargs)
File "C:\Users\rbernon\AppData\Local\Continuum\Anaconda3\lib\multiprocessing\pool.py", line 463, in _handle_results
 task = get()
File "C:\Users\rbernon\AppData\Local\Continuum\Anaconda3\lib\multiprocessing\connection.py", line 251, in recv
 return _ForkingPickler.loads(buf.getbuffer())
AttributeError: Can't get attribute 'container' on module '__main__' from
    'C:\\Users\\rbernon\\AppData\\Local\\Continuum\\Anaconda3\\lib\\site-packages\\spyder\\utils\\ipython\\start_kernel.py'>

Any help would be greatly apprectiated!
Comment: Possible duplicate of [Object array is not picklable](https://stackoverflow.com/questions/43882605/object-array-is-not-picklable)
Answer: Keep in mind that every piece of data you want to have processed needs to be pickled and sent to the worker processes.
The overhead of this will reduce (and might even eliminate) the advantages of using multiple processes.
If the data file is large, it is probably better to send each worker a start and end offset as a 2-tuple of numbers, so each worker can read part of the file and process it.
Comment: Thanks for the suggestion. So I will instead change to creating processes with multiprocessing.Process() and pass it tuple arguments of filename, start and end offset
Comment: I would suggest making a list of tuples and pass that to `Pool.imap_unordered`. The length of the list should correspond to the number of cores on your CPU.


Capturar valor do campo pela sua ID e transformar em uma variavel

Question: Quero pegar o valor de um campo de minha tabela e transformar ele em uma variável.
Exemplo:
VALOR EXEMPLO

quero pegar o conteúdo e transformá-lo em uma variável usando javascript, acredito q seja fácil mas n entendo muito de programação
tentei assim mas nao consegui:

e para chamar ela no php:
<?php

$variavelphp = "";

echo "$variavelphp"
?>

Answer: Mude sua linha de código js para o seguinte:
var teste = $("#exemplo").html();

Ficaria assim:

var teste = $("#exemplo").html();
alert(teste);

    VALOR EXEMPLO 1
    VALOR 2

Primeiramente, a chamada do evento do JQuery $("#exemplo").val() se refere ao atributo value de algum elemento, onde normalmente ficam guardados os valores dos elementos, porém o seu elemento em questão na verdade é um td(estrutura do corpo de uma tabela) que além de tudo, também não possui um atributo value nativo, para pegar seu valor, o certo semanticamente seria colocar um outro elemento dentro dele, por exemplo um span ou um label, que ficaria mais ou menos assim: VALOR EXEMPLO 1	, desse modo sua linha de comando JQuery nem precisaria ser alterada. Mas isso vai de acordo com cada um...
Estruturando da forma como você deseja, o elemento td apenas "escreve" na tela o que esta contido nele, ou seja o tipo de elemento td não possui nativamente o atributo value.
Para pegar o conteúdo/valor contido dentro de um td, você devera usar o evento JavaScript innerHTML(); que em JQuery equivale ao evento HTML();
Comment: funcionou perfeitamente para o que eu queria, muito obrigado
Answer: Se quer pegar o conteúdo de um elemento em JS, basta isso:
var teste = document.getElementById('exemplo').innerText;

Mas vale dizer que não vai funcionar com um td avulso, sem a estrutura da tabela.
Veja um exemplo funcional:

var teste = document.getElementById('exemplo').innerText;

//So para demonstrar:
document.body.innerHTML += 'O valor é ' + teste;

VALOR EXEMPLO

Neste caso usei uma div para evitar o problema mencionado com o td avulso.
Foi usado o innerText, que é preferível para pegar o conteúdo textual. Se quiser pegar algo que contenha elementos filhos, dê preferência ao innerHTML.
Se sua dúvida é sobre variáveis de PHP, aí o assunto muda, e vale a pena uma lida nisso:

Igualar variável php a uma variável javascript
Comment: Creio o que ele se expressou mal, fica claro ao ver o último bloco de código. Sendo assim, sua reposta não esta correta, pois ele mesmo resolveu o problema de pegar o valor de um elemento e botar em uma variável, só que em JavaScript.
Comment: obrigado pela ajuda, li a pergunta sobre igualar varial php a uma do javascript e me ajudou por terei que fazer isso.
Comment: @user5978 eu respondi a parte que não era duplicata, pois ficou claro que o autor não tem muita experiência com esta parte de integração. A parte do PHP eu pus o link pra resposta que tem o que ele procura, pois não vai ajudar ninguém eu colocar conteúdo repetido no site. Se você olhar o histórico de edições, vai ver que na verdade eu tinha até fechado como duplicata, mas preferi cobrir todas as condições possíveis para ajudar o autor, portanto reabri e respondi com o que faltava:  http://pt.stackoverflow.com/posts/125296/revisions
Comment: @user5978 agora, se apontar onde é que minha resposta está errada, aí podemos ver o que fazer. Reli tudo, e não fez muito sentido esse seu comentário. Se puder ser mais específico em qual parte não está correta, ajudaria. Afinal, mostrei como fazer em JS (que ele vai precisar de qualquer forma, mesmo passando pra PHP), e apontei pra como fazer em PHP. Faltou o que?
Comment: O cara diz que precisa pegar uma variável em JavaScript, e deve passar ela para o PHP. E ele afirma que tentou de determinado jeito (mostra que pegou corretamente o valor com o JavaScript), mas que porém não conseguiu fazer este valor chegar ao PHP.
Comment: Mostrar outra forma de fazer o que ele já fez, sem ao menos dar uma dica do trecho que ele realmente precisa, não é uma solução para a problema. Na minha humilde opinião.
Comment: @user5978 Então sua sugestão é em vez de colocar o link, reproduzir a outra resposta aqui? Isso eu não vou fazer. O que eu percebi é que a outra resposta que faz o mesmo que a minha, mas precisa de jQuery, você não comentou nada, então isso esclarece outras coisas também. De qualquer forma, grato pelo retorno.
Comment: Geralmente eu utilizo comentários para apontar soluções externas, quando não tenho nada a acrescentar (A respeito do conteúdo do link).
Comment: Verdade, bati o olho naquela resposta, e podia jurar que o cara tinha sugerido a utilização de ajax ... eu ia comentar lá ... mas chega de treta por hoje :D
Comment: @user5978 nao tem treta, fique sossegado que pra mim é numa boa. Você apontou algo, e eu quis entender melhor. Só isso. Respeito 100% sua opinião, independente de concordar ou não, e acho muito bom que você a expresse. E fique à vontade pra criticar sempre que achar necessário.


Proving that the order of $(a,b)$ is the lcm of $|a|,|b|$

Question: I want to solve the following exercise from Dummit & Foote's Abstract Algebra text:

Prove that the elements $(a,1)$ and $(1,b)$ of $A \times B$ commute and deduce that the order of $(a,b)$ is the least common multiple of $|a|$ and $|b|$.

The first part is easy: $$(a,1)(1,b)=(a \star 1,1 \diamond b)=(a,b)=(1 \star a,b \diamond 1)=(1,b)(a,1) $$
The second part isn't that much harder to prove. The thing is I can't see how a proof can be deduced by the mere fact that $(a,1)$ and $(1,b)$ commute. Is such a proof possible?
Thanks.
Comment: An example for why commuting is necessary. For $D_\infty = \langle r, s \mid s^2 = e, srs = r^{-1} \rangle$, the infinite dihedral group, both $rs$ and $s$ have order $2$, but their product, $r$ has infinite order. Oops.
Comment: @HenrySwanson I have no doubts that commutativity is necessary. I'm asking how can this fact by itself reveal the order of the product.
Answer: Hint: We have $\left(A \times \{1\}\right) \cap (\{1\} \times B) = \{(1,1)\}$. Since $(a,1)$ and $(1,b)$ commute, we have that $(a,b)^n=(a,1)^n(1,b)^n$. Since the order of $(a,1)$ is $|a|$, and the order of $(1,b)$ is $|b|$, what does this tell you about the order of $(a,b)$?
Comment: That it is $\leq$ lcm of $|a|,|b|$? I'm afraid that's not enough.
Comment: @user1337 It tells you more than that.
Comment: @user1337 Oops, I think you're right. You should also need that $A \times \{1\} \cap \{1\} \times B = (1,1)$. This is trivial, though, and I assume Dummit and Foote allow you to use that in this proof.
Comment: I still don't see how this extra fact solves the problem. Can you please elaborate?
Comment: @user1337 The extra fact gives us that for $(a,1)^n(1,b)^n=(1,1)$, we need $(a,1)^n=(1,1)$ and $(1,b)^n=(1,1)$ (because otherwise, $(a,1)^n$ has inverse $(1,b)^n$ and thus $(1,b)^n \in (A \times \{1\})$, which is impossible). Does that do it for you?
Comment: I think so. I also need the fact that if $x^n=e$ then $|x| | n$, right?
Comment: @user1337 Yup - and then the definition of LCM finishes the job.
Answer: Hint $\ \ 1 = (a,b)^k = (a,1)^k (1,b)^k\iff (a,1)^k = (1,b)^{-k}\in \langle(a,1)\rangle\cap \langle (1,b)\rangle = \{(1,1)\}$
$\qquad\  \iff (a,1)^k = (1,1) = (1,b)^k\iff|a|,\,|b|\mid k\iff {\rm lcm}(|a|,|b|)\mid k$


Statistics of lottery

Question: I have a dozen donuts and 84 friends. Since there is not enough to go around and no one wants to share, I will put all 84 names in a hat (a hat that perfectly randomizes) and draw 12 names.  What are the chances of getting a donut?  12 out of 84 or ~14.3%.
Let's calculate the chances of getting a donut another way by calculating the chances as we draw names out of the hat.
1st draw    1.19%   1 out of 84
2nd draw    1.20%   1 out of 83
3rd draw    1.22%   1 out of 82
4th draw    1.23%   1 out of 81
5th draw    1.25%   1 out of 80
6th draw    1.27%   1 out of 79
7th draw    1.28%   1 out of 78
8th draw    1.30%   1 out of 77
9th draw    1.32%   1 out of 76
10th draw   1.33%   1 out of 75
11th draw   1.35%   1 out of 74
12th draw   1.37%   1 out of 73
Sum equals   =              15.32%
The sum total of these is ~15.32% Why isn't it equal to 14.3%?
Comment: The probability of getting the donut on the third draw is the probability of not getting it on the first, and (conditioned on that) not getting it on the second, and (conditioned on both those) getting it on the third, which is $\frac{83}{84}\times\frac{82}{83}\times\frac{1}{82}=\frac{1}{84}$.  Similar calculations apply for all the others, making the overall probability of getting a donut $\frac{12}{84}$ as you might expect intuitively.
Answer: They're different because the numbers you're adding up shouldn't be added.
A smaller example
I have three donuts and four friends. Since there is not enough to go around and no one wants to share, I will put all four names in a hat (a hat that perfectly randomizes) and draw three names. What are the chances of getting a donut? Three out of four or 75%.
Let's calculate the chances of getting a donut another way by calculating the chances as we draw names out of the hat.

Draw
Probability
Reasoning

1st draw
25%
1 out of 4

2nd draw
33.3%
1 out of 3

3rd draw
50%
1 out of 2

Sum equals = 108.3%. That's not good.
What happened?
Each outcome depends on the one before it: if my name came up in the second draw, it can't come up again in the third.
These probabilities are conditional probabilities, so you can't add them directly. The 50% is the chance of getting drawn on turn 2 given that you weren't picked on turn 1.
Let's introduce some notation. Let $W_i$ be the draw on turn $i$. The outcomes $w_i$ and $\neg w_i$ mean that my name did or didn't come up on turn $i$. The values in our Probability column, then, are $p(w_1)$ then  $p(w_2 \mid \neg w_1)$, then $p(w_3 \mid \neg w_1, \neg w_2)$.
How do we make the results match?
Well, I know my name comes up if I draw it on the first, or I draw it on the second, or I draw it on the third.
\begin{align}
p(\text{donut}) =& p(w_1) \\
   & + p(\neg w_1) \times p(w_2 \mid \neg w_1) \\
   & + p(\neg w_1) \times p(\neg w_2 \mid \neg w_1) \times p(w_3 \mid \neg w_1, \neg w_2) \\
=& 0.25 \\
&+ 0.75 \times 0.\overline{3} \\
&+ 0.75 \times 0.\overline{6} \times 0.5 \\
=& 0.75 \text{ which is the same as } \frac{3}{4}\text{.}
\end{align}
Using the conditional probabilities and the chain rule of probability, we get to the same answer as the first method.
You can extend this reasoning to your example with bigger numbers.
Comment: *given that you weren't picked on turn 1*  ahhh and the light bulb goes on!  thanks
Comment: A small note as convenience for those who don't want to read through the rather complex notation on the linked wikipedia page: You can more easily calculate probabilities like this by using the fact that it's one (100%) minus the probability of never getting picked. Which is 1 - 3/4 * 2/3 * 1/2 = 1 - 1/4 = 3/4.
Answer: Because probabilities don't add like that - if you'd have 54 donuts surely the chance of winning one is not $\sum_{d=0}^{53}1/(84-d)\approx 102\%$?
You have to keep in mind that the chance of winning the $n$th donut is conditional on not winning any of the $1, ..., n-1$ donuts. The probability of something not happening is one minus the probability of it happening, or not winning the first donut has probability $1-\frac{1}{84} \approx 98.81\%$. The chance of then not winning the second one is multipicative with that, or $(1-\frac{1}{84})(1-\frac{1}{83})\approx97.62\%$. In general the probability of not winning any of the first $n$ donuts is $\prod_{d=0}^{n-1}1-\frac{1}{84-d}$.
The probability of winning any of the first $n$ donuts is then again one minus the above. Back to your example with 12 donuts, where the chance of winning any of those is $1-\prod_{d=0}^{11}1-\frac{1}{84-d}\approx 14.29\%$ which is $\frac{12}{84}$. You can check this for any other number of donuts and they will match.
Answer: Let's calculate the chances of getting a donut another way by calculating the chances as we draw names out of the hat.

1st draw    1.19%   1 out of 84

2nd draw    1.20%   1 out of 83

3rd draw    1.22%   1 out of 82

4th draw    1.23%   1 out of 81

5th draw    1.25%   1 out of 80

6th draw    1.27%   1 out of 79

7th draw    1.28%   1 out of 78

8th draw    1.30%   1 out of 77

9th draw    1.32%   1 out of 76

10th draw   1.33%   1 out of 75

11th draw   1.35%   1 out of 74

12th draw   1.37%   1 out of 73

Sum equals   =              15.32%

This table shows an increasing chance of getting the donut, but the chances of getting a donut on a particular time/draw should be continuous function.
For example: For a friend of you, whether they get a donut in the 1st draw or in the 12th draw, that should be equal, as your hat should make it for a person as much likely to be drawn 1st as 12th. It is not more likely to get the donut on the 1st draw as on the 12th draw. You have 1/84 probability for both cases.
What your table shows instead are conditional probabilities. The probability to get the donut in the k-th draw, conditional on not having had it during the previous (k-1) draws. The comment by Henry explains well how you can create a sum with these conditional probabilities such that you still end up with 12/84.
$$\text{P(donut on k-th turn) = P(donut no donut before k-th turn) $\times$ P(donut on k-th turn conditional on no donut before k-th turn)} $$
You computed the terms $\text{P(donut on k-th turn conditional on no donut before k-th turn)}$ on the right-hand side and used it as $\text{P(donut on k-th turn)}$ on the left-hand side.

Statistics of lottery


Random Effects for Mantel Haenszel

Question: I'm familiar with the standard Mantel Haenszel method for Odds ratios and Risk ratios. Is there also a random effects method? If so, can anyone provide the formulae and/or citations?
Answer: Jonathan Deeks and Julian Higgins have a nice document showing all the calculations used in Review Manager. Scroll down to page 8  for DerSimonian and Laird random-effects models that can be used with the Mantel-Haenszel summary models.
Comment: As far as I know, RevMan is the only software that implements this hybrid approach. This aside, I am not saying that the approach necessarily needs to be challenged -- it's just not a proper random-effects model generalization of the M-H method. In fact, it's basically just the standard normal-normal model, but with the amount of heterogeneity estimated using a DL-type estimator that uses the M-H estimate for computing the Q-statistic.
Comment: Note that this is some strange hybrid of the Mantel-Haenszel method and the 'normal-normal' model. I would not consider this a proper random-effects model extension of the M-H method.
Comment: I won't argue with you as I'm not a statistician, but it also makes we wonder why these methods haven't been challenged by statisticians in a more concerted effort since Cochrane reviews uses RevMan (and as an extension these formulas) as well as I would dare to guess a large number of published reviews. I also use Comprehensive Meta-analysis by Michael Borenstein, Higgins and others and I don't have their calculations with me right now assume that they use similar methods. To be honest, I've never been challenged by using these RE models in my published work including at JAMA, BMJ, CMAJ, etc
Comment: That document link is no longer active. The current link is https://training.cochrane.org/handbook/current/statistical-methods-revman5 (2010 Statistical algorithms in Review Manager 5 by Deeks and Higgins)
Comment: Thanks Wolfgang for the explanation. Hopefully new versions of RevMan will be more robust in their analytic options.
Answer: A proper random-effects model extension to the standard Mantel-Haenszel procedure is described by van Houwelingen, Zwinderman, and Stijnen (1993). In essence, one can think of the M-H procedure as a model based on the (non-central) hypergeometric distribution (Mantel & Haenszel, 1959). So, using this as the starting point, van Houwelingen and colleagues extend the method by adding a random effect to the model where the 2x2 tables are modeled by non-central hypergeometric distributions. See also Stijnen, Hamza, and Ozdemir (2010). The resulting model can also be thought of as a conditional mixed-effects logistic regression model.
The equations get a bit messy, but we can write things pretty compactly if we let $L(\theta_i|a_i, b_i, c_i, d_i)$ denote the likelihood function of a non-central hypergeometric distribution for the $i$th study, where $a_i, b_i, c_i, d_i$ are the 2x2 table counts and $\theta_i$ is the true log odds ratio (see wikipedia for the pmf of the non-central hypergeometric distribution). Now let $f(\theta_i)$ denote the density of a normal distribution with mean $\mu$ and variance $\tau^2$. So the log-likelihood for the random-effects model is given by $$ll = \sum_{i=1}^k \ln \left[\int_{-\infty}^\infty L(\theta_i|a_i, b_i, c_i, d_i) f(\theta_i)d\theta_i\right].$$ There is no closed-form solution to the values of $\mu$ and $\tau^2$ that maximize $ll$, so those values must be obtained numerically.
References
van Houwelingen, H. C., Zwinderman, K. H., & Stijnen, T. (1993). A bivariate approach to meta-analysis. Statistics in Medicine, 12(24), 2273-2284.
Mantel, N., & Haenszel, W. (1959). Statistical aspects of the analysis of data from retrospective studies of disease. Journal of the National Cancer Institute, 22(4), 719-748.
Stijnen, T., Hamza, T. H., & Ozdemir, P. (2010). Random effects meta-analysis of event outcome in the framework of the generalized linear mixed model with applications in sparse data. Statistics in Medicine, 29(29), 3046-3067.

Random Effects for Mantel Haenszel


Understanding part of a theorem of Calculus of Variations

Question: I have trouble understanding the following statement (From Gelfland's Calculus of Variations book):

If $\phi[h]$ is a linear functional and if
$$\frac{\phi[h]}{\left|\left|h\right|\right|}\rightarrow 0,$$
as $||h||\rightarrow0$, then $\phi[h]=0$ for all $h$. In fact, suppose
  $\phi[h_0]\neq0$ for some $h_0\neq0$. Then, setting
$$h_n=\frac{h_0}{n},\;\;\;\;\lambda=\frac{\phi[h_0]}{||h_0||},$$
we see that $||h_n||\rightarrow 0$ as $n\rightarrow \infty,$ but
$$\lim_{n\rightarrow\infty}\frac{\phi[h_n]}{||h_n||}=\lim_{n\rightarrow\infty}\frac{n\phi[h_0]}{n||h_0||}=\lambda\neq0,$$
contrary to hypothesis.

In the above $h$ belongs to some normed linear (function) space $\mathcal{F}$, $||\cdot||$ is the norm function in that space and $\phi[\cdot]$ is a linear functional.
My question is about the part:

$\displaystyle\frac{\phi[h]}{\left|\left|h\right|\right|}\rightarrow
 0,\;\;\;$    as $||h||\rightarrow0$, then $\phi[h]=0$ for all $h$.

I don't understand why does the $\phi[h]$ need to equal $0$? Isn't it enough that $\phi[h]\rightarrow 0$ faster than $||h||$?
Thank you for your help! Please let me know if you need more info.
Here is a picture of the part in my book. I have highlighted the area, where I have problems
Comment: Could you explain a little bit? I mean you quoted a proof for this theorem. Have you understand it?
Comment: Hi @tired this is part of a theorem in my book. No I have not understood the theorem because I got stuck with this one. Do you want more details from the book? The theorem's claim is: "The differential of a differentiable functional is unique" I will add a picture of the theorem here asap :)
Answer: The notation isn't the best. I would write the theorem like this: if $\phi$ is a linear functional on $\mathcal{F}$ such that, for any unit vector $u\in\mathcal{F}$, $\frac{\phi[tu]}{|t|}\to0$ as $|t|\to0$, then $\phi=0$ identically. But written like this it becomes obvious since $\frac{\phi[tu]}{t}=\phi[u]$, so the condition pretty much says that $\phi[u]=0$ for all unit vectors $u\in\mathcal{F}$, which of course implies $\phi=0$.
Comment: Note that $h=\|h\|u$ for a unit vector $u$ - I have replaced $\|h\|$ by $t$ so that we have a fixed unit vector.
Comment: Thank you for your help! =)
Comment: But, I still did not get it 100% sry :) Because the theorem didn't state any assumptions that $h$ should be a unit vector. Or does it follow that $h$ needs to be a unit vector?
Answer: You are given a space ${\cal F}$ and a  linear functional $\phi:\>{\cal F}\to{\mathbb C}$ that you are trying to better understand. The only thing you are told is  that
$$\lim_{h\to0}{\phi(h)\over\|h\|}=0\ .$$
The statement in question  says that in such a case one necessarily has $\phi(x)\equiv0$ on ${\cal F}$.
For a proof consider an arbitrary $x\in{\cal F}$, $x\ne0$. Then
$$\phi(x)=\|x\|{\phi(\lambda x)\over \|\lambda x\|}\qquad\forall \lambda>0$$
and therefore
$$\phi(x)=\|x\|\>\lim_{\lambda\to 0}{\phi(\lambda x)\over \|\lambda x\|}=0\ .$$
Comment: Excellent, that one did it! =) Thank you!
Comment: I think my problem was mostly with the notation.


How to judge, which random effects to include in a mixed model?

Question: I am currently writing my master thesis about the effect of an insecticide (clothianidin) on the microflora of bumblebees. I received the bumblebees from an experiment with a nested study design. 16 fields were paired according to land use of the surroundings etc. In each field 2 boxes were placed, which contained 2 hives (colonies) each.
I was trying to determine if the treatment affects the prevalence of certain organisms including ABPV, N.bombi and Snodgrasella as you can see in this data frame:
    structure(list(treatment = structure(c(2L, 2L, 2L, 2L, 1L, 1L,
1L, 1L, 2L, 2L, 2L, 2L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 1L, 1L,
1L, 1L, 2L, 2L, 2L, 2L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 2L,
2L, 2L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 1L, 1L, 1L, 1L, 2L, 2L,
2L, 2L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L), .Label = c("Clothianidin",
"Control"), class = "factor"), pair = structure(c(1L, 1L, 1L,
1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 3L, 3L, 3L,
3L, 3L, 3L, 3L, 3L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 5L, 5L, 5L,
5L, 5L, 5L, 5L, 5L, 6L, 6L, 6L, 6L, 6L, 6L, 6L, 6L, 7L, 7L, 7L,
7L, 7L, 7L, 7L, 7L, 8L, 8L, 8L, 8L, 8L, 8L, 8L, 8L), .Label = c("P01",
"P02", "P03", "P04", "P05", "P10", "P11", "P12"), class = "factor"),
    field = structure(c(6L, 6L, 6L, 6L, 12L, 12L, 12L, 12L, 1L,
    1L, 1L, 1L, 2L, 2L, 2L, 2L, 10L, 10L, 10L, 10L, 13L, 13L,
    13L, 13L, 7L, 7L, 7L, 7L, 16L, 16L, 16L, 16L, 8L, 8L, 8L,
    8L, 9L, 9L, 9L, 9L, 3L, 3L, 3L, 3L, 11L, 11L, 11L, 11L, 4L,
    4L, 4L, 4L, 5L, 5L, 5L, 5L, 14L, 14L, 14L, 14L, 15L, 15L,
    15L, 15L), .Label = c("VR02", "VR03", "VR04", "VR05", "VR06",
    "VR07", "VR09", "VR12", "VR13", "VR14", "VR16", "VR17", "VR18",
    "VR20", "VR21", "VR23"), class = "factor"), box.nested = c(12,
    11, 12, 11, 23, 24, 23, 24, 1, 1, 2, 2, 4, 3, 3, 4, 20, 20,
    19, 19, 25, 26, 25, 26, 14, 14, 13, 13, 31, 31, 32, 32, 16,
    15, 15, 16, 18, 17, 17, 18, 6, 5, 5, 6, 21, 22, 22, 21, 8,
    8, 7, 7, 9, 9, 10, 10, 28, 27, 28, 27, 29, 30, 30, 29), hive.nested = c(24L,
    21L, 23L, 22L, 46L, 48L, 45L, 47L, 2L, 1L, 4L, 3L, 8L, 5L,
    6L, 7L, 40L, 39L, 38L, 37L, 49L, 52L, 50L, 51L, 27L, 28L,
    26L, 25L, 62L, 61L, 64L, 63L, 31L, 29L, 30L, 32L, 36L, 34L,
    33L, 35L, 12L, 9L, 10L, 11L, 41L, 43L, 44L, 42L, 15L, 16L,
    13L, 14L, 17L, 18L, 20L, 19L, 55L, 54L, 56L, 53L, 58L, 59L,
    60L, 57L), ABPV.detected = structure(c(0, 0, 0, 0, 0, 0,
    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0,
    1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
    0), .Dim = c(64L, 1L), .Dimnames = list(NULL, "ABPV.detected")),
    N.bombi.detected = structure(c(0, 0, 0, 0, 0, 0, 0, 0, 1,
    1, 1, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0), .Dim = c(64L,
    1L), .Dimnames = list(NULL, "N.bombi.detected")), Snodgrasella.detected = structure(c(0,
    1, 0, 0, 1, 1, 1, 1, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1,
    1, 1, 1, 1, 0, 0, 1, 0, 1, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1,
    1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1,
    1, 1, 1, 1, 1, 1), .Dim = c(64L, 1L), .Dimnames = list(NULL,
        "Snodgrasella.detected"))), .Names = c("treatment", "pair",
"field", "box.nested", "hive.nested", "ABPV.detected", "N.bombi.detected",
"Snodgrasella.detected"), class = "data.frame", row.names = c(NA,
-64L))

I was trying estimate the treatment effect with a model that included pair, field, box and hive as (nested) random effects:
library(lme4)
ABPV.prev <- glmer(ABPV.detected ~ treatment
                   + (1|pair/field/box.nested/hive.nested)
                   ,data=data.f,
                   family=binomial)
summary(ABPV.prev)

The models of ABPV and N. bombi failed to converge, because I have so many zeros. ABPV was only found in one pair and N. bombi was only found in 2 pairs.
Warning message:
In checkConv(attr(opt, "derivs"), opt$par, ctrl = control$checkConv,  :
  Model failed to converge with max|grad| = 0.100788 (tol = 0.001, component 2)

The p-values of the models did indicate significant treatment effects, but I guess it's pair or field effects that cause the variation...
In another forum I read that it can be tested whether the failure to converge represents a real problem using this function..
relgrad <- with(ABPV.prev@optinfo$derivs,solve(Hessian,gradient))
max(abs(relgrad))

... and it does as the p-value is rather large p=0.1 (for ABPV).
I removed some of the random effects and it works and it works e.g. when I remove both hive.nested and box.nested from the model, though increasing the AIC (why?).
I also tried to include pair as a fixed effect:
library(lme4)
ABPV.prev <- glmer(ABPV.detected ~ treatment + pair
                   + (1|field/box.nested/hive.nested)
                   ,data=data.f,
                   family=binomial)

but it produced an error:
Error: (maxstephalfit) PIRLS step-halvings failed to reduce deviance in pwrssUpdate

My questions are

How do I judge which random effects to include and which not?
How do I test if it is a pair (or field effect) not a treatment effect that causes the variation?

N.B. In the Snodgrasella model it makes absolutely no difference if I exclude, any or all of the random effects. Why is that?
Hope you can help me, thanks!
Comment: This should be asked on the CrossValidated.com website. (It's not really a coding question but rather a statistical methods question.)
Answer: There are too many questions here.  It would be a really good idea if you were able to get some local statistical help, as you're operating at the edge of what you can do with generalized linear mixed models.  Frank Harrell's rule of thumb is that if you have p "effective" samples (which in your case would be the number of detections for a particular species) you shouldn't be trying to fit a model with more than p/10 parameters (optimistically; the denominator should perhaps even be 20).
colSums(data.f[,6:8])
##   ABPV.detected      N.bombi.detected Snodgrasella.detected
##               5                     5                    50

p/10 is less than 1 for the first two cases (ABPV and N. bombi). That means all you can really do with your smaller samples is to collapse your data to the simplest possible case --- a straight-up treatment comparison --- and explain to your audience that it's just not feasible to try to control for non-independence:
ABPV.tab <- with(data.f,table(ABPV.detected,treatment))
##              treatment
## ABPV.detected Clothianidin Control
##             0           31      28
##             1            1       4
chisq.test(ABPV.tab,simulate.p.value=TRUE)
## data:  ABPV.tab
## X-squared = 1.9525, df = NA, p-value = 0.3603

You'd get a similar answer from prop.test(x=c(1,4),n=c(32,32)).
In general, people are pretty ready to let you simplify your model when you give them a "negative" (p>0.05) answer, as they figure you're not trying to get away with something.  What you should not do is accept the null hypothesis (make strong claims that the treatment does not have an effect): prop.test tells you
95 percent confidence interval:
-0.25447656  0.06697656

i.e. the 95% CI on the difference of the probability of detection is between -25% and +6% (you might be anywhere from 25% less likely to 6% more likely to detect ABPV in the Clothianidin treatment).
There are a number of reasons you shouldn't believe the results from the GLMMs in these cases -- even if the model converged correctly, inference from GLMMs is most reliable when the data sets are "large" in some sense.

N.B. In the Snodgrasella model it makes absolutely no difference if I exclude, any or all of the random effects. Why is that?

Because most (not all) of the random effects are exactly or nearly zero.
Snodgrasella.prev <- glmer(Snodgrasella.detected ~ treatment
               + (1|pair/field/box.nested/hive.nested)
               ,data=data.f,
               family=binomial)
VarCorr(Snodgrasella.prev)
##  Groups                                Name        Std.Dev.
##  hive.nested:(box.nested:(field:pair)) (Intercept) 0.00047247
##  box.nested:(field:pair)               (Intercept) 0.00000000
##  field:pair                            (Intercept) 1.08244578
##  pair                                  (Intercept) 0.00000000

This would suggest that excluding field:pair would make a difference,
and excluding hive.nested:... would make a very small difference.
summary(Snodgrasella.prev)

Suggests a weak effect (decrease of 1.84 log-odds units from Clothianidin to Control, p = 0.057). This is backed up by a slightly more accurate likelihood ratio test:
Snodgrasella.null <- update(Snodgrasella.prev,.~.-treatment)
anova(Snodgrasella.prev,Snodgrasella.null)

The weird thing is that the overall effect seems to be in the opposite direction
(stab <- with(data.f,table(Snodgrasella.detected,treatment)))
## Snodgrasella.detected Clothianidin Control
##                     0            3      11
##                     1           29      21
chisq.test(stab,simulate=TRUE)

I would again suggest collapsing the data to the most aggregated level you can (see Murtaugh "Simplicity and complexity in ecological data analysis"):
library("plyr")
d2 <- ddply(data.f,c("field","pair","treatment"),
          summarise,
          tot=sum(Snodgrasella.detected),
          n=length(Snodgrasella.detected),
          prop=tot/n)
summary(g1 <- glm(prop~treatment,weights=n,data=d2))
anova(g1,update(g1,.~1),test="Chisq")

The more reliable (LRT) p-value = 0.059, is similar to the results above ...
Some further comments, pasted here in case this gets migrated to CrossValidated:

if you want individual confidence intervals for each treatment separately then binom.test() will give you better results ("Clopper-Wilson" CIs);
however, CIs on the individual groups are answering a different question from testing the differences in proportions between groups, which is what I'm trying to address above;
the examples above seem to show that the results for ABPV and N.bombi are not significant at $\alpha<0.05$, but very low-powered; the results for Snodgrasella are marginally significant
if you're worried about the chi-squared warnings from the proportion tests, Fisher's test is OK -- some good statisticians have issues with it but in this case I think the practical differences will be small.  You could check out the version of chisq_test in the coin package for another alternative ...
Comment: Thanks for the excellent answer. I was trying to find the confidence intervals of each of the proportions like this: library(plyr)
`ABPV<-ddply(data.f,.(treatment),summarise,
  prop=sum(ABPV.detected)/length(ABPV.detected),
  low=prop.test(sum(ABPV.detected),length(ABPV.detected))$conf.int[1],
  upper=prop.test(sum(ABPV.detected),length(ABPV.detected))$conf.int[2])``
Comment: It does not look significant to me when I plot that. Why is that? Should I be worried about the warnings that the Chi^2 approximation of prop.test may be incorrect? I read fishers test can be used for small sample sizes. What do you think about that?
Comment: (1) if you want confidence intervals for each treatment then `binom.test()` will give you better results; (2) that's different from testing the *differences* in proportions between groups; (3) I don't think I said it was significant above (the p-value from `chisq.test()` with simulations was 0.3603 ...); (4) Fisher's test is OK -- it has some definitional issues  -- but I think all the different tests are going to tell you in this case that at least for ABPV/N. bombi, you just don't have enough information to say much ...
Comment: Thanks a lot for the answers. I couldnt comment before as a new user. I have plotted now both the proportions and the differences, both with CIs. Of course you were right that you didn't say ABPV was significant, I looked at a different organism. One more question: I used a lmer to determine the effect of the treatment on the weight of the bees. I have ten bees per colony so 640 "effective" samples. Can I use the lmer in that case?
Comment: Hello again, I still have a question about the LRT. Does it matter if the normality assumption (of anovas) is violated in g1?
Comment: Thanks again for the elaborated and helpful answer. Could you maybe explain why you recommend the LRT here? From Figure 1 one of your publication "Generalized linear mixed models: a
practical guide for ecology and
evolution" I understood that LRT is mainly to estimate random effects. It would be really great to understand why LRT works also in this case.


$\not\exists$ number $c\geq 0$ for which $||f||_{max}\leq c||f||_1$. But $\exists$ $c\geq 0 $ for which $||f||_1\leq c||f||_{max}$

Question: I'm reading through Real Analysis by Royden & Fitzpatrick and I always try to deal with the first few problems of each section. For the first section on $L^p$ spaces there were mostly routine exercises on proving norms, but this subquestion has me a bit confused:
Show that
a)  $\not\exists$ number $c\geq 0$ for which $||f||_{max}\leq c||f||_1$ $\forall f \in C[a,b] $.
b) But $\exists$ $c\geq 0 $ for which $||f||_1\leq c||f||_{max}$ $\forall f \in C[a,b] $
Where:
$||f||_{max}:= max_{x\in[a,b]}|f(x)|$
$||f||_1:=\int_a^b|f|$
EDIT: Does the following counterexample work for part a)?
Let $f(x)=x^n$ on $[0,1]$, $max|f(x)| > c \int_a^b|f(x)|$ leads to $1>|\frac{c}{n+1}|$ and for any c, however large, we can take n=c and that will keep our inequality true.
Answer: The max norm is not the (absolute value of) the function at one specific point, but at a point that depends on the function itself. In a more general setting where functions are not necessarily continuous, it is called the supremum norm.
The integral of $|f|$ cannot be higher than the length of the integration interval multiplied by the maximum of $|f|$ because of the definition of the Riemann integral (the constant function $\max(|f|)$ defines an upper sum in the sense of the Riemann integral).
On the other hand, one can construct positive continuous functions on the interval that have very small surface areas underneath their graphs, yet their maximum is defined by a very sharp spike.
Comment: Thanks for your answer. So would something like this work?:

Let $f(x)=x^n$ on $[0,1]$, then $max|f(x)| > c \int_a^b|f(x)|$ leads to $1>|\frac{c}{n+1}|$ and for any c, however large, we can take n=c and that will keep our inequality true.
Comment: That is a good example. Even on a smaller interval, even though the max would converge to 0, it would still do so by a factor $(n+1)$ more slowly than the integral, with the result that the ratio between the max and the integral becomes arbitrarily large.
Answer: Hints:

For nonexistence of $c$ you could try to construct non-negative continuous functions, which have a small integral, i.e., $\|f\|_1$ is small, but with large $\|f\|_{max}$.
The second inequality follows with $c = b - a$.
Comment: Thanks, the second one is silly I should've thought it through. Does this work for the first one:

Thanks for your answer. So would something like this work?:

Let $f(x)=x^n$ on$[0,1]$, $max|f(x)| > c \int_a^b|f(x)|$ leads to $1>|\frac{c}{n+1}|$ and for any c, however large, we can take n=c and that will keep our inequality true.
Comment: Yes, that is fine. And it can be adopted to arbitrary intervals $[a,b]$.


Compactness of Gelfand topology

Question: I have a trouble to understand the proof of Theorem 16 of Chapter 18 in Lax's functional analysis. I post the proof and relevant definitions below.
Here's my question. In the proof, he defines $p(N)=t_N$ and proves that it is homomorphism. But how can we know this homomorphism comes from the Gelfand representation? Or does Gelfand representation contains all homomorphisms?
Answer: The function $p:J \times \mathcal{L} \to \mathbb{C}$ does "contain" all complex homomorfisms:
For each $h:\mathcal{L} \to \mathbb{C}$ nonzero homomorfism, $\mathcal{M}:=\ker(h)$ has codimension 1 and is a proper ideal ($I\not\in \mathcal{M}$), thus $\mathcal{M} \in J$. Therefore $h = p(\mathcal{M},\cdot).$
So every $t$ in the closure of (17) is the image of some $\mathcal{M} \in J$ under (17).
Note: I think he means that the Gelfand representation is the function $N \in \mathcal{L} \mapsto p(\cdot, N)$, and that the function $p(\cdot, N): J \to \mathbb{C}$ is the representation of $N$. So it is not correct to say "the Gelfand representation contains all homomorphisms", because the homomorfisms are the functions of the form $p(\mathcal{M}, \cdot)$.

Compactness of Gelfand topology


angularjs-google-maps - info-window does not work with ng-repeat

Question: I use google maps with ng-map and use markers and info-windows attached to these markers added to the map with ng-repeat. My angular view is the following:

<map center="current-location" zoom="9" on-bounds_changed="getLocations()">

    <marker  ng-repeat="myMarker in myMarkers"
        clickable="true"
        on-click="showInfoWindow(event, '{{myMarker.infoWindowId}}')"
        id="{{myMarker.id}}"
        position="[{{myMarker.lat}},{{myMarker.lon}}]"
        title="{{myMarker.title}}"
        draggable="false"
        opacity="{{myMarker.opacity}}"
        visible="{{myMarker.visible}}"
        icon="{{myMarker.icon}}">
    </marker>

    <info-window ng-repeat="infoWindow in infoWindows"
        id="{{infoWindow.id}}"
        visible-on-marker="{{infoWindow.markerId}}">

{{infoWindow.name}}

{{infoWindow.text}}

                Get forecast

    </info-window>

</map>

the myMarker.infoWindowId correspond to infoWindow.id and myMarker.id to infoWindow.markerId. There seems to be no issue in that, the markers and the infowindows are listed just fine in the DOM after loading the view and controller.
The markers are shown just fine on the map, as they are updated when the on-bounds_changed="getLocations()" function is executed.
The list of info-windows is updated in getLocations() too, the markers and the info-windows can be seen in the DOM, but the info-windows are not shown when I click on the corresponding marker. Tried using a single info-window item in the view and update its content when the user clicks on a marker, but nothing changed.
Can anyone please point me in the right direction to what am I not doing right here? Thank you.
A second question: if I must use ng-non-bindable in the info-window content (ng-map complains otherwise), how can I dynamically update/generate the content of the info-window? But this issue should show up only after the infow-windows are shown.
Answer: Sorry for the late response.
short answer, info-window must not be used with ng-repeat.
http://plnkr.co/edit/lBxdmm?p=preview

  <marker  ng-repeat="myMarker in myMarkers"
      name="A" text="B" url="http://foo.bar"
      clickable="true"
      on-click="showInfoWindow('myInfoWindow')"
      id="{{myMarker.id}}"
      position="[{{myMarker.lat}},{{myMarker.lng}}]"
      draggable="false"
      opacity="{{myMarker.opacity}}">
  </marker>

  <info-window id="myInfoWindow">

{{this.name}}

{{this.text}}

        Get forecast

  </info-window>


Busted guitar top, how to fix?

Question: all.  I am new to this exchange.
I recently bought a 7 string Cort guitar with a busted top (for cheap).  I am hoping to repair back to playable condition.  It is in good condition except what you see in the photos.  Any ideas on the best way to repair?  Should I just give it up?
I can do the electrical work (which is still functional).  It's just the body damage.  I would like to get repaired. If I reconstruct the body (glue what I can and fill the rest with wood putty), it would work but be very ugly.  I am afraid I would have to paint the entire thing if I did the work myself.
Another option I considered is to just put a pickguard on the front.  I would probably have to make a custom one.
Any thoughts?
Comment: Show the underside of the damage!
Comment: It depends if you want a guitar in playable condition, or a guitar which look is also perfect. For the former there are a lot of ways to have the electronic working and steady on that, even if a bit of resin is involved. For the latter it is probably another matter... What do you want :)?
Comment: I edited the post.  The electrical still works and I put that together myself.  The body work is a different story.  I want the guitar to look pretty.  It has a beautiful speckled red finish.  I am afraid I would have to repaint the entire thing if I did it myself.  That is why I am asking if anyone has any other options.
Comment: Very big and fancy pots knobs?
Comment: The guitar: "You should see the other guy!"
Comment: Looking at where the damage is, I would look at the cost of repair. You may consider getting a couple of estimates on repairs. Also - check around as many places as you are able. The price and quality will vary. Read reviews too - these should help you choose. I wish you the best in getting it fixed economically! So you will play on!
Comment: Get some shiny knobs made for a Weber grill and put them on the guitar, that should cover the damage.  Another option might be to use a control plate that comes standard on most telecasters (cut off the end with the slot for the switcher of course).
Comment: I added some pictures of underside
Comment: big knob, lol.  How big is TOO big?
Answer: This is a relatively simple repair if you don't mind that the guitar doesn't end up looking the same as it did new:

Drill out the damaged parts of the wood.
Add a pickguard with the slot for the switch in the same position and the holes for the potentiometers in approximately the same positions.  If you can't find a standard product that matches, you will have to make one (or have one made) from blank pickguard material (probably black for this instrument).  If well made, it will look like it was meant to be there from the start.  A custom one could cover as much or as little of the body as you like, as long as it covers the damaged areas.

Some guitars (e.g. my Danelectro baritone) already have the electronics cavity open to both top and bottom of the instrument like this, enclosed by the pickguard on top and a cover on bottom.
Comment: Thanks!  This is the conclusion I had pretty much come to before I posted.  I appreciate the validation, though.  If it was a beat up body, there would be no question, but the paint is really pretty.
Answer: I think Theodore's answer of a custom pick guard is a good one but I have another idea that I think would also work. Maybe you can get two large washers similar to the ones used for the pickup switch on a Les Paul to attach over the holes and mount the pots on them. Find a diameter that covers the holes. This way more of the original finish would be visible. They can be the same color as the knobs or a contrasting color, say silver and black.
Comment: Unfortunately, I don't think I can get washers big enough.  The damage goes about 1-1/2 inch out.  That would be a really big washer.  Thanks anyway
Answer: By far the simplest will be a pickguard. It can be whatever shape and size you think fit, and colour and material will be choices too. The damaged area looks pretty flat, but if the pickguard needed to go close to the edge, it could have a spacer under it at the point it gets screwed onto the body.
The existing holes could then be opened up to allow the body of the pots and switch to fit easily, all of which I guess is accesible from the back. You could even move the switch and pots if needed, with any extra holes made then covered by the pickguard.
At the same time, maybe consider some alterations to the controls - phase switching, tandem pots, etc. With those pups there will be many options, and another switch or pot won't go amiss, surely?
Consider either leaving the damage, or filling it in - there may be some gain to the tone one way or the other - albeit minimal.
To keep it as original as possible, John's idea of washers is the best - maybe carefully routing out enough depth for them - otherwise you'll end up painting at least the top of the guitar.

Busted guitar top, how to fix?


IIS7 migrating from 32bit to 64bit problems

Question: We are currently in the progress of migrating multiple sites from a x86 win 2008 to a x64 win 2008. We have copied the config dir from and wwwroot's from the old server to the new server but when we start the server we get a 503 error page and in the event log are 5 warnings and then a error.
Warning:
A listener channel for protocol 'http' in worker process '2060' serving application pool 'SiteAppPool' reported a listener channel failure.  The data field contains the error number.

The xml of the event:
<Event xmlns="http://schemas.microsoft.com/win/2004/08/events/event">
<System>
  <Provider Name="Microsoft-Windows-WAS" Guid="{524B5D04-133C-4A62-8362-64E8EDB9CE40}" EventSourceName="WAS" />
  <EventID Qualifiers="32768">5139</EventID>
  <Version>0</Version>
  <Level>3</Level>
  <Task>0</Task>
  <Opcode>0</Opcode>
  <Keywords>0x80000000000000</Keywords>
  <TimeCreated SystemTime="2011-04-14T11:10:04.000Z" />
  <EventRecordID>334493</EventRecordID>
  <Correlation />
  <Execution ProcessID="0" ThreadID="0" />
  <Channel>System</Channel>
  <Computer>WEBSRV64</Computer>
  <Security />
  </System>
<EventData>
  <Data Name="AppPoolID">SiteAppPool</Data>
  <Data Name="ProcessID">2060</Data>
  <Data Name="param3">0</Data>
  <Data Name="ProtocolID">http</Data>
  <Binary>7E000780</Binary>
  </EventData>
  </Event>
We get 5 of those but all with a different worker process number.
After that we get this error:
Application pool 'SiteAppPool' is being automatically disabled due to a series of failures in the process(es) serving that application pool.

We have absolutely no clue why this error happens,, we did an 1 on 1 copy of the site. Currently we are still running on the 32 bit server but we like to migrate asap. Does anyone have a clue why we get this error?
Answer: Could be a lot of things but a few things jump to my mind :

Was the old site using a different ID
for the application pool, perhaps a
local machine user?  If so, it could be something internal to the application itself that isnt handling the new ID properly.
Is the proper version of the .Net
Framework installed on the new
machine?
Have you compared the old and new
application pools point-by-point
using the Advanced Settings view?

If you create a new site/application pool and accept the default settings, does it still do this for the new site?
Comment: @dave what do you mean with different ID,, where to find the ID? or do you mean the name?
Comment: The user ID that the application pool runs as.
Comment: @dave can you then give a example of why the application could not handle it propperly?
Comment: Some applications install modules in the http pipeline and if those modules do anything that leaves the server, like calling a database, then that would fail and things breaking in the pipeline lead to sometimes strange errors
Comment: I'd actually be interested to see if you can create a new functional site and pool just using the default settings.  If not, then it might be that something came over in the /inetsrv/config that shouldn't have been copied.
Comment: Just out of curiousity, have you restarted the machine since copying over the config?
Comment: Yes we did restart the server
Comment: Your comments helped me the most,,
Answer: It's likely a component in your site that isn't compatible with x64.  It could be an isapi filter or possibly some managed code or a COM+ call.
If it fails right away for an http request then it's likely an isapi filter.  You can confirm by disabling all filters and testing a test.html page.  Then add things back until it fails again.
You have 2 solutions:

Easiest: run your app pool in 32 bit mode.  That's a good setting anyway.  You can set it from the app pool advanced properties, one of the top options.  Set it as an app pool default and future app pools will also be set that way.  In IIS7, you can leverage the high memory of x64 while still running app pools in 32-bit mode.
Alternately, once you narrow down the component in question, get an update from the vendor.
Comment: I'm not positive if that will work or not.  What I would test then is if a new app pool and site will serve up correctly.  This will let you know if the general upgrade worked, or if the failure is related to your particular app pool and site.  You may be able to narrow it down to a single reference in the Program Files folder vs. Program Files(x68) or something like that.  Otherwise, what I suggest is to start over and use MSDeploy, which will take care of the bitness conversation, or manually copy your , app pools and location sections manually.  That will get most settings.
Comment: it is a clean IIS installation and we copied the config folder from the 32bit to 64bit. windows folder/system32/inetsrv/config folder.
Comment: Yeah, don't do that. Like Scott says, migrate it using the catchily-titled Web Deployment Tool or similar - 32 and 64-bit configs don't usually look the same, and the 64-bit version is built with a bunch of preconditions and helpful bitness-management settings built in.


drupal_goto is not refreshing the webform on submit

Question: I have a webform node. I need the users to fill it and on submit, the user will be redirected to some link.
if ($form_id == 'webform_client_form_970') {
    $form['#submit'][] = 'dl_pdf';
}

function dl_pdf(){
        drupal_goto("http://dev.site.com/ar/printpdf/9", $options);
    }

When the form is submitted, drupal_goto works ( it actually just downloads a PDF file automatically ) but the form does not get refreshed.
What i have been doing wrong. Any clue?
Solution:
if ($form_id == 'webform_client_form_970') {
        //$form['#submit'][] = 'dl_pdf';
        drupal_add_js(
            'jQuery(document).ready(function () {
                jQuery(".webform-submit").on("click", function(){
                    var win = window.open("'.dl_pdf().'", "_blank");
                    win.focus();
                });
            });',
        array(
            'type' => 'inline',
            'scope' => 'footer',
            'weight' => 5
            )
        );
    }

function dl_pdf(){
        return "http://dev.site.com/ar/printpdf/9?name=".$userinfo->title."&date=".$course_date."&course_type=off-non-reg&course_name_ar=".$courseinfo->title."";
}

Answer: If you redirect to a URL that does not return a page but instead returns some other type of resource (such as a PDF in this case), then the current page will not be refreshed, as you have observed, because the response to the form request is returning the PDF, not HTML.
If you want the page to be refreshed as well then a common technique is to return the HTML for the new page from the form, and then redirect again to return the PDF. Because you need the new page to load fully (so the browser renders it), you'll need to use JavaScript to provide the redirect to the PDF. You can have a link in the page as well, to say something like "If the file does not download automatically, click here".
Comment: doing it with javascript worked.
Answer: For redirect form after submit you have to implement
$form_state['redirect'] = "Your URL"

For more information visit here
Comment: Yes, this is the correct technique but the drupal_goto the OP has coded will have exactly the same effect (form processing calls drupal_goto for you instead of you having to call it directly).


To create JButton, JSlider and Graphics in a program file

Question: Help me to create a class file which consists of JButton and JSlider and Java Graphics.
I tried a lot of methods but not working in netbeans 7.2: Jpanel, Jcomponent, paint(), paintComponent().
Can any one give me a class file for example to create that one?
My code is here:
    package floating;
    import designs.*;
    import java.awt.*;
    import javax.swing.*;

    public class Test extends JFrame
    {
        String frame_name;
        boolean START,PASS;
        int SPEED=1;
        JSlider jSlider1 = new javax.swing.JSlider();
        JSeparator js=new JSeparator();
        JToggleButton jToggleButton1 = new javax.swing.JToggleButton("START");
        JToggleButton jToggleButton2 = new javax.swing.JToggleButton("PASS");

        Test(String a)
        {

           JFrame jf=new JFrame(a);
            Dimension dim=Toolkit.getDefaultToolkit().getScreenSize();
            jf.setSize(dim.width,dim.height-30);
            jf.setDefaultCloseOperation(jf.EXIT_ON_CLOSE);

            js.setOrientation(SwingConstants.VERTICAL);
            js.setForeground(Color.red);
            js.setLocation(dim.width/2,0);
            js.setPreferredSize(dim);
            js.setSize(10,dim.height);
            jf.add(js);

            jSlider1.setLocation(dim.width-300,20);
            jSlider1.setSize(250,50);
            jSlider1.setToolTipText("Set to Seconds");
            jSlider1.setMinimum(1);jSlider1.setMaximum(5);jSlider1.setMajorTickSpacing(1);jSlider1.setMinorTickSpacing(1);jSlider1.setValue(1);
            jSlider1.setPaintLabels(true);
            jSlider1.setPaintTicks(true);
            jSlider1.setPaintTrack(true);
            jSlider1.addMouseListener(new java.awt.event.MouseAdapter() {
                public void mouseClicked(java.awt.event.MouseEvent evt) {
                    jSlider1MouseClicked(evt);
                }
            });
            jf.add(jSlider1);

            jToggleButton1.setLocation((dim.width/2)+30,25);
            jToggleButton1.setSize(100,30);
            jToggleButton1.addItemListener(new java.awt.event.ItemListener() {
                public void itemStateChanged(java.awt.event.ItemEvent evt) {
                    jToggleButton1ItemStateChanged(evt);
                }
            });

            jToggleButton2.setLocation((dim.width/2)+50+100,25);
            jToggleButton2.setSize(100,30);
            jToggleButton2.addItemListener(new java.awt.event.ItemListener() {
                public void itemStateChanged(java.awt.event.ItemEvent evt) {
                    jToggleButton2ItemStateChanged(evt);
                }
            });

            jf.add(jToggleButton1);
            jf.add(jToggleButton2);

            jf.setLayout(null);  \\if layout is null the only all buttons and slider at positions and showing in JFrame
            jf.setVisible(true);

        }

        public void jToggleButton1ItemStateChanged(java.awt.event.ItemEvent evt)
        {
            if(jToggleButton1.getActionCommand()=="START")
            {
                System.out.printf(jToggleButton1.getText());
                jToggleButton1.setText("STOP");
                this.START=true;
                System.out.println(this.START);
            }
            else
            {
                System.out.printf(jToggleButton1.getText());
                jToggleButton1.setText("START");
                this.START=false;
                System.out.println(this.START);
            }
        }
        public void jToggleButton2ItemStateChanged(java.awt.event.ItemEvent evt)
        {
            if( jToggleButton2.getActionCommand()=="PASS")
            {
                System.out.printf(jToggleButton2.getText());
                jToggleButton2.setText("RESUME");
                this.PASS=true;
                System.out.println("   "+this.PASS);
            }
            else
            {
                System.out.printf(jToggleButton2.getText());
                jToggleButton2.setText("PASS");
                this.PASS=false;
                System.out.println( "  " +this.PASS);

            }
        }
        private void jSlider1MouseClicked(java.awt.event.MouseEvent evt)
        {

           this.SPEED=jSlider1.getValue();
           System.out.println(SPEED);
        }
        public static void main(String args[])
        {
            Test a=new Test("Test");

        }
        public void paint(Graphics g) // for example but not shwowing in JFrame.
        {
             g.setColor(Color.red);
            RRectangle a=new RRectangle(60,100,250,190,60,60);
           a.drawShape(g);
           System.out.println(a);
        }

    }

Comment: PLs Add what U tried..??
Comment: Read the [Swing tutorial](http://docs.oracle.com/javase/tutorial/uiswing/TOC.html). There are section on `How to Use Buttons`, `How so Use Sliders`, `Custom Painting`. They all come with examples. So read the tutorial, download the example code and play with it. Then if you still have problems you can ask a specify question.
Comment: _"Help me to create a class file which consists of JButton and JSlider and Java Graphics."_ You have no explained what you expect these to do. So elaborate on _"not working"_
Comment: Try this problem and Tell me Please.
Comment: You can't do JButton and Graphics in Same class sure.Try Above Problem once and Tell me if it is right or Wrong not by looking
Comment: *"SEND THE FIXED CODE"*  1) Stop SHOUTING at us.  2) For better help sooner, post an [SSCCE](http://sscce.org/).
Answer: Your class extends JFrame, but then within your class you create an instance of JFrame and you add all the components to this instance of JFrame and make this frame visible. The extended class is never used or displayed.
So the paint() method that you override does nothing.

you should NOT be extending JFrame.
custom painting is done by overriding the paintComponent() method of a JPanel and then you add the panel to the frame

I gave you a link to the Swing tutorial in my comment above. Read the section on Custom Painting for a working example.


Prestaging user accounts

Question: In Active Directory, what is the concept of prestaging user accounts?
Thanks
Comment: Can you elaborate?  Do you mean pre-staging *computer* accounts?
Comment: If you do mean pre-staging client computers check out this Technet article - http://technet.microsoft.com/en-us/library/cc759196(WS.10).aspx
Comment: also look up DJOIN if your prestaging win7 or w2k8r2 computer accounts.
Answer: Usually we pre-stage COMPUTER accounts, which simply means creating them in AD before they are joined from the workstation, either manually or using an automated/unattended install script.
For users, this makes no sense as obviously a user must be created in AD before it can log in.

Prestaging user accounts


What options for Windows Server 2008/SQL Server 2008 replication/mirroring across data centres?

Question: Our Microsoft web-application processes around 2000 orders per day. I need to support failover to a secondary data centre.
What are the options and experience of implementing a replication/mirroring solution?
I've heard it referred to as geo-replication and I read the MSDN article here:
http://msdn.microsoft.com/en-us/library/dd263442(v=sql.100).aspx which describes the performance.
I'm not a DBA and have limited experience of replication/mirroring. Obviously when the time comes I will bring in the relevent expertise but I would appreciate anyone describing their experience in implementing this.
Answer: I have a client who does mirroring (synchronously, but without a witness) from one data-centre to another. Every so often they've had trouble with the link getting flooded, despite no abnormal transactional behaviour. Feels to me like the mirroring is trying to reinitialise, sending more information down the link than it ought to if things were smooth.
I'd generally steer clear of mirroring over large distances, although asynchronous should be better as it doesn't wait for the reply. It then feels a lot like log-shipping without having to wait for the log-backups to be done.


What are "sweeping phrases"?

Question: I am studying music, and English is not my first language.
In the follwing sentence, what does "sweeping phrases" mean? Does it have a special meaning?

"Laitman's vocal melodies have large, sweeping phrases with arching
  shapes that  highlight the voice. She unifies her song cycles with
  recurring motives and rhythmic  gestures. She often uses sparse
  textures in her accompaniments, helping to highlight the  vocal
  melodies"

from "The new American song: a catalog of published
songs by 25 living American composers
by Sarah Elizabeth Snydacker"
Answer: Sweeping means a similar thing to swaying when it comes to describing melodies.
The perfect example I can think of is Muse's 'Bliss':

Notice the way that the opening melody is 'swaying', or 'sweeping' up and down the keyboard.
thinking in metaphor, phrases are like musical sentences, with bars being words and notes being the individual letters/syllables.  In the song above, the ascending/upward arpeggio could be considered one phrase, and the downward arpeggio another.
Hope that helps!

What are "sweeping phrases"?


The sigma algebra generated by a stochastic process is equivalently generated by finite intersections.

Question: I am reading a stochastic analysis script and in one proof the following 'fact' is used.
Let $(\Omega, \mathcal{F}, \mathbb{P})$ be a probability space, $I \neq \emptyset$ an index set and $(S, \mathcal{S})$ a measurable space. For a process $X = (X_i)_{i \in I}$ consisting of $S$ valued $\mathcal{F}-\mathcal{S}-$measurable random variables the following is claimed (without proof):
Let $\mathcal{I} = \{\bigcap_{j \in J} X_j^{-1}(A_j)| J \subset I \text{ finite }, A_j \in \mathcal{S}\}$, then $\sigma(\mathcal{I}) = \sigma(X_i, i \in I) (= \sigma( \bigcup_{i \in I} X_i^{-1}(\mathcal{S})))$. The interesting direction is to show that every set $\bigcup_{i \in I} X_i^{-1}(A_i)$, with $A_i \in \mathcal{S}$ is an element of $\sigma(\mathcal{I})$.
For uncountable $I$, I wanted to proof it myself, but is this even correct?
For example: Consider $(\Omega, \mathcal{F}, \mathbb{P}) = ([0,1], \mathcal{B}, \lambda)$ and $(S, \mathcal{S}) = (\mathbb{R}, \mathcal{B})$ and $X_i = 1_{\{i\}}$, for $i \in I$, where $I$ is some nonmeasureable subset of $[0,1]$.
Now, we have $\sigma(\mathcal{I}) \subset \mathcal{B}$, but $\bigcup_{i \in I} X_i^{-1}(\{1\}) = \bigcup_{i \in I} \{i\}  = I \in \sigma(X_i, i \in I)$. So, according to the above claim, we would have $I \in \mathcal{B}$ which is false.
Am I missing something? If I am, how would you actually prove it?
Comment: @ÁlvaroRomaniega No, actually it is just an arbitrary collection of random variables.
Comment: Yes, thanks, I figured it already out. See my comment to Snoop's answer.
Comment: Does your notes assume that the process has continuous paths a.s.?
Comment: Ok, nevertheless your counterexample is not correct as the union is not countable.
Comment: In English, it says that the sigma algebra generated by intersections of size 1 is the same as the sigma algebra generated by finite intersections. This is true because you can go from each sigma algebra to the other.
Answer: I think the claim about $\sigma(\mathcal{I})$ can be proved as follows with no mention of the 'interesting direction'.
We have that $X_i^{-1}(\mathcal{S})\subseteq \mathcal{I},\,\forall i \in I$, as for all $J=\{i\}$ we have $X^{-1}_i(A)\in \mathcal{I},\forall A \in \mathcal{S}$. Therefore, $\cup_{i \in I}X^{-1}_i(\mathcal{S})\subseteq \mathcal{I}$.
Now for arbitrary $X_i\in (X_i)_{i \in I},A_i\in \mathcal{S}$ we have $X_i^{-1}(A_i)\in \sigma(X_i,i\in I)$. By the properties of $\sigma$-algebras, any finite intersection $\cap_{j \in J}X_j^{-1}(A_j)\in \sigma(X_i,i\in I)$.
It follows that
$$\bigcup_{i \in I}X_i^{-1}(\mathcal{S})\subseteq \mathcal{I}\subseteq \sigma(X_i,i \in I)$$
and that $\sigma(\mathcal{I})=\sigma(X_i,i \in I)$.
Comment: Thank you, I get it. My misunderstanding was that I thought that sets of the form $\bigcup_{i \in I} X_i^{-1}(A_i)$ have do be in $\sigma(X_i, i\in I)$. But this is not the case. Even though $\sigma(X_i, i\in I)$ is generated by the sets $X_i^{-1}(A_i)$, there is no reason that $\bigcup_{i \in I} X_i^{-1}(A_i)$ should be in $\sigma(X_i, i\in I)$ (and therefore my counterexample is incorrect and your answer correct).


Retrieving an RxJS Observable of a nested Firestore query in AngularFire

Question: I'm trying to convert my Observable of an Object with DocumentReferences to an Observable of my entire Object.
My Firestore query returns an Observable of QuestDocument, which looks as follows (stripped of primitive types):
export interface QuestDocument {
    ...
    owner: DocumentReference<User>;
    ...
    collaborators?: DocumentReference<User>[];
    categories?: DocumentReference<Category>[];
}

Within my converter, I can call my other Firestore services to retrieve the values of the DocumentReferences to User and Category (flat structures, so no problems here).
My goal is to create an Observable of type Quest, but my nested Observables are not being resolved correctly.
export interface Quest {
  ...
  owner: User;
  ...
  collaborators?: User[];
  categories?: Category[];
}

Here's what I have so far:
doc$(docId: string): Observable<Quest> {
  return this.doc(docId).valueChanges()
  .pipe(
    mergeMap(questDoc => {
      const owner$ = this.userService.doc$(questDoc.owner.id);
      const collaborators$ = forkJoin(questDoc.collaborators.map(
        (userRef: DocumentReference) => {
          return this.userService.doc$(userRef.id)
        }
      ));
      const categories$ = forkJoin(questDoc.categories.map(
        (categoryRef: DocumentReference) => this.categoryService.doc$(categoryRef.id)
      ));
      const joined = forkJoin({
        owner: owner$,
        collaborators: collaborators$,
        categories: categories$
      });
      joined.subscribe(data => console.log(data));
      return joined.pipe(
        map(value => {
          return Object.defineProperties(questDoc, {
            qid: { value: docId },
            owner: { value: value.owner },
            collaborators: { value: value.collaborators },
            categories: { value: value.categories }
          }) as Quest;
        })
      )
    })
  );
}

All the typings match up and I should receive an Observable<Quest>, but when I try to print the value it returns undefined and the second .pipe() is never reached.
Comment: `forkJoin` will only emit once all of the source observables have emitted and completed.  Do calls to `categoryService.doc$()` and `userService.doc$()` return observables that complete?  If not, you could add `.pipe(first())` to each of your 3 sources inside your `joined` forkJoin.
Comment: I'm not sure as to what *completion* means in terms of an Observable, as I'm still new to these concepts. The `.doc$()` calls of both services return Observables of the respective document-like types (see `QuestDocument`), mapped to the realized types (only added the document's ID onto the `Category` and `User`). The underlying functions that retrieve the document-like types are extensions of AngularFire's Firestore SDK.
Answer: You are not using the forkJoin operator correctly.
An observable that is complete will no longer emits data. Take it like a closed pipe.
ForkJoin will wait that all steams are completed (closed) before emitting one single data.
If you're fetching your data using this.afs.collection(...).doc(...).valueChanges(), these observables stay active. They will emit each time the data is updated in firestore.
To complete them, use a take(1) or first() (they will emit once then complete), or use combineLatest() to combine active streams and keep your data updated in real time (don't forget to unsubscribe onDestroy to prevent any memory leak).
Here's an example with completed streams:
doc$(docId: string): Observable<Quest> {
  return this.doc(docId).valueChanges()
  .pipe(
    mergeMap(questDoc => {
      // observable will emit then complete thanks to the "take(1)"
      const owner$ = this.userService.doc$(questDoc.owner.id).pipe(take(1));
      const collaborators$ = forkJoin(questDoc.collaborators.map(
        (userRef: DocumentReference) => {
          // same thing here
          return this.userService.doc$(userRef.id).pipe(take(1))
        }
      ));
      const categories$ = forkJoin(questDoc.categories.map(
         // and here
        (categoryRef: DocumentReference) => this.categoryService.doc$(categoryRef.id).pipe(take(1))
      ));
      const joined = forkJoin({
        owner: owner$,
        collaborators: collaborators$,
        categories: categories$
      });
      // joined.subscribe(data => console.log(data));
      return joined.pipe(
        // NEVER subscribe within a pipe, use a tap operator for side effects
        tap(data => console.log(data)),
        map(value => {
          return Object.defineProperties(questDoc, {
            qid: { value: docId },
            owner: { value: value.owner },
            collaborators: { value: value.collaborators },
            categories: { value: value.categories }
          }) as Quest;
        })
      )
    })
  );
}

Comment: Thanks a ton! I was stuck on this problem for quite some time and never really thought about completion / the underlying Observables still being active. Also thanks for the pointer to the possibility of live updates (`combineLatest()`), as that was what I would try next :)


Custom teasers and show summary checkbox

Question: The function generating teasers in D6 does not make nice teasers.  At the same time I do not want to bother my users to set teasers themselves, I would rather get rid of the whole system.
Anyway, I tried writing a little helper module which went through the published nodes and tried to correct teasers that were too short or too long.
My problem:

Between the node_load() and a node_save(), what parts should I care about, just place a  in $node->body or adjust $node->teaser?
I had the problem after adjusting $node->teaser and deleting the break; the "Show summary in full view" checkbox was unchecked when manually editing this node.  Which variable is controlling this checkbox and how do I set it?
If I wanted to implement some teaser-corrections via hook_nodeapi(), which event should I hook to, when I do not want to patch the node core module and interfere with its node_teaser() function?

I know there are a couple of modules around, that store teaser data in separate CCK fields.  I would like to avoid this if possible.  (and yes, I want to have a proper value for the teaser variable and not just manipulate the output via views etc.)
Answer:
Set $node->teaser to the value you want to use as teaser. That is what node_submit(), the function indirectly called from node_form_submit(), does.
node_body_field(), the function that add the form fields for the node body, contains the following code:

// Check if we need to restore the teaser at the beginning of the body.
  $include = !isset($node->teaser) || ($node->teaser == substr($node->body, 0, strlen($node->teaser)));

// …

$form['teaser_include'] = array(
  '#type' => 'checkbox',
  '#title' => t('Show summary in full view'),
  '#default_value' => $include,
  '#prefix' => '
',
  '#suffix' => '
',
);

The checkbox is not selected if

the teaser is set, or
the teaser is not the initial part of the body

I would use hook_nodeapi('presave'), which is invoked before the node is saved, but before hook_nodeapi('insert') or hook_nodeapi('update').

To notice that, if the problem is the length of the teaser, node_teaser(), uses the value of the "teaser_length" Drupal variable as length if the teaser. I am not using Drupal 6, but if I remember well, there should be a setting page that allow to change the value of that variable. If the value of the variable is not modified from a setting page, then you can set it in settings.php, or from a custom module.
Comment: Thanks a lot.  Somehow I was looking at the wrong place, I was aware of teaser_include from some debug output but must have overlooked the quoted code.  My problem resulted because the teaser I inserted had stripped tags and thus differed from the substr of body.


Integration formula which is based on Integration by cancellation

Question: $$
\int e^x \left( f(x) + (-1)^{n-1} f^n(x) \right) dx
$$
I think I discovered a formula for this integral where $f^n(x)$ is the $n$th derivative of $f(x)$.
The answer is in terms of $f(x)$ and it includes all of its derivatives up to the $(n-1)$th derivative
Comment: Welcome to MSE. For some basic information about writing mathematics at this site see, *e.g.*, [basic help on mathjax notation](/help/notation), [mathjax tutorial and quick reference](//math.meta.stackexchange.com/q/5020), [main meta site math tutorial](//meta.stackexchange.com/a/70559) and [equation editing how-to](//math.meta.stackexchange.com/q/1773).
Answer: Yes, such a result does exist. To get that what you have to do is, add and subtract $f'(x), f^{\prime\prime}(x), \ldots$ upto $f^{n}(x)$ to the $f(x)+(-1)^{n-1}f^{n}(x)$ term. Then group positive and negative signed terms together and observe that the negative terms are derivative of positive terms. Then a simple by parts operation would solve the question.


DBCombobox salvando indice

Question: Eu sou novato em Delphi e estou fazendo um form onde todas as entradas são DBLookup. Necessito de um Combobox para selecionar se a pessoa possui pais conhecidos ou não. Exemplo:

0 - Possui pais,
1 - Não possui.

Eu consigo colocar isto no DBCombobox mas como faço para atualizar o banco com 0 ou 1? O campo é do tipo varchar. Com o DBLookupCombobox eu teria que obter os dados de um sql, o que não vem ao caso por serem apenas duas informações.
Comment: qual versão do delphi você usa?
Answer: O componente ComboBox cria um índice para cada item que você inclui na lista. Neste caso, se você criar na ordem que apresentou em sua pergunta, os índices ficariam 0 = "Possui Pais" e 1 = "Não possui". Depois disso é só chamar a propriedade ItemIndex do ComboBox para gravar no banco de dados a opção selecionada pelo usuário, conforme o exemplo abaixo:
query.edit;    // edita o registro
query.fieldbyname('CampoDaTabela').AsString := IntToStr(ComboBox.ItemIndex);
query.post;   // salva o registro

Comment: Se o campo for `Integer` você usa `AsInteger` no lugar de `AsString` que ficaria assim: `query.fieldbyname('CampoDaTabela').AsInteger := ComboBox.ItemIndex;`
Answer: a forma mais correta seria clicando em um botão após todas as alterações ou o cadastro estar realizado onde você pode realizar da seguinte forma.
query.append;  // inclui um novo registro no banco de dados
query.edit;    // edita o registro
query.fieldbyname('CampoDaTabela').value := valor do edit, combo, etc;
query.post;   // salva o registro

ou da forma nao muito correta que seria ao sair do campo.
para realizar dessa forma no evento onExit da combo coloque o mesmo procedimento acima, validando se é inclusão ou alteração, para o determinado campo.

DBCombobox salvando indice


Does the site want questions on "everyday economics" about consumer markets?

Question: I moderate Cooking.Stackexchange. Every now and then, we get questions about the price or availability of certain food items. For example:

Why is canned tuna cheaper than frozen or fresh tuna?
Why is high fructose corn syrup not available as an ingredient?

I don't have other examples right now, but I'm sure I have seen them on Cooking, as well as on other sites. People wonder about prices all the time. They tend to ask it on sites about topics to which the good in question is connected, assuming that price is deterministically dependent on production costs.
These questions are closed on Cooking, and I also vote to close them on other sites. In theory, it should be possible to migrate them. So:

Does the Economics.SE community see these questions as on-topic?
If they fall within the scope, do you want them, or do you feel that they will be unwelcome because they are too basic to be interesting to this community, or because finding such a specific answer is too much work for a SE question (or for another reason?
If they are outside your scope, do you have a canonical question explaining basic microeconomics? Preferably one which mentions that one shouldn't expect prices to be determined by "expenses for producing this unit + 5% profit margin"?

Basically, while we can't answer these questions on Cooking, I would like us to be able to point our users into a direction where they can learn more about what they are wondering. Then they get something out of their asking even though their question got closed.
Comment: "Economics Stack Exchange is a question and answer site for professional and academic economists and analysts.". I think that says it pretty clearly.
Answer: My approach: questions about pricing, relative prices and the like are on topic here but it is my impression that they will rarely get an answer that matches the very narrow and specific level that they are asked (the OP's "finding such a specific answer is too much work for a SE question" conjecture).
Still, what the asker could gain from seeing the question migrated here, would be answers from people that have a solid background on the methodology to analyze such issues and are used to think about them, which will allow them to offer some qualitative insight on the main causes on what the question asks.
For example, to the question

"Why is canned tuna cheaper than frozen or fresh tuna?"

although I have not any experience with the tuna market, I could immediately point out that the risk associated with selling canned tuna is less than selling fresh tuna, because canned tuna can be stored -and the cost of storage does not fully offset the gain in additional "waiting-for-the-customer" time, which considerably increases the chance for a sale.
Canned tuna is also cheaper than frozen tuna, because storing cans is a low-energy consumption activity, while storing frozen tuna is a high-energy consumption activity (to maintain deep-freeze temperatures).
Things like that.
I would wait for other senior members and especially for our moderators to offer their views on "on-topicness".
Comment: @majmun Or, the increased flood of less interesting questions drives experts away. Given that there's no real target for us (we don't need to have solid 10 questions per day to stay alive as a site), I don't see increased traffic as a intrinsically relevant.
Comment: I also agree that they probably won't get the answer they are looking for, but I wish to point out that it is possible for them to at least get an answer -- as you give an example of --  and it may bring more traffic to this site, which may benefit Economics SE (granted, if the increased traffic generates questions that get no answered, then it will be a short-lived boon).
Answer: Of the one's we've received so far, they're pretty much all terrible questions.
In almost all cases, there's only one rudimentary economics concept involved - the crossing of supply and demand curves.
And the answer to why is X cheap, why is Y expensive, why does Y cost more than X, requires knowledge about the XY market, to explain why the supply and demand curves cross where they do.
There are millions of questions of this kind, but only one economics concept.
So I suggest we have one canonical question, with an answer that explains the basic concept, and explains why we don't answer questions about specific industries; and then close all the other "why this price?" questions as duplicates of that one.
And for the odd exception where there's an answer that requires more interesting economic concepts (e.g. the yield curve for different loan durations), then we can keep those open.
Comment: OK, so what do you propose that we on other sites do? Migrate these questions to you so you guys can close them? Close them on our sites and do nothing? Close them, but advice them to read through your canonical question and figure out for themselves how it explains their problem? Also, will your canonical question focus on "this is how prices work", or on "this is how people imagine prices work, and we now explain why that's wrong"?
Answer: I don't think these are on-topic here. We most likely don't have the knowledge of the particular product to say more than general economics insights.
Moreover, these aren't really "deep" questions, so they are neither particularly interesting, nor is really a PhD in economics required to know why canned tuna is cheaper than other.
See also our "mission":

Economics Stack Exchange is a question and answer site for professional and academic economists and analysts.

Which is a very far step away from "everyone who wonders why his consumption good is so darn expensive"
Answer: Somewhat following up on @Alecos's answer : I'll leave it to others to decide whether these kind of questions are on topic, but if they are, I think we should adopt a policy similar to the one we adopted for homework questions when we decided to ban questions with specific numbers.
What I have in mind is that a necessary (but not necessarily sufficient) condition for questions like

"Why is canned tuna cheaper than frozen or fresh tuna?"

to be on topic is that they be formulated as

"Why is canned food cheaper than frozen or fresh food?",

that is, with as little reference as possible to a specific market/product.


Dynamically store user data

Question: First, I have a table look like this:

Then, from my code, I have a method to check user permission
  public bool HasPermission(Guid userTaskId)

Every time I insert new row into usertask table (by sql script), I must store it id to a constant to check its permission, as below:
  public static readonly Guid TaskA = new Guid("6F28B771-2E3E-47DD-9CB4-48B4130A8CBE");
  public static readonly Guid TaskB = new Guid("8B273B24-AD3A-41D6-969D-49A854B4E896");

  // Check permission
  if(HasPermission(Helper.TaskA)){
       // Do something if user has permission on task A
  }

The problem is my program has many tasks , and I need to store many constants. Is there anyway dynamically to check permission without store all of them by hand? Mean application allows admin user add dynamically many tasks they want, then I can check permission of all tasks  for other user.
Thanks in advance.
Comment: Not sure what your question is here...
Comment: Can't you create a new table in database UsersTasksPermissions and store there the information?
Answer: How about leveraging a Dictionary. You could cache all of your keys up front like this:
var tasks = new Dictionary<string, string>();
var selectCmd = "SELECT UserTaskId, Name FROM UserTasks";

using (SqlConnection c = new SqlConnection(connString))
{
    c.Open();
    using (SqlCommand cmd = new SqlCommand(selectCmd, c))
    {
        // provide any parameters

        using (SqlDataReader rdr = cmd.ExecuteReader())
        {
            tasks.Add(rdr.GetString(0), rdr.GetString(1));
        }
    }
}

Now, you'll need to create and store this Dictionary somewhere that you can get to it globally. Maybe a Singleton named GlobalConfiguration.
Then you would change the way you call HasPermission to just receive a string:
public bool HasPermission(string userTaskId) ...

Now, I think there may be one more field missing here -the UserId. But I don't see it at the moment. You're going to want to create a Dictionary<string, List<string>> to house the permissions a user has. You would fill it in a very similar way to the other one.
One other thing. Right now you're accessing it by UserTaskId, but if it's possible, switch that around to use the Name instead. You could simply switch up the order the fields are selected in my example.

Dynamically store user data


Adding Bad Features to Decrease Model Performance

Question: I have a dataset on which some researchers have already performed some definitive data analysis and feature selection. Fitting a model to this dataset returns pretty good accuracy.
In order to demonstrate my feature selection skills, I want to add bad features to this dataset so I can obtain a baseline model with worsened performance.
Can anyone recommend the best way to create some new features in order to achieve this goal? Should I just add some random features, with a normal distribution? Anything else anyone can recommend?
Answer: (1) First, you may want to add "bad" feature detectors whose responses are highly correlated with the responses of the existing "good" feature detectors. These "bad" feature detectors provide information which is "redundant" with the information that you already have available from the "good" feature detectors. Under the assumption that as you add more feature detectors the number of parameters in the model increases, this should make the learning problem more challenging and decrease performance [because there are more probability distributions in the probability model for the learning machine to choose from].
(2) Second, you can add "bad" feature detectors which do not provide useful predictive information (or better yet make the wrong predictions) to support your inference tasks used to evaluate the performance of the model.  Again, under the assumption that as you add more feature detectors the number of parameters in the model increases this should make the learning problem more challenging and decrease performance.
(3) Third, you can do what you suggested which is adding some "bad" feature detectors which generate random responses but the potential problem with this is that you may get some useful predictive feature detectors by accident (see point 2 above) and the responses of these feature detectors will tend to be uncorrelated with your existing good feature detectors (see point 1 above).


TimeSpan.Parse of string including days dd-hh:mm:ss

Question: The time span I want to parse is of the format dd-hh:mm:ss
It is the output by the Linux command that returns how long a process has been running.
Example:
string s = "5-15:10:20"; // 5 days 15h 10m 20s
TimeSpan.Parse(s);

This generates the error
System.FormatException was unhandled
Message="Input string was not in a correct format."
Source="mscorlib"
StackTrace:
   at System.TimeSpan.StringParser.Parse(String s)
   at System.TimeSpan.Parse(String s)

Important note: Code to be written in .net Framework 2.0
Is there a way to let the TimeParse correctly identify the first date part?
Edit: I tried replacing the - with : but it gives the same error.
Comment: Have you tried "5.15:10:20"?
Comment: You can looking link = https://learn.microsoft.com/en-us/dotnet/standard/base-types/custom-timespan-format-strings
Comment: I failed to mention that I also tried replacing the "-" with a ":", but it gives the same error
Comment: `TimeSpan result = TimeSpan.ParseExact(source, @"d\-h\:m\:s", null);` here we *escape* delimiters with `\`
Answer: This works for me:
TimeSpan.Parse(s.Replace('-', '.'));

As does this:
TimeSpan.ParseExact(s, @"d\-hh\:mm\:ss", null);

For more info on the format strings you can use, see the manual.. They're subtly different to DateTime format strings
Comment: Thanks, you are correct! I cannot use the 2nd suggestion because ParseExact isn't available yet in .net Framework 2.0
Answer: I think that "-" is definitely the wrong sign.
The "-" is for specifying a negative TimeSpan
Since you've tried the ":" shin, give it a try with a "." at this point.
The "." is the official symbol to separate the day from the hours.
Comment: Please, I was happy to help you further.
Answer: The problem with your string is that the char "-" is a optional minus sign, which indicates a negative TimeSpan. So, you have to use the Replace() method before parsing your string.
On this link you can see all the common chars that works with that method. For that, something like that will work:
string s = "5-15:10:20"; // 5 days 15h 10m 20s
TimeSpan.Parse(s.Replace('-', '.'));