Mixed model specification with nlme in R

Question: i'm having a hard time finding the right model for my data. The study is about the effect of a drug (more precise: the effect of the dose of a drug) and the time on the subject (rat). So i got the following variables:

Dependent Variable: Relative Change
Independent Variables: Dose (Levels: 1, 2, 4, 10) and Time (1,2,3)
Further we got the subject ID (1 to 6)

resulting in data like this:

ID Dose Time Change
1  1    1    0.342
1  1    2    0.212
1  1    3    0.121
1  2    1    0.423
1  2    2    0.321
1  2    3    ...
1  4    1    ...
....
6  10   1    0.121
6  10   2    0.221
6  10   3    0.111

As you can see the different doses were applied to all subjects. Three measurements were made for each subject+dose after 1, 2 and 3 minutes.
My idea for a model:
$$ y_{ijt} = \beta_0 + \beta_1 dose_j + \beta_2 time_t + \beta_3 dose_j*time_t + u_{i} + \epsilon_{ijt}$$
with Dose and Time being fixed effects and $u_i$ being the subject-specific random intercept. Of course this model does not respect the repeated measurements. So I would expect the residuals to be correlated (over the three time-points), modeling this with an adequate residual variance structure like the following:
$$ \epsilon_{i} \sim N(0, R_i)$$
with $\epsilon_i$ being a vector of all residuals of subject i and $R_i$ being a block-diagonal matrix with diagonal elements
$$ R_{i,diag} = \begin{pmatrix} \sigma^2 & \sigma_{1,2} & \sigma_{1,3} \\
                         \sigma_{1,2} & \sigma^2 & \sigma_{2,3} \\
                         \sigma_{1,3} & \sigma_{2,3}& \sigma^2
\end{pmatrix}$$.
$$ R_i = \begin{pmatrix}
                    R_{i, diag} & 0 & 0 & 0 \\
                    0 & R_{i, diag} & 0 & 0 \\
                    0 & 0 & R_{i, diag} &0 \\
                    0 & 0 & 0 & R_{i, diag} \\
\end{pmatrix}$$
I would like to know:

Is this an adequate way to model this situation or is there a more simple way to do that (would be great! :-)).
If this is a right way: Is there a way to estimate this using the lme-function in R (nlme-package)? The problem I have: how might I specify this residual variance-covariance-structure? I got the impression that I need to implement my own varFunc, which doesn't seem to be fun.

Concluding remark: At the moment I have no access to "Mixed-Effects Models in S (Pinheiro and Bates)". It will arrive next week. :-)
Comment: (+1) Just a tip: not everything needs to be done using mixed models - you might be fine using "simpler" (more robust??) methods like `gls`! But I just started with it and have no experience so it's just a tip for you where to investigate...
Comment: I agree with Tomas. You can also use standard multivariate regression, see section 3 of  John Fox's appendix http://socserv.mcmaster.ca/jfox/Books/Companion/appendix/Appendix-Multivariate-Linear-Models.pdf (but use Type II sum of squares and not Type III)
Comment: And be careful with your design from the practictal point of view. Smoking 2 grams of marijuana has not the same effect according to whether you have already smoked 1 gram yesterday or not.
Comment: Thanks for your comments. I did not really think about using different methods. @Stephane Laurent: There is an adequate period between the runs with different doses. But thanks for your tip.
Answer: If I understand your question correctly, you can specify your model with nested random effects like this:
fit.1 <- lme(Change ~ Dose*Time, random=~1|ID/Dose, data=mydata)

To specify the covariance structure, e.g. a simple compound symmetry form, try this:
fit.2 <- lme(Change ~ Dose*Time, random=~1|ID/Dose, data=mydata, cor=corCompSymm())

To look at the estimated parameters try:
summary(fit.1)

To get all estimated coefficients try:
coef(fit.1)

To get the p-values then use:
anova(fit.1)

Notice that if you need to specify the covariance structure of the residuals, you'll have to use nlme as although lme4 (i.e. the lmer function) is a more advanced package, currently it does not support that feature.
Answer: Looks like you want to fit a mixed effects model with Dose-Time interaction with random intercepts for each animale (ID) e.g.
lmer(Change ~ Dose*Time + ( 1 | ID ), data=data)

A model that allows for random slopes (over Time) in addition to random intercepts would look like this:
lmer(Change ~ Dose*Time + ( Time | ID ), data=data)

Also have a look here
Comment: Thanks for your answer. I thought about this models, you are talking about, too. But I got the impression, that these models do not really respect the "nestedness" of my data. I mean in this data I got kind of two repeated measure variables nested in each other: **Each** dose is used to **each** rat on the first level. On the second level I got the three measurements for each dose.


QEMU - incorrect real disk size of a virtual drive

Question: df and ls report different sizes on my host machine because of the difference between the allocated size and the amount of space that's actually used in the EXT4 filesystem.
The problem is that both report the wrong size. qemu-img also doesn't report the actual space that's used inside the guest's filesystem (also EXT4).
On the host:
# qemu-img info sdb.raw
image: sdb.raw
file format: raw
virtual size: 2.0T (2173253451776 bytes)
disk size: 1.9T

# ls -larth sdb.raw
-rw-r--r-- 1 hypervisor hypervisor 2.0T Mar  6 13:47 sdb.raw

# du -sh sdb.raw
1.9T   sdb.raw

# fdisk -l sdb.raw
Disk sdb.raw: 2 TiB, 2173253451776 bytes, 4244635648 sectors
Units: sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disklabel type: gpt
Disk identifier: E6242A7E-1253-E74A-9389-68654A21E4F4

Device     Start        End    Sectors Size Type
sdb.raw1    2048 4244635614 4244633567   2T Linux filesystem

On the guest (/dev/vdb1):
# df -h
Filesystem      Size  Used Avail Use% Mounted on
dev              32G     0   32G   0% /dev
run              32G  496K   32G   1% /run
/dev/vda2       220G  100G  111G  48% /
tmpfs            32G     0   32G   0% /dev/shm
tmpfs            32G     0   32G   0% /sys/fs/cgroup
tmpfs            32G   26M   32G   1% /tmp
/dev/vdb1       2.0T  761G  1.2T  41% /root
tmpfs           6.3G     0  6.3G   0% /run/user/1002

As you can see, I'm only using 761G on the guest system and there's still 1.2T available. Despite that, qemu-img says that I'm using 1.9T. What's the reason? Is there a way to fix this? I'd like to see the actual used space on the host machine. I know it can be achieved because it worked correctly before I filled sdb.raw with data - qemu reported the correct disk size based on the space used inside the disk. Unfortunately, it worked only one way - when the used space was gradually increasing. After I deleted some files and reduced the used space from 1.9T to 761G, the size reported by qemu-img didn't change to a smaller value, it remained at 1.9T.
Comment: `du --bytes sdb.raw `
Comment: @hanshenrik `du --bytes -h sdb.raw`: 2.0T sdb.raw.
Answer: qemu-img and du both report the actual allocated space from host point of view. They can not know/understand if the guest OS is really using that space or if, as in you case, it was freed by the user.
To inform the host that your guest has a ton of free space you need to fstrim your guest filesystem and you must be sure that your qemu/guest block device stack correctly passes down TRIM/discard requests. In order to do that, you need to:

use a qemu block device driver with TRIM/discard support. Example of such drives are virtio-scsi, scsi and sata/ahci. All these drivers expose block devices using the classical /dev/sd[abcd...] nomenclature. On the other hand it appears that your guest is using a plain virtio driver (with /dev/vd[abcd...] names), which does not support TRIM/discard. You can check if your driver support discards by issuing lsblk -D;
enable the relative libvirt domain discard=unmap option;

Finally, your host must be using a filesystem with hole_punching support as ext4 (which you are using) and xfs.
You can read here for some more information.
If all prerequisites are true, issuing fstrim <mount_point> inside your guest will automatically de-allocate unused space on host also. Be sure to understand that the logical/apparent file size will remain unchanged (ie: it will show 2.0 TB ever after fstrim), but using qemu-img or du will reveal the true (smaller) allocated file size.
If the prerequisites are not met, you need to offline compact your image file via virt-sparsify or qemu-img convert after cleaning your guest free space with zeroes (ie: dd if=/dev/zero of=bigfile bs=1M count=<almost_all_free_space>; rm bigfile).
Be sure to understand what the above steps means: doing any error can irremediably corrupt your image file. And be sure to have a know-good backup before attempting any operation on your disk image file!*
Comment: Perfect. Thank you for the detailed explanation!
Answer: It's expected behavior. As you wrote, "after I deleted some files and reduced the used space from 1.9T to 761G" - raw virtual image cannot "collect garbage" automatically and the real space will remain written and allocated even for removed files.
Workaround is to perform (double)conversion raw>qcow2(>raw).
More detailed explained here - https://balau82.wordpress.com/2011/05/08/qemu-raw-images-real-size/
and here - https://techpiezo.com/tech-insights/raw-vs-qcow2-disk-images-in-qemu-kvm/
Comment: same question has been already answered here -https://serverfault.com/questions/329287/free-up-not-used-space-on-a-qcow2-image-file-on-kvm-qemu
Comment: Great, thanks for the answer.


L2 gradient solution time

Question: There is something I don't understand.
Imagine I want to solve :
$$Min_{u}\int_{B(0,1)} \left| \nabla u(x) \right|^{2}+F(u(x))dx$$
It's L2 gradient flow is given by :
$$\partial_{t} u =2 \Delta u - F^{\prime}(u)$$
with $u=0$ on $\partial B(0,1)\times [0;T]$
If I have correctly understood solving the partial equation gives you the minimum of $$Min_{u}\int_{B(0,1)} \left| \nabla u(x) \right|^{2}+F(u(x))dx$$.
However the solution of the PDE depends (a priori) on time but the solution of the minimization doesn't. So I think there is something I don't understand.
Answer: Take a look at the post:
What is the $L^2$ gradient flow?
The basic idea behind it is that the gradient flow allows you to start with an initial $u_0$ and consists of the evolution equation for this $u$, for which it eventually converges to a minimum. This evolution is parametrised by the time variable. The hope is that the minimum you reach is an stationary state, that is, independent of time.
It is always easier to think in the lowest dimensional analogue, and as said in the linked post, that corresponds to vector fields and their flow: given a real valued function, you might want to find the minimum of this function, and for this you first generate the associated gradient vector field and then its corresponding flow. The idea is that given any initial point, if you follow the flow of the vector field, you would eventually reach the minimum.

L2 gradient solution time


Android- Unstable, slow, unreliable PING

Question: I have android app, where's list of servers and code to ping them. But, I when I ping one of them, it always works, but for pinging more of them in a row or more then one (with few seconds dealy) the app is very unstable, lags or whatever (sometimes logcat says that some (600+) frames skipped becouse too much work on main thread (Choreographer: Skipped 4230 frames!  The application may be doing too much work on its main thread.)). App worked perfectly when i had only 1 server to ping, I tried to use the metod posted in code here, with ping them all by one button or ping only 1 half of them etc. Whats wrong? (Should it be too many onClickListeners? I think n not because when i had only one button to ping all of them it did same). The app after click on that textView  does not crash, but lag for 5+ sec.
Second_Fragment.java
package myapp.testapp;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import java.io.IOException;
import java.lang.InterruptedException;
import java.lang.Override;
import java.lang.Process;
import java.lang.Runtime;

public class Second_Fragment extends Fragment {

    long uae;
    long brazil;
    long russia;
    long eueast;
    long euwest;
    long asia;
    long australia;
    long useast;
    long uswest;
    long africa;
    long india;

    View myView2;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        myView2 = inflater.inflate(R.layout.second_layout, container, false);

        //click button
        TextView clickFirstButton = (TextView) myView2.findViewById(R.id.uae);
        clickFirstButton.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                pingUAE();

                if(pingUAE())
                {

                    TextView textView = (TextView)myView2.findViewById(R.id.uaeping);
                    textView.setText("server on, ping is: " + uae + "ms");
                }
                else
                {
                    TextView textView = (TextView)myView2.findViewById(R.id.uaeping);
                    textView.setText("server off ");
                }

            }
        });

        TextView clickRussia = (TextView) myView2.findViewById(R.id.russia);
        clickRussia.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                pingRUSSIA();

                if(pingRUSSIA())
                {

                    TextView textView = (TextView)myView2.findViewById(R.id.russiaping);
                    textView.setText("server on, ping is: " + russia + "ms");
                }
                else
                {
                    TextView textView = (TextView)myView2.findViewById(R.id.russiaping);
                    textView.setText("server off ");
                }

            }
        });

        TextView clickBrazil = (TextView) myView2.findViewById(R.id.brazil);
        clickBrazil.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                pingBRAZIL();

                if(pingBRAZIL())
                {

                    TextView textView = (TextView)myView2.findViewById(R.id.brazilping);
                    textView.setText("server on, ping is: " + brazil + "ms");
                }
                else
                {
                    TextView textView = (TextView)myView2.findViewById(R.id.brazilping);
                    textView.setText("server off ");
                }

            }
        });

        TextView clickEUEast = (TextView) myView2.findViewById(R.id.eueast);
        clickEUEast.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                pingEUEAST();

                if(pingEUEAST())
                {

                    TextView textView = (TextView)myView2.findViewById(R.id.eueastping);
                    textView.setText("server on, ping is: " + eueast + "ms");
                }
                else
                {
                    TextView textView = (TextView)myView2.findViewById(R.id.eueastping);
                    textView.setText("server off ");
                }

            }
        });

        TextView clickEUWest = (TextView) myView2.findViewById(R.id.euwest);
        clickEUWest.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                pingEUWEST();

                if(pingEUWEST())
                {

                    TextView textView = (TextView)myView2.findViewById(R.id.euwestping);
                    textView.setText("server on, ping is: " + euwest + "ms");
                }
                else
                {
                    TextView textView = (TextView)myView2.findViewById(R.id.euwestping);
                    textView.setText("server off ");
                }

            }
        });

        TextView clickAsia = (TextView) myView2.findViewById(R.id.asia);
        clickAsia.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                pingASIA();

                if(pingASIA())
                {

                    TextView textView = (TextView)myView2.findViewById(R.id.asiaping);
                    textView.setText("server on, ping is: " + asia + "ms");
                }
                else
                {
                    TextView textView = (TextView)myView2.findViewById(R.id.asiaping);
                    textView.setText("server off ");
                }

            }
        });

        TextView clickAustralia = (TextView) myView2.findViewById(R.id.australia);
        clickAustralia.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                pingAUSTRALIA();

                if(pingAUSTRALIA())
                {
                    TextView textView = (TextView)myView2.findViewById(R.id.australiaping);
                    textView.setText("server on, ping is: " + australia + "ms");
                }
                else
                {
                    TextView textView = (TextView)myView2.findViewById(R.id.australiaping);
                    textView.setText("server off ");
                }

            }
        });

        TextView clickUSEast = (TextView) myView2.findViewById(R.id.useast);
        clickUSEast.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                pingUSEAST();

                if(pingUSEAST())
                {
                    TextView textView = (TextView)myView2.findViewById(R.id.useastping);
                    textView.setText("server on, ping is: " + useast + "ms");
                }
                else
                {
                    TextView textView = (TextView)myView2.findViewById(R.id.useastping);
                    textView.setText("server off ");
                }

            }
        });

        TextView clickUSWest = (TextView) myView2.findViewById(R.id.uswest);
        clickUSWest.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                pingUSWEST();

                if(pingUSWEST())
                {
                    TextView textView = (TextView)myView2.findViewById(R.id.uswestping);
                    textView.setText("server on, ping is: " + uswest + "ms");
                }
                else
                {
                    TextView textView = (TextView)myView2.findViewById(R.id.uswestping);
                    textView.setText("server off ");
                }

            }
        });

        TextView clickAfrica = (TextView) myView2.findViewById(R.id.africa);
        clickAfrica.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                pingAFRICA();

                if(pingAFRICA())
                {
                    TextView textView = (TextView)myView2.findViewById(R.id.africaping);
                    textView.setText("server on, ping is: " + africa + "ms");
                }
                else
                {
                    TextView textView = (TextView)myView2.findViewById(R.id.africaping);
                    textView.setText("server off ");
                }

            }
        });

        TextView clickIndia = (TextView) myView2.findViewById(R.id.india);
        clickIndia.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                pingINDIA();

                if(pingINDIA())
                {
                    TextView textView = (TextView)myView2.findViewById(R.id.indiaping);
                    textView.setText("server on, ping is: " + india + "ms");
                }
                else
                {
                    TextView textView = (TextView)myView2.findViewById(R.id.indiaping);
                    textView.setText("server off ");
                }
            }

        });

        return myView2;
    }

    public boolean pingUAE() {
        Runtime runtime = Runtime.getRuntime();
        try {
            long a = System.currentTimeMillis() % 1000;
            Process ipProcess = runtime.exec("/system/bin/ping -c 1 220.127.116.11");
            int     exitValue = ipProcess.waitFor();
            uae = System.currentTimeMillis() % 1000 - a;
            return (exitValue == 0);
        } catch (IOException e)          { e.printStackTrace(); }
        catch (InterruptedException e) { e.printStackTrace(); }
        return false;
    }

    public boolean pingBRAZIL() {
        Runtime runtime = Runtime.getRuntime();
        try {
            long b = System.currentTimeMillis() % 1000;
            Process ipProcess = runtime.exec("/system/bin/ping -c 1 188.8.131.52");
            int     exitValue = ipProcess.waitFor();
            brazil = System.currentTimeMillis() % 1000 - b;
            return (exitValue == 0);
        } catch (IOException e)          { e.printStackTrace(); }
        catch (InterruptedException e) { e.printStackTrace(); }
        return false;
    }

    public boolean pingRUSSIA() {
        Runtime runtime = Runtime.getRuntime();
        try {
            long c = System.currentTimeMillis() % 1000;
            Process ipProcess = runtime.exec("/system/bin/ping -c 1 220.127.116.11");
            int     exitValue = ipProcess.waitFor();
            russia = System.currentTimeMillis() % 1000 - c;
            return (exitValue == 0);
        } catch (IOException e)          { e.printStackTrace(); }
        catch (InterruptedException e) { e.printStackTrace(); }
        return false;
    }

    public boolean pingEUEAST() {
        Runtime runtime = Runtime.getRuntime();
        try {
            long d = System.currentTimeMillis() % 1000;
            Process ipProcess = runtime.exec("/system/bin/ping -c 1 188.8.131.52");
            int     exitValue = ipProcess.waitFor();
            eueast = System.currentTimeMillis() % 1000 - d;
            return (exitValue == 0);
        } catch (IOException e)          { e.printStackTrace(); }
        catch (InterruptedException e) { e.printStackTrace(); }
        return false;
    }

    public boolean pingEUWEST() {
        Runtime runtime = Runtime.getRuntime();
        try {
            long e = System.currentTimeMillis() % 1000;
            Process ipProcess = runtime.exec("/system/bin/ping -c 1 188.8.131.52");
            int     exitValue = ipProcess.waitFor();
            euwest = System.currentTimeMillis() % 1000 - e;
            return (exitValue == 0);
        } catch (IOException e)          { e.printStackTrace(); }
        catch (InterruptedException e) { e.printStackTrace(); }
        return false;
    }

    public boolean pingASIA() {
        Runtime runtime = Runtime.getRuntime();
        try {
            long f = System.currentTimeMillis() % 1000;
            Process ipProcess = runtime.exec("/system/bin/ping -c 1 22.214.171.124");
            int     exitValue = ipProcess.waitFor();
            asia = System.currentTimeMillis() % 1000 - f;
            return (exitValue == 0);
        } catch (IOException e)          { e.printStackTrace(); }
        catch (InterruptedException e) { e.printStackTrace(); }
        return false;
    }

    public boolean pingAUSTRALIA() {
        Runtime runtime = Runtime.getRuntime();
        try {
            long g = System.currentTimeMillis() % 1000;
            Process ipProcess = runtime.exec("/system/bin/ping -c 1 126.96.36.199");
            int     exitValue = ipProcess.waitFor();
            australia = System.currentTimeMillis() % 1000 - g;
            return (exitValue == 0);
        } catch (IOException e)          { e.printStackTrace(); }
        catch (InterruptedException e) { e.printStackTrace(); }
        return false;
    }

    public boolean pingUSEAST() {
        Runtime runtime = Runtime.getRuntime();
        try {
            long h = System.currentTimeMillis() % 1000;
            Process ipProcess = runtime.exec("/system/bin/ping -c 1 220.127.116.11");
            int     exitValue = ipProcess.waitFor();
            useast = System.currentTimeMillis() % 1000 - h;
            return (exitValue == 0);
        } catch (IOException e)          { e.printStackTrace(); }
        catch (InterruptedException e) { e.printStackTrace(); }
        return false;
    }

    public boolean pingUSWEST() {
        Runtime runtime = Runtime.getRuntime();
        try {
            long i = System.currentTimeMillis() % 1000;
            Process ipProcess = runtime.exec("/system/bin/ping -c 1 22.214.171.124");
            int     exitValue = ipProcess.waitFor();
            uswest = System.currentTimeMillis() % 1000 - i;
            return (exitValue == 0);
        } catch (IOException e)          { e.printStackTrace(); }
        catch (InterruptedException e) { e.printStackTrace(); }
        return false;
    }

    public boolean pingAFRICA() {
        Runtime runtime = Runtime.getRuntime();
        try {
            long j = System.currentTimeMillis() % 1000;
            Process ipProcess = runtime.exec("/system/bin/ping -c 1 22.214.171.124");
            int     exitValue = ipProcess.waitFor();
            africa = System.currentTimeMillis() % 1000 - j;
            return (exitValue == 0);
        } catch (IOException e)          { e.printStackTrace(); }
        catch (InterruptedException e) { e.printStackTrace(); }
        return false;
    }

    public boolean pingINDIA() {
        Runtime runtime = Runtime.getRuntime();
        try {
            long k = System.currentTimeMillis() % 1000;
            Process ipProcess = runtime.exec("/system/bin/ping -c 1 184.108.40.206");
            int     exitValue = ipProcess.waitFor();
            india = System.currentTimeMillis() % 1000 - k;
            return (exitValue == 0);
        } catch (IOException e)          { e.printStackTrace(); }
        catch (InterruptedException e) { e.printStackTrace(); }
        return false;
    }

}

second_layout.xml
<?xml version="1.0" encoding="utf-8"?>
<TableLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    xmlns:android="http://schemas.android.com/apk/res/android">

    <TableRow
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_marginStart="3dp"
        android:layout_marginTop="3dp"
        android:layout_marginBottom="4dp">
        <TextView
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:text="@string/uae"
            android:id="@+id/uae"
            android:layout_above="@+id/button_first"
            android:layout_centerHorizontal="true"
            android:layout_marginStart="3dp"
            android:layout_marginBottom="4dp" />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textAppearance="?android:attr/textAppearanceSmall"
            android:text="@string/space"
            android:id="@+id/uaeping"
            android:layout_marginStart="3dp"
            android:layout_marginBottom="4dp" />
    </TableRow>

    <TableRow
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_marginStart="3dp"
        android:layout_marginBottom="4dp">
        <TextView
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:text="@string/brail"
            android:id="@+id/brazil"
            android:layout_above="@+id/button_first"
            android:layout_centerHorizontal="true"
            android:layout_marginStart="3dp"
            android:layout_marginBottom="4dp" />
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textAppearance="?android:attr/textAppearanceSmall"
            android:text="@string/space"
            android:id="@+id/brazilping"
            android:layout_marginStart="3dp"
            android:layout_marginBottom="4dp" />
    </TableRow>

    <TableRow
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_marginStart="3dp"
        android:layout_marginBottom="4dp">
        <TextView
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:text="@string/russia"
            android:id="@+id/russia"
            android:layout_above="@+id/button_first"
            android:layout_centerHorizontal="true"
            android:layout_marginStart="3dp"
            android:layout_marginBottom="4dp" />
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textAppearance="?android:attr/textAppearanceSmall"
            android:text="@string/space"
            android:id="@+id/russiaping"
            android:layout_marginStart="3dp"
            android:layout_marginBottom="4dp" />
    </TableRow>

    <TableRow
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_marginStart="3dp"
        android:layout_marginBottom="4dp">
        <TextView
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:text="@string/eu_east"
            android:id="@+id/eueast"
            android:layout_above="@+id/button_first"
            android:layout_centerHorizontal="true"
            android:layout_marginStart="3dp"
            android:layout_marginBottom="4dp" />
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textAppearance="?android:attr/textAppearanceSmall"
            android:text="@string/space"
            android:id="@+id/eueastping"
            android:layout_marginStart="3dp"
            android:layout_marginBottom="4dp" />
    </TableRow>

    <TableRow
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_marginStart="3dp"
        android:layout_marginBottom="4dp">
        <TextView
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:text="@string/eu_west"
            android:id="@+id/euwest"
            android:layout_above="@+id/button_first"
            android:layout_centerHorizontal="true"
            android:layout_marginStart="3dp"
            android:layout_marginBottom="4dp" />
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textAppearance="?android:attr/textAppearanceSmall"
            android:text="@string/space"
            android:id="@+id/euwestping"
            android:layout_marginStart="3dp"
            android:layout_marginBottom="4dp" />
    </TableRow>

    <TableRow
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_marginStart="3dp"
        android:layout_marginBottom="4dp">
        <TextView
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:text="@string/asia"
            android:id="@+id/asia"
            android:layout_above="@+id/button_first"
            android:layout_centerHorizontal="true"
            android:layout_marginStart="3dp"
            android:layout_marginBottom="4dp" />
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textAppearance="?android:attr/textAppearanceSmall"
            android:text="@string/space"
            android:id="@+id/asiaping"
            android:layout_marginStart="3dp"
            android:layout_marginBottom="4dp" />
    </TableRow>

    <TableRow
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_marginStart="3dp"
        android:layout_marginBottom="4dp">
        <TextView
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:text="@string/australia"
            android:id="@+id/australia"
            android:layout_above="@+id/button_first"
            android:layout_centerHorizontal="true"
            android:layout_marginStart="3dp"
            android:layout_marginBottom="4dp" />
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textAppearance="?android:attr/textAppearanceSmall"
            android:text="@string/space"
            android:id="@+id/australiaping"
            android:layout_marginStart="3dp"
            android:layout_marginBottom="4dp" />
    </TableRow>

    <TableRow
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_marginStart="3dp"
        android:layout_marginBottom="4dp">
        <TextView
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:text="@string/us_east"
            android:id="@+id/useast"
            android:layout_above="@+id/button_first"
            android:layout_centerHorizontal="true"
            android:layout_marginStart="3dp"
            android:layout_marginBottom="4dp" />
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textAppearance="?android:attr/textAppearanceSmall"
            android:text="@string/space"
            android:id="@+id/useastping"
            android:layout_marginStart="3dp"
            android:layout_marginBottom="4dp" />
    </TableRow>

    <TableRow
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_marginStart="3dp"
        android:layout_marginBottom="4dp">
        <TextView
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:text="@string/us_west"
            android:id="@+id/uswest"
            android:layout_above="@+id/button_first"
            android:layout_centerHorizontal="true"
            android:layout_marginStart="3dp"
            android:layout_marginBottom="4dp" />
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textAppearance="?android:attr/textAppearanceSmall"
            android:text="@string/space"
            android:id="@+id/uswestping"
            android:layout_marginStart="3dp"
            android:layout_marginBottom="4dp" />
    </TableRow>

    <TableRow
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_marginStart="3dp"
        android:layout_marginBottom="4dp">
        <TextView
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:text="@string/africa"
            android:id="@+id/africa"
            android:layout_above="@+id/button_first"
            android:layout_centerHorizontal="true"
            android:layout_marginStart="3dp"
            android:layout_marginBottom="4dp" />
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textAppearance="?android:attr/textAppearanceSmall"
            android:text="@string/space"
            android:id="@+id/africaping"
            android:layout_marginStart="3dp"
            android:layout_marginBottom="4dp" />
    </TableRow>

    <TableRow
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_marginStart="3dp"
        android:layout_marginBottom="4dp">
        <TextView
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:text="@string/india"
            android:id="@+id/india"
            android:layout_above="@+id/button_first"
            android:layout_centerHorizontal="true"
            android:layout_marginStart="3dp"
            android:layout_marginBottom="4dp" />
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textAppearance="?android:attr/textAppearanceSmall"
            android:text="@string/space"
            android:id="@+id/indiaping"
            android:layout_marginStart="3dp"
            android:layout_marginBottom="4dp" />
    </TableRow>

</TableLayout>

logcat
http://pastebin.com/ycK4q2dn
Thank you for any solution.
Answer: Each time you press a button, your main UI thread is launching a process and then waiting for it to finish, causing the UI thread to pause. This pause is what is causing Android to report the "too much work on main thread" warnings and your App to "lag".
You need to change your ping() methods so they are launched in separate threads and do not cause your UI thread to wait.
Something like this:
public class Second_Fragment extends Fragment {

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        myView2 = inflater.inflate(R.layout.second_layout, container, false);
        //click button
        TextView clickFirstButton = (TextView) myView2.findViewById(R.id.uae);
        clickFirstButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // launch the ping process in a separate thread
                new Thread(pingUAE).start();
            }
        });
        return myView2;
    }

    void setPingResult(int id, long pingtime) {
           TextView textView = (TextView)myView2.findViewById(id);
           if (pingtime >= 0) {
               textView.setText("server on, ping is: " + pingtime + "ms");
           }
           else {
               textView.setText("server off ");
           }
    }

    public Runnable pingUAE = new Runnable() {
        @Override
        public void run() {
            // initialise time to -1
            uae = -1;
            Runtime runtime = Runtime.getRuntime();
            try {
                long a = System.currentTimeMillis() % 1000;
                Process ipProcess = runtime.exec("/system/bin/ping -c 1 18.104.22.168");
                int     exitValue = ipProcess.waitFor();
                uae = System.currentTimeMillis() % 1000 - a;
            } catch (IOException e)          { e.printStackTrace(); }
            catch (InterruptedException e) { e.printStackTrace(); }

            // update the ping result - we need to call this on the UI thread
            // because it updates UI elements (TextView)
            getActivity().runOnUIThread(new Runnable() {
                @Override
                public void run() {
                    setPingResult(R.id.uae, uae);
                }
            });

        }
    }

}

Comment: Can you please give me some hint? I already googled and tried some methods, but i dont know ho to do it with boolean...


Salesforce picklist values not showing up in picklist

Question: I have added values to a Custom Object multi-select picklist as well as a Standard Object multi-select picklist (both fields are custom) and the new values fail to show up on the record as a choice in the picklist.  No field level security was changed or any visibility settings were altered.  Anyone know why these new values will not show?
Thanks!!
Answer: Go to the Record Type settings for the standard and custom objects.  Click on the record type and you'll see the "Picklists Available for Editing" section.  From there you should be able to add the new picklist values.
The picklist values at the field level are like a master list.  Using record types you can allow only a subset of the list to show up.
Comment: Thank you!  This was spot on.
Answer: Solved: In the case of field dependencies, you need to add the individual picklist values to each dependent value for each stage.
Answer: I had to go to the "Sales Process" (search) and then choose the opportunity type I was editing. I could then add the field picklist value in.
SF does seem overly complex at times!


On an exercise concerning continuous random variables

Question: I'd like to understand how to deal with continuous random variables. Well, my problems concern the relationships between probability density function and the distribution function. I obtain the distribution function [resp. the probability density function] by integrating [resp. by deriving] the probability density function [resp. the distribution function]. But if I slightly change the random variable, how to compute both the distribution function and the probability density function? Below, I found a very interesting exercise on the subject. Can you help me to solve it, in order to better understand continuous random variables?
Let $X$ be a continuous random variable with probability density function $f_X(x)=3x^2 1_{[0,1]}(x)$.

Compute the distribution function of $X$.

My solution: it seems that
$$
\int_0^1 f_X(x)dx=1
$$
Now, as I need to find a function, I think that the correct way to integrate is
$$
\int_0^t f_X(x)dx
$$
How to integrate when there is an indicator function?

Compute mean and variance of X.

I found how to do these computations!

Set $Y = 1-X$. Compute the distribution function $F_Y$ of $Y$, and hence the probability density function $f_Y(y)$.

I have no clue.

Compute mean and variance of Y.

Very similar to part $2)$.
Comment: You've already figured out in (1) that you need to integrate over $[0,1]$. On that interval, the indicator is just multiplying by one... so you ignore it. However the distribution *function* takes variable input, you're just integrating over a constant interval. Check your definitions. As for the others, you can very simply look it up! "Mean and variance of continuous random variable"
Comment: @FShrike I edited my question. Well, the problem occurs in parts 1 and 3. Can you provide me a detailed answer, please?
Answer: $\newcommand{\d}{\,\mathrm{d}}$A series of strong hints.
When asked to compute the distribution function in $(1)$, they mean find: $$F_X=\int_{-\infty}^xf_X(t)\d t$$Which is known as the cumulative distribution function. It models the probability that $X\le x$. Since $f_X=0$ outside of $[0,1]$, due to the indicator function, the above integral reduces to (for $x\ge0$): $$\int_0^{\min\{1,x\}}f_X(t)\d t$$Note that $\mathbf{1}_{[0,1]}\equiv1$ on the interval $[0,1]$, so you can "ignore" it in the latter integration. We need to take a minimum since, if $x\gt1$, the integral vanishes on the region $(1,x]$ (because of the indicator function...). What happens if $x\lt0$? Can you piece together a pretty piecewise evaluation for $F_X$? $$F_X(x)=\begin{cases}?&x\gt1\\?&0\le x\le1\\?&x\lt0\end{cases}$$
In $(4)$, note that $Y\le y\iff1-X\le y\iff1-y\le X$, so have a think about how to resolve from here.
Further clarification on $(1)$: $$\int_{-\infty}^x f_X(t)\d t=\begin{cases}\int_{-\infty}^0f_X(t)\d t+\int_0^xf_X(t)\d t&x\le1\\\int_{-\infty}^0f_X(t)\d t+\int_1^xf_X(t)\d t+\int_0^1f_X(t)\d t&x\gt1\end{cases}$$Have a think about which integrals are relevant.


Finding condition for integral roots of a quadratic equation.

Question: I need to find the values of k(possible) for which the quadratic equation $$x^2+2kx+k =0$$ will have integral roots.
So I assumed roots to be $a,b$
Then I got the condition $a+b=-2k$and $a\cdot b=k$; so combining these I get $a+b+2ab=0$;
And now I need to find the integral values of $a,b$ for which this equation is satisfied,how should I procced from here??
Also is there any shorter much elegant way to do this question.
(Note-A hint would suffice)
Comment: Why not complete the square in the original quadratic and see where that leads you?
Answer: HINT:
$$x=\dfrac{-2k\pm\sqrt{4k^2-4k}}2=-k\pm\sqrt{k(k-1)}$$
So we need the product of two consecutive integers namely, $k(k-1)$ to be perfect sqaure
Answer: Here is a hint to develop your existing method. Multiply the equation in $a$ and $b$ by $2$ and add a constant which enables you to factorise it.
Answer: Given $$x^2+2kx+k=0\Rightarrow x^2+2kx+k^2 = k^2-k\Rightarrow (x+k)^2=k^2-k$$
So we get $$\displaystyle (x+k)^2= \left(\sqrt{k^2-k}\right)^2\Rightarrow x+k =\pm \sqrt{k^2-k} $$
So we get $$\displaystyle x= \pm \sqrt{k^2-k}-k\;,$$ Now here $x\in \mathbb{Z}$
So let $$k^2-k=l^2\Rightarrow 4k^2-4k = 4l^2\Rightarrow (4k^2-4k+1) = (2l)^2+1$$
So we get $$(2k-1)^2-(2l)^2=1\Rightarrow (2k+2l-1)\cdot (2k-2l-1) = 1\times 1 = -1\times 1$$
$\bullet\; $ If $2k+2l-1 = 1$ and $2k-2l-1 = 1\;,$ after solving we get $(k,l) = (1,0)$
$\bullet\; $ If $2k+2l-1 = -1$ and $2k-2l-1 = -1\;,$ after solving we get $(k,l) = (0,0)$


How can I calculate p-values in R?

Question: I am trying to construct a hypothesis test for the variance of two populations.
My test statistic is $F=$${\sigma_b^2}$/${\sigma_A^2}$.  I want to implement this as a function in R so I computed: a=function(B,A){ var(B)/var(A) }
Now, I want to compute the p-value using this test statistic in R. How can I do this?
Comment: If you really have two *populations*, there is no point in testing; they are either equal or not. OTOH, this is not a good way to test the variance of two *samples*, use the Levene / Brown-Forsythe test instead (see: [Why Levene test of equality of variances rather than F-ratio](http://stats.stackexchange.com/a/24024/7290)). Instead, use [?leveneTest](http://www.inside-r.org/packages/cran/car/docs/leveneTest) in the `car` package.
Answer: Since you are calculating the F-statistic could use the pf function.
As an example, let's take the following data as an example.
set.seed(123)
x <- rnorm(50, mean = 0, sd = 2)
y <- rnorm(30, mean = 1, sd = 1)
f <- var(x)/var(y)

# make sure to double for two-sided
pf(f, df1=49, df2=29, lower.tail=F)*2
[1] 0.0001897506

As gung noted, I failed to realize you are trying to do Hartley's Fmax test.  In which case, you don't even need to calculate the F statistic or even the variances, you can just use var.test.
var.test(x, y)$p.value
[1] 0.0001897506

Also as noted by gung, there is Levene's test (leveneTest) in the car package.
Comment: The OP is attempting to conduct Hartley's $F$-max test, thus the df you give are incorrect (see [here](http://stats.stackexchange.com/a/126181/7290), & [here](http://stats.stackexchange.com/a/24024/7290)).
Comment: @gung You are correct, I embarrassingly overlooked that.  Updated now.
Comment: That's OK, it's an easy thing to overlook. Please correct the df in your answer, though.

How can I calculate p-values in R?


Is this an equivalence relation? $xRy$ if and only if $|x+y| = |x| + |y|$

Question: I can prove that it is reflexive, but I am not sure how to formally prove that this relation is symmetric and transitive.
Comment: Note that $|x+y|=|x|+|y|$ iff $x$ and $y$ have the same sign (with the convention of $0$ being positive and negative)
Comment: This is the set of all vectors that have the same direction.  "The shortest distance between two points is a straight line" sort of thing.  Depends on whether you include the origin.
Answer: Hint:
$$|1+0|=|1|+|0|$$
$$|0-1|=|0|+|-1|$$
To check symmetric:
Notice that $|x+y|=|y+x|$ and $|x|+|y|=|y|+|x|$, hence if $|x+y|=|x|+|y|$, what can you conclude about $|y+x|$.
Answer: Pick, as in the above hint, $x=-1$
$y=0$
$z=2$
We have that $xRy$, because $|x+y|=|-1 + 0| = |-1| + |0|=|x|+|y|$,
$yRz$, because $|y+z| = |0+2| = |0| + |2|$
But from the fact that the following is false
$1=|-1+2| = |-1| + |2|=3$
it does not follow that $xRz$.


Otimizando uma tabela Mysql com 40 campos

Question: Olá, pessoal! Possuo uma tabela em Mysql com 40 campos, trata-se de um sistema de currículos. Estou fazendo a otimização tanto da tabela, como das próprias consultas executadas no PHP.
A questão é que para realizar buscas por perfis específicos, utiliza-se 20 desses campos, ou seja, fica uma consulta "pesada". Quando um determinado campo não é utilizado pelo usuário no momento de preencher os dados da busca, ela não é incluida em minha query. De toda forma, quando fui configurar os meus índices, vi que o máximo aceitável é 16 colunas. Por isso estou aqui para pedir uma opinião de vocês.
Confira abaixo alguns dos campos desta tabela:
cur_nome
cur_cpf
cur_senha
cur_nascimento
cur_estado_civil
cur_endereco
cur_estado
cur_cidade
cur_area1  (área de interesse 1) -> recebe um id de outra tabela
cur_area2  (área de interesse 2) -> recebe um id de outra tabela
cur_area3  (área de interesse 3) -> recebe um id de outra tabela
cur_habilitacao_a (carteira de habilitacao a) -> Recebe Sim ou Não
cur_habilitacao_b (carteira de habilitacao b) -> Recebe Sim ou Não
cur_habilitacao_c (carteira de habilitacao c) -> Recebe Sim ou Não
cur_habilitacao_d (carteira de habilitacao d) -> Recebe Sim ou Não
cur_habilitacao_e (carteira de habilitacao e) -> Recebe Sim ou Não

Com base na sugestão de um amigo nos comentários abaixo, peguei essa tabela e a dividi em três, ficando da seguinte forma:
Tabela1  com 15 campos
Tabela2  com 15 campos
Tabela3  com 10 campos

A Tabela2 e Tabela3 possuem como chave estrangeira (id da Tabela1) a própria chave primária.
Uma dúvida que tive é a seguinte:
Supondo que todos os campos são submetidos de uma só vez, no momento eu que gravar os dados, então eu faria 3 inserts no mysql, certo?
exemplo:
sql1 = insert into Tabela1 (campos) values (valores);
sql2 = insert into Tabela2 (campos) values (valores);
sql3 = insert into Tabela3 (campos) values (valores);

Nesse caso, para eu garantir que a Tabela2 e Tabela3 irão receber em suas chaves estrangeiras, a primária da Tabela1, é recomendável eu resgatar o valor do id gravado da tabela1, e assim fazer sua referência nas tabelas 2 e 3? Ficaria assim:
 sql1 = insert into Tabela1 (campos) values (valores);
 $idgravado = mysqli_insert_id($conexao);

 sql2 = insert into Tabela2 (tab2_codigo, outros_campos) values ($idgravado, valores);
 sql3 = insert into Tabela3 (tab3_codigo, outros_campos) values ($idgravado, valores);

O que me dizem pessoal?
Comment: Isso é só para pesquisa? Precisas ter os campos todos para pesquisa? A pergunta está um bocado ampla, porque depende de muitas coisas. O ideal era não ter tantos campos na pesquisa... Mas se você precisa, o que se poderá fazer?
Comment: Eu faria também, uma tabela por etapa, e depois usava o join pra buscar os registros pertinentes, fica muito melhor pra adicionar, consultar, inclusive, se você quiser consultar um registro em especifico, de uma etapa especifica, não precisa buscar em toda tabela, só busca o necessário mesmo.
Comment: Ola, André e Jorge, fiz uma edição em minha pergunta com algumas dúvidas sobre essa questão de divisão de tabelas em mais, veja acima.
Comment: Me parece justo, Jorge manja mais de SQL, mas eu faria o mesmo procedimento que lhe disse, e recupero o id da tabela principal e insiro nas outras pertinentes.
Comment: Irei uitlizar ao todo uns 16 campos para pesquisa, é necessário consultar os registros atraves de diversos critérios.
Comment: Vou fazer isso então, obrigado voces.
Answer: Cara, o ideal seria você criar várias tabelas por exemplo:

tblDadosPessoais
tblEndereco
tblExperiencia

Assim depois você poderia usar o INNER JOIN para buscar dados em outras tabelas com o mesmo índice. Dê uma lida neste artigo.
Comment: Olá Cleidimar, Obrigado pelos esclarecimentos. Vou fazer uma modificação em minha pergunta para sanar algumas dúvidas em relação à sua sugestão.


If $H$ is positive definite and $A$ has full row rank, prove that $ \begin{bmatrix} H & A^T\\ A & 0\end{bmatrix} $ is nonsingular?

Question: How to prove that $ \begin{bmatrix} H & A^T\\ A & 0\end{bmatrix} $ is nonsingular if $H$ is positive definite and $A$ has full row rank?
$H$ is $(n\times n)$ and $A$ is $(p\times n)$.
Comment: This is easy to show with the Schur complement
Answer: Let $x_1 \in \mathbb{R}^n$ and $x_2 \in \mathbb{R}^p$ be such that
$$ \begin{bmatrix} H & A^T \\ A & 0\end{bmatrix} \begin{bmatrix} x_1 \\ x_2 \end{bmatrix} = 0$$
This gives us $Hx_1 + A^Tx_2 = 0$ and $Ax_1 = 0$. Premultiplying by $x_1$ in the first equation, we get, $x_1^T H x_1 = -x_1^T A^T x_2$. Since $Ax_1 = 0$, therefore, $x_1^T H x_1 = 0$. However, $H$ is positive definite implying $x_1 = 0$ and consequently, $A^T x_2 = 0$. Since $A$ has a full row rank, the only solution to $A^T x_2 = 0$ is $x_2 =0$.  Thus, the only element in the null space of the given matrix is $0$ implying it is non singular.
Comment: Then we have $Hx_1+A^Tx_2=0$. How did you get $Hx_1=0$ and $A^Tx_2=0$ separately?
Comment: Thanks for pointing that out. I have edited the answer accordingly. Sorry about the mistake.
Answer: \begin{align}
\begin{bmatrix} H & A^T \\ A & 0\end{bmatrix} \begin{bmatrix} x \\ y \end{bmatrix} = 0 &\iff Hx+A^Ty=0 \wedge Ax=0 \\
&\iff AH^{-1}A^Ty=0 \\
&\implies y^TAH^{-1}A^Ty=0 \\
&\iff A^Ty=0\ (H \text{ and thus }H^{-1}\text{ is positive definite}) \\
&\iff y=0 (A\text{ is of full row rank}) \\
&\implies x=-H^{-1}A^Ty =0 \implies Ax=-AH^{-1}A^Ty=0.
\end{align}
Therefore, $x=y=0$ and the matrix $\begin{bmatrix} H & A^T \\ A & 0\end{bmatrix}$ is nonsigular.
Answer: Since $H$ is positive definite, so is $B = AH^{-1}A^T$. To see this note that $H^{-1}$ is positive definite, and if $u$ is such that $u^TBu = 0 \implies  (A^Tu)^T H^{-1} (A^Tu) = 0 \implies A^Tu = 0 \implies u =0$ (as A is full row rank.) So in particular $B$ is invertible.
The result now follows since the given matrix is a product of non-singular matrices:
$$
\begin{bmatrix} I & 0 \\ AH^{-1} & I \end{bmatrix} \begin{bmatrix} H & 0 \\ 0 & -AH^{-1}A^T\end{bmatrix}   \begin{bmatrix} I & H^{-1}A^T \\ 0 & I \end{bmatrix}
 = \begin{bmatrix} H & A^T \\ A & 0 \end{bmatrix}.
$$


How to get value from adapter to activity on recyclerview item click event in Android?

Question: I'm learning RecyclerView and I built an app that can populate simple data from SQLite database
I have an Adapter as follows :-
public class BookAdapter extends RecyclerView.Adapter<BookAdapter.BookViewHolder> {
Context mContext;
Cursor mCursor;
OnBookListener mOnBookListener;
public int id;

public BookAdapter(Context context, Cursor cursor, OnBookListener onBookListener){
    mContext = context;
    mCursor = cursor;
    mOnBookListener = onBookListener;

}
public class BookViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
    public TextView id_textView, name_textView;
    OnBookListener onBookListener;

    public BookViewHolder(@NonNull View itemView, OnBookListener onBookListener) {
        super(itemView);

        id_textView = itemView.findViewById(R.id.book_id);
        name_textView = itemView.findViewById(R.id.book_name);
        this.onBookListener = onBookListener;
        itemView.setOnClickListener(this);
    }

    public String getId_textView() {
        return (String)id_textView.getText();
    }
    public String getName_textView() {
        return (String)name_textView.getText();
    }

    @Override
    public void onClick(View v) {
       onBookListener.onBookClick((String)id_textView.getText());
        //Log.d(TAG, "onBookClick : Clicked " + id_textView.getText());
    }
}

public interface OnBookListener{
    void onBookClick(String id);
}

@NonNull
@Override
public BookViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
    LayoutInflater inflater = LayoutInflater.from(mContext);
    View view = inflater.inflate(R.layout.book_item,parent,false);
    return new BookViewHolder(view, mOnBookListener);
}

@Override
public void onBindViewHolder(@NonNull BookViewHolder holder, int position) {
    if(!mCursor.moveToPosition(position)){
        return;
    }

    id = mCursor.getInt(mCursor.getColumnIndex(Book.BookEntry.COLUMN_ID));
    String name = mCursor.getString(mCursor.getColumnIndex(Book.BookEntry.COLUMN_NAME));

    holder.id_textView.setText(String.valueOf(id));
    holder.name_textView.setText(name);

    if(position %2 == 1)
    {
        holder.itemView.setBackgroundColor(Color.parseColor("#E9EEF3"));
    }
    else
    {
        holder.itemView.setBackgroundColor(Color.parseColor("#0FA9E8"));
    }

}

@Override
public int getItemCount() {
    return mCursor.getCount();
}

public void swapCursor(Cursor newCursor){
    if(mCursor != null){
        mCursor.close();
    }
    mCursor = newCursor;

    if(newCursor != null){
        notifyDataSetChanged();
    }
}

now with the Activity itself :
public class MainActivity extends AppCompatActivity implements BookAdapter.OnBookListener {

    public SQLiteDatabase mdatabase;
    public BookAdapter madapter;
    private static final String TAG = "MainActivity";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //SqliteDBHelper dbHelper = new SqliteDBHelper(this);
        SqliteAssetHelper dbHelper = new SqliteAssetHelper(this);
        mdatabase = dbHelper.getReadableDatabase();

        RecyclerView recyclerView = findViewById(R.id.recycler_view);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        madapter = new BookAdapter(this, getAllBooks(), this);
        recyclerView.setAdapter(madapter);

        madapter.swapCursor(getAllBooks());
    }

    private Cursor getAllBooks(){
        return mdatabase.query(Book.BookEntry.TABLE_NAME,null,null,null
        ,null,null,null);
    }

    @Override
    public void onBookClick(String id) {
        Intent intent = new Intent(this, HadithsList.class);
        intent.putExtra("id", ???);
        startActivity(intent);
    }

What code can I replace the question marks in the above intent to actually get the id from the interface : OnBookListener That is implemented in the activity.
Thanks in advance
Answer: Assuming you want to pass an id to the next Activity, and assuming the followinf line retrieve the id you want
onBookListener.onBookClick((String)id_textView.getText());

Then, the id is your parameter, so you just have to do this
intent.putExtra("id", id);

Answer: Create this class
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;
import androidx.recyclerview.widget.RecyclerView;

public class RecyclerTouchListener implements RecyclerView.OnItemTouchListener
{

   private GestureDetector gestureDetector;
   private ClickListener clickListener;

   public RecyclerTouchListener(Context context, final RecyclerView recyclerView, final ClickListener clickListener) {
     this.clickListener = clickListener;
     gestureDetector = new GestureDetector(context, new GestureDetector.SimpleOnGestureListener() {
        @Override
        public boolean onSingleTapUp(MotionEvent e) {
            return true;
        }

        @Override
        public void onLongPress(MotionEvent e) {
            View child = recyclerView.findChildViewUnder(e.getX(), e.getY());
            if (child != null && clickListener != null) {
                clickListener.onLongClick(child, recyclerView.getChildPosition(child));
            }
        }
    });
}

@Override
public boolean onInterceptTouchEvent(RecyclerView rv, MotionEvent e) {

    View child = rv.findChildViewUnder(e.getX(), e.getY());
    if (child != null && clickListener != null && gestureDetector.onTouchEvent(e)) {
        clickListener.onClick(child, rv.getChildPosition(child));
    }
    return false;
}

@Override
public void onTouchEvent(RecyclerView rv, MotionEvent e) {
}

@Override
public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {

}

public interface ClickListener {
    void onClick(View view, int position);

    void onLongClick(View view, int position);
}

}
handle onClick
recyclerView.addOnItemTouchListener(new
        RecyclerTouchListener(getApplicationContext(), recyclerView, new
        RecyclerTouchListener.ClickListener() {
        @Override
        public void onClick(View view, int position) {
            MealListModel model = myList.get(position);
        }
        @Override
        public void onLongClick(View view, int position) {

        }
    }));


OnChange do select não carrega no jquery?

Question: Eu tenho uma aplicação que possui vários select aninhados e uso a função onchange() para o select selecionado alterar o subsequente, mas preciso selecionar o conteúdo clicado, mas como já possui a função on(change) no js, este segundo não funciona, a minha classe principal está assim:
var selects = $("#table_com_parcelas select");
    var index = null;
    var valor = null;
    selects.on('change', function () {
        var valor = this.value;
        indice = selects.index(this);
        selects.each(function (index) {
            if (index > indice) {
                $(this).val(valor);
            }
        });
    }); //pega o valor selecionado do select e seta os subsequentes com o mesmo valor.

e no select inseri o seguinte código,
<select id="select-1" onchange="sel(this.value)">/*options*/</select>

mas acontece que ele não chama a função sel(); me falaram para usar EventListener, o caminho é este mesmo? ou preciso alterar a forma de chamar no select?
Pois o onchange do select está subscrevendo o do arquivo .js

var parcelas = 3;
var x = 1;

function insere_option() {
  var options = "";
  options += "<option value='1'>Boleto</option>";
  options += "<option value='2'>Cartão</option>";
  options += "<option value='3'>Cheque</option>";
  options += "<option value='4'>Dinheiro</option>";
  options += "<option value='5'>Transferência</option>";
  return options;
}

var selects = $("#table select");
var index = null;
var valor = null;
selects.on('change', function() {
  var valor = this.value;
  indice = selects.index(this);
  selects.each(function(index) {
    if (index > indice) {
      $(this).val(valor);
    }
  });
});

function boletos(id){
       console.log(id);
    }

    while (x <= parcelas) {
  $('#table tbody').append('
' + x + ' de ' + parcelas + '	01/' + x + '/2017	R$ 100,00	<select id="select-' + x + '" onchange="boletos(this.id)">' + insere_option() + '</select>
');
  x++;
}

      parcela
      vencimento
      valor
      pago com

Answer: Seu script está funcionando corretamente. O que está acontecendo, é que você está tentando definir um evento em elementos que não existem ainda.
Coloque:
var selects = $("#table select");
var index = null;
var valor = null;
selects.on('change', function() {
  var valor = this.value;
  indice = selects.index(this);
  selects.each(function(index) {
    if (index > indice) {
      $(this).val(valor);
    }
  });
});

Abaixo de:
while (x <= parcelas) {
  $('#table tbody').append('
' + x + ' de ' + parcelas + '	01/' + x + '/2017	R$ 100,00	<select id="select-' + x + '" onchange="boletos(this.id)">' + insere_option() + '</select>
');
  x++;
}

var parcelas = 3;
var x = 1;

function insere_option() {
  var options = "";
  options += "<option value='1'>Boleto</option>";
  options += "<option value='2'>Cartão</option>";
  options += "<option value='3'>Cheque</option>";
  options += "<option value='4'>Dinheiro</option>";
  options += "<option value='5'>Transferência</option>";
  return options;
}
function boletos(id){
       console.log(id);
    }

while (x <= parcelas) {
  $('#table tbody').append('
' + x + ' de ' + parcelas + '	01/' + x + '/2017	R$ 100,00	<select id="select-' + x + '" onchange="boletos(this.id)">' + insere_option() + '</select>
');
  x++;
}

var selects = $("#table select");
var index = null;
var valor = null;
selects.on('change', function() {
  var valor = this.value;
  indice = selects.index(this);
  selects.each(function(index) {
    if (index > indice) {
      $(this).val(valor);
    }
  });
});

      parcela
      vencimento
      valor
      pago com

Comment: Não sabia que precisaria ter está ordem, aprendi mais uma hoje, muito obrigado @WéllingthonM.deSousa


Can I use hook form alter to add an attribute to a webform field?

Question: I am trying to use hook form alter to add an onchange attribute to a select field but it is not working. Is it possible or is there something wrong with my module code?

function addonchange_form_alter(&$form, &$form_state, $form_id){
  // target a single form
  if($form_id == "webform_client_form_22"){
    $form['submitted']['company']['#onchange'] = 'changevalue';
  }
}

Thanks for any help.
Answer: You have to do something like this:
function addonchange_form_alter(&$form, &$form_state, $form_id){
  // target a single form
  if($form_id == "webform_client_form_22"){
    $form['submitted']['company']['#attributes']['onchange'] = 'changevalue';
  }
}


Intuition for higher moments in circular statistics

Question: In circular statistics, the expectation value of a random variable $Z$ with values on the circle $S$ is defined as
$$
m_1(Z)=\int_S z P^Z(\theta)\textrm{d}\theta
$$
(see wikipedia).
This is a very natural definition, as is the definition of the variance
$$
\mathrm{Var}(Z)=1-|m_1(Z)|.
$$
So we didn't need a second moment in order to define the variance!
Nonetheless, we define the higher moments
$$
m_n(Z)=\int_S z^n P^Z(\theta)\textrm{d}\theta.
$$
I admit that this looks rather natural as well at first sight, and very similar to the definition in linear statistics. But still I feel a little bit uncomfortable, and have the following
Questions:
1.
What is measured by the higher moments defined above (intuitively)? Which properties of the distribution can be characterized by their moments?
2.
In the computation of the higher moments we use multiplication of complex numbers, although we think of the values of our random variables merely as vectors in the  plane or as angles. I know that complex multiplication is essentially addition of angles in this case, but still:
Why is complex multiplication a meaningful operation for circular data?
Answer: The moments are the Fourier coefficients of the probability measure $P^Z$.  Suppose (for the sake of intuition) that $Z$ has a density.  Then the argument (angle from $1$ in the complex plane) of $Z$ has a density on $[0,2\pi)$, and the moments are the coefficients when that density is expanded in a Fourier series.  Thus the usual intuition about Fourier series applies -- these measure the strengths of frequencies in that density.
As for your second question, I think you already gave the answer: "complex multiplication is essentially addition of angles in this case".
Comment: Thank you, this is really helpful. (Shame on me for not recognizing a Fourier series even when hurtling towards it...)
Comment: Does this mean that the moments of a circular distribution should be compared to the characteristic function of a linear distribution rather than to its moments?
Comment: @Rasmus: I guess that depends on exactly what you want to do with the information, but in general I'd say yes.


How do I export and import Release Management 2013 templates

Question: Is there any way to import / export a release manager 2013 template?
I can't seem to find anything (other than backing up the whole database) and we'd like to have some means of rolling back to a previous version of a template (or at least comparing two versions)
Our primary use cases are when a team member breaks a template OR for when a component is used across multiple templates and one team changes it breaking the other teams projects. Ideally we'd like some way to revert back to a previous version.
We're using Update 3 so any advice would be great.
Answer: Unfortunately, this is not supported, even in Update 4.
Backing up and restoring the database is the easiest at the moment. The database schema for Release Management is quite straightforward so you could also look at taking copies of individual tables to create some way of version control.
There's been some discussion of creating a custom tool to support exporting/importing data for RM. If you want this, maybe you can add a suggestion to UserVoice
Comment: Another possibility is to consider migrating to DSC/"vNext" release templates. Doing this makes the templates much simpler, since the core deployment logic lives in a source-controlled DSC script. I wouldn't recommend messing with the database, since there's no guarantee that the schema won't massively change from update to update.
Comment: @DanielMann yes you're correct. A PowerShell approach allows you store all your scripts and configuration data in PowerShell and let RM only run those scripts. However, you would still need to keep track of environments, components and templates. I've already had some cases where someone changed a component path and 'things stopped working'. It would be nice of those would be version controlled.
Comment: Oh, I totally agree. It would be great if the workflows were sourced from source control, or at least *could* be sourced from source control instead of from a separate database.
Comment: Thanks guys, just wanted to make sure we hadn't missed anything.


Como passar uma matriz como argumento com o usuário definindo o nº de colunas?

Question: Vou fazer um programa simples só pra exemplificar meu problema.
#include<iostream>
using namespace std;

void recebeValor( int mat[][col]) // me da erro de comp;
{
   mat[0][0] = 2;
   cout << mat[0][0];
}

int main()
{
cout << "Entre o numero de linhas da matriz A: ";
int lin;
cin >> lin;

cout << "Entre o numero de colunas da matriz A> ";
int col;
cin >> col;

int mat[lin][col];

recebeValor(mat); // isso me da erro de compilacao

Comment: Dê uma olhada no [tour]. Você pode aceitar uma resposta se ela resolveu seu problema. Você pode votar em todos os posts do site também. Alguma lhe ajudou mais? Precisa que algo seja melhorado?
Answer: Decida-se se vai usar C ou C++. Em C dá para fazer isto na maioria dos compiladores:
void recebeValor(int size, int mat[][size]) {
   mat[0][0] = 2;
}

int main() {
    int lin = 3;
    int col = 3;
    int mat[lin][col];
    recebeValor(col, mat);
}

Veja funcionando no ideone. E no repl.it. Também coloquei no GitHub para referência futura.
Também dá para usar apenas ponteiros no lugar do array e funciona para C++.
Se vai usar C++, não use array bruto.
Até dá para criar uma gambiarra para resolver isto com template. Mas a solução de fato é usar uma estrutura mais abstrata e mais preparada para lidar com isto. Prefira usar um Vector.
#include<iostream>
#include <vector>
using namespace std;

void recebeValor(vector<vector<int>> mat) {
   mat[0][0] = 2;
   cout << mat[0][0];
}

int main() {
    cout << "Entre o numero de linhas da matriz A: ";
    int lin;
    cin >> lin;
    cout << "Entre o numero de colunas da matriz A> ";
    int col;
    cin >> col;
    vector<vector<int>> mat(lin, vector<int>(col));
    recebeValor(mat);
}

Veja funcionando no ideone. E no repl.it. Também coloquei no GitHub para referência futura.
Answer: O problema é que você não declarou col em lugar nenhum. Por causa disso o compilador vai reclamar, pois mat é um parâmetro, mas col ele não sabe o que é.
Além disso, em C++, se você quiser definir o tamanho da matriz no parâmetro, terá que fazê-lo estaticamente. Ou seja, o tamanho exato tem que ser conhecido em tempo de compilação. O motivo é que para que o compilador possa fazer a verificação de tipos, ele deve ter conhecimento completo do tipo em tempo de compilação, e portanto o tipo não pode depender de algo que só exista durante a execução.
E o mais importante: Para que o compilador possa calcular quanto espaço de memória cada elemento vai ocupar, ele vai precisar saber em tempo de compilação qual o tamanho que cada posição do parâmetro array ocupa. Como o tipo do parâmetro é uma matriz (array de arrays), então o compilador necessariamente precisa saber o tamanho exato em tempo de compilação de todas as dimensões com exceção da primeira.
Assim, isso daqui não é válido:
int a, b, c;

// Erro, os valores a, b e c não estão disponíveis em tempo de compilação, só em tempo de execução.
void funcaoQualquer(int mat[a][b][c]) {
}

Já isso daqui é válido, pois o compilador sabe exatamente qual é o tamanho de cada dimensão:
void funcaoQualquer(int mat[5][5][5]) {
}

Isso daqui também é válido. Embora o compilador não saiba o tamanho do array como um todo, ele sabe qual é o tamanho de cada elemento na primeira dimensão.
void funcaoQualquer(int mat[][5][5]) {
}

Já esses daqui não são válidos. O compilador não tem como saber qual é o tamanho de cada elemento na primeira dimensão:
void funcaoQualquer1(int mat[][][5]) {
}

void funcaoQualquer2(int mat[][][]) {
}

void funcaoQualquer3(int mat[5][][]) {
}

void funcaoQualquer4(int mat[5][5][]) {
}

void funcaoQualquer5(int mat[][5][]) {
}


PHP mail() is not working, need help setting up exim4

Question: I have the symbolic link setup for /usr/sbin/sendmail which points to my exim directory /usr/sbin/exim4/ and my php.ini pointing to /usr/sbin/sendmail. My mail isn't sending. I don't know what to do, but when I tried to reconfigure, it just shows the gui and goes straight to the next bash line with twomuchwork:~# 1;2c1;2c1;2c.
Update: I checked my iptables to make sure 25 was open. I think it might have something to do with google apps. At this point, I just want to be able to use Google apps and send mail using PHP's mail(). I have some web applications that requires the mail(). I even tried this post: How to Setup Ubuntu Mail Server with Google Apps?
Update2: I tried almost everything out there. I tried setting up exim4 as smarthost, I tried sendmail, everything works when I send a e-mail to my @gmail.com from terminal, but I still cannot get my PHP mail() to work.
Answer: Interesting, dialog appears to be broken on your system for some reason.  Try
dpkg-reconfigure -freadline exim4-config

Can you send email from the terminal (eg mail email@example.com -s "subject goes here" then entering an email body ending with a . on a line by itself)?  Is /usr/sbin/sendmail/ a typo, or do you really have a / on the end, because that shouldn't be there.
Comment: Hahaha, that is a typo.
Comment: It works when I send it from the terminal, but not from php.
Comment: What does exim's log show when you try sending from PHP?
Comment: I only see a mainlog in `/var/log/exim4` and it doesn't say anything significant there. Just says `2010-10-31 20:09:08 Start queue run: pid=6389
2010-10-31 20:09:08 End queue run: pid=6389
`
Answer: You seem to think this problem is in some way related to PHP. IME that's very rarely the case, but you've not provided any details of how your php is configured for mail.

It works when I send it from the terminal, but not from php

Can you provide a transcript showing how you sent it from the CLI. Also the permissions for the binary. What happens when you replicate the CLI commands using popen() in php?
Comment: For the record, I don't think this problem is related to PHP; I am saying I cannot send mail with PHP because of a reason I don't know of. I can provide details if I knew what to provide; I said I do not know what to do, and I hope to get help and direction here. With that said, I am trying to send using a foo.php using the `mail()` of PHP. Also, this is the command I used `echo "This is a test." | mail -s Testing email@example.com` from this guide: http://library.linode.com/email/exim/send-only-mta-debian-5-lenny
Comment: The "mail" command is **not** how PHP sends mail. However its worth checking what happens when you try to exec this from PHP. Your ini file should contain something like 'sendmail_path = /usr/sbin/sendmail -t '. You need to check that the binary is where its supposed to be and that it reads the envelope from the headers supplied in the message on stdin.
Answer: If the machine is not supposed to receive incoming email try to install nullmailer:
# apt-get install nullmailer
# dpkg-reconfigure nullmailer

This is not a solution to your problem, especially if the machine is supposed to receive mail too. But it is an effort to walk around it.


.NET 4 WebBrowser hangs

Question: I am using .NET 4 and trying to use the desktop authentication for the StackApps site via the web-browser control (WPF and/or WinForms) to develop a NNTP Bridge for accessing StackOverflow (https://stackapps.com/questions/4215/stackapp-nntp-bridge-for-accessing-stackexchange-forums-like-stackoverflow).
It seems that the login cannot be done, because the web browser hangs up, after the page from "StackExchange Login" is displayed.
I use the following URL:
https://stackexchange.com/oauth/dialog?client_id=1736&scope=no_expiry&redirect_uri=https://stackexchange.com/oauth/login_success
It works in the normal IE browser, but not in a WinForms or WPF window... Does anyone know what the problem is?
It is simple to repoduce:

Create a WinForms-Project
Add the "WebBrowser" control to the dialog
Double-Click on the Form1
Add the following code
private void Form1_Load(object sender, EventArgs e)
{
  webBrowser1.Navigate("https://stackexchange.com/oauth/dialog?client_id=1736&scope=no_expiry&redirect_uri=https://stackexchange.com/oauth/login_success");
}

Start the application
Login by pressing the "login with Stack Exchange" account symbol
A new page gets loaded; it is displayed correctly, but you cannot enter your login name; the window hangs...

The same happens, if I use WPF-App and the WPF-WebBrowser-Control... it seems that it is stuck in an endless-loop in JavaScript...
Any hint on how to solve ths problem?
Or is it possible to debug the JavaScript in the WebBrowser-Control???
Comment: Is anyone able t reproduce this issue?
Comment: You can try this -> set property 'ScriptErrorsSuppressed' of your 'WebBrowser' control to 'True'. And if this is not helping, try updating your Internet Explorer to a newer version. After that, 'WebBrowser' control will use the newer version of IE and maybe it will be better. Just first two ideas:) I hope i helped.

EDIT: this [link](http://stackoverflow.com/questions/14713596/how-to-add-the-firefox-and-chrome-to-c-sharp-browser-control) and this [link](http://stackoverflow.com/questions/2141668/use-chrome-as-browser-in-c) can help too.
Comment: I also tried setting the scriptErrorsSuppressed property; it does not change anything... also I have the latest version of IE on Win7...
Comment: And what about links leading to IE WebBrowser control alternatives (Firefox core, Chrome core)? If you insist on using the IE then my apologize. I do not know how to help further. EDIT: For example gecko for Firefox WebBrowser core in your app: https://code.google.com/p/geckofx/
Comment: I will try alternatives... But mostly they are not very easy to deploy... i will take a look and check it out.... but it would be also good, if the page would solve the javascript endless loop ;)
Comment: It's already a year and a half since this was asked. I don't know if it's solved for .NET, but in Delphi I've still got the same issue using a TWebBrowser. I'm aware that there is a [duplicate of this question on StackApps](http://stackapps.com/questions/4244/desktop-login-url-webbrowser-hangs-net-javascript-endless-loop), but since I don't have enough rep there, I'll start a bounty here.
Comment: If you are using WPF you can try using Awesomium - it is a browser control with lots of cool features based on Chrome. Also you never said what version of IE you are using, because that could have a great impact. Have you tried doing the same thing in Internet Explorer and seeing if you have problems there?
Comment: @Phoenix Thanks, I have, I put my findings (and a work-around) in [my answer below](http://stackoverflow.com/a/27585156/511529).
Comment: @GolezTrol do you see any error windows when form is loaded ?
Comment: Duplicate of: http://stackoverflow.com/questions/6717055/how-do-i-turn-off-compatibility-view-on-the-ie-webbrowsercontrol-in-a-winforms-a
Comment: @kjbartel That answer might be a work-around for this question, but the question is not a duplicate at all and there might be other solutions as well to really solve it.
Comment: @GolezTrol No they are exactly the same. You are asking how to use a website which requires a newer IE engine to work in the native IE [webbrowser control](http://msdn.microsoft.com/en-us/library/aa752040(v=vs.85).aspx) which defaults to compatibility view. .Net has wrappers for the control and I assume Delphi also, but it's still the same underlying control. How does changing the website make this a different question? All the answers will be exactly the same.
Comment: First of all *I* didn't ask this at all, although I captured this question a bit, because I had the same issue. The question here is *"Why does the StackExchange login hang in a WebBrowser control and not in a real web browser and how can I solve it."* There is no mention of a website that needs a newer IE, because that fact was apparently unknown. Actually, I found that out and described that in my answer (which is indeed mine), but because the answer is similar, doesn't mean that the question is too. `Sqrt(25)` is not the same question as `2+3`.
Answer: Fixing WebBrowser Control
I also had the issue of the WebBrowser control handing when trying to login.
Although requesting a token in IE (11) works, I found that IE itself also hangs when I put it in IE 7 emulation mode. This suggested to me that my previous attempt to make the WebBrowser control use a newer version had failed.
I found this article, Web Browser Control Specifying the IE Version, which suggests that for 32 bit applications in 64 bit mode, you need to set a different registry value.
So now, I've added two values in the registry:
HKEY_CURRENT_USER\Software\Microsoft\Internet Explorer\Main\FeatureControl\FEATURE_BROWSER_EMULATION

and
HKEY_CURRENT_USER\Software\Wow6432Node\Microsoft\Internet Explorer\MAIN\FeatureControl\FEATURE_BROWSER_EMULATION

In both of them, I added a DWORD value named 'MyExecutable.exe' (where MyExecutable is the actual name of my executable). The value for each of them is 9000 which will work for IE9 and above. Watch out when using RegEdit to test this, it will default to hexadecimal instead of decimal. Also, make sure it is a DWORD value, not any other type.
This seems to do the trick. I can now run the application, go through the login process, and eventually I am redirected to the url specified by me, which I can then capture using the OnNavigate event of the webbrowser control.
Remaining issue
It doesn't really work perfectly. The first time I was redirected to some OpenID page as well, but at least the form didn't hang. With subsequent attempts, apparently the login (which succeeded before) is remembered and I get the message "Navigation to the webpage was cancelled" with a link to refresh the page. When I click that link, I am immediately redirected to the redirect_url I specified when requesting the login form. At least that part works, and I get an actual access_token and an expiry time, so for now I'm happy.
Update: After some testing, it turned out that the previous login was remembered. That causes the request uri to direct to the redirect_uri immediately. I used the OnBeforeNavigate event to detect this, but it isn't fired in this case. I now linked the NavigateComplete2 event, and that one is triggered in this scenario.
Fix for .NET?
I think for .NET the solution should be the same: add the executable (and MyExecutabl.vshost.exe as well, for debugging purposes in Visual Studio) to the first key. If it's a 32 bit executable running on 62 bit Windows, you might also need to add it to the second key, although I'm sure if that rule applies to .NET as well. I don't do C# on a daily basis, and I'm trying to get it to work in Delphi first, but if I find time to test this in C# I will post the update here.
In the end, it would be nice if the actual issue would be solved, and the JavaScript would work in IE7 mode as well, but at least this seems to be a proper work-around.
Answer: Unfortunately, I'm not a JavaScript developer, so I only could try to explain you how to debug a JavaScript that executes in the WebBrowser control.
This approach is for the Microsoft Visual Studio, I don't know if Delphi can provide similar functionality.

Enable Script Debugging (both Internet Explorer and Other) in Internet Explorer settings.
Disable Friendly HTTP messages in Internet Explorer settings.
Enable Display a notification about every script error in Internet Explorer settings.
From Visual Studio, start your WebBrowser hosting application without debugging (i. e., Ctrl + F5).
In Visual Studio, go to Debug → Attach to Process… and select your application in the list.
Hit the Select… button to the right of Attach to: field and choose Script code.
Hit the Attach button. Visual Studio starts the script debugger.
In your application, navigate to the deadlocking page by pressing the Login with Stack Exchange account symbol.
Go to Visual Studio and press the Pause button on the debugging toolbar.

Now you can look into your script code and investigate the code itself, the call stack, the variable values and so on. You can set breakpoints too. Perhaps you can then find the place where the script hangs. As I said before, I'm not a web developer and cannot help you with this…
Update:
I guess I can propose you a working solution.
My investigation shows that the WebBrowser hangs when it renders the content in the IE7 mode (what is the default mode even if you have IE10 in your system). You should force it to switch into IE9 mode. In IE9 mode, the page renders well and does not cause the script to stuck in an endless loop.
You can switch your WebBrowser to the IE9 mode using one of the following methods:

Define the global browser emulation mode for your application in Windows registry.

For 32 bit OS, go to HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Internet Explorer\MAIN\FeatureControl\FEATURE_BROWSER_EMULATION.
For 64 bit OS, use HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\Internet Explorer\MAIN\FeatureControl\FEATURE_BROWSER_EMULATION.
In this node, create a new DWORD parameter called YourApplicationExeName.exe with a value 9000 (0x2710). You can create another entries for your *.vshost.exe executables, if you want this to work in Visual Studio debug mode.

Manipulate the source for the WebBrowser to switch it in the IE9 mode.

This will be more complicated. You need to alter the  tag of the html document adding a new <meta> tag preferably as a first element: <meta http-equiv="X-UA-Compatible" content="IE=9"/>.
This will cause the WebBrowser to switch its mode on document rendering. Since you can't change the compatibility mode after the document is rendered, you could use a proxy as a source for your WebBrowser, so this proxy will add the header.
I`ve successfully tested this with the 1st approach, and the second one should work too.
Hope that helps!
Comment: Thanks, I may try this, but even if I found a bug, I wouldn't know how to solve this, since this script is part of the StackApp/StackExchange login form.
Comment: Maybe you then know what you could change in your browser settings etc. so the script doesn't stuck in the endless loop.
Comment: Just updated the answer with a proposed solution, which I've successfully tested on my machine.
Comment: Thanks, I found out about option 1 myself and put it in an answer. I don't really know how to test option 2, but it seems a cumbersome approach relative to 1. Thanks for all your effort!
Answer: Project + Properties, Debug tab, tick the "Enable native code debugging" option.  Ensure that you've got the Microsoft Symbol server enabled (Tools + Options, Debugging, Symbols), I know you do :)
You can now use Debug + Break All and see what's going on inside the browser.  Do so repeatedly to get the lay of the land.  You'll see that Javascript is executing (jscript8.dll) and constantly forcing the layout engine to recalculate layout, never getting the job done.
Browsers in general are vulnerable to Javascript that's stuck in an endless loop.  A regular browser tends to put up a dialog after several dozen seconds to allow the user to abort the JS, but WebBrowser doesn't have that feature.  Nor does it have the dev tools so debugging the JS isn't going to be a great joy either.  This is going to be difficult to get fixed.
You might consider using the OAuth 2.0 api instead.  Notes on usage are on this web page.  Exactly how to integrate that with WebBrowser is a bit murky to me, I don't have a key to test this.  Find help for this at the Stackapps site.  You are probably not the first SE api user that ran into this problem.
Comment: I already asked in the stackapps site: http://stackapps.com/questions/4244/desktop-login-webbrowser-hangs-net    but they redirecte me to C# ;)    so I will try again to ask there for help... it seems so that desktop-authentication is not used very often... and maybe not under Windows....   I also tried IE compatibility-ode, but maybe I used the worng values....
Comment: I have no idea how to use OAuth directly... also I do not know if this is even supported... as far as I see is the login done in the server, and therefor always an url needed... It would be great if you have any links...

.NET 4 WebBrowser hangs


REST webservice using Spring MVC returning null while posting JSON

Question: Developing a REST web service using Spring MVC which accepts a JSON request body.
And process the received message further.
Iam using following :
Eclipse, Tomcat, Spring 3.0.1, Jackson lib, Curl for testing the web service

    `curl -i -H "Content-Type: application/json" -H "Accept: application/json" -X POST -d '{"fname":"my_firstname" , "lname":"my_lastname"}' http://localhost:8080/SpringMVC/restful`
returning
"Saved person: null null"
My controller class

        import com.samples.spring.Person;

    @Controller
    public class RestController {

    @RequestMapping(value="{person}", method = RequestMethod.POST)
    @ResponseBody
        public String savePerson(Person person) {
             // save person in database
            return "Saved person: " + person.getFname() +" "+ person.getLname();
        }

My person class

       package com.samples.spring;

    public class Person {

        public String fname;
        public String lname;

        public String getFname() {
            return fname;
        }
        public void setFname(String fname) {
            this.fname = fname;
        }
        public String getLname() {
            return lname;
        }
        public void setLname(String lname) {
            this.lname = lname;
        }
    }

Comment: Solved. Did two things as follows: 1.)Added @RequestBody 2.)Changed the Curl's JSON parameters from -d '{"fname":"my_firstname" , "lname":"my_lastname"}' ---- -d "{"""fname""":"""my_firstname""" , """lname""":"""my_lastname"""}". Can anyone explain this ???
Answer: try to add @RequestBody
@RequestMapping(value="{person}", method = RequestMethod.POST)
@ResponseBody
    public String savePerson(@RequestBody Person person) {
         // save person in database
        return "Saved person: " + person.getFname() +" "+ person.getLname();
    }

Answer: try to add a constructor your Person class:
public Person(String fname, String lname) {
    this.fname = fname;
    this.lname = lname;
}


How many treble keys should I have for accordion?

Question: I want to buy an accordion with 48 basses. I googled and found there are two different numbers treble keys, 26 and 34. My question is: is 26-treble key okay to play most songs as good as 34-treble key? Or there is a quite big difference between them?
Thanks.
Steve
Answer: 34 keys already tends to be quite limited: it is a range of less than 3 octaves (which would be 37 keys).  With 48 basses, you are confined to keys harmonically close to C major (and playing with other people may cause you to run out of basses pretty fast, particular in minor modes) which limits your starting positions, and once you start playing more than one note, a second voice will easily stray a sixth from the main melody, leaving a rather confined space to work with.
Regarding the workable range, chromatic button accordions tend to squeeze quite a bit more range into the same space particularly of small accordions but require more practice until you can play utilising simple scales (the advantage being that there are just 3 scales with regard to fingering compared to the 12 scales on a piano accordion; but at least when you are playing alone, you can avoid most of those scales on the piano accordion or postpone learning them for later).
Accordion literature tends to be playable mostly on 37 keys (typical for 96 basses) but sometimes wanting 41.  Of course, that's not small instrument stuff.  If you are playing simple melodies written for other instruments, one reference point may be the lowest note of a violin (which is a standard folk instrument), G3.  You want to have that on your accordion keyboard.  A 34-key accordion has it (typically starting at F3), a 26-key accordion hasn't (typically starting at B3).
Answer: It also rather depends what kind of music you're planning on playing. If you're playing folk music a 34 key will do you proud, because the music fits within that compass; they are also popular amongst Morris musicians because they are lighter to carry around. If you're playing classical or jazz, the wider range the better as every 12 keys gives you another octave.


Are eye disorders more common in wind instrument players?

Question: I played the clarinet for 12 years (from 9 to 21), and occasionally I practiced for hours a day. Out of curiosity I read that eye pressure increases temporarily during play.
Those who are professional players, do you think wind instrument players have more issues with their eyes?
Comment: It's probably more true that drumming makes you go deaf...
Comment: You'd have to ask Squinty & Bog-Eye, but right now they're on a gig with Picky the guitarist & the drummer, Thumbs.  *[sorry, couldn't resist] ;)*
Comment: @Tim I thought it was deaf people became drummers :-)
Comment: @tim WHAT!?!?!?
Comment: Please post a link to that allegation.  We really don't like responding to random claims from the fog of the internet.
Comment: https://www.ncbi.nlm.nih.gov/pubmed/10647731
https://www.researchgate.net/publication/49755064_Intraocular_pressure_fluctuations_in_professional_brass_and_woodwind_musicians_during_common_playing_conditions
https://www.ncbi.nlm.nih.gov/pubmed/10958606
Answer: I've spent nearly 50 years in the company of 'blowers' and can't say it's ever been an issue.  We could probably get the 'Daily Mail' to run a scare story.   (That's our British sensationalist newspaper, specialising in patriotic racism and  'Badgers give you cancer' scares. Sorta like Fox News?)
Comment: The plural of "anecdote" is not "data."
Comment: @CarlWitthoft - true. The plural of 'an ecdote' is 'several ecdotes'...
Comment: But a complete absence of anecdotes is of interest.
Comment: Actually, the original quote was from Raymond Wolfinger who is on record with "I said 'The plural of anecdote is data' some time in the 1969-70 academic year while teaching a graduate seminar at Stanford" - and it morphed into the opposite from there.
Answer: I recently developed glaucoma after 2 years of bass clarinet playing (2-4 hours daily).  My ophthalmologist discovered it, has been keeping watch on it, and checked references.  Conclusion: no connection. Instruments with possible links to eye pressure, according to her, are trumpet played a la Louis Armstrong, and bagpipes.