问:
The command '/bin/sh returned a non-zero code: 1
When I try to install a bin file manually inside a ubuntu Docker container it works perfectly,

```<code>./MyBinfile.bin
</code>```

but when I try it from my Dockerfile I always get the error :
The command '/bin/sh -c chmod +x /tmp/snapcenter_linux_host_plugin.bin && ./tmp/MyBinFile.bin' returned a non-zero code: 1

My Dockerfile looks like :

```<code>    FROM debian:jessie

    RUN apt-get update && apt-get install -y openjdk-7-jdk
    ENV JAVA_HOME /usr/lib/jvm/java-7-openjdk-amd64
    RUN echo $JAVA_HOME

    COPY MyBinFile.bin /tmp/MyBinFile.bin
    RUN chmod +x /tmp/MyBinFile.bin && ./tmp/MyBinFile.bin
</code>```

Can anyone help me in this case?

答:
You copied MyBinFile.bin to /tmp/MyBinFile.bin. Those are not the same file. If you need to run it use absolute path for the file that has executable attribute on it. So your last line should be:

```<code>RUN chmod +x /tmp/MyBinFile.bin && /tmp/MyBinFile.bin
</code>```

'.' (dot) represents your current current working directory. It's recommended to always use absolute paths if you're unsure what is your cwd.

EDIT

Running your Dockerfile produces the following output:

```<code>Sending build context to Docker daemon 3.584 kB
Step 1/6 : FROM debian:jessie
 ---> 8cedef9d7368
Step 2/6 : RUN apt-get update && apt-get install -y openjdk-7-jdk
 ---> Using cache
 ---> 1a0005923f41
Step 3/6 : ENV JAVA_HOME /usr/lib/jvm/java-7-openjdk-amd64
 ---> Using cache
 ---> 5651d50b519e
Step 4/6 : RUN echo $JAVA_HOME
 ---> Using cache
 ---> 96655235a2cf
Step 5/6 : COPY MyBinFile.bin /tmp/MyBinFile.bin
 ---> 60c79aaf5aca
Removing intermediate container cd729c315e9b
Step 6/6 : RUN chmod +x /tmp/MyBinFile.bin && /tmp/MyBinFile.bin
 ---> Running in 5db126cbd24c
/bin/sh: 1: /tmp/MyBinFile.bin: Text file busy
The command '/bin/sh -c chmod +x /tmp/MyBinFile.bin &&
/tmp/MyBinFile.bin' returned a non-zero code: 2
</code>```

But if I separate your last step into two different steps:

```<code>FROM debian:jessie

RUN apt-get update && apt-get install -y openjdk-7-jdk
ENV JAVA_HOME /usr/lib/jvm/java-7-openjdk-amd64
RUN echo $JAVA_HOME

COPY MyBinFile.bin /tmp/MyBinFile.bin
RUN chmod +x /tmp/MyBinFile.bin
RUN /tmp/MyBinFile.bin
</code>```

then it executes OK.

Body:
When I try to install a bin file manually inside a ubuntu Docker container it works perfectly,

./MyBinfile.bin

but when I try it from my Dockerfile I always get the error :
The command '/bin/sh -c chmod +x /tmp/snapcenter_linux_host_plugin.bin && ./tmp/MyBinFile.bin' returned a non-zero code: 1

My Dockerfile looks like :

    FROM debian:jessie

    RUN apt-get update && apt-get install -y openjdk-7-jdk
    ENV JAVA_HOME /usr/lib/jvm/java-7-openjdk-amd64
    RUN echo $JAVA_HOME

    COPY MyBinFile.bin /tmp/MyBinFile.bin
    RUN chmod +x /tmp/MyBinFile.bin && ./tmp/MyBinFile.bin

Can anyone help me in this case?

Body:
You copied MyBinFile.bin to /tmp/MyBinFile.bin. Those are not the same file. If you need to run it use absolute path for the file that has executable attribute on it. So your last line should be:

RUN chmod +x /tmp/MyBinFile.bin && /tmp/MyBinFile.bin

'.' (dot) represents your current current working directory. It's recommended to always use absolute paths if you're unsure what is your cwd.

EDIT

Running your Dockerfile produces the following output:

Sending build context to Docker daemon 3.584 kB
Step 1/6 : FROM debian:jessie
 ---> 8cedef9d7368
Step 2/6 : RUN apt-get update && apt-get install -y openjdk-7-jdk
 ---> Using cache
 ---> 1a0005923f41
Step 3/6 : ENV JAVA_HOME /usr/lib/jvm/java-7-openjdk-amd64
 ---> Using cache
 ---> 5651d50b519e
Step 4/6 : RUN echo $JAVA_HOME
 ---> Using cache
 ---> 96655235a2cf
Step 5/6 : COPY MyBinFile.bin /tmp/MyBinFile.bin
 ---> 60c79aaf5aca
Removing intermediate container cd729c315e9b
Step 6/6 : RUN chmod +x /tmp/MyBinFile.bin && /tmp/MyBinFile.bin
 ---> Running in 5db126cbd24c
/bin/sh: 1: /tmp/MyBinFile.bin: Text file busy
The command '/bin/sh -c chmod +x /tmp/MyBinFile.bin &&
/tmp/MyBinFile.bin' returned a non-zero code: 2

But if I separate your last step into two different steps:

FROM debian:jessie

RUN apt-get update && apt-get install -y openjdk-7-jdk
ENV JAVA_HOME /usr/lib/jvm/java-7-openjdk-amd64
RUN echo $JAVA_HOME

COPY MyBinFile.bin /tmp/MyBinFile.bin
RUN chmod +x /tmp/MyBinFile.bin
RUN /tmp/MyBinFile.bin

then it executes OK.


来源: stackexchange

问:
join, group by and count sql to linq conversion
Query:

```<code>SELECT COUNT(*) as Avalied
FROM LeaveMaster as lm
JOIN LeaveSubsidary as ls
ON lm.TransMasterId = ls.TransMasterId
WHERE lm.SystemCode = 'abc123' AND lm.EmployeeCode = '0014' AND lm.Status ='Approved'
Group by ls.Leave_Type
</code>```

How would you convert the above sql query to linq? Thanks :)

Edit :

```<code>from p in db.PY_LeaveTransactionMasterTAB.AsEnumerable()
join e in db.PY_LeaveTransactionSubsidaryTAB.AsEnumerable() on p.LV_TransMasterId equals e.LV_TransMasterId into grp
where p.SystemCode == SysCode && p.EmployeeCode == EmpCode && p.Status == "Approved"
group grp by e.Leave_Type // This line is invalid Why?
</code>```

The above is what I have tried so far, why can't I do e.Leave_Type or what is the right way to do group grp by e.Leave_Type?

答:
You could try this:</p>

```<code>(from p in db.PY_LeaveTransactionMasterTAB
join e in db.PY_LeaveTransactionSubsidaryTAB on p.LV_TransMasterId equals e.LV_TransMasterId
where p.SystemCode == SysCode && p.EmployeeCode == EmpCode && p.Status == "Approved"
group new {p,e} by new {e.Leave_Type } into gr
select new
{
   Leave_Type = gr.Key.Leave_Type ,
   Count = gr.Count()
}).ToList();
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Query:

SELECT COUNT(*) as Avalied
FROM LeaveMaster as lm
JOIN LeaveSubsidary as ls
ON lm.TransMasterId = ls.TransMasterId
WHERE lm.SystemCode = 'abc123' AND lm.EmployeeCode = '0014' AND lm.Status ='Approved'
Group by ls.Leave_Type

How would you convert the above sql query to linq? Thanks :)

Edit :

from p in db.PY_LeaveTransactionMasterTAB.AsEnumerable()
join e in db.PY_LeaveTransactionSubsidaryTAB.AsEnumerable() on p.LV_TransMasterId equals e.LV_TransMasterId into grp
where p.SystemCode == SysCode && p.EmployeeCode == EmpCode && p.Status == "Approved"
group grp by e.Leave_Type // This line is invalid Why?

The above is what I have tried so far, why can't I do e.Leave_Type or what is the right way to do group grp by e.Leave_Type?

Body:
You could try this:

(from p in db.PY_LeaveTransactionMasterTAB
join e in db.PY_LeaveTransactionSubsidaryTAB on p.LV_TransMasterId equals e.LV_TransMasterId
where p.SystemCode == SysCode && p.EmployeeCode == EmpCode && p.Status == "Approved"
group new {p,e} by new {e.Leave_Type } into gr
select new
{
   Leave_Type = gr.Key.Leave_Type ,
   Count = gr.Count()
}).ToList();


问:
Early exit from function in a forEach?
How can I early exit from a function in my TypeScript file?

```<code>checkIfFollowed(){

    this.currentUserInfos.followed.forEach(element => {
        if(18785 == 18785){
            console.log('its true');
            this.alreadyFollowed = true;
            return; // Exit checkIfFollowed() here
        }

    });

    this.alreadyFollowed = false;
    console.log('the end');
    return;
}
</code>```

When I'm running it, it's executed completely, but it should exit after the first:

'its true'

But in my console, I get:

its true

its true

the end

Foreach loops 2 times as expected, but why the method doesn't stop after hitting a "return"?

I'm not trying to get out of the forEach, but ending the method 'checkIfFollowed' in the foreach.

'the end' should not be printed.

答:
Try this instead of forEach

.every() (stops looping the first time the iterator returns false or something falsey)

With every():

```<code>checkIfFollowed(){

        this.currentUserInfos.followed.every(function(element, index) {
            // Do something.
            if (18785 == 18785){
                console.log('its true');
                this.alreadyFollowed = true;
                return false;
            }
        });
        if(this.alreadyFollowed)
        {
            return ;
        }
        this.alreadyFollowed = false;
        console.log('the end');
        return;
}
</code>```

ContentLicense: CC BY-SA 4.0

Title: Early exit from function in a forEach?

Body:
How can I early exit from a function in my TypeScript file?

checkIfFollowed(){

    this.currentUserInfos.followed.forEach(element => {
        if(18785 == 18785){
            console.log('its true');
            this.alreadyFollowed = true;
            return; // Exit checkIfFollowed() here
        }

    });

    this.alreadyFollowed = false;
    console.log('the end');
    return;
}

When I'm running it, it's executed completely, but it should exit after the first:

'its true'

But in my console, I get:

its true

its true

the end

Foreach loops 2 times as expected, but why the method doesn't stop after hitting a "return"?

I'm not trying to get out of the forEach, but ending the method 'checkIfFollowed' in the foreach.

'the end' should not be printed.

Body:
Try this instead of forEach

.every() (stops looping the first time the iterator returns false or something falsey)

With every():

checkIfFollowed(){

        this.currentUserInfos.followed.every(function(element, index) {
            // Do something.
            if (18785 == 18785){
                console.log('its true');
                this.alreadyFollowed = true;
                return false;
            }
        });
        if(this.alreadyFollowed)
        {
            return ;
        }
        this.alreadyFollowed = false;
        console.log('the end');
        return;
}


问:
Java multithreading - joining a CPU heavy thread and volatile keyword
So, follwoing some job interviews I wanted to write a small program to check that i++  really is non-atomic in java, and that one should, in practice,add some locking to protect it. Turns out you should, but this is not the question here.

So I wrote this program here just to check it.

The thing is, it hangs. It seems that the main thread is stuck on on t1.join()
 line, even though both worker threads should finish because of the stop = true from previous line.

I found that the hanging stops if :

I add some printing inside the worker threads (as in the comments), probably causing the worker threads to sometime give up CPU
or

If I mark the flag boolean stop as volatile, causing the write to immediately
be seen by worker threads, or

If I mark the counter tas volatile... for this I have no idea what causes the un-hanging.

Can someone explain what's going on? why do I see the hang and why does it stop in those three cases?

```<code>public class Test {

    static /* volatile */ long t = 0;
    static long[] counters = new long[2];
    static /* volatile */ boolean stop = false;

    static Object o = new Object();
    public static void main(String[] args)
    {
        Thread t1 = createThread(0);
        Thread t2 = createThread(1);

        t1.start();
        t2.start();

        Thread.sleep(1000);

        stop = true;

        t1.join();
        t2.join();

        System.out.println("counter : " + t + " counters : " + counters[0] + ", " + counters[1]  + " (sum  : " + (counters[0] + counters[1]) + ")");

    }

    private static Thread createThread(final int i)
    {
        Thread thread = new Thread() {
            public void run() {
                while (!stop)
                {
//                  synchronized (o) {
                        t++;
//                  }

//                  if (counters[i] % 1000000 == 0)
//                  {
//                      System.out.println(i + ")" + counters[i]);
//                  }
                    counters[i]++;
                }
            };
        };
        return thread;
    }
}
</code>```

答:
It does, actually, what it said to -- provides consistent access to the field between multiple threads, and you can see it.

Without volatile keyword, multithread access to the field is not guaranteed to be consistent, compilers can introduce some optimisations, like caching it in the CPU register, or not writing out from CPU core local cache to external memory or shared cache.

For part with non-volatile stop and volatile t

According to JSR-133 Java Memory Model specification, all writes (to any other field) before volatile field update are made visible, they are happened-before actions.

When you set stop flag after incrementing t, it will be not visible by subsequent read in the loop, but next increment (volatile-write) will make it visible.

See also

Java Language Specification: 8.3.1.4. volatile Fields

An article about Java Memory Model, from the author of Java theory and practice

Body:
So, follwoing some job interviews I wanted to write a small program to check that i++  really is non-atomic in java, and that one should, in practice,add some locking to protect it. Turns out you should, but this is not the question here.

So I wrote this program here just to check it.

The thing is, it hangs. It seems that the main thread is stuck on on t1.join()
 line, even though both worker threads should finish because of the stop = true from previous line.

I found that the hanging stops if :

I add some printing inside the worker threads (as in the comments), probably causing the worker threads to sometime give up CPU
or

If I mark the flag boolean stop as volatile, causing the write to immediately
be seen by worker threads, or

If I mark the counter tas volatile... for this I have no idea what causes the un-hanging.

Can someone explain what's going on? why do I see the hang and why does it stop in those three cases?

public class Test {

    static /* volatile */ long t = 0;
    static long[] counters = new long[2];
    static /* volatile */ boolean stop = false;

    static Object o = new Object();
    public static void main(String[] args)
    {
        Thread t1 = createThread(0);
        Thread t2 = createThread(1);

        t1.start();
        t2.start();

        Thread.sleep(1000);

        stop = true;

        t1.join();
        t2.join();

        System.out.println("counter : " + t + " counters : " + counters[0] + ", " + counters[1]  + " (sum  : " + (counters[0] + counters[1]) + ")");

    }

    private static Thread createThread(final int i)
    {
        Thread thread = new Thread() {
            public void run() {
                while (!stop)
                {
//                  synchronized (o) {
                        t++;
//                  }

//                  if (counters[i] % 1000000 == 0)
//                  {
//                      System.out.println(i + ")" + counters[i]);
//                  }
                    counters[i]++;
                }
            };
        };
        return thread;
    }
}


问:
Annotation box does not appear in matplotlib
The planned annotation box does not appear on my plot, however, I've tried a wide range of values for its coordinates.

What's wrong with that?!

```<code>import numpy as np
from scipy.integrate import odeint
import matplotlib.pyplot as plt

def f(s,t):
    a = 0.7
    b = 0.8
    Iext= 0.5
    tau = 12.5
    v = s[0]
    w = s[1]
    dndt = v - np.power(v,3)/3 - w + Iext
    dwdt = (v + a - b * w)/tau
    return [dndt, dwdt]

t = np.linspace(0,200)
s0=[1,1]

s = odeint(f,s0,t)

plt.plot(t,s[:,0],'b-', linewidth=1.0)
plt.xlabel(r"$t(sec.)$")
plt.ylabel(r"$V (volt)$")
plt.legend([r"$V$"])

annotation_string = r"$I_{ext}=0.5$"
plt.text(15, 60, annotation_string, bbox=dict(facecolor='red', alpha=0.5))

plt.show()
</code>```

答:
The coordinates to plt.text are data coordinates by default. This means in order to be present in the plot they should not exceed the data limits of your plot (here, ~0..200 in x direction, ~-2..2 in y direction).

Something like plt.text(10,1.8) should work.

The problem with that is that once the data limits change (because you plot something different or add another plot) the text item will be at a different position inside the canvas.

If this is undesired, you can specify the text in axes coordinates (ranging from 0 to 1 in both directions). In order to place the text always in the top left corner of the axes, independent on what you plot there, you can use e.g.

```<code>plt.text(0.03,0.97, annotation_string, bbox=dict(facecolor='red', alpha=0.5),
         transform=plt.gca().transAxes, va = "top", ha="left")
</code>```

Here the transform keyword tells the text to use Axes coordinates, and va = "top", ha="left" means, that the top left corner of the text should be the anchor point.

Body:
The planned annotation box does not appear on my plot, however, I've tried a wide range of values for its coordinates.

What's wrong with that?!

import numpy as np
from scipy.integrate import odeint
import matplotlib.pyplot as plt

def f(s,t):
    a = 0.7
    b = 0.8
    Iext= 0.5
    tau = 12.5
    v = s[0]
    w = s[1]
    dndt = v - np.power(v,3)/3 - w + Iext
    dwdt = (v + a - b * w)/tau
    return [dndt, dwdt]

t = np.linspace(0,200)
s0=[1,1]

s = odeint(f,s0,t)

plt.plot(t,s[:,0],'b-', linewidth=1.0)
plt.xlabel(r"$t(sec.)$")
plt.ylabel(r"$V (volt)$")
plt.legend([r"$V$"])

annotation_string = r"$I_{ext}=0.5$"
plt.text(15, 60, annotation_string, bbox=dict(facecolor='red', alpha=0.5))

plt.show()

Body:
The coordinates to plt.text are data coordinates by default. This means in order to be present in the plot they should not exceed the data limits of your plot (here, ~0..200 in x direction, ~-2..2 in y direction).

Something like plt.text(10,1.8) should work.

The problem with that is that once the data limits change (because you plot something different or add another plot) the text item will be at a different position inside the canvas.

If this is undesired, you can specify the text in axes coordinates (ranging from 0 to 1 in both directions). In order to place the text always in the top left corner of the axes, independent on what you plot there, you can use e.g.

plt.text(0.03,0.97, annotation_string, bbox=dict(facecolor='red', alpha=0.5),
         transform=plt.gca().transAxes, va = "top", ha="left")

Here the transform keyword tells the text to use Axes coordinates, and va = "top", ha="left" means, that the top left corner of the text should be the anchor point.


问:
Prevent tooltip in converting HTML Entities

<input ng-model="test" placeholder="pre" type="text" title="PROJECT&GT" />```

The above code for tooltip displays "PROJECT>". But what I need is to display the text as is "PROJECT&GT"

Is there a way to do this? I'm using angular.

答:
One way to go is to separate the & from the GT (or any other similar entity) with a  which is a Zero Width No-Break Space (http://www.codetable.net/hex/feff), like this:

<input ng-model="test" placeholder="pre" type="text" title="PROJECT&GT" />```

Body:
<input ng-model="test" placeholder="pre" type="text" title="PROJECT&GT" />

The above code for tooltip displays "PROJECT>". But what I need is to display the text as is "PROJECT&GT"

Is there a way to do this? I'm using angular.

Body:
One way to go is to separate the & from the GT (or any other similar entity) with a &#xfeff; which is a Zero Width No-Break Space (http://www.codetable.net/hex/feff), like this:

<input ng-model="test" placeholder="pre" type="text" title="PROJECT&&#xfeff;GT" />


问:
Change event on Select without triggering Click event
I've got this code:

```<code>var $d_docSelect = $("<select>").appendTo($registerExamBox).click(function(){
    while($d_docSelect[0].firstChild) $d_docSelect[0].removeChild($d_docSelect[0].firstChild);
    $.ajax({
        url: 'test.php',
        type: 'POST',
        data: {
            func: 87,
        }
    }).done(function($msg){
        try{
            $docs = JSON.parse($msg);
        }catch($e){
            console.log($e.message);
            return false;
        }
        $docs.forEach(function($row){
            $("<option>", {"doc" : $row[0]}).text($row[1] + ' ' + $row[2] + ' ' + $row[3]).appendTo($d_docSelect);
        })
        $("<option>").text("Dodaj").appendTo($d_docSelect);
    });
}).change(function(){
    if($d_docSelect[0].selectedIndex == $d_docSelect[0].length - 1){
        addDoc($d_docSelect);
    }
});
</code>```

Everytime i change option i select, not only "change" event triggers, but "click" too.
I don't want to trigger "click" when changing option, and I don't know how. I didn't find answer here and on Google.

答: in javascript you may be used bubbling for capturing event when you adding event on perticular html if you set 3 rd parameter true on addEventListner()  then you may prevent click </p>

Body:
I've got this code:

var $d_docSelect = $("<select>").appendTo($registerExamBox).click(function(){
    while($d_docSelect[0].firstChild) $d_docSelect[0].removeChild($d_docSelect[0].firstChild);
    $.ajax({
        url: 'test.php',
        type: 'POST',
        data: {
            func: 87,
        }
    }).done(function($msg){
        try{
            $docs = JSON.parse($msg);
        }catch($e){
            console.log($e.message);
            return false;
        }
        $docs.forEach(function($row){
            $("<option>", {"doc" : $row[0]}).text($row[1] + ' ' + $row[2] + ' ' + $row[3]).appendTo($d_docSelect);
        })
        $("<option>").text("Dodaj").appendTo($d_docSelect);
    });
}).change(function(){
    if($d_docSelect[0].selectedIndex == $d_docSelect[0].length - 1){
        addDoc($d_docSelect);
    }
});

Everytime i change option i select, not only "change" event triggers, but "click" too.
I don't want to trigger "click" when changing option, and I don't know how. I didn't find answer here and on Google.


问:
Xvfb plugin to run multiple job instances concurrently on Jenkins
I have a job in Jenkins that runs UI tests written in Selenium. The job can run multiple instances of it concurrently. I am running into a problem while trying to use Xvfb (the Xvfb plugin or otherwise).

Using the Xvfb plugin

The configuration is as below.

The plugin assigns the same display port to 2 concurrent job instances, and then one fails.

From the Xvfb log (note displayfd is 2 and screen is 0 in both cases):

```<code>Xvfb starting$ /usr/bin/Xvfb -displayfd 2 -screen 0 1024x758x16 -fbdir /srv/jenkins/xvfb-86-2156913754362856583.fbdir
Xvfb starting$ /usr/bin/Xvfb -displayfd 2 -screen 0 1024x758x16 -fbdir /srv/jenkins/xvfb-87-5845090375656014678.fbdir
</code>```

One of the above 2 job instances fails. The failure message is this:

```<code>02:11:51 _XSERVTransSocketINETCreateListener: ...SocketCreateListener() failed
02:11:51 _XSERVTransMakeAllCOTSServerListeners: server already running
</code>```

How can this error be fixed so that the concurrent instances run without any issue?

Further, I wonder how Xvfb plugin does the association of the display to the running browser instances (Firefox in this case). Does it do export DISPLAY=:xx internally, where xx = the display port as computed by the plugin?

Command line (not using Xvfb plugin)

The second way I tried is not to use the plugin and run Xvfb directly using the CLI. I used the Jenkins env variable BUILD_NUMBER to ensure unique display association to the job instance.

```<code>export DISPLAY=:${BUILD_NUMBER}
Xvfb :${BUILD_NUMBER} -screen 0 1024x768x24 &
</code>```

Xvfb starts up fine in both job instances, but the tests fail with this.

```<code>Failed to connect to binary FirefoxBinary(/usr/local/bin/firefox) on port 7055; process output follows:
Error: cannot open display: 0:0
</code>```

It appears the tests are still trying to use display 0:0.

Any help to fix this problem is greatly appreciated.

答: Have you tried to use Display environment variable in Jenkins, the same Xvbf has started with? In my case it worked and I followed the instructions, described in this article headless execution selenium tests in Jenkins</p>

Body:
I have a job in Jenkins that runs UI tests written in Selenium. The job can run multiple instances of it concurrently. I am running into a problem while trying to use Xvfb (the Xvfb plugin or otherwise).

Using the Xvfb plugin

The configuration is as below.

The plugin assigns the same display port to 2 concurrent job instances, and then one fails.

From the Xvfb log (note displayfd is 2 and screen is 0 in both cases):

Xvfb starting$ /usr/bin/Xvfb -displayfd 2 -screen 0 1024x758x16 -fbdir /srv/jenkins/xvfb-86-2156913754362856583.fbdir
Xvfb starting$ /usr/bin/Xvfb -displayfd 2 -screen 0 1024x758x16 -fbdir /srv/jenkins/xvfb-87-5845090375656014678.fbdir

One of the above 2 job instances fails. The failure message is this:

02:11:51 _XSERVTransSocketINETCreateListener: ...SocketCreateListener() failed
02:11:51 _XSERVTransMakeAllCOTSServerListeners: server already running

How can this error be fixed so that the concurrent instances run without any issue?

Further, I wonder how Xvfb plugin does the association of the display to the running browser instances (Firefox in this case). Does it do export DISPLAY=:xx internally, where xx = the display port as computed by the plugin?

Command line (not using Xvfb plugin)

The second way I tried is not to use the plugin and run Xvfb directly using the CLI. I used the Jenkins env variable BUILD_NUMBER to ensure unique display association to the job instance.

export DISPLAY=:${BUILD_NUMBER}
Xvfb :${BUILD_NUMBER} -screen 0 1024x768x24 &

Xvfb starts up fine in both job instances, but the tests fail with this.

Failed to connect to binary FirefoxBinary(/usr/local/bin/firefox) on port 7055; process output follows:
Error: cannot open display: 0:0

It appears the tests are still trying to use display 0:0.

Any help to fix this problem is greatly appreciated.


问:
how to change the layout of category page in magento1.9
I'm trying to change the layout of category page in Magento through the admin panel. Did all the changes as needed showing below in image:

custom tab of deafult

In sub-category, I did [Custom Design->Use Parent Category Setting-> yes]

but the problem is changes aren't reflecting in the frontend, no matter whatever the layout is chosen.
this is the view of my frontend page
Added the block in local.xml too.

```<code>   <?xml version="1.0"?>
<layout version="0.1.0">
<default>
</default>
<catalog_category_default>
  <reference name="root">
    <action method="setTemplate"><template>page/2columns-left.phtml</template></action>
  </reference>
</catalog_category_default>
</layout>
</code>```

答:
As I can see from your question, you want to change the page layout for a particular category. you can achieve this using backend panel itself and without writing any xml.

To change the category page layout:

From the Admin menu, select Catalog > Manage Categories.

In the Categories tree, select the category level you want to change.

On the Custom Design tab, set Page Layout to “2 columns left”

Click the Save Category button.

so in your screenshot this tab is open and set to 3 columns, you can change it to 2 columns.

Body:
I'm trying to change the layout of category page in Magento through the admin panel. Did all the changes as needed showing below in image:

custom tab of deafult

In sub-category, I did [Custom Design->Use Parent Category Setting-> yes]

but the problem is changes aren't reflecting in the frontend, no matter whatever the layout is chosen.
this is the view of my frontend page
Added the block in local.xml too.

   <?xml version="1.0"?>
<layout version="0.1.0">
<default>
</default>
<catalog_category_default>
  <reference name="root">
    <action method="setTemplate"><template>page/2columns-left.phtml</template></action>
  </reference>
</catalog_category_default>
</layout>


问:
Azure IoT hub connection string not working anymore - Does azure update the connection string?
For some reason today after 2 months my IoT hub connection string did not work anymore which gave me a :

Exception when sending message:{"Message":"ErrorCode:IotHubUnauthorizedAccess;Unauthorized","ExceptionMessage":""}

I later found out that my connectionString changed in the IoT for which I use a free license. Even though I updated my connectionString to the new one I still get the same error which makes me wonder:

Does Azure IoT hub require you to change your connectionString every now and then? If yes does anyone know a best practice to do this automatically?

Does IoT Hub require you to have the most recent SDK's from Microsoft.azure.devices. and Microsoft.Azure.devices.client ?

As far as I know it just randomly stopped working over the weekend without any explanation and I have no clue why because there where 0 changes in the code or in Azure from me.

答:
Event Hub relies on keys for access. Is there is a chance someone regenerated the key from the Shared Access Policy or via PowerShell?

You also mentioned you are using a free account - if you are sure you have the correct key, is there a chance your free trial has expired or exceeded the quota of 8,000 messages per day - see the pricing calculator.

As far as you questions are concerned:

Key cycling is not enforced by default.

I do not believe that the latest SDK must always be used.

Note that Event Hub is still in preview, so breaking changes are possible. I see you did mention IOT Hub, which works the same way for access control, but is a production service. It should be solid.


问:
How to sum all 32-bit or 64-bit sub-registers in an SSE XMM, or AVX YMM, and ZMM register?
Say your task results in a subtotal in each floating-point subregister.  I'm not seeing an instruction that would sum the subtotals down to one floating-point total.  Do I need to store the MM register in plain old memory then do the sum with simple instructions?

(It's unresolved whether these will be double or single-precision, and I plan on coding for every CPU variation up to the forthcoming (?) 512-bit AVX version if I can find the opcodes.)

答:
```<code>wget http://www.agner.org/optimize/vectorclass.zip
unzip vectorclass.zip -d vectorclass
cd vectorclass/
</code>```

This code is GPLv3.

SSE

```<code>grep -A11 horizontal_add vectorf128.h
</code>```

static inline float horizontal_add (Vec4f const & a) {
#if  INSTRSET >= 3  // SSE3
    __m128 t1 = _mm_hadd_ps(a,a);
    __m128 t2 = _mm_hadd_ps(t1,t1);
    return _mm_cvtss_f32(t2);
#else
    __m128 t1 = _mm_movehl_ps(a,a);
    __m128 t2 = _mm_add_ps(a,t1);
    __m128 t3 = _mm_shuffle_ps(t2,t2,1);
    __m128 t4 = _mm_add_ss(t2,t3);
    return _mm_cvtss_f32(t4);
#endif
--
static inline double horizontal_add (Vec2d const & a) {
#if  INSTRSET >= 3  // SSE3
    __m128d t1 = _mm_hadd_pd(a,a);
    return _mm_cvtsd_f64(t1);
#else
    __m128  t0 = _mm_castpd_ps(a);
    __m128d t1 = _mm_castps_pd(_mm_movehl_ps(t0,t0));
    __m128d t2 = _mm_add_sd(a,t1);
    return _mm_cvtsd_f64(t2);
#endif
}
```

<p>AVX</p>

```grep -A6 horizontal_add vectorf256.h
```

<pre class="lang-c prettyprint-override"><code>static inline float horizontal_add (Vec8f const & a) {
    __m256 t1 = _mm256_hadd_ps(a,a);
    __m256 t2 = _mm256_hadd_ps(t1,t1);
    __m128 t3 = _mm256_extractf128_ps(t2,1);
    __m128 t4 = _mm_add_ss(_mm256_castps256_ps128(t2),t3);
    return _mm_cvtss_f32(t4);
}
--
static inline double horizontal_add (Vec4d const & a) {
    __m256d t1 = _mm256_hadd_pd(a,a);
    __m128d t2 = _mm256_extractf128_pd(t1,1);
    __m128d t3 = _mm_add_sd(_mm256_castpd256_pd128(t1),t2);
    return _mm_cvtsd_f64(t3);
}
</code>```

AVX512

```<code>grep -A3 horizontal_add vectorf512.h
</code>```

static inline float horizontal_add (Vec16f const & a) {
#if defined(__INTEL_COMPILER)
    return _mm512_reduce_add_ps(a);
#else
    return horizontal_add(a.get_low() + a.get_high());
#endif
}

--
static inline double horizontal_add (Vec8d const & a) {
#if defined(__INTEL_COMPILER)
    return _mm512_reduce_add_pd(a);
#else
    return horizontal_add(a.get_low() + a.get_high());
#endif
}
```

<p><code>get_high()</code> and <code>get_low()</code></p>

<pre class="lang-c prettyprint-override"><code>Vec8f get_high() const {
    return _mm256_castpd_ps(_mm512_extractf64x4_pd(_mm512_castps_pd(zmm),1));
}
Vec8f get_low() const {
    return _mm512_castps512_ps256(zmm);
}

Vec4d get_low() const {
    return _mm512_castpd512_pd256(zmm);
}

Vec4d get_high() const {
    return _mm512_extractf64x4_pd(zmm,1);
}
</code>```

For integers look for horizontal_add in vectori128.h, vectori256.h, and vectori512.h.

You can also use the Vector Class Library (VCL) directly

```<code>#include <stdio.h>
#define MAX_VECTOR_SIZE 512
#include "vectorclass.h"

int main(void) {

  float x[16]; for(int i=0;i<16;i++) x[i]=i+1;
  Vec4f  v4  =  Vec4f().load(x);
  Vec8f  v8  =  Vec8f().load(x);
  Vec16f v16 = Vec16f().load(x);

  printf("%f %d\n", horizontal_add(v4), 4*5/2);
  printf("%f %d\n", horizontal_add(v8), 8*9/2);
  printf("%f %d\n", horizontal_add(v16), 16*17/2);
}
</code>```

Compile like this (GCC only my KNL is too old for AVX512)

```<code>SSE2:     g++  -O3 test.cpp
AVX:      g++  -O3 -mavx test.cpp
AVX512ER: icpc -O3 -xMIC-AVX512 test.cpp
</code>```

output

```<code>10.000000 10
36.000000 36
136.000000 136
</code>```

One nice thing with the VCL library is that if you use e.g. Vec8f with a system that only has SSE2 it will emulate AVX using SSE twice.

See the section "Instruction sets and CPU dispatching" in the vectorclass.pdf manual for how to compile for different instruction sets with MSVC, ICC, Clang, and GCC.

Body:
wget http://www.agner.org/optimize/vectorclass.zip
unzip vectorclass.zip -d vectorclass
cd vectorclass/

This code is GPLv3.

SSE

grep -A11 horizontal_add vectorf128.h

static inline float horizontal_add (Vec4f const & a) {
#if  INSTRSET >= 3  // SSE3
    __m128 t1 = _mm_hadd_ps(a,a);
    __m128 t2 = _mm_hadd_ps(t1,t1);
    return _mm_cvtss_f32(t2);
#else
    __m128 t1 = _mm_movehl_ps(a,a);
    __m128 t2 = _mm_add_ps(a,t1);
    __m128 t3 = _mm_shuffle_ps(t2,t2,1);
    __m128 t4 = _mm_add_ss(t2,t3);
    return _mm_cvtss_f32(t4);
#endif
--
static inline double horizontal_add (Vec2d const & a) {
#if  INSTRSET >= 3  // SSE3
    __m128d t1 = _mm_hadd_pd(a,a);
    return _mm_cvtsd_f64(t1);
#else
    __m128  t0 = _mm_castpd_ps(a);
    __m128d t1 = _mm_castps_pd(_mm_movehl_ps(t0,t0));
    __m128d t2 = _mm_add_sd(a,t1);
    return _mm_cvtsd_f64(t2);
#endif
}

AVX

grep -A6 horizontal_add vectorf256.h

static inline float horizontal_add (Vec8f const & a) {
    __m256 t1 = _mm256_hadd_ps(a,a);
    __m256 t2 = _mm256_hadd_ps(t1,t1);
    __m128 t3 = _mm256_extractf128_ps(t2,1);
    __m128 t4 = _mm_add_ss(_mm256_castps256_ps128(t2),t3);
    return _mm_cvtss_f32(t4);
}
--
static inline double horizontal_add (Vec4d const & a) {
    __m256d t1 = _mm256_hadd_pd(a,a);
    __m128d t2 = _mm256_extractf128_pd(t1,1);
    __m128d t3 = _mm_add_sd(_mm256_castpd256_pd128(t1),t2);
    return _mm_cvtsd_f64(t3);
}

AVX512

grep -A3 horizontal_add vectorf512.h

static inline float horizontal_add (Vec16f const & a) {
#if defined(__INTEL_COMPILER)
    return _mm512_reduce_add_ps(a);
#else
    return horizontal_add(a.get_low() + a.get_high());
#endif
}

--
static inline double horizontal_add (Vec8d const & a) {
#if defined(__INTEL_COMPILER)
    return _mm512_reduce_add_pd(a);
#else
    return horizontal_add(a.get_low() + a.get_high());
#endif
}

get_high() and get_low()

Vec8f get_high() const {
    return _mm256_castpd_ps(_mm512_extractf64x4_pd(_mm512_castps_pd(zmm),1));
}
Vec8f get_low() const {
    return _mm512_castps512_ps256(zmm);
}

Vec4d get_low() const {
    return _mm512_castpd512_pd256(zmm);
}

Vec4d get_high() const {
    return _mm512_extractf64x4_pd(zmm,1);
}

For integers look for horizontal_add in vectori128.h, vectori256.h, and vectori512.h.

You can also use the Vector Class Library (VCL) directly

#include <stdio.h>
#define MAX_VECTOR_SIZE 512
#include "vectorclass.h"

int main(void) {

  float x[16]; for(int i=0;i<16;i++) x[i]=i+1;
  Vec4f  v4  =  Vec4f().load(x);
  Vec8f  v8  =  Vec8f().load(x);
  Vec16f v16 = Vec16f().load(x);

  printf("%f %d\n", horizontal_add(v4), 4*5/2);
  printf("%f %d\n", horizontal_add(v8), 8*9/2);
  printf("%f %d\n", horizontal_add(v16), 16*17/2);
}

Compile like this (GCC only my KNL is too old for AVX512)

SSE2:     g++  -O3 test.cpp
AVX:      g++  -O3 -mavx test.cpp
AVX512ER: icpc -O3 -xMIC-AVX512 test.cpp

output

10.000000 10
36.000000 36
136.000000 136

One nice thing with the VCL library is that if you use e.g. Vec8f with a system that only has SSE2 it will emulate AVX using SSE twice.

See the section "Instruction sets and CPU dispatching" in the vectorclass.pdf manual for how to compile for different instruction sets with MSVC, ICC, Clang, and GCC.


问:
How setup Node.js error handling?
I have node 7.8.0 and I have read Node.js Best Practice Exception Handling

Still I can't seem to understand error handling in node.js.

For my http I have

```<code>server.on('error', () => console.log('Here I should be replacing
the Error console.'));
</code>```

For 404 I have this code

```<code>app.use((req, res, next) => {
  let err = new Error('Not Found');
  err.status = 404;
  next(err);
});
app.use((err, req, res) => {
  res.status(err.status);
  res.render('error');
});
</code>```

404 is being caught, it creates the Error object and then it's handled by rendering the error view correctly as I want. But it also throws error log to my console and I have no idea where that is coming from and how to stop it.

I would like to use my own error handling and never actually write errors like 404 into the console.

Codes that I tried and don't seem to work.

```<code>var server = http.createServer(app);
const onError = () => console.log('Here I should be replacing the Error console.');
server.on('error', onError);
server.on('uncaughtException', onError);
process.on('uncaughtException', onError);
</code>```

答:
I'm not sure how it can render the error view, given that error handlers require 4 arguments while you're passing it only 3. This is how Express can distinguish error handlers from normal route handlers (documented here).

Try this instead:

```<code>app.use((err, req, res, next) => {
  res.status(err.status);
  res.render('error');
});
</code>```

Title: How setup Node.js error handling?

Body:
I have node 7.8.0 and I have read Node.js Best Practice Exception Handling

Still I can't seem to understand error handling in node.js.

For my http I have

server.on('error', () => console.log('Here I should be replacing
the Error console.'));

For 404 I have this code

app.use((req, res, next) => {
  let err = new Error('Not Found');
  err.status = 404;
  next(err);
});
app.use((err, req, res) => {
  res.status(err.status);
  res.render('error');
});

404 is being caught, it creates the Error object and then it's handled by rendering the error view correctly as I want. But it also throws error log to my console and I have no idea where that is coming from and how to stop it.

I would like to use my own error handling and never actually write errors like 404 into the console.

Codes that I tried and don't seem to work.

var server = http.createServer(app);
const onError = () => console.log('Here I should be replacing the Error console.');
server.on('error', onError);
server.on('uncaughtException', onError);
process.on('uncaughtException', onError);

Body:
I'm not sure how it can render the error view, given that error handlers require 4 arguments while you're passing it only 3. This is how Express can distinguish error handlers from normal route handlers (documented here).

Try this instead:

app.use((err, req, res, next) => {
  res.status(err.status);
  res.render('error');
});


问:
using NDK for Android to write OpenGL code
So here is the deal.
I have been using OpenGL API on windows [Win32] for about 3 years.
I have written multiple shaders in the same.

Now I want to port my project on Android.
My question is, If I want to write the project using C++ [NDK], and use OpenGL ES is it possible?

Short answer I got was 'YES', but, is that a right way?
Am I better off using Java? Are there any performance degrade because I am using NDK, as I am aiming for a VR based OpenGL application performance is the main factor?

Yes its these are multiple questions, but they point at the similar problem, is it practical to use NDK for real-life projects.

答:
It is up to you how much of your application you write in C++ and how much you write in Java. Each JNI call has an associated overhead, so you may want to keep that in mind when decided how to split your Java and native code (for example, writing your entire render loop in C++ will incur just one JNI call per frame, while writing your render loop by calling the OpenGL API via the Java wrapper could incur thousands of JNI calls per frame). What might be considered "correct" depends on your specific requirements.

At a minimum, you will need to obtain either a Surface (from the SurfaceHolder that is provided by a SurfaceView) or a SurfaceTexture (obtained from a TextureView) and pass it via the JNI to your native application, where you can use ANativeWindow_fromSurface or ANativeWindow_fromSurfaceTexture (see here) to obtain a native window with which you can create your OpenGL ES surface and context. You will probably want to encapsulate your JNI calls within Java classes that listen to the SurfaceHolder or SurfaceTexture callbacks. For example:

```<code>public class GlSurfaceHolder {
    private SurfaceHolder mSurfaceHolder;
    private SurfaceHolder.Callback mSurfaceHolderCallback;

    public GlSurfaceHolder(SurfaceHolder surfaceHolder) {
        mSurfaceHolder = surfaceHolder;
        mSurfaceHolderCallback = new SurfaceHolder.Callback() {
            // JNI calls in here
        }

        mSurfaceHolder.addCallback(mSurfaceHolderCallback);
    }
};
</code>```

If you don't need this level of control, you might consider using GLSurfaceView, which is a SurfaceView that manages its own OpenGL ES surface, context and render loop. The disadvantage of GLSurfaceView is that it unnecessarily couples a whole load of ostensibly unrelated things. Decoupling these functions is not only neater from the perspective of the single responsibility principle, it allows you to potentially perform your rendering in a separate thread (which will of course require synchronization with the UI thread, but may have performance benefits).

If you don't even care about any of your application running Java-side, you can use the NativeActivity convenience class, which bundles all of the previously mentioned functions as well as some other stuff into an Android Activity. It's the quick and dirty option.

Body:
It is up to you how much of your application you write in C++ and how much you write in Java. Each JNI call has an associated overhead, so you may want to keep that in mind when decided how to split your Java and native code (for example, writing your entire render loop in C++ will incur just one JNI call per frame, while writing your render loop by calling the OpenGL API via the Java wrapper could incur thousands of JNI calls per frame). What might be considered "correct" depends on your specific requirements.

At a minimum, you will need to obtain either a Surface (from the SurfaceHolder that is provided by a SurfaceView) or a SurfaceTexture (obtained from a TextureView) and pass it via the JNI to your native application, where you can use ANativeWindow_fromSurface or ANativeWindow_fromSurfaceTexture (see here) to obtain a native window with which you can create your OpenGL ES surface and context. You will probably want to encapsulate your JNI calls within Java classes that listen to the SurfaceHolder or SurfaceTexture callbacks. For example:

public class GlSurfaceHolder {
    private SurfaceHolder mSurfaceHolder;
    private SurfaceHolder.Callback mSurfaceHolderCallback;

    public GlSurfaceHolder(SurfaceHolder surfaceHolder) {
        mSurfaceHolder = surfaceHolder;
        mSurfaceHolderCallback = new SurfaceHolder.Callback() {
            // JNI calls in here
        }

        mSurfaceHolder.addCallback(mSurfaceHolderCallback);
    }
};

If you don't need this level of control, you might consider using GLSurfaceView, which is a SurfaceView that manages its own OpenGL ES surface, context and render loop. The disadvantage of GLSurfaceView is that it unnecessarily couples a whole load of ostensibly unrelated things. Decoupling these functions is not only neater from the perspective of the single responsibility principle, it allows you to potentially perform your rendering in a separate thread (which will of course require synchronization with the UI thread, but may have performance benefits).

If you don't even care about any of your application running Java-side, you can use the NativeActivity convenience class, which bundles all of the previously mentioned functions as well as some other stuff into an Android Activity. It's the quick and dirty option.


问:
asp.net mvc: how to mock Url.Content("~")?
anybody knows how to mock Url.Content("~") ?

(BTW: I'm using Moq)

答:
```<code>controller.Url = Substitute.ForPartsOf<UrlHelper>();
controller.Url.Content("~").Returns("path");
</code>```

Fell free with ForPartsOf (Partial subs and test spies) in NUnit

Body:
controller.Url = Substitute.ForPartsOf<UrlHelper>();
controller.Url.Content("~").Returns("path");

Fell free with ForPartsOf (Partial subs and test spies) in NUnit


问:
Disable photo sharing in IOS, Ionic2 native Photo Viewer plugin
I am using photo viewer plugin in Ionic-native in an Ionic2 app.

My code is this._photoViewer.show(bookImgPath, '', {share: false});

I have disabled the sharing, but sharing is enabled on Ios.

It is working in Android only.

Please help.

答:
Unfortunately, you can do that for Android only.There is No support for iOS yet.

Optionally you can pass third parameter which can be used to hide the
  share button [ONLY FOR ANDROID]

Official PhotoViewer Cordova Plugin Doc


问:
Matlab: 3D Surface Plot of values from own vectors
I have 3 vectors with values for coordinates (X,Y,Z) and I want to plot them as a surface. I have tried all sorts of solutions from here and other forums and cannot for the life of me get it to look like anything that makes sense. I have a picture that can describe the situation better but I can't post it as I don't have enough reputation. Please help. Thank you.

EDIT: This is the link to the picture :

In the picture, the origin of each vector arrow represents the point in a 3D coordinate, with the length of the vector arrow giving the magnitude of the required torque to move at that point in 3D space.

Right now, the data is separated in line vectors with each point's coordinate: so that's one vector for the X, one for Y. Z is one line inside a 3 line matrix as the whole matrix describes the required torque in a 3 coordinate axes.

I've tried using meshgridon the X and Y vectors and then attributed the Z value using griddataand then surfbut I'm not getting something that looks like the original:

The plot is linear but I'm pretty sure the data is not... at least not that linear.

答:
Plot each data point separately within a loop:

```<code>figure; hold on; grid on;

for i = 1:length(x)
    stem3(x(i),y(i),z(i));
end
</code>```

Don't forget to add hold on. Use "Rotate 3D" button from the toolbar in the figure window if the plot was shown in 2D at first.

Body:
Plot each data point separately within a loop:

figure; hold on; grid on;

for i = 1:length(x)
    stem3(x(i),y(i),z(i));
end

Don't forget to add hold on. Use "Rotate 3D" button from the toolbar in the figure window if the plot was shown in 2D at first.


问:
How to lock a critical section in Django?
I can't find a good clean way to lock a critical section in Django.  I could use a lock or semaphore but the python implementation is for threads only, so if the production server forks then those will not be respected.  Does anyone know of a way (I am thinking posix semaphores right now) to guarantee a lock across processes, or barring that a way to stop a Django server from forking.</p>

答:
If you use RDBMS, you can use its "LOCK" mechanism.
For example, while one "SELECT FOR UPDATE" transaction locks a row, the other "SELECT FOR UPDATE" transactions with the row must wait.</p>

```<code># You can use any Python DB API.
[SQL] BEGIN;

[SQL] SELECT col_name FROM table_name where id = 1 FOR UPDATE;

[Process some python code]

[SQL] COMMIT;
</code>```

Body:
If you use RDBMS, you can use its "LOCK" mechanism.
For example, while one "SELECT FOR UPDATE" transaction locks a row, the other "SELECT FOR UPDATE" transactions with the row must wait.

# You can use any Python DB API.
[SQL] BEGIN;

[SQL] SELECT col_name FROM table_name where id = 1 FOR UPDATE;

[Process some python code]

[SQL] COMMIT;

ContentLicense: CC BY-SA 2.5


问:
Consuming and Producing Kafka messages on different servers
How can I produce and consume messages from different servers?
I tried the Quickstart tutorial, but there is no instructions on how to setup for multi server clusters.

My Steps

Server A

1)bin/zookeeper-server-start.sh config/zookeeper.properties

2)bin/kafka-server-start.sh config/server.properties

3)bin/kafka-topics.sh --create --zookeeper localhost:2181 --replication-factor
   1 --partitions 1 --topic test

4)bin/kafka-console-producer.sh --broker-list SERVER-a.IP:9092 --topic test

Server B

1A)bin/kafka-console-consumer.sh --bootstrap-server SERVER-a.IP:9092 --topic
   test --from-beginning

1B)bin/kafka-console-consumer.sh --bootstrap-server SERVER-a.IP:2181 --topic
   test --from-beginning

When I run 1A) consumer and enter messages into the producer, there is no messages appearing in the consumer. Its just blank.

When I run 1B consumer instead, I get a huge & very fast stream of error logs in Server A until I Ctrl+C the consumer. See below

Error log on Server A streaming at hundreds per second

WARN Exception causing close of session 0x0 due to java.io.EOFException (org.apache.zookeeper.server.NIOServerCnxn)

O Closed socket connection for client /188.166.178.40:51168 (no session established for client) (org.apache.zookeeper.server.NIOServerCnxn)
Thanks

答:
Yes, if you want to have your producer on Server A and your consumer on server B, you are in the right direction.

You need to run a Broker on server A to make it work.

```<code>bin/kafka-server-start.sh config/server.properties
</code>```

The other commands are correct.

Body:
Yes, if you want to have your producer on Server A and your consumer on server B, you are in the right direction.

You need to run a Broker on server A to make it work.

bin/kafka-server-start.sh config/server.properties

The other commands are correct.


问:
Creating a table in Crystal Reports Basic (one built in vs2008)?
Is it possible to create a table with this crystal reports, because I need to layout or format my data into a table(not cross tab), is there a way to do this cause I think my tool box is only limited to lines and boxes and basic shapes. </p>

答: If you need to display the data as a table, you can get creative with details, groups, subsections, and formulae.  For example, the formula sum({A},{B}) adds all the values of {A} for each group {B} (best used in a group footer).  If you have any specific questions, I can try to answer them.


问:
When to use Django get_absolute_url() method?
Django documentation says:

get_absolute_url() method to tell Django how to calculate the canonical URL for an object.

What is canonical URL mean in this is context?

I know from an SEO perspective that canonical URL means picking the best URL from the similar looking URLs (example.com , example.com/index.html). But this meaning doesn't fit in this context.

I know this method provides some additional functionality in Django admin, redirection etc. And I am fully aware of how to use this method.

But what is the philosophy behind it? I have never actually used it in my projects. Does it serve any special purpose?

答:
get_absolute_url allows to keep your object DRY. To have a url which defines that object instance. In most case a detail page for that object.

Couple this with models.permalink and you can define the object detail url very easily.

What is @permalink and get_absolute_url in Django?

Later if you change the structure of the url you have to modify only in one place, the urls.


问:
SonarQube MSBuild runner and scm root
good day
today i was setup sonarqube with ms build runner and mercurial scm provider
i have next structure of repository (schematic):

```<code><ROOT>
-.hg
-src
----prj.infrastructure
----prj.domain
----prj.application
----prj.sln
</code>```

and i used next command for run analysis:

```<code>"%env.SonarMsBuildRunner%\MSBuild.SonarQube.Runner" begin /n:prj /k:prj /v:1.0
"%env.MsBuildLocation%\msbuild" src\prj.sln /p:Configuration=Debug
"%env.SonarMsBuildRunner%\msbuild.sonarqube.runner" end
</code>```

all analysis are work well, but scm not work (i see message like " Missing blame information for the following files:")

when i see generated sonar-project.properties i saw that problem is in projectBaseDir - it generates for each project in solution separately

i try to specify in command line like /d:sonar.projectBaseDir=... but no changes - it fully ignored

so my question is - can i use ms build runner and scm provider together with my repository structure?

UPDATE 1
i awas added verbose flag to my script..
now i run analysis with next command:

```<code>MSBuild.SonarQube.Runner begin /n:projectName /k:projectKey /v:1.0 /d:sonar.scm.enabled=true /d:sonar.scm.provider=hg /d:sonar.projectBaseDir=d:\work\project1 /d:sonar.verbose=true
msbuild project1\src\solution.sln /p:Configuration=Debug
msbuild.sonarqube.runner end
</code>```

in log i can see this messages:

```<code>[14:18:20] :     [Step 4/4] 14:18:20.403 DEBUG: Working directory: D:\work\project1\src\
[14:18:20] :     [Step 4/4] 14:18:20.416 DEBUG: Executing: hg blame -w -v --user --date --changeset API/AssignmentsController.cs
[14:18:20] :     [Step 4/4] 14:18:20.423 DEBUG: Executing: hg blame -w -v --user --date --changeset API/Commands/ImportCommand.cs
[14:18:20] :     [Step 4/4] 14:18:20.424 DEBUG: Executing: hg blame -w -v --user --date --changeset API/Dto/Assignment.cs
[14:18:20] :     [Step 4/4] 14:18:20.600 DEBUG: The mercurial blame command [hg blame -w -v --user --date --changeset API/AssignmentsController.cs] failed: abort: no repository found in 'D:\work\project1\src\' (.hg not found)!
[14:18:20] :     [Step 4/4]
</code>```

and this is right - in folder d:\work\project1\src no .hg directory, because it's place in d:\work\project1

UPDATE2

ok, finally i find than i my mistake... on build machine folder .hg missed by some reasons...

答:
This is a limitation of the SonarQube Mercurial Plugin. It currently expects to find the .hg folder precisely in the basedir. Other plugins like SVN where updated to look recursively in parent folders.

We are no more actively developing the Mercurial plugin, but feel free to submit a pull request to fix the issue.

As a workaround, you can force the SCM using /d:sonar.scm.provider=hg in the begin step.

Title: SonarQube MSBuild runner and scm root

Body:
good day
today i was setup sonarqube with ms build runner and mercurial scm provider
i have next structure of repository (schematic):

<ROOT>
-.hg
-src
----prj.infrastructure
----prj.domain
----prj.application
----prj.sln

and i used next command for run analysis:

"%env.SonarMsBuildRunner%\MSBuild.SonarQube.Runner" begin /n:prj /k:prj /v:1.0
"%env.MsBuildLocation%\msbuild" src\prj.sln /p:Configuration=Debug
"%env.SonarMsBuildRunner%\msbuild.sonarqube.runner" end

all analysis are work well, but scm not work (i see message like " Missing blame information for the following files:")

when i see generated sonar-project.properties i saw that problem is in projectBaseDir - it generates for each project in solution separately

i try to specify in command line like /d:sonar.projectBaseDir=... but no changes - it fully ignored

so my question is - can i use ms build runner and scm provider together with my repository structure?

UPDATE 1
i awas added verbose flag to my script..
now i run analysis with next command:

MSBuild.SonarQube.Runner begin /n:projectName /k:projectKey /v:1.0 /d:sonar.scm.enabled=true /d:sonar.scm.provider=hg /d:sonar.projectBaseDir=d:\work\project1 /d:sonar.verbose=true
msbuild project1\src\solution.sln /p:Configuration=Debug
msbuild.sonarqube.runner end

in log i can see this messages:

[14:18:20] :     [Step 4/4] 14:18:20.403 DEBUG: Working directory: D:\work\project1\src\
[14:18:20] :     [Step 4/4] 14:18:20.416 DEBUG: Executing: hg blame -w -v --user --date --changeset API/AssignmentsController.cs
[14:18:20] :     [Step 4/4] 14:18:20.423 DEBUG: Executing: hg blame -w -v --user --date --changeset API/Commands/ImportCommand.cs
[14:18:20] :     [Step 4/4] 14:18:20.424 DEBUG: Executing: hg blame -w -v --user --date --changeset API/Dto/Assignment.cs
[14:18:20] :     [Step 4/4] 14:18:20.600 DEBUG: The mercurial blame command [hg blame -w -v --user --date --changeset API/AssignmentsController.cs] failed: abort: no repository found in 'D:\work\project1\src\' (.hg not found)!
[14:18:20] :     [Step 4/4]

and this is right - in folder d:\work\project1\src no .hg directory, because it's place in d:\work\project1

UPDATE2

ok, finally i find than i my mistake... on build machine folder .hg missed by some reasons...


问:
How to underlay a content stream with using PDPageContentStream?
I am trying to create a watermark with using PDPageContentStream. This is what I have right now

```<code>PDPageContentStream contentStream = new PDPageContentStream(doc,page, true,true);
contentStream.beginText();
contentStream.setFont(font,40);
contentStream.setTextRotation(Math.PI/4,page.getMediaBox().getWidth()/4,page.getMediaBox().getHeight()/4);
contentStream.setNonStrokingColor(210,210,210); //light grey
contentStream.drawString(_text);
contentStream.endText();
contentStream.close();
</code>```

What happens is it creates a 45 degree angled text with the light grey color. But -of course- it overlays the actual page content beneath it and it is not possible to see some of the content.

Is it possible to create the contentStream first and then append the page content?
I found this example. It uses PDExtendedGraphicsState and PDResources. I am new to pdfbox and almost have no graphics experience.
Are these what I need and What is a resource in pdfbox?

Thanks in advance.

p.s. I am aware that I can use overlay utility with a jpeg. But I am trying to figure out this problem with PDPageContentStream for now.

答:
If you use PDFBox 2.0+, then its slightly easier now:</p>

```<code>PDExtendedGraphicsState extendedGraphicsState = new PDExtendedGraphicsState();
extendedGraphicsState.setNonStrokingAlphaConstant((float) alpha);
contents.saveGraphicsState();
contents.setGraphicsStateParameters(extendedGraphicsState);
// do your stuff
contents.restoreGraphicsState();
</code>```

Body:
I am trying to create a watermark with using PDPageContentStream. This is what I have right now

PDPageContentStream contentStream = new PDPageContentStream(doc,page, true,true);
contentStream.beginText();
contentStream.setFont(font,40);
contentStream.setTextRotation(Math.PI/4,page.getMediaBox().getWidth()/4,page.getMediaBox().getHeight()/4);
contentStream.setNonStrokingColor(210,210,210); //light grey
contentStream.drawString(_text);
contentStream.endText();
contentStream.close();

What happens is it creates a 45 degree angled text with the light grey color. But -of course- it overlays the actual page content beneath it and it is not possible to see some of the content.

Is it possible to create the contentStream first and then append the page content?
I found this example. It uses PDExtendedGraphicsState and PDResources. I am new to pdfbox and almost have no graphics experience.
Are these what I need and What is a resource in pdfbox?

Thanks in advance.

p.s. I am aware that I can use overlay utility with a jpeg. But I am trying to figure out this problem with PDPageContentStream for now.

Body:
If you use PDFBox 2.0+, then its slightly easier now:

PDExtendedGraphicsState extendedGraphicsState = new PDExtendedGraphicsState();
extendedGraphicsState.setNonStrokingAlphaConstant((float) alpha);
contents.saveGraphicsState();
contents.setGraphicsStateParameters(extendedGraphicsState);
// do your stuff
contents.restoreGraphicsState();


问:
Angular 2: Argument of type 'Route[]' is not assignable to parameter of type 'Route[]'.
I'm getting this error when I updated to the last version of nativescript-angular, I suppose the problem is related to the difference in the version of Angular 2 I'm using and the one used by the module. Is anyone able to tell me what are the right versions I should use to make it work?
Mind that my intention to upgrade to the last version of nativescript-angular was to use the RouterExtensions.

```<code>Argument of type 'Route[]' is not assignable to parameter of type  'Route[]'.
  Type 'Route' is not assignable to type 'Route'.
    Types of property 'pathMatch' are incompatible.
      Type 'string' is not assignable to type '"full" | "prefix"'.
        Type 'string' is not assignable to type '"prefix"'.
const routes: Route[]
</code>```

these are my package.json dependencies:

```<code>"dependencies": {
    "@angular/common": "2.0.0-rc.4",
    "@angular/compiler": "2.0.0-rc.4",
    "@angular/core": "2.0.0-rc.4",
    "@angular/forms": "0.3.0",
    "@angular/http": "2.0.0-rc.4",
    "@angular/platform-browser": "2.0.0-rc.4",
    "@angular/platform-browser-dynamic": "2.0.0-rc.4",
    "@angular/platform-server": "2.0.0-rc.4",
    "@angular/router": "^3.0.0-rc.1",
    "@angular/router-deprecated": "2.0.0-rc.2",
    "@angular/upgrade": "2.0.0-rc.4",
    "nativescript-angular": "^0.3.1",
    "nativescript-plugin-firebase": "^3.5.3",
    "reflect-metadata": "^0.1.8",
    "rxjs": "5.0.0-beta.6",
    "tns-core-modules": "^2.3.0-2016-08-29-3966",
    "zone.js": "^0.6.17"
  },
</code>```

the app.routes.ts:

```<code>import { RouterConfig } from '@angular/router';
import { nsProvideRouter} from 'nativescript-angular/router';
import { LoginComponent } from './components/login.component';
import { DashboardComponent } from './components/dashboard.component';

const routes: RouterConfig = [
    {
        path: '',
        redirectTo: '/login',
        terminal: true
    },
    {
        path: 'login',
        component: LoginComponent
    },
    {
        path: 'dashboard',
        component: DashboardComponent
    }
];

export const APP_ROUTER_PROVIDERS = [
    nsProvideRouter(routes, { enableTracing: false })
];
</code>```

答:
There seems to be no property RouterConfig exported by @angular/router. Try using Routes instead.

```<code>const routes: Routes = [ // <==
    {
        path: '',
        redirectTo: '/login',
        terminal: true
    },
    {
        path: 'login',
        component: LoginComponent
    },
    {
        path: 'dashboard',
        component: DashboardComponent
    }
];
</code>```

Body:
I'm getting this error when I updated to the last version of nativescript-angular, I suppose the problem is related to the difference in the version of Angular 2 I'm using and the one used by the module. Is anyone able to tell me what are the right versions I should use to make it work?
Mind that my intention to upgrade to the last version of nativescript-angular was to use the RouterExtensions.

Argument of type 'Route[]' is not assignable to parameter of type  'Route[]'.
  Type 'Route' is not assignable to type 'Route'.
    Types of property 'pathMatch' are incompatible.
      Type 'string' is not assignable to type '"full" | "prefix"'.
        Type 'string' is not assignable to type '"prefix"'.
const routes: Route[]

these are my package.json dependencies:

"dependencies": {
    "@angular/common": "2.0.0-rc.4",
    "@angular/compiler": "2.0.0-rc.4",
    "@angular/core": "2.0.0-rc.4",
    "@angular/forms": "0.3.0",
    "@angular/http": "2.0.0-rc.4",
    "@angular/platform-browser": "2.0.0-rc.4",
    "@angular/platform-browser-dynamic": "2.0.0-rc.4",
    "@angular/platform-server": "2.0.0-rc.4",
    "@angular/router": "^3.0.0-rc.1",
    "@angular/router-deprecated": "2.0.0-rc.2",
    "@angular/upgrade": "2.0.0-rc.4",
    "nativescript-angular": "^0.3.1",
    "nativescript-plugin-firebase": "^3.5.3",
    "reflect-metadata": "^0.1.8",
    "rxjs": "5.0.0-beta.6",
    "tns-core-modules": "^2.3.0-2016-08-29-3966",
    "zone.js": "^0.6.17"
  },

the app.routes.ts:

import { RouterConfig } from '@angular/router';
import { nsProvideRouter} from 'nativescript-angular/router';
import { LoginComponent } from './components/login.component';
import { DashboardComponent } from './components/dashboard.component';

const routes: RouterConfig = [
    {
        path: '',
        redirectTo: '/login',
        terminal: true
    },
    {
        path: 'login',
        component: LoginComponent
    },
    {
        path: 'dashboard',
        component: DashboardComponent
    }
];

export const APP_ROUTER_PROVIDERS = [
    nsProvideRouter(routes, { enableTracing: false })
];

Body:
There seems to be no property RouterConfig exported by @angular/router. Try using Routes instead.

const routes: Routes = [ // <==
    {
        path: '',
        redirectTo: '/login',
        terminal: true
    },
    {
        path: 'login',
        component: LoginComponent
    },
    {
        path: 'dashboard',
        component: DashboardComponent
    }
];


问:
After updating Android Studio to 2.3 , my app works fine in device ( Nexus 5X) but it crash every time when i install the apk explicitly
I did these things:
1) Clean the code and remove everything in /build folder.
2) Analyse AndroidManifest.xml file all activities have proper package name as suffix

Multidex is already enabled

These are the Error Logs i got every time.:

E/AndroidRuntime: FATAL EXCEPTION: main
                                                                      Process: com.android.packagename, PID: 25752
                                                                      java.lang.RuntimeException: Unable to instantiate application
  com.android.packagename.BaseApplication:
  java.lang.ClassNotFoundException: Didn't find class
  "com.android.packagename.BaseApplication" on path: DexPathList[[zip
  file
  "/data/app/com.android.packagename-1/base.apk"],nativeLibraryDirectories=[/data/app/com.android.packagename-1/lib/arm64,
  /system/lib64, /vendor/lib64]]
                                                                          at android.app.LoadedApk.makeApplication(LoadedApk.java:802)
                                                                          at
  android.app.ActivityThread.handleBindApplication(ActivityThread.java:5377)
                                                                          at android.app.ActivityThread.-wrap2(ActivityThread.java)
                                                                          at
  android.app.ActivityThread$H.handleMessage(ActivityThread.java:1545)
                                                                          at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                          at android.os.Looper.loop(Looper.java:154)
                                                                          at android.app.ActivityThread.main(ActivityThread.java:6119)
                                                                          at java.lang.reflect.Method.invoke(Native Method)
                                                                          at
  com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
                                                                          at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
                                                                       Caused by: java.lang.ClassNotFoundException: Didn't find class
  "com.android.packagename.BaseApplication" on path: DexPathList[[zip
  file
  "/data/app/com.android.packagename-1/base.apk"],nativeLibraryDirectories=[/data/app/com.android.packagename-1/lib/arm64,
  /system/lib64, /vendor/lib64]]
                                                                          at
  dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:56)
                                                                          at java.lang.ClassLoader.loadClass(ClassLoader.java:380)
                                                                          at java.lang.ClassLoader.loadClass(ClassLoader.java:312)
                                                                          at
  android.app.Instrumentation.newApplication(Instrumentation.java:992)
                                                                          at android.app.LoadedApk.makeApplication(LoadedApk.java:796)
                                                                          at
  android.app.ActivityThread.handleBindApplication(ActivityThread.java:5377)

```<code>                                                                    at android.app.ActivityThread.-wrap2(ActivityThread.java)
                                                                    at
</code>```

android.app.ActivityThread$H.handleMessage(ActivityThread.java:1545)
                                                                          at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                          at android.os.Looper.loop(Looper.java:154)
                                                                          at android.app.ActivityThread.main(ActivityThread.java:6119)
                                                                          at java.lang.reflect.Method.invoke(Native Method)
                                                                          at
  com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)

```<code>                                                                    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
</code>```

答:
Ok  try to install instant run for your target api

Or disable instant run from Android studio

More about instant run

Body:
I did these things:
1) Clean the code and remove everything in /build folder.
2) Analyse AndroidManifest.xml file all activities have proper package name as suffix

Multidex is already enabled

These are the Error Logs i got every time.:

E/AndroidRuntime: FATAL EXCEPTION: main
                                                                      Process: com.android.packagename, PID: 25752
                                                                      java.lang.RuntimeException: Unable to instantiate application
  com.android.packagename.BaseApplication:
  java.lang.ClassNotFoundException: Didn't find class
  "com.android.packagename.BaseApplication" on path: DexPathList[[zip
  file
  "/data/app/com.android.packagename-1/base.apk"],nativeLibraryDirectories=[/data/app/com.android.packagename-1/lib/arm64,
  /system/lib64, /vendor/lib64]]
                                                                          at android.app.LoadedApk.makeApplication(LoadedApk.java:802)
                                                                          at
  android.app.ActivityThread.handleBindApplication(ActivityThread.java:5377)
                                                                          at android.app.ActivityThread.-wrap2(ActivityThread.java)
                                                                          at
  android.app.ActivityThread$H.handleMessage(ActivityThread.java:1545)
                                                                          at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                          at android.os.Looper.loop(Looper.java:154)
                                                                          at android.app.ActivityThread.main(ActivityThread.java:6119)
                                                                          at java.lang.reflect.Method.invoke(Native Method)
                                                                          at
  com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
                                                                          at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
                                                                       Caused by: java.lang.ClassNotFoundException: Didn't find class
  "com.android.packagename.BaseApplication" on path: DexPathList[[zip
  file
  "/data/app/com.android.packagename-1/base.apk"],nativeLibraryDirectories=[/data/app/com.android.packagename-1/lib/arm64,
  /system/lib64, /vendor/lib64]]
                                                                          at
  dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:56)
                                                                          at java.lang.ClassLoader.loadClass(ClassLoader.java:380)
                                                                          at java.lang.ClassLoader.loadClass(ClassLoader.java:312)
                                                                          at
  android.app.Instrumentation.newApplication(Instrumentation.java:992)
                                                                          at android.app.LoadedApk.makeApplication(LoadedApk.java:796)
                                                                          at
  android.app.ActivityThread.handleBindApplication(ActivityThread.java:5377)

                                                                    at android.app.ActivityThread.-wrap2(ActivityThread.java)
                                                                    at

android.app.ActivityThread$H.handleMessage(ActivityThread.java:1545)
                                                                          at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                          at android.os.Looper.loop(Looper.java:154)
                                                                          at android.app.ActivityThread.main(ActivityThread.java:6119)
                                                                          at java.lang.reflect.Method.invoke(Native Method)
                                                                          at
  com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)

                                                                    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)


问:
How to multiply all columns in SAS by another column?
Suppose data set looks like:

```<code>A  B  C
1  2  0.2
2  7  0.3
3  10 0.7
</code>```

and I want to multiply columns A and B by C and update the values? What is the most efficient way to do this?

答:
Maybe I'm misunderstanding, but this is quite basic. Then again, basics are the most important bit. </p>

```<code>data begin;
    input A  B  C;
    cards;
    1  2  0.2
    2  7  0.3
    3  10 0.7
    ;
run;

data wanted;
    set begin;
    AC=A*C;
    BC=B*C;
run;
</code>```

Body:
Suppose data set looks like:

A  B  C
1  2  0.2
2  7  0.3
3  10 0.7

and I want to multiply columns A and B by C and update the values? What is the most efficient way to do this?

Body:
Maybe I'm misunderstanding, but this is quite basic. Then again, basics are the most important bit.

data begin;
    input A  B  C;
    cards;
    1  2  0.2
    2  7  0.3
    3  10 0.7
    ;
run;

data wanted;
    set begin;
    AC=A*C;
    BC=B*C;
run;


问:
Getting decimal number from edittext
I know something similar has already been asked, but I'm having some trouble to get a decimal number that come from keyboard.

My Java code in the onCreate method should be:

```<code>textS0 = (EditText)findViewById(R.id.editS0);
Button btn_S0 = (Button)findViewById(R.id.getS0);

btn_S0.setOnClickListener(new View.OnClickListener()
{
    public void onClick(View v)
    {
        //how should I get here the number from keyboard?
        //I think  I should be something like
        //double S0=textS0.getText()....
    }
});
</code>```

And that's what my XML file contains

```<code><EditText
       android:id="@+id/editS0"
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:ems="10"
       android:hint="@string/S0"
       android:inputType="numberDecimal" />
<Button
       android:id="@+id/getS0"
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:text="@string/setS0" />
</LinearLayout>
</code>```

答:
May b you face null pointer exception in string so try this....

get the number decimal from edittext using this

```<code>   Double BText=ParseDouble(String.valueOf(edittext.getText()));
</code>```

after that paste this code.. it prevents you from null pointer exception

```<code>double ParseDouble(String strNumber) {
if (strNumber != null && strNumber.length() > 0) {
    try {
        return Double.parseDouble(strNumber);
    } catch(Exception e) {
        return -1;
    }
}
else return 0;
}
</code>```

Title: Getting decimal number from edittext

Body:
I know something similar has already been asked, but I'm having some trouble to get a decimal number that come from keyboard.

My Java code in the onCreate method should be:

textS0 = (EditText)findViewById(R.id.editS0);
Button btn_S0 = (Button)findViewById(R.id.getS0);

btn_S0.setOnClickListener(new View.OnClickListener()
{
    public void onClick(View v)
    {
        //how should I get here the number from keyboard?
        //I think  I should be something like
        //double S0=textS0.getText()....
    }
});

And that's what my XML file contains

<EditText
       android:id="@+id/editS0"
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:ems="10"
       android:hint="@string/S0"
       android:inputType="numberDecimal" />
<Button
       android:id="@+id/getS0"
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:text="@string/setS0" />
</LinearLayout>

Body:
May b you face null pointer exception in string so try this....

get the number decimal from edittext using this

   Double BText=ParseDouble(String.valueOf(edittext.getText()));

after that paste this code.. it prevents you from null pointer exception

double ParseDouble(String strNumber) {
if (strNumber != null && strNumber.length() > 0) {
    try {
        return Double.parseDouble(strNumber);
    } catch(Exception e) {
        return -1;
    }
}
else return 0;
}


问:
How to display and hide a div with CSS?
In my script there are three divs. I want to display div with class="ab" when I hover on first line and display div with class="abc", when hover on second line. Otherwise I want to display div with class="a" by default.

But it never displays the div with class="a".

.abc,.ab {
    display: none;
}
#f:hover ~ .ab {
    display: block;

}
#f:hover ~ .abc,.a {
    display: none;

}
#s:hover ~ .abc {
    display: block;

}
#s:hover ~ .ab,.a {
    display: none;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code>Show First content!
<br/>
Show Second content!!
<div class="a">Default Content</div>
<div class="ab">First content</div>
<div class="abc">Second content</div></code>```

Here is my JSFiddle of my problem: JSFiddle Link

答:
you can use any of the following five ways to hide element, depends upon your requirements.

Opacity

```<code>.hide {
  opacity: 0;
}
</code>```

Visibility

```<code>.hide {
   visibility: hidden;
}
</code>```

Display

```<code>.hide {
   display: none;
}
</code>```

Position

```<code>.hide {
   position: absolute;
   top: -9999px;
   left: -9999px;
}
</code>```

clip-path

```<code>.hide {
  clip-path: polygon(0px 0px,0px 0px,0px 0px,0px 0px);
}
</code>```

To show use any of the following:
opacity: 1;
visibility: visible;
display: block;

Source : https://www.sitepoint.com/five-ways-to-hide-elements-in-css/

Title: How to display and hide a div with CSS?

Body:
In my script there are three divs. I want to display div with class="ab" when I hover on first line and display div with class="abc", when hover on second line. Otherwise I want to display div with class="a" by default.

But it never displays the div with class="a".

.abc,.ab {
    display: none;
}
#f:hover ~ .ab {
    display: block;

}
#f:hover ~ .abc,.a {
    display: none;

}
#s:hover ~ .abc {
    display: block;

}
#s:hover ~ .ab,.a {
    display: none;
}

Show First content!

Show Second content!!

Default Content

First content

Second content

Here is my JSFiddle of my problem: JSFiddle Link

Body:
you can use any of the following five ways to hide element, depends upon your requirements.

Opacity

.hide {
  opacity: 0;
}

Visibility

.hide {
   visibility: hidden;
}

Display

.hide {
   display: none;
}

Position

.hide {
   position: absolute;
   top: -9999px;
   left: -9999px;
}

clip-path

.hide {
  clip-path: polygon(0px 0px,0px 0px,0px 0px,0px 0px);
}

To show use any of the following:
opacity: 1;
visibility: visible;
display: block;

Source : https://www.sitepoint.com/five-ways-to-hide-elements-in-css/


问:
How to declare a parent application context
I find myself using two identical beans in my applicationContext.xml and my applicationContext-test.xml. I'd like my test context to be able to inherit from my app context, to avoid repeating myself.

I've seen plenty of material indicating that you can declare a parent application context and reference beans from that context, but I can't find a useful example. Can anyone help?

Update
As some background info, my normal application context is being loaded in web.xml:

```<code><context-param>
    <description>Application Contexts for Spring</description>
    <param-name>contextConfigLocation</param-name>
    <param-value>/WEB-INF/classes/applicationContext.xml</param-value>
</context-param>

<listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
</code>```

My test application context is loaded in my unit tests:

```<code>@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "/applicationContext-test.xml")
</code>```

So let's say I have a bean in my regular context:

```<code><bean name="someBean" class="com.foo.MyClass" />
</code>```

Then, in my test application context, I'd like to refer to this bean. How do I do it?

Update

Per skaffman's suggestion, I've moved the bean into a SharedBeans.xml file and imported it into my applicationContext.xml. However, this causes a SAXParser exception:

```<code>org.springframework.beans.factory.parsing.BeanDefinitionParsingException: Configuration problem: Failed to import bean definitions from URL location [classpath:SharedBeans.xml]
Offending resource: ServletContext resource [/WEB-INF/classes/applicationContext.xml]; nested exception is org.springframework.beans.factory.xml.XmlBeanDefinitionStoreException: Line 1 in XML document from class path resource [SharedBeans.xml] is invalid; nested exception is org.xml.sax.SAXParseException: cvc-elt.1: Cannot find the declaration of element 'bean'.
    at org.springframework.beans.factory.parsing.FailFastProblemReporter.error(FailFastProblemReporter.java:68)
</code>```

I can't be sure what I'm doing wrong. The bean was working fine in my context file, and all I did was cut and paste into the new file. Here are the contents of SharedBeans.xml in its entirety:

```<code><bean name="properties" class="com.foo.Properties">
    <constructor-arg><value>${module.name}</value></constructor-arg>
    <constructor-arg><value>${businessUnit}</value></constructor-arg>
    <constructor-arg><value>${product}</value></constructor-arg>
    <constructor-arg><value>${env}</value></constructor-arg>
    <constructor-arg><value>${machineName}</value></constructor-arg>
    <constructor-arg><value>${collectionSet.company}</value></constructor-arg>
    <constructor-arg><value>${route.tag}</value></constructor-arg>
    <constructor-arg><value>${timeout}</value></constructor-arg>
</bean>
</code>```

答:
You can move your common declaration to the separate XML file and place it in classpath (for easy access from test). Then you can do the following:

```<code><context-param>
    <description>Application Contexts for Spring</description>
    <param-name>contextConfigLocation</param-name>
    <param-value>
        /WEB-INF/classes/applicationContext.xml
        classpath:/common-beans.xml
    </param-value>
</context-param>
</code>```

.

```<code>@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(
    locations = {"/applicationContext-test.xml", "common-beans.xml"})
</code>```

You can also include common-beans.xml from both contexts using <import>, as suggested by skaffman.

Body:
I find myself using two identical beans in my applicationContext.xml and my applicationContext-test.xml. I'd like my test context to be able to inherit from my app context, to avoid repeating myself.

I've seen plenty of material indicating that you can declare a parent application context and reference beans from that context, but I can't find a useful example. Can anyone help?

Update
As some background info, my normal application context is being loaded in web.xml:

<context-param>
    <description>Application Contexts for Spring</description>
    <param-name>contextConfigLocation</param-name>
    <param-value>/WEB-INF/classes/applicationContext.xml</param-value>
</context-param>

<listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

My test application context is loaded in my unit tests:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "/applicationContext-test.xml")

So let's say I have a bean in my regular context:

<bean name="someBean" class="com.foo.MyClass" />

Then, in my test application context, I'd like to refer to this bean. How do I do it?

Update

Per skaffman's suggestion, I've moved the bean into a SharedBeans.xml file and imported it into my applicationContext.xml. However, this causes a SAXParser exception:

org.springframework.beans.factory.parsing.BeanDefinitionParsingException: Configuration problem: Failed to import bean definitions from URL location [classpath:SharedBeans.xml]
Offending resource: ServletContext resource [/WEB-INF/classes/applicationContext.xml]; nested exception is org.springframework.beans.factory.xml.XmlBeanDefinitionStoreException: Line 1 in XML document from class path resource [SharedBeans.xml] is invalid; nested exception is org.xml.sax.SAXParseException: cvc-elt.1: Cannot find the declaration of element 'bean'.
    at org.springframework.beans.factory.parsing.FailFastProblemReporter.error(FailFastProblemReporter.java:68)

I can't be sure what I'm doing wrong. The bean was working fine in my context file, and all I did was cut and paste into the new file. Here are the contents of SharedBeans.xml in its entirety:

<bean name="properties" class="com.foo.Properties">
    <constructor-arg><value>${module.name}</value></constructor-arg>
    <constructor-arg><value>${businessUnit}</value></constructor-arg>
    <constructor-arg><value>${product}</value></constructor-arg>
    <constructor-arg><value>${env}</value></constructor-arg>
    <constructor-arg><value>${machineName}</value></constructor-arg>
    <constructor-arg><value>${collectionSet.company}</value></constructor-arg>
    <constructor-arg><value>${route.tag}</value></constructor-arg>
    <constructor-arg><value>${timeout}</value></constructor-arg>
</bean>

Body:
You can move your common declaration to the separate XML file and place it in classpath (for easy access from test). Then you can do the following:

<context-param>
    <description>Application Contexts for Spring</description>
    <param-name>contextConfigLocation</param-name>
    <param-value>
        /WEB-INF/classes/applicationContext.xml
        classpath:/common-beans.xml
    </param-value>
</context-param>

.

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(
    locations = {"/applicationContext-test.xml", "common-beans.xml"})

You can also include common-beans.xml from both contexts using <import>, as suggested by skaffman.


问:
Change button title color in UIAlertView
How can I change the color of the UIAlertView button title.

I want title Ok in red color.

答:
for Swift 3, use:

```<code>alertController.view.tintColor = UIColor.red
</code>```

AFTER you present your alert controller

Body:
for Swift 3, use:

alertController.view.tintColor = UIColor.red

AFTER you present your alert controller


问:
AngularJs plunker not working? New to Plunker
I am relatively new to plunker, what am I doing wrong? There are errors in the console, and the live preview is not working. The code works perfectly fine in my localhost.

Here's the link for it. http://plnkr.co/edit/cZ48oeBBDthtVqXMRJPy?p=preview

```<code>    <html ng-app="myApp">

  <head>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.1/angular.min.js"></script>
    <script data-require="jquery@*" data-semver="3.1.1" src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
    <script data-require="less.js@*" data-semver="2.6.1" src="https://cdnjs.cloudflare.com/ajax/libs/less.js/2.6.1/less.min.js"></script>
    <link rel="stylesheet" href="style.less" />
    <script src="script.js"></script>
  </head>

  <body ng-controller="mainCtrl">
    <div class="container">
      <!-- Parent scope -->
      <div class="">
        <div prevent="" visible="isVisible" object-data="objectData">
          <table class="datatable">
            <tbody>
              <tr ng-repeat="t in templateData">
                <td class="haseebtesting" ng-click="current.selected = t; confusedFunction(t)" id="{{'test ' + $index}}">{{t.templateName}}</td>
                <td>{{t.templatePath}}</td>
              </tr>
            </tbody>
          </table>
          <div ng-show="isVisible" class="parented">
            <form class="haseebform">
              <input type="text" ng-model="objectData.entername" placeholder="Enter name" />
              <br />
              <input type="text" ng-model="objectData.entercomment" placeholder="Enter comment" />
              <input type="button" class="btn btn-info" ng-click="addT(objectData)" value="Submit" />
            </form>
          </div>
        </div>
      </div>
    </div>
    <script src="script.js"></script>
  </body>

</html>
</code>```

答:
plnkr edit

I started it without errors.

script code:

```<code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/less.js/2.7.2/less.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.3/angular.min.js"></script>
<script src="app.js"></script>
</code>```

Body:
I am relatively new to plunker, what am I doing wrong? There are errors in the console, and the live preview is not working. The code works perfectly fine in my localhost.

Here's the link for it. http://plnkr.co/edit/cZ48oeBBDthtVqXMRJPy?p=preview

    <link rel="stylesheet" href="style.less" />

                {{t.templateName}}
                {{t.templatePath}}

            <form class="haseebform">
              <input type="text" ng-model="objectData.entername" placeholder="Enter name" />

              <input type="text" ng-model="objectData.entercomment" placeholder="Enter comment" />
              <input type="button" class="btn btn-info" ng-click="addT(objectData)" value="Submit" />
            </form>

Body:
plnkr edit

I started it without errors.

script code:

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/less.js/2.7.2/less.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.3/angular.min.js"></script>
<script src="app.js"></script>


问:
Single Quotes Instead of Double Quotes?
Since both are acceptable by HTML as well as languages like ASP.NET and PHP when using attributes or strings, why is it that some people use single quotes and double quotes interchangeably?

It is my understanding that it is syntactically correct to use double quotes where possible, single when you need to embed a double quote for inline logic.

Is there something I am missing?

For examples:

HTML

```<code><a href='http://google.com'>Google</a>
</code>```

PHP

```<code><? echo 'Hello World!'; ?>
</code>```

ASP.NET

```<code><form id='myForm' runat='server'></form>
</code>```

答:
I would say that for most people, single and double quotes are treating and used interchangeably without a real understanding of the difference.

Both are used to create/delineate strings.

```<code>'Hello'

"Hello"
</code>```

Both are strings and are treated the same when used in this circumstance.

The difference in in processing. Technically, single quotes strings are not processed when created and stored in to memory. They are taken as is and made into strings.

Double quoted strings are processed when created and stored into memory. That is why you can put a variable into a double quoted string and it's value will be put in, but in a single quoted string the literal variable is put in. For most things, there is not a real difference if you sing a single or double quote except when creating strings with variables, function calls, etc and for saving some milliseconds in processing.

Title: Single Quotes Instead of Double Quotes?

Body:
Since both are acceptable by HTML as well as languages like ASP.NET and PHP when using attributes or strings, why is it that some people use single quotes and double quotes interchangeably?

It is my understanding that it is syntactically correct to use double quotes where possible, single when you need to embed a double quote for inline logic.

Is there something I am missing?

For examples:

HTML

Google

PHP

<? echo 'Hello World!'; ?>

ASP.NET

<form id='myForm' runat='server'></form>

Body:
I would say that for most people, single and double quotes are treating and used interchangeably without a real understanding of the difference.

Both are used to create/delineate strings.

'Hello'

"Hello"

Both are strings and are treated the same when used in this circumstance.

The difference in in processing. Technically, single quotes strings are not processed when created and stored in to memory. They are taken as is and made into strings.

Double quoted strings are processed when created and stored into memory. That is why you can put a variable into a double quoted string and it's value will be put in, but in a single quoted string the literal variable is put in. For most things, there is not a real difference if you sing a single or double quote except when creating strings with variables, function calls, etc and for saving some milliseconds in processing.