How to model nested fixed-factor with GLMM

Question: I am a beginner on learning in GLMM and R, please forgive me if I am not making sense or asking something that is very basic.
I am trying to specify a nested fixed-factor in my GLMM model, but I don't seem to find the way to do it. I would really appreciate if someone can answer this question.
My experiment consists of four different species (A,B,C,D), and I have used all possible combinations of the four species as different treatments (composition, Compo, each Compo n = 4 in each ExpRun). Compo is therefore nested within SPrich, because Compo consisting only species A will only be possible under SPrich of 1, but not others. Therefore my data is not balanced under factor SPrich. For example:
SPrich  Compo(abbr.)
0       Control
1       A
1       B
1       C
1       D
2       AB
2       AC
2       AD
2       BC
2       BD
2       CD
3       ABC
...
4       ABCD

I am interested to know whether the species richness SPrich (five levels) and composition Compo (16 levels) has an effect on the response variable WaterChlA, which I measured on different Day from each of my experimental tanks TankNo. WaterChlA is not normally distributed, but more closely resemble a lognormal distribution, so gaussian link log is used. Samples from each TankNo are taken between Day, thus they are not independent.  I have conducted the experiment for three times, denoted in factor ExpRun. TankNo are denoted differently in all three ExpRun and therefore a nested random factor.
Here is a section of my data to demonstrate:
> str(Wetland)
'data.frame':   480 obs. of  31 variables:
$ TankNo    : Factor w/ 150 levels "1","2","3","4",..: 1 2 3 4 5 6 7 8 9 10 ...
$ ExpRun    : Factor w/ 3 levels "1","2","3": 2 2 2 2 2 2 2 2 2 2 ...
$ Day       : Factor w/ 4 levels "1","8","15","22": 1 1 1 1 1 1 1 1 1 1 ...
$ SPrich    : Ord.factor w/ 5 levels "0"<"1"<"2"<"3"<..: 1 1 1 1 2 2 2 2 2 2 ...
$ FxRich    : Ord.factor w/ 3 levels "0"<"1"<"2": 1 1 1 1 2 2 2 2 2 2 ...
$ Compo     : Factor w/ 16 levels "1","2","3","4",..: 1 1 1 1 2 2 2 2 3 3 ...
$ MIFI      : Factor w/ 2 levels "0","1": 1 1 1 1 2 2 2 2 1 1 ...
$ KAPU      : Factor w/ 2 levels "0","1": 1 1 1 1 1 1 1 1 2 2 ...
$ DUME      : Factor w/ 2 levels "0","1": 1 1 1 1 1 1 1 1 1 1 ...
$ POME      : Factor w/ 2 levels "0","1": 1 1 1 1 1 1 1 1 1 1 ...
$ WaterChlA : num  8.33 1.99 35.56 17.49 22.04 ...

The question comes as my fixed-factor Compo should be nested within SPrich but it seems that it is more common to nest random factors in glmm, and I have not encounter on how to nest fixed-factors. I read in a Github post by Prof Bolker that specifying A/B in R actually equals to 1 + A + A:B, but I wonder if writing that would be enough to specify the nestedness between SPrich and Compo (as below)? If not, what should be the correct way to specify that Compo is nested within SPrich?
I input the following into the model to run glmer with package lme4:
glmm1 <- glmer(WaterChlA ~ ExpRun + Day + SPrich/Compo + ExpRun*Day + ExpRun*SPrich +
ExpRun*SPrich/Compo + Day*SPrich + Day*SPrich/Compo + (1|ExpRun/TankNo), data = Wetland,
family = gaussian(link = "log"), na.action = na.exclude)

It said:
fixed-effect model matrix is rank deficient so dropping 404 columns / coefficients

which is understandable because my fixed-factors are not full-rank but nested, so I am not too surprised if it has to drop the non-existing combinations of coefficients. However, it sort of demonstrates that the nestedness isn't really put into consideration by the model specified above(?). It also failed to converge:
Warning messages:
1: In (function (fn, par, lower = rep.int(-Inf, n), upper = rep.int(Inf,  :
  failure to converge in 10000 evaluations
2: In checkConv(attr(opt, "derivs"), opt$par, ctrl = control$checkConv,  :
  Model failed to converge with max|grad| = 0.112084 (tol = 0.001, component 1)

I want to know whether the way I specify the nested Compo in SPrich is correct. I also wonder if GLMM is the most suitable way to analyze this type of data, or is there any other more suitable tools for this, perhaps GLM would be sufficient to analyze my data? I go for GLMM because there is quite a large variance among different Tanks and thus masking the effect of factors that are of interests, and treating TankNo as a random factor should help lower the influence.
Other than SPrich, I'm also interested to look at how functional richness FxRich affects the response, but Compo is nested within FxRich differently than within SPrich (say Compo A & B is same functional group and C & D is another, then Compo AB will be SPrich 2 and FxRich 1, while Compo AC will be SPrich 2 and FxRich 2, thus the nesting is quite different and complicated), which I think is more sensible to resolve later in another model that do not include SPrich or Compo. I wonder if this is reasonable? Perhaps this should go into another question thread and be discussed later...
Thank you all for you attention! Really appreciate any thoughts on the above!
Comment: by the time I finished answering I realized this should probably be on CrossValidated instead: voting to close/migrate
Answer: Stream of consciousness:

you might want to consider log-transforming the response (provided there are no zeros) rather than using the log link, i.e. lmer(log(WaterChlA) ~ ...) rather than glmer(WaterChla ~ ..., family=gaussian(link="log")); I say this because log-transforming can take care of heteroscedasticity in the response (specifically a standard deviation approximately proportional to the expected mean value), which the log-link approach doesn't do (also, lmer tends to be a little bit faster and more stable than glmer)
Nested fixed effects are indeed hard to specify in linear models (as opposed to ANOVA frameworks), where the underlying framework is explicitly trying to estimate parameters rather than just evaluate sums of squares/proportions of variance explained. If the parameters are not uniquely identifiable, then the model will end up dropping some terms. If your experimental design doesn't allow it, you simply can't estimate an interaction, which is necessary for nested terms. For example, you can't tell how the effect of Compo=AB varies among species richnesses, because Compo=AB only exists when species richness is 2.  You have a further problem: you can't even estimate the effect of species richness uniquely when Compo is in the model, because Compo is redundant with species richness (once you know the Compo, you know the species richness). Such redundancy is allowed in variance-decomposition approaches, or in Bayesian models, but not in linear models based on parameter estimation and models descended from them. You could make Compo a random effect (also a good modeling strategy because it has many levels, which will be expensive in terms of degrees of freedom); that would still allow you to quantify the effects.
Since you have 480 data points, you should keep in mind the rule of thumb (e.g. from Harrell's Regression Modeling Strategies) that you should not try to fit a model with more than at most n/10 = 48 parameters (that's extreme - typically the rule is stated as n/20, which would mean 24 parameters).  Because your predictors are all factors, trying to estimate interactions among them will rapidly make your model size blow up.
lme4 is known to give false-positive convergence warnings in some cases, but they look real in this case; I think the problem is that you have a model that is way overspecified/too complex ... see if stripping it down (as suggested below) helps.
In general you shouldn't include a categorical variable (factor) as both a fixed effect and a random-effect grouping variable: that's a redundant model specification.

I would say a reasonable start for this model would be
lmer(log(WaterChlA) ~ Day*SPrich + (1|Compo) + (1|ExpRun/TankNo),
 data = Wetland, na.action = na.exclude)

although trying to estimate the interaction between Day and SPrich gives you 20 parameters, which is pushing it a bit.  You might consider whether you're willing to convert one or both of those factors to numeric (i.e. only looking for linear trends, or if you used poly(Day,SPrich,degree=2) that would give you quadratic terms with only 5 parameters ...)
Comment: Thank you so much for your quick and very informative reply! I guess with such a small number of data points, it is quite hard to come up with a realistic GLMM model. This is extremely useful and your answer points me to a new direction/approach. Thanks again!!!


In jsp directive

Question: I need to include the following tag to my entire application JSP pages but is there any way we can include that in only one location and used in entire project.
Here is the tag;-
<%@ page contentType="text/html; charset=UTF-8" %>

Comment: No, it is a directive.
Answer: Yes you can.
A solution is using tiles, so you can create structure:
https://tiles.apache.org/framework/tutorial/basic/pages.html
You can build a web page layout and put all your configuration like:

content type
link
link js

in one place, preferably into header section and display everytime a different body (another jsp).

In jsp directive


Hankel norm and H infinity norm model reduction exam question.

Question: Shown below is a question from a model reduction exam. I'm not sure how to answer the questions and I'm wondering if my approach is correct.
A continuous time system relates the inputs $u_1$ and $u_2$ to the output $y$ according to the differential equation.
$$\dot{y}+ \rho y= u_1 + 2u_2$$
Where $\rho$ is a real parameter.
a) $\quad$ Determine for arbitrary $\rho > 0$ the Hankel norm of this system.
b) $\quad$ Determine for arbitrary $\rho > 0$ the $H_{\infty}$ norm of this system.
For the hankel norm we first must determine the state space representation. We assume $\dot{y} = \dot{x}$. Which leads to:
$$\dot{x}=-\rho x+u_1+2u_2, \quad y=1$$
So the state space form becomes:
$$\dot{x} = \begin{bmatrix} -\rho \end{bmatrix}x + \begin{bmatrix} 1&2 \end{bmatrix} \begin{bmatrix} u_1\\u_2 \end{bmatrix}, \quad y = \begin{bmatrix} 1 \end{bmatrix} x $$
So $A = \begin{bmatrix} -\rho \end{bmatrix}, \quad B = \begin{bmatrix} 1&2 \end{bmatrix}, \quad C = \begin{bmatrix} 1 \end{bmatrix}$ and $D = 0$
Next, we need to determine the continuous time $\infty$ horizon reachability and observability gramians using.
$$0 = AP+PA^{\top}+BB^{\top}$$
$$0 = A^{\top}Q + QA +C^{\top}C$$
This leads to $P = \frac{5}{2 \rho}$ and $Q = \frac{1}{2 \rho}$
The Hankel norm can then be determined using: $||\Sigma||_H=\sqrt{\lambda_{max}(PQ)}= \sqrt{\lambda_{max}(\frac{5}{4 \rho^2})}$
The $H_{\infty}$ norm can be determined using $||\Sigma||_{H_{\infty}}=sup
 \ \sigma_{max}(G(i \omega))$
In which $G(i \omega)=C(SI-A)^{-1}B+D$ But the matrix dimensions are incorrect to perform this calculation. So I don't have an idea on how to calculate the $||\Sigma||_{H_{\infty}}$ norm.
Answer: The dimensions of the matrices are consistent, $C$ is a $1\times 1$ matrix, $sI-A$ is a $1\times 1$ matrix and $B$ and $D$ are $1\times 2$ matrices.
You have found $\|\Sigma\|_H = \frac{\sqrt{5}}{2\rho}$ and you should find $\|\Sigma\|_{H_\infty} = \frac{\sqrt{5}}{\rho}$. You can check that $\|\Sigma\|_H\leq \|\Sigma\|_{H_\infty}$.


Confusion determining eigenvalues

Question: Matrix $A$:
$$A = \begin{bmatrix}
    -5 &14& -8 \\
    -9 &16& -6 \\
    -9 &11& -1
\end{bmatrix} $$
Determining eigenvalue of Matrix $A - 1I$ hence $\lambda = 1$ (other eigenvalues are 4 and 5).
Matrix $A - 1I:$
$$\begin{bmatrix}
    -6 &14& -8 \\
    -9 &15& -6 \\
    -9 &11& -2
\end{bmatrix}
\begin{bmatrix}
x_1 \\
x_2 \\
x_3
\end{bmatrix}=\begin{bmatrix}
0 \\
0 \\
0
\end{bmatrix}$$
1. Figuring out each $x_i$ so the above equation complies will give me the eigenvector for eigenvalue $\lambda = 1$ right?
2. the sum of all $x_i$ must be $0$?
3. How would you go about determining $x_i$, do you just play around till you get a right combination?
Comment: Your point 2 is wrong. The sum of $x_i$ is $0$ if the eigenvetor is orthogonal to $(1,1,1)^T$. Actually, here, they are collinear...
Answer: Using gaussian elimination, your system is equivalent to the following, writing only the matrix, not the $x_i$ nor the right hand side since there are only zeros in the RHS anyway:
$$\left(\begin{matrix}
-6 &14& -8 \\
-9 &15& -6 \\
-9 &11& -2
\end{matrix}\right)$$
$$\left(\begin{matrix}
-3 &7& -4 \\
-9 &15& -6 \\
-9 &11& -2
\end{matrix}\right)$$
$$\left(\begin{matrix}
-3 &7& -4 \\
0 &-6& 6 \\
0 &-10& 10
\end{matrix}\right)$$
$$\left(\begin{matrix}
-3 &7& -4 \\
0 &-6& 6 \\
0 &0& 0
\end{matrix}\right)$$
$$\left(\begin{matrix}
-3 &7& -4 \\
0 &-6& 6 \\
0 &0& 0
\end{matrix}\right)
\left(\begin{matrix}
x_1 \\ x_2 \\ x_3
\end{matrix}\right)
=\left(\begin{matrix}
0 \\ 0 \\ 0
\end{matrix}\right)$$
That is, $x_3$ is arbitrary, then $x_2=x_3$ from the second equation, and finally $x_1=-\frac13(4x_3-7x_2)=x_3$.
Therefore, $(1,1,1)^T$ is an eigenvector of $A$ for the eigenvalue $1$.
When solving such system, if the eigenvalue is correct, you know for sure there is at least one arbitrary component. There are more if the eigenspace has dimension greater than $1$.
Comment: @coders Yes, the eigenvector is a column vector, so it's the transpose of a row vector. This is a usual trick to save some vertical space.
Comment: There are then two non-collinear eigenvectors - that is, the eigenspace has dimension two. Then there are two arbitrary parameters, $x_2$ and $x_3$, and two possible eigenvectors would be $(1,0,1)^T$ and $(1,1,0)^T$ (set $x_2=0, x_3=1$ for the first, and $x_2=1,x_3=0$ for the second). Of course, there are infinitely many pairs of eigenvectors, actually any two noncollinear vectors in the plane defined by the above two.
Comment: @coders The sum of the multiplicities must be the dimension of the space. Here it's 3, and there are three distinct eigenvalues, so each has multiplicity 1, and there will be one parameter for each system. However, bear in mind than even when there is an eigenvalue with multiplicity $k>1$, the eigenspace has dimension **at most** $k$. It can happen that it's actually less.
Comment: @coders For instance, take any upper triangular $n\times n$ matrix $A$ with only ones on the diagonal, such that $A\neq I_n$. It has then only one eigenvalue (it's $1$), with multiplicity $n$. However, its associated eigenspace can't have dimension $n$. If it where so, there would be a matrix $P$ of eigenvectors (the columns of $P$), and $P$ would be invertible, with $A=PDP^{-1}$. But since $D=I_n$, you would have $A=I_n$. Contradiction. Hence the eigenspace has dimension $<n$ and $A$ is not diagonalizable.
Comment: When you write $(1,1,1)^T$, what does the $T$ stand for? The only examples where I have seen the notation $T$ is when speaking about the transpose.
Comment: Yes that is clever. Say the $3*3$ matrix has only 0's on the bottom 2 rows. and the top row is `|-1 1 1|`, thus $x_1 = x_2 + x_3$. How would you express this in vector form?
Comment: That makes things very clear, I think I can also deduce that the eigenvalue in $A - 4*I$ (different matrix to above question) which I was working with has multiplicity 2? Thanks for all the help!

Confusion determining eigenvalues


scp between US and India: how to improve throughput?

Question: I have two ubuntu boxes one in US and another in India and have a 12 Mbps connection. when i copy from using scp the transfer rate is 50KB/s is there a way to increase the speed. these boxes have 4GB ram and a good processor
Comment: You have a 12Mbps private connection end to end? If so, what is the latency across it? You are going to suffer with the bandwidth delay product (Elephant network) here
Comment: Is your connection via cable or satellite? Can you add a `traceroute -n`, may be shortened ip-addresses?
Answer: Your problem here is not with the bandwidth, but latency.
The TCP overhead on such a link will cause all sorts of link speed troubles, which you're experiencing. TCP and by proxy SCP/SSH was never meant to work on this kind of link fast, as it's upmost priority is security and reliability of the transfer stream.
There are multiple solutions to the issue.

Switch from TCP to UDP, UFTP is specifically designed to solve this problem, I've used it extensively over satellite links, which are almost comparable to your setup in latency. It also supports key based encryption for the streams which is managed by a tool that comes with the package

You need to install the client daemon on all the hosts you'd like to push data to (it can use multicast, hence you can push a file to multiple endpoints at the same time as well, as long as the network supports it).
With the server tool, you specify what you want to put where on which remote machines

Switch to HPN-SSH, this has very different buffer parameters and tuning for high speed transfers, if you must stick with ssh for some reason, but most probably will not fix your problem.
Comment: Hi Thanks for the info can you please send me some info on how to shift from TCP to UDP for SSH.
Comment: @kumar I've updated the answer with a basic explanation. The logic is a bit backwards, due to the multicast nature (the clients are persistent daemons, and the server is a simple process), but I think it's pretty straight forward. The manpages have examples at the bottom.


Generate Random Joint from Known Marginals

Question: I hope you are doing well. I've got a question.
My ultimate goal is to model an arbitrary language based on a pre-defined set of marginals and joints.
Let us assume I want to model language for words $a...d$ and I have known marginals $p(a)$ to $p(d)$. We also know that $p(a)>p(b)>...$ and so on (Zipfs Law).
1) I want to generate a symmetric random joint probability matrix $p(a,b)$ with zero diagonal based on the marginals:
<code>    N=4
    p_of_w = [ 0.48,  0.24,  0.16,  0.12]

    p_of_w_rev = list(reversed(p_of_w)) #Reverse ordered marginals

    jpm = np.zeros([N,N]) # Zero joint prob mat

    for i in range(N-1):
       p_vector = np.random.dirichlet(np.ones(N-i-1)) * (p_of_w_rev[i] - np.sum(jpm[i]))
       p_vector = np.insert(p_vector, 0,0)
       jpm[i,i:N] = jpm[i:N,i] = p_vector
</code>
The np.sum(jpm[:,i]) and np.sum(jpm[i]) are all equal to the corresponding marginals, except for the last one. There's something wrong with my reasoning, however I am somewhat stuck.
2) Is there a more elegant solution to this problem?
3) Let us assume I want to introduce some sparsity in the joint which is inversely proportional to the corresponding marginal $p(a)$. I.e. higher: marginal, less probability of sparse entries in the corresponding row of the joint. Can you think of a solution?
Thank you for your time.
Answer: Ok, so its technically possible under the relaxation that jmp[0,0] and jmp[-1,-1] are allowed to be nonzero.
<code>    p_of_w_rev = list(reversed(p_of_w))
    jpm = np.zeros([N,N])

    for i in range(N):
       if i > 0 and i != N-1:
       p_vector = np.random.dirichlet(np.ones(N-i-1)) * (p_of_w_rev[i] - np.sum(jpm[i]))
       p_vector = np.insert(p_vector, 0,0)
       jpm[i,i:N] = jpm[i:N,i] = p_vector
    elif i == 0:
       p_vector = np.random.dirichlet(np.ones(N-i)) * (p_of_w_rev[i] - np.sum(jpm[i]))
       jpm[i,i:N] = jpm[i:N,i] = p_vector
    elif i == N-1:
       jpm[i,i] = p_of_w_rev[i] - np.sum(jpm[i])
</code>


hotel price comparison logic using wordpress posts

Question: Consider a situation, I've post meta fields:

Min_Price
Max_Price

So every post has these two fields, and value can be any integer from non zero to 1000.
Lets take an example:

post #1 min_price = 5; max_price = 100
post #2 min_price = 50; max_price = 150

I'd like to make custom order logics to use with query_posts. So users can select price ranges and see posts with selected values.
Now if I had only 1 price and 1 field, it would be easy to let users select price range and get posts which fall into these range, like so:
query_posts( array(
    'post_type' => 'product',
    'meta_query' => array(
        array(
            'key' => 'price',
            'value' => array( 100, 200 ),
            'compare' => 'BETWEEN',
            'type' => 'numeric',
        )
    )
) );

So here every post with price between 100-200 would be visible.
But I have a range of values... and I thought this would work:
query_posts( array(
    'post_type' => 'product',
    'meta_query' => array(
        array(
            'key' => 'min_price',
            'value' => array( 100, 200 ),
            'compare' => 'BETWEEN',
            'type' => 'numeric',
        ),
            array(
            'key' => 'max_price',
            'value' => array( 100, 200 ),
            'compare' => 'BETWEEN',
            'type' => 'numeric',
        )
    )
) );

Here client selected range 100<->200
Both post #1 and post #2 have values that fall in this range, so visitor will be interested in both of them. Unfortunately my query logic excludes them.
My brain is not working well right now, so I'm missing something simple. Any hints?
Answer: I now know your way should work, except McNab is probably right (there are plenty of examples right here: http://codex.wordpress.org/Class_Reference/WP_Query#Custom_Field_Parameters) but I'll let my old answer remain. Someone might find it useful for non-standard stuff.
I don't know if you can do this using query post parameters, but I looked it up in the source code and this is how the query looks:
SELECT $found_rows $distinct $fields
FROM $wpdb->posts $join
WHERE 1=1 $where
$groupby
$orderby
$limits

And these are filters corresponding to the relevant query variables:
$where = apply_filters_ref_array('posts_where', array( $where, &$this ) );
$join = apply_filters_ref_array('posts_join', array( $join, &$this ) );

So that means that the problem can be reduced to SQL:
function postmeta_join( $join )
{
    $join .= "
    LEFT JOIN $wpdb->postmeta AS max_price ON max_price.meta_key = 'max_price'
    LEFT JOIN $wpdb->postmeta AS min_price ON min_price.meta_key = 'min_price'";
    return $join;
}

function filter_prices($where)
{
    $where .= " AND max_price.max_price BETWEEN 100, 200 AND min_price.min_price BETWEN 100, 200";
    return $where;
}

add_filter( 'posts_where', 'filter_prices' );
add_filter( 'posts_join', 'postmeta_join' );

Now I'm not an SQL expert so there may be problems with this. But if you don't get any other answer, you could play with this. (And BTW, you probably want to remove the filters when you're done with them.)
Comment: It is really useful to have the this info IMO, I had a heck of a time debugging a big meta_query issue recently and I think it's very useful to relate it to the SQL it's generating.  I had a couple of thoughts and will update my answer too.
Answer: What you've done should work but you've missed the 'relation' parameter.  It should be;
                'meta_query' => array(
                    'relation' => 'AND',
                    array(
                        'key' => 'min_price',
                        'value' => array( 100, 200 ),
                        'compare' => 'BETWEEN',
                        'type' => 'numeric',
                    ),
                        array(
                        'key' => 'max_price',
                        'value' => array( 100, 200 ),
                        'compare' => 'BETWEEN',
                        'type' => 'numeric',
                    )
                )

The other thing to note is that in the first instance the meta_id is 'price' and in the second you are using 'min_price' and 'max_price'.  Have these definitely been set?
I'm mentioning this because recently I had a hard time on these meta_queries with multiple sub-arrays and the AND relation where the values had been submitted by the user in a form (exactly like my understanding of your question).  There was an issue where the query didn't work where there are null values for items in the array.  This is meant to be fixed by scribu;
http://core.trac.wordpress.org/ticket/18158
But I could not get this to work at all. Tearing my hair out. I ended up checking the submitted value to see if there was one and then creating the arrays individually.  The query would work if either $min_array or $max_array was NULL, but not at all if either of the meta_values was NULL and it was built the way you are doing it. I hope this makes sense, my code is below;
                if ($min_price) {
                  $min_array = array('key' => 'min_price','value' => $min_price, 'value' => '=', 'type' => 'numeric');
                }

                if ($max_price) {
                  $max_array = array('key' => 'max_price','value' => $max_price, 'value' => '=', 'type' => 'numeric');
                }

                'meta_query' => array(
                    'relation' => 'AND',
                    $min_array,
                    $max_array
                )


Ao carregar (entrar) em uma página mover a barra de rolagem automaticamente até um elemento específico, sem clicar em nada

Question: Já consegui fazer clicando em algum link etc, mas gostaria que ao entrar numa página a barra de rolagem vertical do navegador descesse até um elemento específico, sem precisar clicar em nada.
Comment: sem efeito de rolagem, pode fazer assim tb http://pt.stackoverflow.com/questions/82850/carregar-p%c3%a1gina-e-rolar-automaticamente-para-um-determinado-elemento
Answer: Bem simples, aqui vai:
<code>$(document).ready(function () { //Função para que o script comece quando a página carregar
    $('html, body').animate({
        scrollTop: $('DIV PARA QUAL A PÁGINA IRÁ').offset().top
    }, 'slow');
});
</code>
Código tirado do https://stackoverflow.com/questions/18103534/scroll-to-specific-div-on-page-load
Comment: @user49454, quando uma resposta funcionar-lhe perfeitamente, você pode favoritá-la, assim saberão que seu problema está resolvido. :)
Comment: exato, funcionou perfeitamente. obrigado.
Comment: como se faz para favoritar uma resposta?


MS Access - Parameters from report in VBA

Question: If you open a report based on a query with some parameters (e.g. StartDate and EndDate), I know that I can used those parameters in the report as [Reports]![ReportName]![StartDate]. But now I would like to use these parameters in a VBA function, but using the same expression doesn't work for me:
MsgBox [Reports]![Test]![StartDate]

This gives me the error:

Run-time error '2465': Microsoft Access can't find the field
  'StartDate' referred to in your expression.
Answer: And it never will find it.
I never use dynamic parameterized queries. I use controls on a form to select filter criteria and refer to the controls in the WHERE argument of OpenReport command (same for OpenForm).
DoCmd.OpenReport "Test", , , "[StartDate] = #" & Me.tbxStart & "#"
MsgBox = Me.tbxStart
Or if you really prefer dynamic parameters - the report query parameters can refer to the form controls.
VBA code will not find the parameter but it can find textbox in report that references the parameter and pull the parameter value that way.
Comment: Thanks you very much! But the queries are already written that way, so I actually need to use dynamic parameters. Do you know how I can use this parameter in the Report_Load() event?
Answer: If you have a report or form that has a query as its Record Source, you can bind the fields of the query--like StartDate--to controls on the report or form, and get the value(s) of that field in a VBA function by referencing the control. For instance, suppose you have a report named DateReport. If the Record Source of DateReport contains a StartDate field, then you can create a text box on the report--we'll call it StartDateBox--and set its Control Source to "StartDate". Then in VBA, you can get the value of this field for the current record with Report_DateReport.StartDateBox. There may be another way to reference Record Source field values of a form or report without binding them to an control, but I don't have MS Access available right now to test this.
Answer: You can do it by using a public variable and changing  sql of record source dynamically.
You can store parameter value in public variable before calling the report.
First declare a varaible in a module
eg, Public filtDate as Date
Secondly, assign the parameter value to filtDate before running the report
Then, change sql of records source in the report_open event of report
Private Sub Report_Open(Cancel As Integer)
Me.RecordSource = "SELECT * FROM Test WHERE [StartDate] = #" & filtDate & "#"
MsgBox  filtDate
End Sub

Here, the sql of recordsource is dynamically set  and parameter value can be used directly.


Docs for sympy symbol naming conventions for special rendering?

Question: Is there any documentation that lists the predefined symbol names (or spelling conventions) that sympy renders as specialized math symbols?  For instance, I found the ones shown below by trial and error.

I've tried Google searches and searches within the sympy docs and source code without finding anything other than a listing of greek letter names.
I'm using sympy 0.7.6 (in ipython notebook 2.3).
Comment: I believe your are seeing LaTeX rendering of the symbol...so whatever LaTeX understands is what you will see, e.g. the name `x_1` will create an x with a subscript 1.
Comment: @smichr Thanks, it looks like the general rule is to omit the LaTex '\' when applying accents to symbols, e.g. 'vdot' instead of 'v\dot', and to keep the the '\' for non-alphanumerics.  Hopefully someone very familiar with sympy will post an answer that clarifies the rules exactly.
Answer: This code file contains the items that are identified as LaTeX entities.
Comment: Accepted and thanks! Note that it's necessary to follow an outdated link to mathjax.org in a comment in the source code to see the full list of supported LaTeX symbols.   The currently equivalent link is http://docs.mathjax.org/en/latest/tex.html?highlight=latex#supported-latex-commands
Comment: This link is now broken


What exactly are complex sounds in terms of audio waves?

Question: If you listen to a song through headphones you have a "right" sound wave and a "left" sound wave, correct?
But these waves have a lot of complex sounds combined in them and a digital sound wave is really just a series of sampled points anyway.
Questions:
Are sound waves really just single streams of audio that shift extremely quickly?
If you have a variety of instruments in a mix would the wave sampled at any one point just be a single sound?
Comment: You are right that digital sound waves are made up of a series of sampled values, so it is [not a continuous wave](http://www.centerpointaudio.com/Images/Analog-Digital%20frequency%20examples.png) the same way an analog wave is. But once they reach your speakers/headphones the signals (one for left, one for right channel) have been converted back to analog, and will look more like the waves in JCPedroza's excellent answer.
Comment: To be precise, the wave sampled at any one point would just be a single *number*. Sound consists of air pressure going up and down in certain patterns, tens or hundreds or thousands of times per second. Any piece of digital audio is simply a sequence of numbers, each representing the air pressure at one point in time. When you mix two audio signals together, you're just adding the numbers.
Answer: What you see and hear in the final waveform is the sum of all the instruments, the sum of all the individual sources.
All those sounds can be encoded in a single waveform. In the case of your first example (stereo sound) you have two channels (two waveforms, two signals) instead of one.
In other words, yes, it is a single sound (or two sounds in the case of stereo). It isn't different to what happens when you hear a sound live. Your ears pick up the sum of all the sounds in the room at that particular time and position. The same sum is taking place acoustically in the room and digitally or electronically in a waveform.
A 20Hz tone

and a 200Hz tone

can be summed into this single waveform:

This interaction can be destructive too.
Any waveform

summed with an identical waveform, but with inverted phase

will cancel each other out.

The same is happening in more musical scenarios, in everyday songs.
Kick

snare

and bass line

can be all summed into one single waveform.
Comment: To complement Teental's great answer, if you want to break the complex waveforms back apart into their component sine waves then study the mathematics topic of Fourier Analysis. This is both very interesting theoretically and of great practical importance. Saying much more would be way off topic in a music group. The Wikipedia page is quite good but jumps quite quickly into fairly advanced maths. [Fourier Analysis at Wikipedia](https://en.wikipedia.org/wiki/Fourier_analysis)
Comment: Could you please suggest some book to read more about it in terms of math from beginning?
Answer: Any sound may be modeled as a combination of sinusoidal waveforms at different frequencies; in many cases, if a sound contains multiple frequencies which are all multiples or near-multiples of a common "fundamental" frequency, the union of those sounds will be perceived as one sound whose frequency is that of the fundamental, and whose "character" is determined by the frequency and amplitude ratios involved.  Note that in some cases a listener will perceive the fundamental frequency even if no sound of that frequency is present.  For example, a combination of 300Hz, 500Hz, and 700Hz would generally be perceived not as a collection of tones, but as a single 100Hz tone.  Adding content at 200Hz, 600Hz, 900Hz, or other multiples of 100Hz wouldn't change the perceived pitch of the sound, but would likely make it sound "edgier".
Note that sound reproduction is seldom perfect; when vibrations in the air are converted to electrical signals or vice versa, or when electrical signals or vibrations are "moved around", there are four general kinds of things that can happen:

Simple linear scaling simply multiples the amplitude of all frequency content by a constant amount.
Other linear effects modify the signal in such a way that applying the linear effect to the combination of two signals would yield the same result as applying the effect to each signal individually and combining the result.  Note that linear effects can be (and often are) affected by what the signal has been doing in the past.  Consider, for example, a simple echo effect that adds to a signal 50% of the same signal, delayed by 0.001 second.  Such an effect would boost by 50% the amplitude of any multiple of any frequency that was a multiple of 1000Hz (since the delayed signal would be in-phase with the non-delayed one) but cut by 50% the amplitude of any signal that was an odd-numbered multiple of 500Hz (since the delayed signal would have its high-points at the same time as the non-delayed one had its low points).  Other frequencies would be boosted or reduced by differing amounts.  Linear processes will change the amplitudes and phase relationships of frequencies which are present in the original signal, but will not change the frequencies themselves.
Harmonic distortion modifies a signal in such a way that the resulting instantaneous amplitude at any moment in time will depend in some arbitrary way on the instantaneous amplitude of the original signal at that moment in time.  Unlike linear effects, the output of a harmonic distortion process does not depend in any way upon what the signal has done at any earlier moment in time.  Given a signal that contains some combination of frequencies, the result of a harmonic distortion process will contain only frequencies that can be expressed as the sum of arbitrary (positive or negative) integer multiples of signals which are present in the original.  If all frequencies which are present in the original are multiples of a common fundamental frequency, all frequencies which are present in the distorted signal will likewise be multiples of that frequency.
Effects that can neither be characterized as linear, nor as being purely time-independent harmonic distortion, can be thrown into an "everything else" category.  Passing a signal through multiple linear effects is equivalent to passing them through one potentially-more-complicated one; likewise passing a signal through multiple kinds of harmonic distortion effects will yield some form of harmonic distortion.  Combining effects, however, may yield results that cannot be simplified in such fashion.

Harmonic distortion effects can often be pleasing when all the frequencies in the original signal are multiples of a common fundamental; applying linear effects after such distortion may also yield a pleasant sound.  Adding distortion after many kinds of linear effects, however, will frequently yield rather unpleasant sounds, since different frequencies will end up having distortion applied to them in different ways.
Comment: I object a bit to saying "perceive the fundamental frequency even if no sound of that frequency is present". A combination of 300 Hz, 500 Hz and 700 Hz sinusoidals _has_ 100 Hz as its fundamental frequency: the oscillation repeats every 10 milliseconds, the inverse of that time is _by definition_ the frequency! It just so happens that 100 Hz is not contained in the signal's Fourier spectrum. But Fourier transform, though it's an extremely useful tool and the ear does something rather similar, is ultimately just an arbitrary basis switch.
Comment: @leftaroundabout - a very interesting point. hadn't thought of things in that way before.


centralizer of a chief factor

Question: Let $G$ be a finite solvable group and $p$ be a prime. Let $G^*$ be the smallest normal subgroup of $G$ for which the corresponding factor is abelian of exponent dividing $p-1$. Show that every chief factor of order $p$ is central in $G^*$.
Comment: Almost every theorem is a part of an article.
Comment: It's part of an article... .
Comment: Do you understand why $G^*$ is well-defined?
Comment: @DerekHolt: The OP assumes there exists such smallest normal subgroup. So by well-defined do you mean there is always one?
Comment: @user795571 I don't see that assumption stated anywhere. Strictly speaking, you should not write "Let $x$ be the object with property $P$" without first proving that there is a unique $x$ with property $P$. But in fact any group does have a smallest (wrt inclusion) normal subgroup with the property in question.
Answer: If $H/K$ is a chief factor of order $p$, then $G/C_G(H/K)$ is isomorphic to a subgroup of ${\rm Aut}(C_p)$, which is abelian of order $p-1$, so this quotient of $G$ is abelian of exponent dividing $p-1$. Hence $G^* \le C_G(H/K)$, QED.

centralizer of a chief factor


Is divisi notation needed for brass or woodwind in an orchestra?

Question: I'm composing for orchestra.
I've read that divisions [of parts] should be notated using divisi. (or div.) above the staff. But I'm wondering whether this notation is mandatory for all instruments.
I can see why the notation is needed for strings to clear ambiguity against double-stopping but is there any rule regarding brass and woodwind instruments? Could the division be implied without the use of divisi notation?
(As far as I know, brass and woodwind instruments can't double-stop so divisions can't be ambiguous, but some affirmation would be nice.)
Answer: First, be aware that there's often a difference between the conductor's score and the individual parts. To save space and make it easier to navigate, a score often has multiple parts condensed onto one staff, even if the result would be horribly complex to decipher while playing.
The individual parts can be written either combined or separate, depending on what makes more sense. If the parts generally move in the same rhythm and don't cross, then it's not a problem to combine them. Or if there's tricky interplay between the parts, it may be beneficial to combine them on the page. But if the parts are very independent, then they should be separated.
So the roundabout answer to your question is that the parts should be written in a way that such markings aren't needed. Obviously, a wind instrument can only play one note at a time (in general, yes I know about multiphonics), so if there are two notes they will divide. But if you are trying to write a combined part and find yourself needing to write a bunch of unison/1st only/2nd only instructions, then that's a sign that you should be writing two separate parts.
Comment: Right, one of my concerns was in the score's spacing and layout. And true, most of the divisions in my parts are homophonic, so your points do illuminate my situation a bit more. Thanks! (Also, I didn't know about multiphonics! :P)
Answer: The usual situation, if there is more than one part for the same instrument in a piece, is that the instruments do not play the same note.  Such parts can be, and usually are, notated on the same staff in an orchestral score.  Each such staff can be extracted into a single part or into multiple parts, as described by MattPutnam.  Having a separate part for each player is the norm, as noted by Michael Seifert in a comment.
Since it's common for a single staff to carry two parts, it is not customary to write divisi on the staff when there is more than one line of notes.  Instead, the composer or copyist must indicate what to do in the opposite case, when there's only a single line of notes.
If the single line of notes is supposed to be played by more than one part, the usual marking is not unison, but a due or, for a staff carrying three parts, a tre.  This is frequently written as a 2 or a 3.  An example may be found in the German Requiem of Johannes Brahms, in the bassoons, in the second movement, at measure 1 (I'm looking at the Dover reprint of the Breitkopf and Härtel complete works).
If there is a single note that only one part should play, the marking is primo or secondo, often written as 1º, Iº, 1., or I. and 2º, IIº, 2., or II., using Italian or German conventions for writing ordinal numbers.  An example may be found in the Brahms, in the first movement, at measure 45, in the trombones.  Another possibility is to write a rest under the note, if the note is for the first player, or above it, if the note is for the second player.  An example of this is seen in the second movement at measures 33 and 34, in the oboes and bassoons.
If the parts combine for just a few notes, the convention is to write each note with both upward and downward pointing stems.  This can be seen in the second movement of the Brahms, in the bassoons, from measure 13 through measure 22.  For notes that have no stem, the convention is to write two notes side by side.  This can be seen in the last measure of the same movement, on the third-trombone-and-tuba staff.
Finally, to underscore the fact that there is no need to mark divisi explicitly, look again at the beginning of the same movement, where the bassoons are a due.  On the third beat of measure 12, they divide without comment, and on the downbeat of the next measure, where they are again in unison, the note has two stems.  The parts remain divided until measure 42, where the staff is marked a 2.
I will close with an endorsement of Carl Witthoft's answer, which applies in the context of writing for wind and brass sections as is perhaps more common for bands.  The assumption in orchestral writing is that each woodwind and brass part is assigned to a single player.  There are certainly cases in which orchestral wind and brass parts have been doubled, such as at the premiere of Beethoven's ninth symphony.  In such a case it would be for the conductor to decide whether any passage should be played by the entire section or as a solo.  A composer could explicitly call for multiple-player sections in an orchestral piece, and then markings like solo, tutti, divisi, and unison would be useful, but that is not the convention.
Comment: Speaking as an orchestral brass player, I can confirm that parts where two lines are written on the same staff are relatively rare, and that I groan internally when I do encounter one.  I *much* prefer having my own part if at all possible.
Comment: @MichaelSeifert indeed.  But it's by far the usual situation in scores to have multiple parts on each staff.  It's usually two parts per staff, but the first movement of the Brahms has a single staff for three trombones (there is no tuba in that movement).
Comment: I'm already doing *1.* and *a2* in places; but your answer provides me more ground to move on. Thanks for the comprehensive and clearly-structured answer. :-)
Answer: It never hurts to be clear even if mildly redundant.  Consider one possibility: you write two parts for a wind section and mark (intentionally) the upper line as "solo," to be played by one person with the remainder of the section playing the other line (this makes more sense in a wind ensemble/concert band than an orchestra).  The solo ends; everyone plays the single line; then later on you want a divisi. If you don't indicate, they might think it's another solo line.
Comment: This is an good consideration to have in mind even though it caters to solos and ensembles. Thanks all the same! :-)


Normal Mixer vs Joyo RockHouse/JamHub

Question: I have an instrumental trio with E-Drum, guitar and bass.
Due to the fact that I have some neighbors near to my house, we are forced to make a silent rehearsal. Next Saturday will be our first attempt.
I have a TASCAM US-16X8 audio interface which I think is big enough in terms of input, but I'm wondering if I would be able to send a unique stereo mix to 3 of those 8 output channels. It's probably is possible, but I don't know.
I have seen that most people that perform silent rehearsals choose to buy a dedicated component like Joyo Rockhouse or JamHub, but by being in Argentina, these two products are not available to me.
However, I am wondering what's the difference between theses devices and other mixers out there; can I buy a normal mixer such as a Behringer Xenyx or something similar in order to be able to hear a custom mix in the best of the cases? Is there any budget friendly option to solve my problem?
Sorry, I'm a bit lost with these kind of configurations that's why I'm asking.
Comment: Yeah, the JamHub was really neat for these situations. Too bad it isn't made anymore!
Comment: With only three instruments, it really shouldn't be necessary to need three different mixes. Especially for rehearsals. We should all be capable of playing with two others and producing a decent mix between them all.
Answer: Well, for a start you'll have to send your 3 stereo mixes to SIX of those output channels, configured as three stereo pairs.
I don't think the supplied Settings Panel software is powerful enough to do what you want by itself.   But software like the Control Room feature in Cubase will be able to.
You'll need some headphone amplifiers too.
But why do you need three different mixes?  Take the single headphone output of the US-16X8 into a simple headphone amplifier with at least three outputs. Choose one with a volume control for each output.   A 'more me' mix doesn't really help anyone play more musically.
Comment: A regular mixer supplies ONE stereo headphone output (and so does your US-16X8).   Additional monitor mixes will be Line level and require a headphone amplifier.   This has nothing to do with phantom power, which is a microphone thing.  I've expanded my answer.
Comment: Thanks for your answer Laurence. Do you think that a regular mixer provides power for headphones? One of the ones that I have is 80 ohms, so I guess that I would need some phantom power, is that correct?
Comment: The need of different mixes comes by thinking that probably each one wants to hear more presence of its own instrument, but it would be in the best of the cases, I'm fine with the same one for the three of us.

Normal Mixer vs Joyo RockHouse/JamHub


Erro ao carregar arquivo com File Editor

Question: Estou tentando fazer um editor de html, mas não estou conseguindo ler o arquivo no editor utilizando JavaScript.
 var loadFile = function(name) {
        fileSystem.root.getFile(name, {}, function(fileEntry) {
          currentFile = fileEntry;
          fileEntry.file(function(file) {
            var reader = new FileReader();
            reader.onloadend = function(e) {
              updateVisualEditor(this.result);
            }
          }, fsError);
        }, fsError);
      };

Comment: Seria interessante adicionar detalhes do erro.
Comment: Não aparece erro nenhum , só não o a nova aba abre em branco
Answer: Acredito que o que falta é você ler o arquivo.
Introduza a seguinte linha no seu código e faça o teste.

reader.readAsText(file);

 var loadFile = function(name) {
        fileSystem.root.getFile(name, {}, function(fileEntry) {
          currentFile = fileEntry;
          fileEntry.file(function(file) {
            var reader = new FileReader();
            reader.onloadend = function(e) {
              updateVisualEditor(this.result);
            }
            reader.readAsText(file);
          }, fsError);
        }, fsError);
      };


Cpp input until ctrl+d

Question: How to pass last four values from entry into function distance as arguments?
For example if I enter values
2 6
1 2
4 8
I want the compiler to pick up last four values 1,2,4 and 8 and print (1,2) (4,8) =6.7
How to pick them up from buffer?
Thanks
<code>#include <iostream>
#include <cmath>
#include <string>

struct point{

  int x1,x2;
  int y1,y2;

};

double distance(int x1,int y1,int x2,int y2){

  double d=sqrt(pow((x1-x2),2)+pow((y1-y2),2));

   return (int)(d*10.0)/10.0;

}

int main(){

point a;

while(std::cin>>a.x1>>a.y1>>a.x2>>a.y2){

std::cout<<"Distance: "<< distance(a.x1,a.y1,a.x2,a.y2);

}
return 0;
}

</code>
Comment: Do you mean that you want to discard all input except the last 4 ints, or do you mean that you want to skip 2 and read the third thru sixth?  Either way, just write a loop to discard the desired data.  The first case is slightly more difficult; you'll need to store some elements.
Comment: FYI, prefer multiplication, `x * x`, to `pow(x,2)`.  The `pow` function is for floating point and may introduce errors when converting from or to integer.  Also, `x * x` and usually be performed by a couple of instruction.  The `pow` function requires setup instructions, call instructions, content instruction, and the return instructions.  Usually a lot more than a multiply.
Comment: Also, in most geometry and programming terms, a Point is usually `` (for 2d Cartesion system).  A `Line` consists of 2 points; so you should name your structure as a `Line` and not a `point`.
Answer: Try reading the first row and ignoring it:
<code>std::string text_to_ignore;
std::getline(std::cin, text_to_ignore);
std::cin >> a.x1 >> a.y1 >> a.x2 >> a.y2;
</code>
Comment: In order to ignore a single line, it would probably be more efficient to call `std::cin.ignore( std::numeric_limits::max(), '\n' )`. However, this would require an additional header file to be included (`#include `).

Cpp input until ctrl+d


cost minimization knowing the cost of labor and capital

Question: The production function is $f(L,M)=4L^{0.5}M^{0.5}$
, where
L
 is the number of
units of labor and
M
 is the number of machines used
. If the cost of labor is \$100 per unit and the cost
of machines is \$16 per unit, then the total cost of producing 7
 units of output will be:
a.  \$140.
b.  \$406.
c.  \$112.
d.  \$280.
e. \$ None of the above.
The answer is a). Why is that? I am not able to come up with any explanation it is not simply isoquant slope equal isocost  slope, thus how to solve this question?
Answer: You need to produce seven units of output, therefore: $7 = 4L^{0.5}M^{0.5}$. Squaring, you find that are restricting yourself to the curve $LM = 49/16$ in the first quadrant as $L,M>0$.
The cost function is $C(L,M) = 100L + 16M$. You want to minimize this subject to the constraint $LM = 49/16$. We can do this more generally, but in this case, it is simple enough to solve $L = \frac{49}{16M}$ and so
$$ C = 100\frac{49}{16M} + 16M. $$
Now we have a function defined on $(0,\infty)$. Notice that $\lim_{M\to 0}C = \lim_{M\to\infty}C = \infty$, so the function has a global minimum. As it is differentiable, that global minimum will be at a critical point. So find the critical points of $C$ (i.e., solve $C' = 0$) and figure out which has the lowest value of $C$.

If you take a step back, notice that by the multivariable chain rule, denoting a derivative by subscripting and using the implicit function theorem, finding critical points involves solving the equation
$$ C'(L(M),M) = C_L(L,M)L_M + C_M(L,M) = 0 $$
Note that $-C_M/C_L$ is the slope of the isocost curve.
What is $L_M$? This is defined implicitly: $\frac{\partial}{\partial M}f(L(M),M) = f_L(L(M),M)L_M + f_M(L(M),M)$ so $L_M = -f_M/f_L$. This is the slope of the isoquant curve.
Solving, the, we have $L_M = -C_M/C_L$. In other words, the condition that $C' = 0$ boils down to "the slope of the isocost curve equals the slope of the isoquant curve."


Styling submit button 'error'?

Question: I am trying to style a submit button, but for some reason this is not working. I tried setting the height and it's not working. I got an example from W3 schools, styled it just the same and that's not working. Has anyone ever encountered a similar problem? Hopefully the following code is enough, but if it's not I can edit this post.
https://snag.gy/bpdTU8.jpg
Code:

 .mainBox {
 padding-top: 15px;
 margin: auto;
 background-color:#998200;
 width: 65%;
 color: black;

 }
input[type=submit] {
    width: 50%;
    height: 40px;
    background-color: orange;
    color: white;
    padding: 14px 20px;
    margin: 8px 0;
    border: none;
    border-radius: 4px;
    cursor: pointer;
}

<input type="submit" value="Submit">

Comment: try adding `display: block` inside of the css for the input.
Comment: It works! Thank you so much.
Comment: Well I guess there is just one big  problem. It alters all the previous positioning/aligning  for my form elements. Not to sure how to restore that.
Comment: could you please show any other code that it might be affecting so that I may update my answer? thanks :) also, if this helped you, please consider selecting my answer as correct. :)
Comment: @Shinji-san please let me know what you wan't exactly.
Comment: Sure thing. I add a  after each input element, in case you need that info. Here's the rest of the CSS code, please let me know if you need the HTML. I just don't want to have to do all the editing if I don't need it.

https://jsfiddle.net/f0sLzx8m/
Comment: @CaelanGrgurovic Ok sure I will edit this post along with the full JS fiddle of what I'm after.
Comment: @Shinji-san look at the edit for my answer! no need for a jsfiddle now :)
Answer: Inside of the input CSS, try adding display: block;. Like so:
input[type=submit] {
    display: block;
    width: 50%;
    height: 40px;
    background-color: orange;
    color: white;
    padding: 14px 20px;
    margin: 8px 0;
    border: none;
    border-radius: 4px;
    cursor: pointer;
}

EDIT:
change display: block to display: inline-block
Hope this helps! :)
Comment: For some reason display: block alters the whole layout though. I used to have all my input headers to the left of the box, but now every other input header is to above and to the right of the text fields. Would you know how to fix that issue?
Comment: @Shinji-san no problem! have fun with building your website :) p.s: chuck us an upvote ;))
Comment: Oh I will, and you'll have fun too if you play YGO. How? O.O. Oh, I checked off your answer.

Styling submit button 'error'?


Halmos' Naive Set Theory Cardinal Arithmetic Exercise

Question: On page 95 of Halmos' Naive Set Theory, we get the exercise

If $\{a_i\}$ and $\{b_i\}$ are families of cardinal numbers such that $a_i< b_i$, then $$\sum_i a_i<\prod_ib_i$$

I know that we get $\le$ easily (one can create an injection from the LHS to RHS). The real task is to prove a bijection cannot happen. I tried doing a diagonalization argument like in Cantor's theorem, but it didn't pan out. The arbitrary index $I$ makes it tough to do something like that. Even if we replace it with an ordinal, because it could be uncountable.
I'm thinking maybe one must use transfinite induction on the ordinals (on the index)?
Any tips/solutions?
Comment: Do you mind elaborating on what the injection that we can get is? Thanks!
Answer: Before the proof, I notice that the sum $\sum_{i\in I} a_i$ is identified to the disjoint union $\bigcup_{i\in I} a_i\times\{i\}$ for convenience.
You can prove the inequality is strict by diagonal argument. Remember that $|A|\le |B|$ if and only if there is an injection from $A$ to $B$. If every function from $A$ to $B$ is not onto, then $|A|<|B|$. From this, we should prove: if $f:\sum_{i\in I} a_i \to \prod_{i\in I} b_i$ is an injective function then there is a function $c\in \prod_{i\in I} b_i$ which is not an element of the range of $f$ (so $f$ should not be an bijection.)
Consider $f\upharpoonright a_i$, function $f$ whose domain is restricted from $a_i$. Since $a_i<b_i$, the cardinality of the range of $f\upharpoonright a_i$ is less than $b_i$. Also, the range of $f\upharpoonright a_i$ consists of functions $x$ from $I$ with $x(i)\in b_i$ for all $i\in I$. From above facts we get
$$|\{x(i)\in b_i : x\in \text{range of }f\upharpoonright a_i\}|\le a_i<b_i$$
so we can choose $c_i\in b_i$, with $c_i\neq x(i)$ for all $x\in (\text{range of }f\upharpoonright a_i)$.
Let define $c\in\prod_{i\in I}b_i$ with $c(i)=c_i$. You can check that $c_i\in b_i$ for each $i$, and $c\neq f(x)$ for all $x\in \sum_i a_i$.
Comment: I like your answer. One question: given the collection of functions $\mathrm{ran}\left( f\upharpoonright (\{i\}\times a_i) \right)$, is there a way to "replace" each one with its value at $i$ without using the axiom of replacement? (I ask this because otherwise I must figure out as a lemma that replacement of sets can only decrease the cardinal number... I can see an injection argument, but I'm interested either way)
Comment: @AlbertoTakase I think about your answer but I don't understand it :( I do not know the reason - maybe my poor English is a reason why I don't comprehend your asking. Can you explain about your additional question?
Comment: http://math.stackexchange.com/questions/1175130/given-a-collection-of-functions-f-i-with-the-same-domain-how-to-replace-with I posted another question that asks this exact same question (more generally). I will also post how I found your solution helpful for others to see.
Answer: Thanks to tetori, I know how the diagonalization argument works. I'm posting the formal proof for others who may have this same question.

The trick is to project the collection of functions $\mathrm{ran} f\upharpoonright (\{i\}\times k_i)$ onto $i$ which (by the axiom of choice) has cardinal number less than or equal the collection.
Comment: How do you prove $\left| \bigcup_{i \in I} \{i\} \times I_i \right| \leq \left| \times_{i \in I} l_i \right|$?


Unir arrays por chaves iguais, mas separando valores

Question: Cenário (exemplo):
Tenho 2 Arrays, X e Y (criados dinamicamente, individuais):
$arX = Array('AAA' => 173.696, 'BBB' => 72.436, 'CCC' => 142.692);
$arY = Array('AAA' => 127, 'DDD' => 72.333);

Objetivo:
O que gostaria, é de uni-los pela chave, mas, separar os valores.
Exemplo do resultado esperado:
Array
    (
        [AAA] => Array
        (
            [X] => 173.696,
            [Y] => 127
        )
        [BBB] => Array
        (
            [X] => 72.436
        )
        [CCC] => Array
        (
            [X] => 142.692
        )
        [DDD] => Array
        (
            [Y] => 72.333
        )
    )

Dúvidas:

Existe uma função nativa para isso?
Como poderia obter o resultado?
Comment: Pergunta da hora +1. Ótimo desafio :p
Comment: Cara, tá osso pensar na pressa que eu estou. Depois dou uma resposta melhor.
Answer: Você pode usar a função array_walk para realizar o que necessita.
O ponto central, é referenciar no callback qual é o novo array que você irá criar ($newArray) e, como terceiro parâmetro de array_walk, o prefíxo da chave (que pode ser X, Y ou qualquer outra chave que quiser, caso houverem mais arrays).
$arX = Array('AAA' => 173.696, 'BBB' => 72.436, 'CCC' => 142.692);
$arY = Array('AAA' => 127, 'DDD' => 72.333);
$newArray = [];

$callback = function($value, $key , $prefix) use (&$newArray)
{
    //valida se a chave já existe no array
    if (!array_key_exists($key , $newArray))
    {
        $newArray[$key] = [];
    }

    // Adiciona o novo array ao já existente, utilizando o prefixo enviado via parâmetro.
    $newArray[$key] += [$prefix => $value];
};

//Cada array será processado individualmente e adicionado em $newArray
//que é referenciado no callback.
array_walk($arX , $callback , "X");
array_walk($arY , $callback , "Y");

Resultado:
array(4) {
  ["AAA"]=>
  array(2) {
    ["X"]=>
    float(173.696)
    ["Y"]=>
    int(127)
  }
  ["BBB"]=>
  array(1) {
    ["X"]=>
    float(72.436)
  }
  ["CCC"]=>
  array(1) {
    ["X"]=>
    float(142.692)
  }
  ["DDD"]=>
  array(1) {
    ["Y"]=>
    float(72.333)
  }
}

Código em funcionamento: https://3v4l.org/Xmlv4
Comment: `isset` pode falhar acaso o valor seja null.
Comment: @GuilhermeNascimento sim, mas, ai depende da necessidade do autor da pergunta. Alterei para array_key_exists
Answer: Eu tinha tentado dar uma resposta mais elaborada, usando funções sofisticadas de array, mas nada foi mais fácil que usar o próprio foreach.
Veja:
$result = [];

foreach ($arX as $key => $value)
{
    $result[$key]['X'] = $value;
}

foreach ($arY as $key => $value)
{
    $result[$key]['Y'] = $value;
}

var_dump($result);

Resultado:
[
 "AAA" => [
   "X" => 173.696,
   "Y" => 127,
 ],
 "BBB" => [
   "X" => 72.436,
 ],
 "CCC" => [
   "X" => 142.692,
 ],
 "DDD" => [
   "Y" => 72.333,
 ],
]

Se ainda quiser insistir no uso de funções para fazer isso, pode combinar o poder do array_merge_recursive com array_map.
veja:
$result = array_merge_recursive(
    array_map(function ($x) { return ['X' => $x]; }, $arX),
    array_map(function ($y) { return ['Y' => $y]; }, $arY)
);

Numa terceira opção, você poderia usar o operador + junto com array_keys para iterar com todas as keys dos seu array.
Veja:
$result = [];

foreach (array_keys($arX + $arY) as $key) {

    if (isset($arX[$key]))
        $result[$key]['X'] = $arX[$key];

    if (isset($arY[$key]))
        $result[$key]['Y'] = $arY[$key];
}

Comment: Gostei dessa última opção! Ficou bem limpa. Convém trocar o `isset` para `array_key_exists`?
Comment: @rbz depende, o único problema do `isset` nesse caso é que, se a chave existir, porém for `NULL`, ele retorna `FALSE`, mas acredito que pro seu caso não faça diferença.
Answer: Um unico foreach com array_key_exists já resolveria o problema, pois desta forma só vai iterar uma vez, exemplo com uma função (não precisa ser uma função se vai usar somente uma vez):
<?php

function mesclar(array $arrX, array $arrY)
{
    //Cria uma nova array
    $z = array();

    //Pega as chaves de ambas arrays
    $chaves = array_merge( array_keys($arrX), array_keys($arrY) );

    foreach ($chaves as $chave)
    {
        // A performance do `=== false` é minima ou nenhuma na maioria dos casos, mas se o array for gigante mesmo talvez isto torne o script razoavelmente mais performatico
        if (isset($z[$chave]) === false) {
            $z[$chave] = array();
        }

        //Copia o valor do primeiro array para X
        if (array_key_exists($chave, $arrX))
        {
            $z[$chave]['X'] = $arrX[ $chave ];
        }

        //Copia o valor do primeiro array para Y
        if (array_key_exists($chave, $arrY))
        {
            $z[$chave]['Y'] = $arrY[ $chave ];
        }
    }

    return $z;
}

$arX = array('AAA' => 173.696, 'BBB' => 72.436, 'CCC' => 142.692);
$arY = array('AAA' => 127, 'DDD' => 72.333);

$novaArray = mesclar($arX, $arY);

print_r( $novaArray );

Exemplo no IDEONE: https://ideone.com/3loYc9
Comment: @rbz `isset` e `array_keys_exists` são semelhante, mas não identicos, é como eu disse no começo, eu não tenho ideia de quantos valores teu array vai ter e nem muito menos se os valores serão sempre numeros, se ocorrer de aparecer um NULL no meio dos valores o `isset` iria ignorar a chave especifica, por isso eu fiz o script contra falhas em todos cenários possiveis (pois não tenho ideia da sua aplicação real) - Veja esta resposta: https://pt.stackoverflow.com/a/117504/3635
Comment: Não está trazendo o "DDD".
Comment: @rbz tem toda razão :/ vou revisar
Comment: @rbz revisado https://ideone.com/3loYc9
Comment: Não sei se muda algo, mas assim `if (array_key_exists($chave, $z))` funciona também. Melhoraria o "problema" que você disse "A performance do `=== false`......" ?
Comment: @rbz não tem porque checar nada no `$z`, ela é uma array totalmente nova que é criada depois de passado os valores. O `=== false` só terá diferença em arrays gigantes, geralmente mesmo em array gigantes o ganho é pouco, mas eu criei o script sem saber qual cenário vc vai precisar, ou seja um script que funciona bem para os grandes e pequenos processos.
Comment: Desculpa minha confusão... mas o `isset` não está checando se `$z` tem aquela chave, da mesma forma que o `array_key_exists`?


Select All Distinct Words in Column MYSQL

Question: I have a column in which is stored nothing but text separated by one space. There may be one to maybe 5 words in each field of the column. I need a query to return all the distinct words in that column.
Tried:
SELECT DISTINCT tags FROM documents ORDER BY tags

but does not work.
To Elaborate.
I have a column called tags. In it I may have the following entries:
Row 1 Red Green Blue Yellow
Row 2 Red Blue Orange
Row 3 Green Blue Brown

I want to select all the DISTINCT words in the entire column - all fields. It would return:
Red Green Blue Yellow Orange Brown

If I counted each it would return:
2 Red
2 Green
3 Blue
1 Yellow
1 Brown
1 Orange

Comment: *"does not work"* - Can you elaborate on that? What results are you getting now and what are the expected results? You also need to post the schema/values and relevance to php here. Edit: To which the php tag was removed in an edit. http://stackoverflow.com/revisions/43499498/2
Comment: If DISTINCT didn't work, try adding GROUP BY
Comment: If each tag was on its own row in another table this would be the simplest thing in the world ...
Comment: By selecting DISTINCT on the column MYSQL will only return the distinct string of words for each field in the column. Not the DISTINCT individual word.
Comment: First splt strings into rows: http://stackoverflow.com/questions/17942508/sql-split-values-to-multiple-rows then you can group by and get counts now that you have normalized data.
Answer: To fix this I ended up creating a second table where all keywords where inserted on their own row each along with a record key that tied them back to the original record in the main data table. I then just have to SELECT DISTINCT to get all tags or I can SELECT DISTINCT with a WHERE clause specifying the original record to get the tags associated with a unique record. Much easier.
Answer: There is not a good solution for this.  You can achieve this with JSON functions as of 5.6, I think, but it's a little tricky until 8.0, when mySQL added the JSON_TABLE function, which can convert json data to a table like object and perform selects on it, but how it will perform is dependent on your actual data.  Here's a working example:
CREATE TABLE t(raw varchar(100));
INSERT INTO t (raw) VALUES ('this is a test');

You will need to strip the symbols (commas, periods, maybe others) from your text, then replace any white text with ",", then wrap the whole thing in [" and "] to json format it.  I'm not going to give a full featured example, because you know better than I do what your data looks like, but something like this (in its simplest form):
SELECT CONCAT('["', REPLACE(raw, ' ', '","'), '"]') FROM t;

With JSON_TABLE, you can do something like this:
SELECT CONCAT('["', REPLACE(raw, ' ', '","'), '"]') INTO @delimited FROM t;

SELECT *
FROM JSON_TABLE(
    @delimited,
    "$[*]"
    COLUMNS(Value varchar(50) PATH "$")
) d;

See this fiddle: https://dbfiddle.uk/?rdbms=mysql_8.0&fiddle=7a86fcc77408ff5dfec7a805c6e4117a
At this point you have a table of the split words, and you can replace SELECT * with whatever counting query you want, probably SELECT Value, count(*) as vol.  You will also need to use group_concat to handle multiple rows.  Like this:
insert into t (raw) values ('this is also a test'), ('and you can test it');

select concat(
    '["',
    replace(group_concat(raw SEPARATOR '","'), ' ', '","'),
    '"]'
) into @delimited from t;

SELECT Value, count(*) as vol
FROM JSON_TABLE(
  @delimited,
  "$[*]"
  COLUMNS(Value varchar(50) PATH "$")
) d
GROUP BY Value ORDER BY count(*) DESC;

If you are running <8.0, you can still accomplish this, but it will take some hackiness, like generating an arbitrary list of numbers and constructing the paths dynamically from that.


Como obter o ID de um elemento dentro de um div?

Question: Tenho uma div e umas imagens, cada imagem representa um item em um array global. Quando eu arrasto esta imagem para a div de edição é habilitado um formulário de edição, caso contrário é habilitado um formulário para criar nova regra e gerar um nova imagem.
Eu preciso saber quando há uma imagem na div para habilitar o modo inclusão ou edição e para isto preciso saber o ID dela pois é o índice do array.
if(document.getElementById("manage").innerHTML == ""){
    console.log("vazio");
else{
    var id = document.getElementById("manage").innerHTML;
    console.log(id.attr("id"));
}

Como "id" é uma string com o conteúdo:
img id="ico-3" class="img-drag" src="images/isp.jpg" draggable="true" ondragstart="drag(event)"

Neste exemplo de IMG, o índice no array é 3.
Comment: Saber o ID é o menor dos seus problemas, até porque o programa já consegue recuperar o ID pelo código que você deixou aqui. O `console.log(id.attr('id'))` recupera o ID da imagem e o mostra no console, assim é só pegar o valor do ID e formatar do jeito que quiser, como um charAt().
Comment: então eu esperava algo como isto que coloquei no log(attr), mais genérico e sem ficar percorrendo a String mas… Vlw pela ajuda.
Comment: Pode postar a estrutura do seu HTML? Esse código que você escreveu não deveria funcionar, pois o `innerHTML` deveria retornar uma string, e como você chamaria o `attr` em uma string?!
Comment: pois é, sua resposta funcionou mas tinha q ficar controlando a quantidade de caractere do id. mas a resposta abaixo caiu como uma luva. vlw
Answer: Considerando que você só tenha uma imagem dentro dessa div:
// Usando JavaScript puro
var img = document.querySelector("div.manage img.img-drag");
var id = null;
// Se a imagem existe na div
if(img) id = img.id;

// Usando jQuery
var id = $("div.manage img.img-drag").attr("id");

Caso a imagem exista id será a string do id, caso contrário será null (primeiro exemplo) ou undefined(jQuery).


What is Extended Fisher-Kolmogorov (EFK)?

Question: What is Extended Fisher-Kolmogorov (EFK)?
There are many references to it, but I failed to find what is actually is. Is it some kind of non-linear differential equation? Does it describe physical systems?
Answer: Short answer would be:
It is a nonlinear PDE, usually stated as
$$u_t+\gamma u_{xxxx}-u_{xx}-u+u^3=0 $$
as introduced in Dee & van Sarloos' paper. Most authors like to emphasize its application in modeling of phase transitions at critical points.


Reecrever url com htaccess

Question: Por falta de experiência, estou tendo dificuldade em reescrever a url do meu blog, tentei conforme abaixo:
http://www.meusite.com/blog/article.php?a=3&v=5&at=teste-do-primeiro-post

No final gostaria do resultado abaixo:
http://www.meusite.com/blog/article/teste-do-primeiro-post

Coloquei o .htaccess na raiz e depois dentro da pasta blog, qual a pasta que o .htaccess tem que ficar?
Minha última tentativa abaixo:
RewriteEngine on

RewriteRule ^article/([0-9]+)/([0-9a-zA-Z_-]+) article.php?a=$1&v=$1&at=$1 [NC,L]

Answer: O problema está na expressão regular!
Por exemplo, vc está pegando números com a ER ([0-9]+) no lugar onde viria teste-do-primeiro-post, que é uma sequência de caracteres.
De uma maneira geral, sem restrição a não ser a /, vc pode tentar o abaixo (coloquei mais uma variável at2 além das suas que recebe o resto da URL - até o final):
RewriteRule ^([^\/]*)\/?([^\/]*)\/?([^\/]*)\/?(.*)$ article.php?a=$1&v=$2&at=$3&at2=$4 [L,QSA]

Comment: Inseri na pasta principal do servidor deste jeito RewriteRule ^?([^\/]*)\/?([^\/]*)\/?([^\/]*)\/?(.*)$ article.php?a=$1&v=$2&at=$3 [L,QSA] e gerou o internal error 500
Comment: Você tem que inserir dentro da pasta "blog", onde contem a pasta article!
Comment: Inseri dentro da pasta blog, mas está retornando error 500
Comment: Removi o primeio `?` estava errado na resposta. Você pode tentar colocar o caminho na frente (após o `^`) ou tb utilizar o `RewriteBase /` ou `RewriteBase /blog/`

Reecrever url com htaccess


Saving and loading eclipse uml2 model

Question: I want to save and load eclipse uml2 model programmatically but I cant find method that would help me in this. Any ideas how can I do this?
Answer: I just google it and you should take a look at http://wiki.eclipse.org/MDT/UML2/FAQ .
Hoping it helps,
EBR

Saving and loading eclipse uml2 model


SaltStack: /etc/sudo: /bin/systemctl vs /usr/bin/systemctl

Question: We use SaltStack for configuration management since some weeks.
How to handle the distribution specific location of systemctl?

On Ubuntu: /bin/systemctl
On SuSE: /usr/bin/systemctl

At the moment I add two lines to the sudoers file:
etc_sudoers:
  file.blockreplace:
    - name: /etc/sudoers
    - marker_start: "# START managed etc_sudoers -DO-NOT-EDIT-"
    - marker_end: "# END managed zone etc_sudoers --"
    - content: |
        some_user ALL = NOPASSWD: /bin/systemctl restart apache2
        some_user ALL = NOPASSWD: /usr/bin/systemctl restart apache2
{% endfor %}

    - append_if_not_found: True
    - backup: '.bak'
    - show_changes: True

.... Is there no simpler solution?
Answer: Unfortunately there is no simpler or automatic way. But there is a better way following the Salt Best Practices, using a map.jinja file.

It is a strong convention in Salt Formulas to place platform-specific
  data, such as package names and file system paths, into a file named
  map.jinja that is placed alongside the state files.

Using it will ensure the modularity of your states, making them able to run regardless of the minion's OS.
Below there is an example of how your map.jinja file would be in the scenario you have presented. It will filter the minion by OS family and set the variables according to it:
{% set systemctl = salt['grains.filter_by']({
    'Debian': {
        'location': '/bin/systemctl'
    },
    'Suse': {
        'location': '/usr/bin/systemctl'
    }
} %}

Now you need to import it in your state file and use the variables previously defined:
{% from "systemctl/map.jinja" import systemctl with context %}

etc_sudoers:
  file.blockreplace:
    - name: /etc/sudoers
    - marker_start: "# START managed etc_sudoers -DO-NOT-EDIT-"
    - marker_end: "# END managed zone etc_sudoers --"
    - content: some_user ALL = NOPASSWD: {{ systemctl.location }} restart apache2

    - append_if_not_found: True
    - backup: '.bak'
    - show_changes: True

For more info about it, please take a look at the modularity and the lookup table sessions of the doc.
Comment: It should be noted that mangling `/etc/sudoers` itself is a losing proposition when you can simply add small new files in `/etc/sudoers.d/` these days when any recent `sudoers` file already contains `#includedir /etc/sudoers.d` (and if it doesn't, then make it do that instead).


memory difference on top and htop

Question: I got a new VPS as my database server. I installed only mysql and started. After some time(even after shutting down mysql service), I see only %3-4 of the memory used in htop but according to top I only have 30MB free memory. It has a total of 4GB RAM. I don't know which one to trust. Can someone explain me the difference of top and htop memory usage and what may be causing the high usage at top stats?
thanks.
Answer: It's just the difference of whether you consider memory that contains discardable data as used or not. The memory is used in the sense that it contains information that may be useful. But it's free in the sense that the information can simply be discarded if the memory is needed.
For example, say you run a program. The executable file that holds the program itself is still in memory. But that data is not needed at the time. If the program runs again, however, the information can be used from memory so it doesn't have to be loaded from disk again. But if that memory is needed for some other purpose, the file data can be thrown away since it's on the disk. Should this be considered free memory or not?
The reason so much memory is used is because free memory is wasted memory. Only memory that is being used can improve performance. The OS tries to keep as little memory free as possible, only enough to handle special situations such as bursts of data received from the network. It's not like if you use only 3GB today you can use 5GB tomorrow. If you only use 3GB today, you just wasted 1GB.

memory difference on top and htop


Proving that the estimators of coefficients and variance in GLS model are independent

Question: I have come across this question in a textbook: I have a linear model $Y=Xb+u$ with for instance autocorrelation, in order to introduce GLS $Y^*=X^*b+u^*$ (with $Z^* = \Omega^{-1/2}Z$).
Then an additional question is to show that

$\hat{b}_{GLS} = (X^T\Omega^{-1}X)^{-1} X^T\Omega^{-1}Y$, and
$\hat{\sigma}^2_{GLS} = \dfrac{\hat{u}^{*T}\hat{u}^*}{N-(k+1)}$

are independent.
And I have no precise idea to do it. I can show that their covariance is equal to zero, but unless I assume Normal distributions this does not help me.
Am I supposed to aim at joint density or is there something better?
Comment: Someone edited my question with the "unless I assume" although it was "as these are non". I feel that even if I assume normality (that is of the residuals), these estimates are still not normal and therefore, I cannot conclude with just a zero covariance. I therefore think this edit is misleading (and you probably see I am not sure the best place to signal it)
Comment: Typically, the predictors are assumed fixed, or conditioned on, so assuming the error vector to be normal does imply the estimators are normal. Are you considering X fixed?
Comment: Yes i am, but $\hat{\sigma}^2_{GLS}$ then follows a $\chi^2$ distribution no ?
Comment: I gave an answer that I hope may help. I think you should also tag this question as self-study.
Answer: Edit It's been a while and the OP has provided an answer, so here is a more detailed answer than was originally provided due to the homework-nature of the problem. I use a somewhat simplified notation where $Y = X\beta +u, u\sim N(0, \Omega)$.

We first notice that since $\hat{\sigma}^2$ is a function of $\hat{u}$, it suffices to prove that $\hat{u}$ is independent of $\hat{\beta}$.
Let $P = XH$ and $Q = I - P$, where $H = (X'\Omega^{-1}X)^{-1}X'\Omega^{-1}$. Then $\hat{\beta}=HY$, $\hat{\mu} = PY$ and $\hat{u}=QY$.
Since $Y \sim N(X\beta, \Omega)$, we have $\hat{\beta} \sim N(\beta, H\Omega H')$ and $\hat{u}\sim N(0, Q\Omega Q')$. Thus, it suffices to prove that $\operatorname{Cov}(\hat{\beta}, \hat{u})=0$. Moreover, assuming $X$ is full column rank, we have $$\operatorname{Cov}(\hat{\mu}, \hat{u}) = \operatorname{Cov}(X\hat{\beta}, \hat{u}) = X\operatorname{Cov}(\hat{\beta}, \hat{u})=0 \iff \operatorname{Cov}(\hat{\beta}, \hat{u}) = 0$$
But
\begin{align}\operatorname{Cov}(\hat{\mu}, \hat{u}) &= \operatorname{Cov}(PY, QY) \\
&= P\Omega Q' \\
&= P\Omega - P\Omega P' \\
&= X(X'\Omega^{-1}X)^{-1}X' - X(X'\Omega^{-1}X)^{-1}X'\Omega X(X'\Omega^{-1}X)^{-1}X' \\
&= X(X'\Omega^{-1}X)^{-1}X' - X(X'\Omega^{-1}X)^{-1}X'\\
&= 0,
\end{align}
 which by the above iff condition is equivalent to what we wanted to show.
Answer: Building on the 6th point nicely given by Student001, here is what I have come to :
$cov(\widehat{b}_{MCG},\widehat{u}^*)  = E\left[\left(\widehat{u}^*-E[\widehat{u}^*]\right)
\left(\widehat{b}_{MCG}-E[\widehat{b}_{MCG}]\right)^T\right] \\
 = E\left[\widehat{u}^*\left(\widehat{b}_{MCG}-b\right)^T\right] \\
 = E\left[\widehat{u}^*   \widehat{b}^{\,T}_{MCG}\right] - E[\widehat{u}^*]  b^T \\
=E\left[M^*u^*\left((X^{*T}X^*)^{-1}X^{*T}u^*\right)^{T}\right] \\
=E\left[M^*u^*u^{*^T}X^*\left(X^{*^T}X^*\right)^{-1}\right] \\
=M^*E\left[u^*u^{*^T}\right] X^*(X^{*^T}X^*)^{-1}or\:E[u^*u^{*^T}]=\sigma_u^2 I_T \\
=\sigma^2_u M^*X^*(X^{*^T}X^*)^{-1} \\ %& &\text{ avec  } M^*=I_T-X^*(X^{*T}X^*)^{-1}X^{*T} \\
= \sigma^2_u [X^*(X^{*^T}X^*)^{-1} -X^*(X^{*^T}X^*)^{-1}X^{*^T}X^*(X^{*^T}X^*)^{-1}] \\
=\sigma_u^2[X^*(X^{*^T}X^*)^{-1} -X^*(X^{*^T}X^*)^{-1}] \\
 =0$
Then, as with the right assumption we have that $ \hat{u}^*$ is normal, and $\widehat{b}_{MCG}$ is too, they are independent.
An last, as $\hat{\sigma}_{GLS}^2$ is a function of $ \hat{u}^*$, $\widehat{b}_{MCG}$ and $\hat{\sigma}_{GLS}^2$ are independent.
By the way, is that of any practical help ?


Is it possible to change playing styles in cricket?

Question: Can a player playing as a right hand batsman for a few overs switch to his left hand for rest of his innings?
Can a player bowling spin for 2 or 3 balls in a over switch to being a fast bowler in the same over?
What are the general rules about this?
EDIT:
Given two answers are about switch hitting. I apologize for not providing clear informations. Let me explain clearly. Consider a batsman, for example Dhoni comes to crease and faced two or three deliveries and after that can he face the next delivery as a Left handed batsman. He is a right handed batsman by profile. My question is, is it possible for a batsman or bowler to change is playing style i.e.,right to left or left to right during the match?
Answer: The batsman can change his stance whenever he likes. See Pieterson's switch hitting and the discussion on ESPN here - http://www.youtube.com/watch?v=o2t3ja3sZ5M
In terms of bowling, I believe that you are not able to swap the sides of the wicket you bowl from or which hand you bowl from without first informing the batsman. Theres no reason you can't change the style from medium to spin, I've seen people do this when having a bad over.
Comment: Yes, the batsmen can line up to face anyway he likes. Shivnarine Chanderpaul who plays for the West Indies stands 'face on', as if he was a right handed batsmen about to face a ball delivered from square leg. For the purposes of LBW (which needs a leg and off side defined) the fact that he has a right handed grip means he is considered to have his leg stump as per a right hand batsmen, even though his legs are evenly distributed across the crease.
Comment: Chanderpaul is left-handed, but I agree his stance is the most chest-on I've seen.
Comment: Switch hitting is not a matter, can pieterson bat(facing the ball) as a left hand batsman in a part of his innings?
Answer: As indicated in jimmithy's answer, batsmen have far greater leeway in the rules than bowlers. Exactly what batsmen can and cannot do is a controversial point at present, but 'switch hitting' is currently legal.
Bowlers must inform the Umpire, who in turn informs the batsmen of what side of the wicket they will bowl from and from which hand when they begin their spell. They need to inform the Umpire, who informs the batsmen, if they want to change it, but can do so as often as they like. That is all though, the style of bowling need not be declared, just the side of the wicket and hand.
Andrew Symonds, a former Australian cricketer, bowled both offspin and medium pace. Admittedly he was rubbish at both, but at least we was equally skilled in both styles. It was not uncommon for him to bowl spin to one batsmen and medium pace to another in the same over in order to take advantage of the perceived strengths and weakness of the two batsmen against the two styles of bowling. He did not need to inform the Umpire that he was changing styles each ball.
Answer: To answer the question in its simplest form as asked, a batsman may stand in any position he/she likes and will be treated as right/left handed based on how he was stood at the instant of the delivery.  He need not tell anyone and may change as many times as he likes.
Bowlers may also change the type of bowling and mode of delivery as often as they like.  The only restriction being that if a bowler changes the mode of delivery he must first tell the umpire.  Who will tell the batsman.
The mode is whether he is bowling right/left hand over or around the wicket.
Whether he is bowling spin, pace or any other type is up to him.  I know of spinners who bowl both off and leg spin as well as genuine quick balls too.


XAML Strech TextBlock in Grid Colum

Question:
Each list item must be

TextBlock 1 fill first row with 100% width;
TextBlock 2,3,4 must fill 33% each on separate row;

Why TextBlock 2,3,4 not strech?
<ListView.ItemTemplate><DataTemplate><StackPanel>
    <TextBlock Text="{Binding Name}" />
    <Grid HorizontalAlignment="Stretch">
        <Grid.RowDefinitions>
            <RowDefinition></RowDefinition>
        </Grid.RowDefinitions>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="*"></ColumnDefinition>
            <ColumnDefinition Width="*"></ColumnDefinition>
            <ColumnDefinition Width="*"></ColumnDefinition>
        </Grid.ColumnDefinitions>
        <TextBlock TextAlignment="Right" Grid.Row="0" Grid.Column="0"
             HorizontalAlignment="Stretch" VerticalAlignment="Center"
             Text="{Binding Rest}" FontSize="28"/>
        <TextBlock TextAlignment="Right" Grid.Row="0" Grid.Column="1"
             HorizontalAlignment="Stretch" VerticalAlignment="Center"
             Text="{Binding Currency.Name}" FontSize="25"/>
        <TextBlock TextAlignment="Right" Grid.Row="0" Grid.Column="2"
             HorizontalAlignment="Stretch" VerticalAlignment="Center"
             Text="{Binding FullRest}" FontSize="22"/>
    </Grid>
</StackPanel></DataTemplate></ListView.ItemTemplate>

P.S.
How i can add 1...x rows in list view in design time?
Answer: This code (with normal values, because I don't have the underlying data structure) works fine for me.
Different rows can have different widths however. That can be fixed by setting the Width of the StackPanel to the ActualWidth - margins of the listview.
You can find some info about how to add mock data, for usage in the designer, here: How to get mock data into listview during design time and real data at run time in WPF
Answer: I used a ListBox to bind my data in similar way.
You will need to give stackpanel specific width
And you will have to set textwrapping property to 'no wrap'
<ListBox x:Name="listbox" >
        <ListBox.ItemTemplate>
            <DataTemplate>
                <StackPanel Width="480">
                        <TextBlock Text="{Binding main}" />
                    <Grid>
                        <Grid.ColumnDefinitions>
                            <ColumnDefinition/>
                            <ColumnDefinition/>
                            <ColumnDefinition/>
                        </Grid.ColumnDefinitions>
                        <TextBlock TextWrapping="NoWrap" Text="{Binding one}"/>
                            <TextBlock TextWrapping="NoWrap" Text="{Binding two}" Grid.Column="1"/>
                        <TextBlock TextWrapping="NoWrap" Text="{Binding thr}" Grid.Column="2"/>
                    </Grid>
                </StackPanel>
            </DataTemplate>
        </ListBox.ItemTemplate>
        </ListBox>

This Works perfectly for me!
Answer: Use ListView.ItemContainerStyle
<ListView.ItemContainerStyle>

</ListView.ItemContainerStyle>

XAML Strech TextBlock in Grid Colum


How to determine which independent variables to add in a multivariable regression model when sample size is small

Question: As a post-doc I am working on some data that I did not collect myself.
The central question I'm trying to answer: is there a difference in the fat mass of neonates born to mothers with gestational diabetes mellitus (GDM), versus mothers with normal glucose tolerance?
I thus want to create a model where fat mass is the dependent variable, and GDM (coded 0 for mothers without GDM, and 1 for those with) is the independent variable. I also need to control for other variables such as gestational weight gain, pre-pregnancy BMI, gestational age, etc., as these could potentially confound the relationship between neonatal fat mass and GDM.
Sample size is 72 for GDM mothers/babies and 211 for non-GDM mothers/babies. I'd also like to run the model taking out all missing data for comparison, which would leave me with 68 GDM mothers/babies and 112 non-GDM mothers/babies.
I know I need to consider the sample size when determining how many IVs to add to the model, and I've searched online and found some general rules of thumb for how many IVs are appropriate in multivariable regression with a given sample size. It appears that the data set I'm working on is too small to accommodate the number of potential confounders, especially for the smaller diabetes sub-sample.
Therefore, I'm stuck, as I cannot do what I would like to do - collect more data - and I have about 10 IVs that I think should be added into the model based on their potential to confound the association of interest.
Another thing to note: I recently read a paper discussing how it is inappropriate to test bivariable associations of potential IVs with your outcome of interest in order to determine whether they should be added into the model (based on their bivariable significance). So I've already ruled that out as an option for determining which IVs should make it into the model.
Does anyone have any advice on how to determine which/how many IVs to add that goes beyond what I've already considered?
Thanks so much.
Answer: I would say your sample isn't that small and can definitely accommodate 10 predictors if entered without interactions with the treatment. If this really concerns you, you can estimate a propensity score as the predicted probability of GMD given the predictors and simply fit a model regressing the outcome on GMD and the propensity score (though it would be important to allow this model to be flexibly estimated).
If you're worried some of your predictors are not true confounders, you can use the group lasso with doubly robust estimation described in Koch, Vock, & Wolfson (2018), which estimates a doubly robust treatment effect (robust to misspecification of either the propensity score model or outcome model) and uses lasso to select only the relevant covariates (so the models aren't overly saturated). This was specifically designed to select only the covariates from a large pool of potential confounders that are helpful in estimating the treatment effect.
For missing data, it would inappropriate to drop cases. You should use multiple imputation or FIML estimation to retain your original sample size. It does not significantly complicate the problem to use either of these methods (though FIML cannot be used with propensity scores).
Comment: +1 Just want to emphasize the importance of not dropping cases with missing data in this circumstance. That would omit nearly half of the non-GDM cases, and I suspect that the missing data might be from tests that aren't routinely done in uncomplicated pregnancies. You might want to add a link to FIML, as that might not be so broadly appreciated as multiple imputation.
Comment: Thanks for this! Following Stef van Buuren's book on multiple imputation, I was able to carry this out, and ran my fat mass ~ GDM + confounders model, getting very similar results to 1) the regression run on original data set with missing values and 2) data set following list-wise deletion.
Comment: I would like to report the results of the multiply imputed dataset in the paper, but I can only see how to run the regression model with the imputed data - is there a way to use the imputed data set to do the other tests I'd like to report, e.g. t-tests and Pearson correlations?
Comment: T-tests and Pearson correlations are just regression. A t-test is a regression of a continuous variable on a binary variable. A Pearson correlation is just a standardized regression coefficient from a single regression.


Find a point on a plane so that the position vector of R is perpendicular to the plane.

Question: 3 points: $A = (3,4,8), B=(1,1,2)$ and $C=(-1,7,5)$ which are contained in the plane $\Pi$.
I am trying to find a point R on the plane so that the position vector of R $\vec{(OR)}$ is perpendicular to $\Pi$.
I have the cartesian for $\Pi$ which is $27x+18x-18z=9$ the normal n being $(27,18,-18)$. I am stuck on what to do next?
I am thinking of doing something like $\vec{OR}\cdot$ n $=0$. But I am not sure.
Answer: The normal is of the form $<x,y,z>=t<3,2,-2>$ So $x=3t,y=2t,z=-2t$ Substitute in the plane equation to find t to be $1/17$ Plug this t value in my equation above to find the point on te plane
Comment: So I get $<\frac13,\frac29,-\frac29>$ as my R?
Comment: there is a negative in the z
Comment: Yes sorry I was editing it. So it comes out as the above then?
Comment: That's what I got
Comment: If you don't mind going further, if I wanted to find the distance from the origin to $\Pi$ would I treat it as a line or just a point?
Comment: The distance from O to the plane is the distance from O to the point we just found. That can be done with the Pythagorean Theorem
Comment: Sorry, how did you get $(\frac39,\frac29,\frac29)$ since $27(3t)+18(2t)-18(-2t)=9$ gives $81t+36t+36t=9$ not $81t=9$?
Comment: Yes, you are right, the t value becomes 1/17. It's getting late over here....


Sign test for matched pairs that are non-integer

Question: I have paired data as follows.  These are proportion correct scores (ranging from 0 to 1) from multiple experiments in which Treatment X and Treatment Y were administered.
Treatment X: 0.25, 0.35, 0.15, 0.15, etc.
Treatment Y: 0.55, 0.56, 0.33, 0.08, etc.
Based on theoretical predictions, I should expect close to a 1:1 relationship between data from Treatment X and Treatment Y.  So for instance, experiment 1, the scores should be the same (but they're not, 0.25 vs. 0.55).
Accordingly, if I create a scatterplot of X vs. Y scores, and the 1:1 relationship held, all points should be on a diagonal line with slope 1,1 and intercept at 0.
The key question is: how do I test for Treatment X being different from Treatment Y (or not)?  (My data indicate that predictions in the literature are wrong, and there isn't a 1:1 relationship; I'd like to find a way of testing that).  Two questions follow:

My first thought is to do a sign test, 2-tailed.  In R, however,
binom.test requires positive integers.  Is there a workaround for
that?
Alternatively, do any of you suggest a more sophisticated way to test the relationship between Treatment X and Treatment Y?  For instance, a way to assess how many points fall above or below the predicted relationship (e.g., Y higher than X, or X higher than Y)?

Thanks for any suggestions!
Answer: The thing that the sign test counts is the number of pairs for which the first variable exceeds the second (or vice-versa).
(The values of the observations are supposed to be continuous rather than discrete, so that that under the null, $p=0.5$).
So the 'workaround' is simply to supply binom.test with the correct information.
[If we exclude ties, then something like binom.test(sum(x>y),length(x!=y)) should do]
Comment: Gee, you are on the ball. +1 for all the help you give, although I like my own answer better.
Comment: Thank you Glen_b for these clarifications and the correct code!  Wonderful, and gratefully appreciated!
Answer: Since the data are paired, the sign test computes the probability of obtaining a total number of + or - results from the difference between values. The sign test is easy to understand but not always very powerful. The Wilcoxon signed-rank test may be a better choice as it can be more powerful for discriminating between the location of paired data of this type.
Comment: +1 The signed rank test assumes that the distribution of pair differences will be symmetric when the null is true (it doesn't have to be the case under the alternative). Since people are often prepared to make the somewhat stronger assumption that under the null the two variables have the same distribution (within each pair), this isn't usually controversial; however sometimes it is not reasonably clear that it should be the case even under the null, and then the sign test may be better. [Also, if the distribution is quite peaky/heavy-tailed the sign test may have more power even so]
Comment: I'll leave the comment there for the additional detail it provides.
Comment: @Glen_b Answer amended to reflect your comments.